Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use pytest to test multiple options

Tags:

python

pytest

I am attempting to test a web API. Let's say that an endpoint accepts multiple parameters:

  • type: with possible values of "big", "small", "medium"
  • color: with possible values of "black", "white", "red"
  • shipping: with possible values of "1", "2", "7"

I want to test all combinations of these to ensure the API is returning correct results. At first I thought I could build 3 fixtures:

valid_types = ["big", "small", "medium"]
valid_colors = ['black', 'white', 'red']
valid_shipping = ['1', '2', '7']

@pytest.fixture(params=valid_types)
def valid_type(request):
    return request.param


@pytest.fixture(params=valid_colors)
def valid_color(request):
    return request.param


@pytest.fixture(params=valid_shipping)
def valid_ship(request):
    return request.param

But, I'm not sure how I can create the permutations for all of this. My test should operate like this:

def test_api_options(valid_type, valid_color, valid_ship):
    url_query = "?type={}&color={}&ship={}".format(valid_type, valid_color, valid_ship)
    r = requests.get("{}{}".format(base_url, url_query)

The test should run for each permutation and generate a new url with the available options for each. How can I do this with pytest?

like image 924
Bart Avatar asked Sep 11 '25 10:09

Bart


2 Answers

This is what parametrization is for:

@pytest.mark.parametrize('valid_type', valid_types)
@pytest.mark.parametrize('valid_color', valid_colors)
@pytest.mark.parametrize('valid_ship', valid_shipping)
def test_api_options(valid_type, valid_color, valid_ship):
like image 142
jwodder Avatar answered Sep 13 '25 23:09

jwodder


Your approach works as intended. If you run py.test you'll see it's being called with all possible values:

test_api_options[big-black-1] PASSED
test_api_options[big-black-2] PASSED
test_api_options[big-black-7] PASSED
test_api_options[big-white-1] PASSED
test_api_options[big-white-2] PASSED
test_api_options[big-white-7] PASSED
test_api_options[big-red-1] PASSED
test_api_options[big-red-2] PASSED
test_api_options[big-red-7] PASSED
test_api_options[small-black-1] PASSED
test_api_options[small-black-2] PASSED
test_api_options[small-black-7] PASSED
test_api_options[small-white-1] PASSED
test_api_options[small-white-2] PASSED
test_api_options[small-white-7] PASSED
test_api_options[small-red-1] PASSED
test_api_options[small-red-2] PASSED
test_api_options[small-red-7] PASSED
test_api_options[medium-black-1] PASSED
test_api_options[medium-black-2] PASSED
test_api_options[medium-black-7] PASSED
test_api_options[medium-white-1] PASSED
test_api_options[medium-white-2] PASSED
test_api_options[medium-white-7] PASSED
test_api_options[medium-red-1] PASSED
test_api_options[medium-red-2] PASSED
test_api_options[medium-red-7] PASSED
like image 29
Simeon Visser Avatar answered Sep 14 '25 00:09

Simeon Visser