被测试算法的输入是带有相关年份的字符串列表(预先已知),例如以下所有都是有效输入:
['A_2018', 'B_2019', 'C_2018']
[]
['A_2018']
Run Code Online (Sandbox Code Playgroud)
我有以下简单的年份固定装置:
@pytest.fixture(params=range(2018, 2025))
def year(request):
return request.param
Run Code Online (Sandbox Code Playgroud)
如果我为每个有效字符串创建单独的装置:
@pytest.fixture(params=['A', ''])
def A(request, year):
return request.param, year
@pytest.fixture(params=['B', ''])
def B(request, year):
return request.param, year
Run Code Online (Sandbox Code Playgroud)
等,并在测试中使用它们,例如:
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)
Run Code Online (Sandbox Code Playgroud)
我得到
['A_2018', 'B_2018']
['A_2019', 'B_2019']
['A_2020', 'B_2020']
Run Code Online (Sandbox Code Playgroud)
等等,其中两个参数的年份总是相同的。
有没有办法创建所有组合?
夹具生成组合是必需的吗?因为否则,pytest.mark.parametrize单独应用每个测试输入 arg 会生成输入 args 组合就好了。在下面的示例中,夹具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'
Run Code Online (Sandbox Code Playgroud)
结果,产生了 49 个测试:
$ pytest --collect-only | grep collected
collected 49 items
Run Code Online (Sandbox Code Playgroud)