从 pytest 固定装置产生的调用函数 [英] Calling function that yields from a pytest fixture
问题描述
在我的单元测试中,我有两个非常相似的装置,我希望将一些功能分解为某种辅助函数.鉴于我对 yield
如何生成生成器的理解,我认为这不会导致任何问题.my_fixture_with_helper
,应该只返回`fixture_helper 产生的生成器.
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
但是,如果我运行 pytest --capture=no
,我会得到以下内容
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?
推荐答案
您需要使用 yield from
才能正确传递生成器.否则将返回生成器对象,它不会被 pytest
识别为生成器.
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()
有关 yield from
的更多信息可以在 这个stackoverflow 帖子.
Much more information about yield from
can be found at this stackoverflow post.
这篇关于从 pytest 固定装置产生的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!