pytest使用fixtures作为参数化中的参数

时间:2017-02-02 23:51:21

标签: python pytest

我想使用灯具作为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

夹具参数的问题在于夹具的每个参数都会在每次使用时运行,但我不希望这样。我希望能够根据测试选择使用哪种灯具。

4 个答案:

答案 0 :(得分:8)

如果您使用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钩子找出问题。不过,我无法让自己去研究那么多。

答案 1 :(得分:4)

pytest目前不支持此功能。但是有一个开放的功能请求:https://github.com/pytest-dev/pytest/issues/349

答案 2 :(得分:3)

就目前而言,我唯一的解决方案是创建一个返回灯具字典的灯具。

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的解决方案,但它适用于我。

答案 3 :(得分:3)

Will在正确的路径上,您应该使用request.getfixturevalue来检索灯具。但是您可以在测试中做到这一点,这更简单。

@pytest.mark.parametrize('dirname, expected', [
    ('dir1_fixture', 'expected1'),
    ('dir2_fixture', 'expected2')])
def test_directory_command(dirname, expected, request):
    result = my_package.directory_command(request.getfixturevalue(dirname))
    assert result == expected

另一种方法是使用lazy-fixture插件:

@pytest.mark.parametrize('dirname, expected', [
    (pytest.lazy_fixture('dir1_fixture'), 'expected1'),
    (pytest.lazy_fixture('dir2_fixture'), 'expected2')])
def test_directory_command(dirname, expected):
    result = my_package.directory_command(dirname)
    assert result == expected