一旦我对测试用例感到满意,我可以关闭该选项,以便冗长的日志记录消失
我是 TDD 新手,想要转向这种做法,但无法看到我的打印/日志记录让我感到很不舒服,因为我感到迷失
if __name__ == '__main__'运行代码主要功能的Pytest 也有自己的实现,可以向您展示捕获日志记录时发生的情况。如果您访问此页面上的实时日志:https://docs.pytest.org/en/latest/logging.html,它的解释非常好。您需要一个 pytest.ini 文件,在其中设置:
[pytest]
log_cli = True
Run Code Online (Sandbox Code Playgroud)
这将使您的日志在发出时显示在终端上。然后,您可以通过 pytest 调用设置您想要查看的级别,例如 DEBUG:
pytest --log-cli-level DEBUG
Run Code Online (Sandbox Code Playgroud)
或者您也可以在 pytest.ini 中指定它:
[pytest]
log_cli = True
log_cli_level = DEBUG
Run Code Online (Sandbox Code Playgroud)
其中 log_cli_level 设置显示日志的级别。这种方法不会让您更改自己的代码,这很好。当然,这也要求您首先使用日志记录,但无论如何这是一个好习惯。