从 pytest 固定装置产生的调用函数

oll*_*ien 2 python pytest

在我的单元测试中,我有两个非常相似的装置,我希望将某些功能分解为某种辅助函数。鉴于我对如何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
Run Code Online (Sandbox Code Playgroud)

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

test_foo.py Initialized from the fixture...
.Tearing down after the fixture...
.
Run Code Online (Sandbox Code Playgroud)

我希望“从帮手初始化”和“在帮手之后拆解”得到打印,但事实并非如此,我不知道为什么。为什么这不起作用?

Mar*_*cus 5

您需要使用yield from才能正确地通过生成器。否则将返回生成器对象,它不会被识别pytest为生成器。

@pytest.fixture
def my_fixture_with_helper():
    yield from fixture_helper()
Run Code Online (Sandbox Code Playgroud)

yield from可以在此 stackoverflow 帖子中找到有关更多信息