【问题标题】:Local import as pytest fixture?本地导入为 pytest 夹具?
【发布时间】:2022-09-23 03:44:50
【问题描述】:

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

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

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”。夹具并不意味着 直接调用,但在测试函数时自动创建 请求它们作为参数。看 https://docs.pytest.org/en/stable/explanation/fixtures.html 了解更多 有关固定装置的信息,以及 https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly 关于如何更新您的代码。

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

我怎样才能达到我想要的?我想显然返回函数句柄。

    标签: python pytest fixtures


    【解决方案1】:

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

    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作为参数添加到测试函数中,表明您将其用作夹具:

    def test_something(process_message):
        process_message()
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2023-04-05
      • 2014-03-02
      • 2023-03-11
      • 2019-04-29
      • 1970-01-01
      相关资源
      最近更新 更多