【问题标题】:Pytest parametrized fixture with pytest-lazy-fixture fails if moved to conftest如果移动到 conftest,带有 pytest-lazy-fixture 的 Pytest 参数化夹具会失败
【发布时间】:2021-11-08 11:58:07
【问题描述】:

我已经编写了这个简单的参数化夹具

@pytest.fixture(params=[
    pytest.lazy_fixture("client_a"),
    pytest.lazy_fixture("client_b"),
    pytest.lazy_fixture("client_c"),
])
def client_all(request):
    return request.param

放入测试文件时它可以完美运行。当我将其移至 conftest.py 时,结果是:

加载 conftest 时出现 ImportError '/project/tests/conftest.py'。 conftest.py:181: 在 ??? E AttributeError: 模块 'pytest' 没有属性 'lazy_fixture'

显然调试 pytest 的插件管理器是不可行的,但我注意到 pytest-lazy-fixture 中的 pytest_configure 函数在我收到此错误时从未被调用,但它确实在夹具工作时被调用,所以问题一定是当列表插件已加载。我希望它与其他一些 pytest 选项发生一些奇怪的冲突,但我不知道如何从这里继续前进。

请注意,该插件在整个项目的其他文件中使用,但仅用于参数化单个测试,而不是作为固定参数。

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    插件是在conftest文件和fixture加载后配置的。

    因此,在注册全局装置时,pytest.lazy_fixture 命名空间还不存在,因为对 pytest_configure 的调用尚未发生。

    正确的使用方式是从自己的模块本身加载:

    from pytest_lazyfixture import lazy_fixture
    
    @pytest.fixture(params=[
        lazy_fixture("client_a"),
        lazy_fixture("client_b"),
        lazy_fixture("client_c"),
    ])
    def client_all(request):
       ...
    

    The docs don't clearly mention this,就像调用钩子的确切时间一样,但在源代码中,我们可以看到按以下顺序发生:

    1. main() 被调用
    2. main() 致电 _prepareconfig。它使用插件管理器(PytestPluginManager,Pluggy 的PluginManager 的子类)加载和注册插件。
    3. config._do_configure() 然后通过在 Pluggy 的 _HookCaller 类中调用 call_historic 来进行实际配置。

    【讨论】:

    • 哇哦。我知道这可能是一些棘手的订购问题,但我从未想过这是可能的答案之一。非常感谢
    【解决方案2】:

    好像是old issuepytest_namespace 钩子在 pytest 4.0 中被删除,这意味着由于 pytest.lazyfixture 是一个插件,它仅在 conftest.py 之后添加。直接导入lazy_fixture即可解决

    from pytest_lazyfixture import lazy_fixture
    
    @pytest.fixture(params=[
        lazy_fixture("client_a"),
        lazy_fixture("client_b"),
        lazy_fixture("client_c"),
    ])
    def client_all(request):
        return request.param
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2022-01-21
      • 2022-12-08
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      相关资源
      最近更新 更多