python-3.x - Pytest 在运行时更改 fixture 范围

标签 python-3.x pytest fixtures

我在 conftest.py 中定义了常见的固定装置它在所有模块之间共享,并且范围为“功能”范围,如下所示:

conftest.py

@pytest.fixture(scope="function")
def reset_state(services):
    # resets the state of the services

我的测试目前这样称呼它,

test_module_one:
# change scope to session here
@pytest.mark.usefixtures("reset_state")
def test_something:
    # Test stuff using session-scoped fixtures.

对于上面的具体测试,我想更改reset_state的范围代替“ session ”的通用 fixture 。

有没有办法在运行时更改范围?

最佳答案

由于pytest版本 5.2,支持 dynamic scope .您可以提供自定义可调用对象作为固定范围,允许它确定运行时中的范围。
文档中的示例:

def determine_scope(fixture_name, config):
    if config.getoption("--keep-containers", None):
        return "session"
    return "function"


@pytest.fixture(scope=determine_scope)
def docker_container():
    yield spawn_container()
请注意,它不允许您将运行时范围从测试更改为测试。如果是这种情况,您希望使用 session所有测试的范围,除了少数改变 fixture 内部状态的测试(因此您希望使用 function 范围运行它们)有一个简单且非常明确的解决方法,具有引用透明度:
制作一种方法来创建测试主题和两个不同范围的固定装置,返回这种方法的结果。
例子:
import pytest


def _make_fixture() -> object:
    """
    Returns:
        object: Some fixture for the test
    """
    return object()


@pytest.fixture(scope="function")
def function_scope_fixture() -> object:
    """
    Returns:
        object: Function scope use fixture
    """
    return _make_fixture()


@pytest.fixture(scope="session")
def session_scope_fixture() -> object:
    """
    Returns:
        object: Session scope use fixture
    """
    return _make_fixture()


def test_1(session_scope_fixture):
    """Test without mutation of the fixture"""
    ...


def test_2(function_scope_fixture):
    """Test mutating the internal state of the fixture"""
    ...

关于python-3.x - Pytest 在运行时更改 fixture 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59619621/

相关文章:

django - Airflow 的网络服务器未运行

python - 如何将 RGBA 字节转换为 PNG 图像?

python - 在 python 列表理解中有没有一种方法可以不重复工作

python - 访问 Travis-CI 上的剪贴板

unit-testing - Rails3 : Find method not working with fixtures in test environment

python - 何时使用 TestClass 实例变量与 Pytest Fixtures

python - 在 Python argparse 中,是否可以配对 --no-something/--something 参数?

Python 使用 pytest_mock 在函数中模拟多个查询

python - 使用 ipdb 而不是 pdb 和 py.test --pdb 选项

Scala 中间早期初始化器