Reputation: 41
I am attempting to test a web API. Let's say that an endpoint accepts multiple parameters:
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?
Upvotes: 4
Views: 1118
Reputation: 122516
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
Upvotes: 2
Reputation: 57630
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):
Upvotes: 5