我有一个返回列表的fixture,我想为该列表中的每个元素创建一个测试,所以我试图在pytest.parametrize中将其作为参数传递,但它返回整个列表,只创建一个单独的测试。
@pytest.fixture()
def letters():
lettersABC = ['A', 'B', 'C', 'D']
return lettersABC
@pytest.mark.asyncio
@pytest.mark.parametrize('letter', ["letters"])
async def test_per_letter(letter, request):
name = request.getfixturevalue(letter)
print(f'name {name}')
assert name == 'A'
这样做的结果是:
FAILED digital_alarms_auto_test.py::test_per_letter[letters] - AssertionError: assert ['A', 'B', 'C', 'D'] == 'A'
===================================================================================================== 1 failed,
这只是我想做的一个例子,因为实际的代码更复杂。字母必须是一种固定装置,而不仅仅是一种功能
使用固定装置:
@pytest.fixture(params=['A', 'B', 'C', 'D'])
def letters(request):
return request.param
def test_per_letter(letters):
name = letters
print(f'name {name}')
assert name == 'A'
另一种选择是:
def pytest_generate_tests(metafunc):
if 'letters' in metafunc.fixturenames:
lettersABC = ['A', 'B', 'C', 'D']
metafunc.parametrize('letters', lettersABC)
def test_per_letter(letters):
name = letters
print(f'name {name}')
assert name == 'A'
输出:
================================================================================ short test summary info =================================================================================
FAILED main_test.py::test_per_letter[B] - AssertionError: assert 'B' == 'A'
FAILED main_test.py::test_per_letter[C] - AssertionError: assert 'C' == 'A'
FAILED main_test.py::test_per_letter[D] - AssertionError: assert 'D' == 'A'
==============================================================================
3 failed, 1 passed in 0.14s ===============================================================================