【问题标题】:How can pytest enable print() in src code?pytest 如何在 src 代码中启用 print()?
【发布时间】:2021-12-25 05:34:49
【问题描述】:

这是我的代码

在module.py中:

def myFunc():
    print('aaa')

在 test_module.py 中:

def test_myFunc():
    print('bbb')
    myFunc()

如果我运行pytest -s test_module.py,那么我可以看到打印输出bbb;但我看不到打印输出aaa。 其实我也试过import logging来玩logger,也没有运气。

所以基本上我的问题是,在触发pytest 时,我们如何从 src 代码中看到打印输出?

【问题讨论】:

  • Pytest 拦截打印和日志记录。它们只会在失败时显示。这样应用程序就不会弄乱 pytest 的输出。有命令行参数可以改变行为。
  • 实际上pytest -s 应该这样做,因为它禁用捕获输出 - 我怀疑环境中还有其他事情发生(配置,插件,...)。跨度>
  • 如果没有进一步的信息,这个问题就无法回答,就像给定的例子一样。
  • 我无法重现,你在用capsys/capfd吗?

标签: python printing pytest


【解决方案1】:

我可以确认pytest -s 完成了这项工作。

pytest -s test_module.py

# test_module.py bbb
# aaa

但是,使用 Python logging 模块进行调试可能是一个更好的主意。例如,您只需要导入logging 并通过对logging.info() 的适当级别调用来替换打印。

# module.py
import logging

def myFunc():
    logging.info('aaa')

# test_module.py
from module import myFunc
import logging

def test_myFunc():
    logging.info('bbb')
    myFunc() 

这是输出。

pytest --log-cli-level=INFO test_module.py 

# INFO     root:test_module.py:6 bbb
# INFO     root:module.py:4 aaa

Pytest doc 中的更多信息专门用于日志记录。

【讨论】:

  • 是的,谢谢!我已经意识到记录是比 print() 更好的方法,并且是为此而设计的。
猜你喜欢
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 2013-04-12
  • 2015-05-09
相关资源
最近更新 更多