[英]Can I create a pytest.fixture that returns combinations of arguments?
The inputs to the the algorithm being tested is a list of strings (known in advance) with associated years, eg all of the following are valid inputs: 被测试算法的输入是带有关联年份的字符串列表(预先已知),例如,以下所有均为有效输入:
['A_2018', 'B_2019', 'C_2018']
[]
['A_2018']
I've got the following simple year fixture: 我有以下简单的固定装置:
@pytest.fixture(params=range(2018, 2025))
def year(request):
return request.param
If I create individual fixtures for each valid string: 如果我为每个有效字符串创建单独的灯具:
@pytest.fixture(params=['A', ''])
def A(request, year):
return request.param, year
@pytest.fixture(params=['B', ''])
def B(request, year):
return request.param, year
etc. and use them in tests like: 等,并在测试中使用它们,例如:
def test_foo(A, B):
args = []
if A[0]:
args.append('%s_%d' % A)
if B[0]:
args.append('%s_%d' % B)
assert old_algorithm(args) == new_algorithm(args)
I get 我懂了
['A_2018', 'B_2018']
['A_2019', 'B_2019']
['A_2020', 'B_2020']
etc. where the year is always the same for both parameters. 等等,其中两个参数的年份始终相同。
Is there a way to create all combinations? 有没有办法创建所有组合?
Is a fixture generating combinations a requirement? 灯具产生组合的要求吗? Because otherwise, applying
pytest.mark.parametrize
separately for each test input arg generates the input args combinations just fine. 否则,对每个测试输入arg分别应用
pytest.mark.parametrize
生成输入args组合。 In the example below both fixtures A
and B
are parametrized separately, generating (2025 - 2018)**2
tests in total: 在下面的示例中,夹具
A
和B
分别进行了参数设置,总共生成(2025 - 2018)**2
测试:
@pytest.fixture
def A(request):
return 'A', request.param
@pytest.fixture
def B(request):
return 'B', request.param
@pytest.mark.parametrize('A', range(2018, 2025), indirect=True, ids=lambda year: 'A({})'.format(year))
@pytest.mark.parametrize('B', range(2018, 2025), indirect=True, ids=lambda year: 'B({})'.format(year))
def test_foo(A, B):
assert A[0] == 'A' and B[0] == 'B'
As a result, 49 tests are produced: 结果,进行了49次测试:
$ pytest --collect-only | grep collected
collected 49 items
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.