我在 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/