问题
I would like to use fixtures as arguments of pytest.mark.parametrize
or something that would have the same results.
For example:
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
The problem with fixture params is that every param of the fixture will get run every time it's used, but I don't want that. I want to be able to choose which fixtures will get used depending on the test.
回答1:
If you're on pytest 3.0 or later, I think you should be able to solve this particular scenario by writing a fixture along the lines of:
@pytest.fixture(params=['dir1_fixture', 'dir2_fixture'])
def dirname(request):
return request.getfixturevalue(request.param)
Docs here: http://doc.pytest.org/en/latest/builtin.html#_pytest.fixtures.FixtureRequest.getfixturevalue
However, you can't use this approach if the fixture you're attempting to dynamically load is parametrized.
Alternatively, you might be able to figure something out with the pytest_generate_tests hook. I haven't been able to bring myself to look into that much, though.
回答2:
As for now, my only solution is to create a fixture that returns a dictionary of fixtures.
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
Not the best since it does not use a solution built into pytest, but it works for me.
回答3:
This isn't currently supported by pytest. There is an open feature request for it though: https://github.com/pytest-dev/pytest/issues/349.
来源:https://stackoverflow.com/questions/42014484/pytest-using-fixtures-as-arguments-in-parametrize