python - 如何覆盖 pytest fixture,但仍然能够访问它?

标签 python python-3.x pytest fixtures

我有一个 conftest.py 和一个插件,它们都定义了具有不同实现的相同 fixture :

conftest.py
import pytest
@pytest.fixture
def f():
    yield 1

插件

import pytest
@pytest.fixture
def f():
    yield 2

安装插件时,conftest 仍然会覆盖插件,因此测试文件只会看到 conftest fixture,即

测试_.py
def test(f):
    assert f == 1 # True

我希望能够做这样的事情:

  1. 如果没有安装插件,继续
  2. 否则,从 conftest 插件中,产生插件的 fixture 的值

我成功完成了一半:

conftest.py
import pytest
@pytest.fixture
def f(pytestconfig):
    if pytestconfig.pluginmanager.has_plugin(plugin_name):
        # now what? I have get_plugin and import_plugin, but I'm not able to get the fixture from there...

最佳答案

我看到的最简单的方法是尝试获取插件 fixture 值。如果 fixture 查找失败,那么没有插件定义它,你可以做你自己的事情。示例:

import pytest
from _pytest.fixtures import FixtureLookupError

@pytest.fixture
def f(request):
    try:  # try finding an already declared fixture with that name
        yield request.getfixturevalue('f')
    except FixtureLookupError:
        # fixture not found, we are the only fixture named 'f'
        yield 1

关于python - 如何覆盖 pytest fixture,但仍然能够访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62041948/

相关文章:

python - 使用 python/psycopg2 循环遍历 PostgreSQL 表时发出 w/UPDATE

python - Python导入和嵌入式文件

python - 辛普森法则在 Python 中需要永远运行

python - 如何使用pytest在测试用例中运行 fixture 两次?

python - 当 pytest 运行目录中的所有测试时,它如何决定最后运行哪个测试?

python - 从 pandas 数据透视表中选择一列

python - 将整数转换为具有特定格式的十六进制字符串

python - 当这个类的 __call__ 方法在没有正确参数的情况下被调用时,它是如何工作的?

python - 居中窗口python tkinter

python - Jenkins 中的 py.test 控制台输出