我正在尝试测试一个Web API。让我们说端点接受多个参数:
我想测试这些的所有组合,以确保API返回正确的结果。起初我以为我可以建立3个灯具:
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
但是,我不确定如何为所有这些创建排列。我的测试应该像这样运行:
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)
测试应该针对每个排列运行,并生成一个新的url,其中包含每个排列的可用选项。我怎么能用pytest做到这一点?
答案 0 :(得分:3)
这是parametrization的用途:
@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):
答案 1 :(得分:1)
您的方法按预期工作。如果你运行py.test
,你会看到它被调用所有可能的值:
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