我想使用fixtures作为pytest.mark.parametrize
的参数或具有相同结果的东西。
例如:
import pytest
import my_package
@pytest.fixture
def dir1_fixture():
return '/dir1'
@pytest.fixture
def dir2_fixture():
return '/dir2'
@pytest.parametrize('dirname, expected', [(dir1_fixture, 'expected1'), (dir2_fixture, 'expected2')]
def test_directory_command(dirname, expected):
result = my_package.directory_command(dirname)
assert result == expected
夹具参数的问题在于夹具的每个参数都会在每次使用时运行,但我不希望这样。我希望能够根据测试选择使用哪种灯具。
如果您使用pytest 3.0或更高版本,我认为您应该能够通过编写以下行的方式来解决此特定情况:
@pytest.fixture(params=['dir1_fixture', 'dir2_fixture'])
def dirname(request):
return request.getfixturevalue(request.param)
文档:http://doc.pytest.org/en/latest/builtin.html#_pytest.fixtures.FixtureRequest.getfixturevalue
但是,如果您尝试动态加载的夹具已参数化,则无法使用此方法。
或者,您可以使用pytest_generate_tests钩子找出问题。不过,我无法让自己去研究那么多。
pytest目前不支持此功能。但是有一个开放的功能请求:https://github.com/pytest-dev/pytest/issues/349。
至于现在,我唯一的解决方案是创建一个返回灯具字典的灯具。
import pytest
import my_package
@pytest.fixture
def dir1_fixture():
return '/dir1'
@pytest.fixture
def dir2_fixture():
return '/dir2'
@pytest.fixture
def dir_fixtures(
dir1_fixture,
dir2_fixture
):
return {
'dir1_fixture': dir1_fixture,
'dir2_fixture': dir2_fixture
}
@pytest.mark.parametrize('fixture_name, expected', [('dir1_fixture', 'expected1'), ('dir2_fixture', 'expected2')]
def test_directory_command(dir_fixtures, fixture_name, expected):
dirname = dir_fixtures[fixture_name]
result = my_package.directory_command(dirname)
assert result == expected
不是最好的,因为它不使用内置于pytest的解决方案,但它适用于我。