Calling function that yields from a pytest fixture

旧街凉风 提交于 2021-01-05 11:21:20

问题


In my unit tests, I have two very similar fixtures, and I was hoping to break out some of the functionality into a helper function of some kind. Given my understanding of how yield produces generators, I don't feel like this should cause any kind of problem. my_fixture_with_helper, should just return the generator that `fixture_helper produces.

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

However, if I run pytest --capture=no, I get the following

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

I would expect "Initialized from the helper" and "Tearing down after the helper" to get printed, but it does not, and I cannot figure out why. Why does this not work?


回答1:


You need to use yield from to be able to pass the generator through properly. Otherwise the generator object will be returned, which isn't recognized by pytest as a generator.

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

Much more information about yield from can be found at this stackoverflow post.



来源:https://stackoverflow.com/questions/54541338/calling-function-that-yields-from-a-pytest-fixture

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!