【问题标题】:Pytest - dynamic resolution of fixtures' dependenciesPytest - 夹具依赖项的动态解析
【发布时间】:2019-12-04 23:03:05
【问题描述】:

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

【问题讨论】:

    标签: python dynamic runtime pytest fixtures


    【解决方案1】:

    这可以使用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."""
    

    【讨论】:

      猜你喜欢
      • 2017-05-06
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 2021-06-16
      • 2018-02-27
      • 1970-01-01
      相关资源
      最近更新 更多