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

how to override a pytest fixture, but still be able to access it?

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

conftest.py

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

插件

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

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

test_.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 查找失败,那么没有插件定义它,你可以做你自己的事情。示例:

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