首页 > 解决方案 > Pytest - 夹具依赖项的动态解析

问题描述

我找不到一种解决方案来以任何不同于下面的方式改变固定装置的依赖关系。问题是我需要根据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."""

标签: pythondynamicruntimepytestfixtures

解决方案


这可以使用request.getfixturevalue('that_fixture_name'). 可以在运行时调用夹具。在这种情况下甚至没有夹具的范围违规('session'vs. '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."""

推荐阅读