【问题标题】:Calling function that yields from a pytest fixture调用从 pytest 夹具产生的函数
【发布时间】:2019-02-05 19:02:21
【问题描述】:

在我的单元测试中,我有两个非常相似的装置,我希望将一些功能分解为某种辅助函数。鉴于我对yield 如何生成生成器的理解,我认为这不会引起任何问题。 my_fixture_with_helper,应该只返回 fixture_helper 生成的生成器。

import pytest


def fixture_helper():
    print("Initialized from the helper...")
    yield 26
    print("Tearing down after the helper...")


@pytest.fixture
def my_fixture_with_helper():
    return fixture_helper()


@pytest.fixture
def my_fixture():
    print("Initialized from the fixture...")
    yield 26
    print("Tearing down after the fixture...")


def test_nohelper(my_fixture):
    pass


def test_helper(my_fixture_with_helper):
    pass

但是,如果我运行 pytest --capture=no,我会得到以下信息

test_foo.py Initialized from the fixture...
.Tearing down after the fixture...
.

我希望“Initialized from the helper”和“Tearing down after the helper”会被打印出来,但事实并非如此,我不知道为什么。为什么这不起作用?

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    您需要使用yield from 才能正确传递生成器。否则将返回生成器对象,pytest 无法将其识别为生成器。

    @pytest.fixture
    def my_fixture_with_helper():
        yield from fixture_helper()
    

    更多关于yield from的信息可以在this stackoverflow post.找到

    【讨论】:

    • 为什么无法识别? yield 通常不会返回生成器吗?
    • 啊哈!我的版本不允许 pytest 理解它是一个生成器函数(见inspect.isgeneratorfunction)谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-09-11
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多