python - 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."""
解决方案
这可以使用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."""
推荐阅读
- java - 如何将 ID 信息从一张表传输到另一张表?
- c# - 如何排除 .txt4 文件的生成
- sql - 公用表表达式在函数中非常慢
- regex - 如何在 Javascript 中使用正则表达式获取亚马逊 ASIN 号?
- .net - 在托管环境中获取调试数据的过程
- c# - 尝试 catch 不能按预期对异步委托工作
- react-native - 在 android studio 上看不到我的 react native 应用的演示
- python - 如何在 python 的虚拟环境中安装 pip 后访问资源文件?
- javascript - 使用 JS 在不同元素上恢复正常状态
- python - 在 Listbox tk Python 中查看 Excel 数据