繁体   English   中英

本地导入为 pytest 夹具?

[英]Local import as pytest fixture?

我需要在我的测试中本地导入一些函数(是的,可以更好地设计代码库以避免这种必要性,但假设我们不能这样做)。

这意味着我在一个模块中的所有测试的第一行如下例所示:

def test_something():
    from worker import process_message

    process_message()

现在我想通过创建以下夹具来使其更加干燥:

@pytest.fixture(scope="module", autouse=True)
def process_message():
    from worker import process_message
    return process_message

但我总是得到错误

夹具“process_message”直接调用。 Fixtures 不是直接调用的,而是在测试函数请求它们作为参数时自动创建的。 See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly关于如何更新您的代码。

链接的文档对我帮助不大。

我怎样才能达到我想要的? 我想显然退回 function 手柄。

发生这种情况的原因是您直接从您的一项测试中调用了夹具。 我假设您使用夹具的测试代码如下所示:

import pytest


@pytest.fixture(scope="module", autouse=True)
def process_message():
    from worker import process_message
    return process_message


def test_something():
    process_message()

然后test_something因指定的异常而失败。

修复它的方法是将process_message作为参数添加到测试function中,表明您将其用作夹具:

def test_something(process_message):
    process_message()

顺便说一句,由于您必须在每个测试中指定process_message夹具才能调用它,这意味着使用autouse=True没有意义,并且可以将其删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM