首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用从pytest fixture生成的函数

调用从pytest fixture生成的函数
EN

Stack Overflow用户
提问于 2019-02-06 03:02:21
回答 1查看 1.7K关注 0票数 2

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

代码语言:javascript
复制
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,我会得到以下结果

代码语言:javascript
复制
test_foo.py Initialized from the fixture...
.Tearing down after the fixture...
.

我希望打印出"Initialized from the helper“和"Tearing down after the helper”,但它没有打印出来,我也不知道为什么。为什么这不起作用?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-06 03:17:14

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

代码语言:javascript
复制
@pytest.fixture
def my_fixture_with_helper():
    yield from fixture_helper()

有关yield from的更多信息,请访问this stackoverflow post.

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54541338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档