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

2024-05-17 09:54:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

conftest.py

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

插件

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

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

测试_uupy

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...

Tags: 文件pyimport插件get定义pytestdef
1条回答
网友
1楼 · 发布于 2024-05-17 09:54:27

我看到的最简单的方法是尝试获取插件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

相关问题 更多 >