我有一个 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
我希望能够做这样的事情:
- 如果没有安装插件,继续
- 否则,从 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/