【问题标题】:how to override a pytest fixture, but still be able to access it?如何覆盖 pytest 夹具,但仍然能够访问它?
【发布时间】:2020-05-27 11:25:30
【问题描述】:

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

conftest.py

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

插件

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

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

test_.py

​​>
def test(f):
    assert f == 1 # True

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

  1. 如果没有安装插件,继续
  2. 否则,来自 conftest 插件,产生插件夹具的值

我成功了一半:

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

【问题讨论】:

    标签: python python-3.x pytest fixtures


    【解决方案1】:

    我看到的最简单的方法是尝试获取插件固定值。如果夹具查找失败,则没有插件定义它,您可以自己做。示例:

    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
    

    【讨论】:

    • 酷,虽然我不明白。为什么request.getfixturevalue('f') 中的f 不会被评估为覆盖f
    • 因为在这种情况下你会得到一个无限递归,而夹具查找试图用所有的力量来避免这种情况。
    猜你喜欢
    • 2014-10-26
    • 1970-01-01
    • 2019-09-26
    • 2021-12-15
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    相关资源
    最近更新 更多