【问题标题】:Need to understand how `yield` works for `pytest`?需要了解 `yield` 如何为 `pytest` 工作?
【发布时间】:2020-02-23 08:39:59
【问题描述】:

我正在使用pytest 测试python 应用程序(3.7),但我发现它没有运行最后带有yield 的方法。

下面是我的python方法:

def load(conn):
   print('Hello world')
   if conn.connected:
       yield True

下面是测试用例:

def test_load():
    load(None)

当使用pytest 运行测试用例时,方法load() 不会被事件调用。测试结果显示pass。我如何理解yeildpytest 的工作方式?

【问题讨论】:

  • 这更像是一个“理解 yield 的含义”的问题,而不是一个 pytest 问题。

标签: python pytest


【解决方案1】:

yield 将函数转换为generator,因此调用load() 返回一个生成器对象而不实际执行其内容。

如果您使用-s 标志运行pytest,您可以看到它返回的内容,这会阻止它从capturing 输出print (pytest -s [file]):

def test_load():
    print(load(None))

要实际执行生成器,您可以使用next() 检索生成器生成的下一个项目:

def test_load():
    next(load(None))

【讨论】:

    猜你喜欢
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 2021-11-01
    相关资源
    最近更新 更多