如何管理日志记录¶
pytest 会自动捕获 WARNING 或更高级别的日志消息,并以与捕获的 stdout 和 stderr 相同的方式,在每个失败测试的专属部分中显示它们。
不带选项运行
pytest
显示失败的测试,如下所示
----------------------- Captured stdlog call ----------------------
test_reporting.py 26 WARNING text going to logger
----------------------- Captured stdout call ----------------------
text going to stdout
----------------------- Captured stderr call ----------------------
text going to stderr
==================== 2 failed in 0.02 seconds =====================
默认情况下,每个捕获的日志消息都显示模块、行号、日志级别和消息。
如果需要,可以通过传递特定的格式选项,将日志和日期格式指定为日志模块支持的任何格式
pytest --log-format="%(asctime)s %(levelname)s %(message)s" \
--log-date-format="%Y-%m-%d %H:%M:%S"
显示失败的测试,如下所示
----------------------- Captured stdlog call ----------------------
2010-04-10 14:48:44 WARNING text going to logger
----------------------- Captured stdout call ----------------------
text going to stdout
----------------------- Captured stderr call ----------------------
text going to stderr
==================== 2 failed in 0.02 seconds =====================
这些选项也可以通过配置文件进行自定义
[pytest]
log_format = "%(asctime)s %(levelname)s %(message)s"
log_date_format = "%Y-%m-%d %H:%M:%S"
[pytest]
log_format = %(asctime)s %(levelname)s %(message)s
log_date_format = %Y-%m-%d %H:%M:%S
可以通过 --log-disable={logger_name} 禁用特定的日志记录器。此参数可以传递多次
pytest --log-disable=main --log-disable=testing
此外,可以通过以下方式完全禁用失败测试中捕获内容的报告(stdout、stderr 和日志)
pytest --show-capture=no
caplog fixture¶
在测试内部,可以更改捕获日志消息的日志级别。caplog fixture 支持此功能
def test_foo(caplog):
caplog.set_level(logging.INFO)
默认情况下,级别设置在根日志记录器上,但为方便起见,也可以设置任何日志记录器的日志级别
def test_foo(caplog):
caplog.set_level(logging.CRITICAL, logger="root.baz")
设置的日志级别会在测试结束时自动恢复。
也可以使用上下文管理器在 with 块内临时更改日志级别
def test_bar(caplog):
with caplog.at_level(logging.INFO):
pass
同样,默认情况下,根日志记录器的级别会受到影响,但也可以通过以下方式更改任何日志记录器的级别
def test_bar(caplog):
with caplog.at_level(logging.CRITICAL, logger="root.baz"):
pass
最后,在测试运行期间发送到日志记录器的所有日志都以 logging.LogRecord 实例和最终日志文本的形式在 fixture 上可用。这在您想要断言消息内容时非常有用
def test_baz(caplog):
func_under_test()
for record in caplog.records:
assert record.levelname != "CRITICAL"
assert "wally" not in caplog.text
有关日志记录的所有可用属性,请参见 logging.LogRecord 类。
如果您只想确保某些消息已在给定日志记录器名称下以给定严重性和消息记录,您也可以求助于 record_tuples
def test_foo(caplog):
logging.getLogger().info("boo %s", "arg")
assert caplog.record_tuples == [("root", logging.INFO, "boo arg")]
您可以调用 caplog.clear() 来重置测试中捕获的日志记录
def test_something_with_clearing_records(caplog):
some_method_that_creates_log_records()
caplog.clear()
your_test_method()
assert ["Foo"] == [rec.message for rec in caplog.records]
caplog.records 属性仅包含当前阶段的记录,因此在 setup 阶段它只包含 setup 日志,call 和 teardown 阶段也一样。
要访问其他阶段的日志,请使用 caplog.get_records(when) 方法。例如,如果您想确保使用特定 fixture 的测试永远不会记录任何警告,您可以在 teardown 期间检查 setup 和 call 阶段的记录,如下所示
@pytest.fixture
def window(caplog):
window = create_window()
yield window
for when in ("setup", "call"):
messages = [
x.message for x in caplog.get_records(when) if x.levelno == logging.WARNING
]
if messages:
pytest.fail(f"warning messages encountered during testing: {messages}")
完整的 API 可在 pytest.LogCaptureFixture 处获得。
警告
caplog fixture 会向根日志记录器添加一个处理程序以捕获日志。如果在测试期间修改了根日志记录器,例如使用 logging.config.dictConfig,则此处理程序可能会被删除,导致无法捕获日志。为避免这种情况,请确保任何根日志记录器配置仅添加到现有处理程序。
实时日志¶
通过将 log_cli 配置选项设置为 true,pytest 会将日志记录直接输出到控制台。
您可以通过传递 --log-cli-level 来指定要打印到控制台的日志记录级别,其中日志记录级别等于或高于该级别。此设置接受日志记录级别名称或数字值,如 logging 的文档所示。
此外,您还可以指定 --log-cli-format 和 --log-cli-date-format,它们在未提供时会镜像并默认使用 --log-format 和 --log-date-format,但仅适用于控制台日志处理程序。
所有 CLI 日志选项也可以在配置文件中设置。选项名称为
如果您需要将整个测试套件的日志调用记录到文件中,您可以传递 --log-file=/path/to/log/file。默认情况下,此日志文件以写入模式打开,这意味着它将在每次运行测试会话时被覆盖。如果您希望文件以追加模式打开,则可以传递 --log-file-mode=a。请注意,日志文件位置的相对路径,无论是通过 CLI 传递还是在配置文件中声明,始终相对于当前工作目录解析。
您还可以通过传递 --log-file-level 来指定日志文件的日志级别。此设置接受日志记录级别名称或数字值,如 logging 的文档所示。
此外,您还可以指定 --log-file-format 和 --log-file-date-format,它们与 --log-format 和 --log-date-format 相同,但应用于日志文件日志处理程序。
所有日志文件选项也可以在配置文件中设置。选项名称为
您可以调用 set_log_path() 动态自定义 log_file 路径。此功能被认为是实验性的。请注意,set_log_path() 遵循 log_file_mode 选项。
自定义颜色¶
如果启用了彩色终端输出,日志级别将显示颜色。通过 add_color_level() 支持更改默认颜色或为自定义日志级别设置颜色。示例
@pytest.hookimpl(trylast=True)
def pytest_configure(config):
logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
# Change color on existing log level
logging_plugin.log_cli_handler.formatter.add_color_level(logging.INFO, "cyan")
# Add color to a custom log level (a custom log level `SPAM` is already set up)
logging_plugin.log_cli_handler.formatter.add_color_level(logging.SPAM, "blue")
警告
此功能及其 API 被认为是实验性的,并且可能在版本之间更改而无需弃用通知。
发行说明¶
此功能作为 pytest-catchlog 插件的直接替代品引入,它们相互冲突。当此功能引入时,与 pytest-capturelog 的向后兼容 API 已被删除,因此如果由于此原因您仍需要 pytest-catchlog,您可以通过在配置文件中添加以下内容来禁用内部功能
[pytest]
addopts = ["-p", "no:logging"]
[pytest]
addopts = -p no:logging
pytest 3.4 中的不兼容更改¶
此功能在 3.3 中引入,在社区反馈后,3.4 中进行了一些不兼容更改
除非通过
log_level配置或--log-level命令行选项明确请求,否则不再更改日志级别。这允许用户自行配置日志记录器对象。设置log_level将设置全局捕获的级别,因此如果特定测试需要低于此级别的级别,请使用caplog.set_level()功能,否则该测试将容易失败。实时日志现在默认禁用,可以通过将
log_cli配置选项设置为true来启用。启用后,详细程度会增加,因此每个测试的日志都可见。实时日志现在发送到
sys.stdout,不再需要-s命令行选项才能工作。
如果您想部分恢复 3.3 版本的日志行为,您可以将这些选项添加到您的配置文件中
[pytest]
log_cli = true
log_level = "NOTSET"
[pytest]
log_cli = true
log_level = NOTSET
有关导致这些更改的讨论的更多详细信息,请参见 #3013。