Pytest-灯具依赖关系的动态解析

时间:2019-12-04 23:03:05

标签: python dynamic runtime pytest fixtures

除此波纹管外,我找不到其他改变灯具依赖关系的解决方案。 问题在于,我需要基于pytest.config.getoption参数确定依赖项,而不是这里使用的依赖项(变量在模块级别解析)。

我需要获得两种测试模式:快速和完整,并保持相同的测试源代码。

pytest_generate_tests似乎没有用,或者至少我不知道如何在这里使用它。

import pytest


DO_FULL_SETUP = "some condition that I need take from request.config.getoption(), not like this"

if DO_FULL_SETUP:
    # such a distinction is valid from interpreter's (and pytest's) point of view

    @pytest.fixture(scope="session")
    def needed_environment(a_lot_of, expensive, fixtures_needed):
        """This does expensive setup that I need 
        to avoid in "fast" mode. Takes about a minute (docker pull, etc..)"""

else:
    @pytest.fixture
    def needed_environment():
        """This does a fast setup, has "function scope" 
        and doesn't require any additional fixtures. Takes ~20ms"""


def test_that_things(needed_environment):
    """At this moment I don't want to distinguish what 
     needed_environment is. Tests have to pass in both modes."""

1 个答案:

答案 0 :(得分:0)

可以使用request.getfixturevalue('that_fixture_name')完成此操作。灯具可以在运行时调用。在这种情况下('session''function'甚至没有灯具的范围冲突。

import pytest


@pytest.fixture(scope="session")
def needed_environment_full(a_lot_of, expensive, fixtures_needed):
    """This does expensive setup that I need
    to avoid in "fast" mode. Takes about a minute (docker pull, etc..)"""


@pytest.fixture
def needed_environment_fast():
    """This does a fast setup, has "function scope"
    and doesn't require any additional fixtures. Takes ~20ms"""


@pytest.fixture
def needed_environment(request):
    """Dynamically run a named fixture function, basing on cli call argument."""
    if request.config.getoption('--run_that_fast'):
        return request.getfixturevalue('needed_environment_fast')
    else:
        return request.getfixturevalue('needed_environment_full')


def test_that_things(needed_environment):
    """At this moment I don't want to distinguish what
     needed_environment is. Tests have to pass in both modes."""