简体   繁体   English

本地导入为 pytest 夹具?

[英]Local import as pytest fixture?

I need to import some functions locally within my tests (yes, the code base can be designed better to avoid this necessity, but let's assume we can't do that).我需要在我的测试中本地导入一些函数(是的,可以更好地设计代码库以避免这种必要性,但假设我们不能这样做)。

That means the first line of all my tests within a module looks like in this example:这意味着我在一个模块中的所有测试的第一行如下例所示:

def test_something():
    from worker import process_message

    process_message()

Now I wanted to make this more DRY by creating the following fixture:现在我想通过创建以下夹具来使其更加干燥:

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

But I always get the error但我总是得到错误

Fixture "process_message" called directly.夹具“process_message”直接调用。 Fixtures are not meant to be called directly, but are created automatically when test functions request them as parameters. 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 about how to update your code. 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关于如何更新您的代码。

The linked documentation doesn't help me much.链接的文档对我帮助不大。

How can I achieve what I want?我怎样才能达到我想要的? I'd like to return the function handle obviously.我想显然退回 function 手柄。

The reason this happens is that you are calling the fixture directly from one of your tests.发生这种情况的原因是您直接从您的一项测试中调用了夹具。 I assume that your test code with the fixture looks something like this:我假设您使用夹具的测试代码如下所示:

import pytest


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


def test_something():
    process_message()

And then test_something fails with the specified exception.然后test_something因指定的异常而失败。

The way to fix it is to add process_message as an argument to the test function, indicating that you are using it as a fixture:修复它的方法是将process_message作为参数添加到测试function中,表明您将其用作夹具:

def test_something(process_message):
    process_message()

btw, since you have to specify process_message fixture in every test in order to call it, means there is no point in using the autouse=True and it can be removed.顺便说一句,由于您必须在每个测试中指定process_message夹具才能调用它,这意味着使用autouse=True没有意义,并且可以将其删除。

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

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