从测试代码输出 print/logging 语句的 pytest 选项

pytest option to output print/logging statements from tested code

关于这个主题有一篇很棒的文章: https://pythontesting.net/framework/pytest/pytest-logging-real-time/

  • 我在底层代码中将所有打印语句转换为日志语句
  • 包含我添加的 test_transform() 函数的模块

`

import logging
logging.basicConfig(level=logging.DEBUG)

def test_transform()
   ...

Pytest 也有它自己的实现来向您展示它捕获您的日志记录时发生了什么。如果您转到此页面上的实时日志:https://docs.pytest.org/en/latest/logging.html,它的解释非常好。您需要一个 pytest.ini 文件,您在其中设置:

[pytest]
log_cli = True

这将使您的日志在发出时显示在终端上。然后,您可以将您希望通过 pytest 调用查看的级别设置为例如 DEBUG:

pytest --log-cli-level DEBUG

或者您也可以在 pytest.ini 中指定它:

[pytest]
log_cli = True
log_cli_level = DEBUG

其中 log_cli_level 设置显示日志的级别。这种方法不会让您更改自己的代码,这很好。这当然也要求您首先使用日志记录,但无论如何这是一个好习惯。