从测试代码输出 print/logging 语句的 pytest 选项
pytest option to output print/logging statements from tested code
- pytest 中是否有一个选项,正在测试的代码将其 logging.info(...) 消息输出到控制台
- 这将使开发我的测试用例变得更加容易,因为会发生大量数据转换,而我会迷失在转换过程中
一旦我对测试用例感到满意,我就可以关闭该选项,以便冗长的日志记录语句消失
我是 TDD 的新手,想转向这种做法,但是看不到我的 print/logging 陈述让我很不舒服,因为我感到迷茫
- 我通常会创建一个
if __name__ == '__main__'
来运行代码的主要功能
- 这至少让我可以看到日志语句,这样我就可以理解代码 运行
- 但我似乎在重复工作
关于这个主题有一篇很棒的文章:
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 设置显示日志的级别。这种方法不会让您更改自己的代码,这很好。这当然也要求您首先使用日志记录,但无论如何这是一个好习惯。
- pytest 中是否有一个选项,正在测试的代码将其 logging.info(...) 消息输出到控制台
- 这将使开发我的测试用例变得更加容易,因为会发生大量数据转换,而我会迷失在转换过程中
一旦我对测试用例感到满意,我就可以关闭该选项,以便冗长的日志记录语句消失
我是 TDD 的新手,想转向这种做法,但是看不到我的 print/logging 陈述让我很不舒服,因为我感到迷茫
- 我通常会创建一个
if __name__ == '__main__'
来运行代码的主要功能 - 这至少让我可以看到日志语句,这样我就可以理解代码 运行
- 但我似乎在重复工作
- 我通常会创建一个
关于这个主题有一篇很棒的文章: 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 设置显示日志的级别。这种方法不会让您更改自己的代码,这很好。这当然也要求您首先使用日志记录,但无论如何这是一个好习惯。