IT评测·应用市场-qidao123.com技术社区

标题: pytest日志显示 [打印本页]

作者: 羊蹓狼    时间: 2025-1-7 10:58
标题: pytest日志显示
在 pytest 中,可以通过 钩子函数配置文件 pytest.ini 配置日志的显示方式,实现对日志的机动控制。以下是常用实现方式及配置说明。

方式一:使用 conftest.py 钩子函数自定义日志显示

通过 conftest.py 文件中的钩子函数,实现日志纪录并自定义显示。
实现步骤

  1. import pytest
  2. import logging
  3. # 配置日志格式和输出
  4. def pytest_configure(config):
  5.     log_format = "%(asctime)s - %(levelname)s - %(message)s"
  6.     logging.basicConfig(
  7.         level=logging.INFO,  # 设置日志级别
  8.         format=log_format,
  9.         filename="test.log",  # 日志文件保存路径
  10.         filemode="w"  # 每次运行时重写日志文件
  11.     )
  12.     console = logging.StreamHandler()  # 控制台输出
  13.     console.setLevel(logging.INFO)  # 控制台日志级别
  14.     console.setFormatter(logging.Formatter(log_format))
  15.     logging.getLogger("").addHandler(console)
  16.     logging.info("Logging setup complete.")
  17. # 钩子函数:记录每个测试的开始和结束
  18. @pytest.hookimpl(tryfirst=True, hookwrapper=True)
  19. def pytest_runtest_protocol(item, nextitem):
  20.     logging.info(f"Test started: {item.name}")
  21.     outcome = yield
  22.     result = "PASSED" if outcome.get_result().passed else "FAILED"
  23.     logging.info(f"Test finished: {item.name} - {result}")
复制代码
运行效果

运行测试时,日志会纪录在 test.log 文件中,同时在控制台及时输出。

方式二:通过 pytest.ini 配置文件管理日志显示

使用 pytest.ini 文件设置全局日志配置,省去手动编写 logging 的代码。
配置示例

创建或编辑项目中的 pytest.ini 文件:
  1. [pytest]
  2. log_cli = true  # 启用控制台日志输出
  3. log_cli_level = INFO  # 设置日志级别
  4. log_cli_format = %(asctime)s - %(levelname)s - %(message)s  # 日志格式
  5. log_cli_date_format = %Y-%m-%d %H:%M:%S  # 日期格式
  6. log_file = test.log  # 日志文件保存路径
  7. log_file_level = INFO  # 文件日志级别
  8. log_file_format = %(asctime)s - %(levelname)s - %(message)s  # 文件日志格式
  9. log_file_date_format = %Y-%m-%d %H:%M:%S  # 文件日期格式
复制代码
运行效果



方式三:在测试代码中使用 caplog 捕获日志

使用 pytest 提供的内置 caplog 功能捕获日志,实用于验证日志输出的测试场景。
测试用例示例

  1. import logging
  2. def test_logging_example(caplog):
  3.     logging.info("This is an info log.")
  4.     logging.error("This is an error log.")
  5.     assert "info log" in caplog.text  # 验证日志内容
  6.     assert "error log" in caplog.text
复制代码
运行效果



常见日志配置说明

配置项描述示例值log_cli启用控制台日志输出。truelog_cli_level设置控制台日志输出的级别。INFO, DEBUG, ERRORlog_cli_format控制台日志的格式。%(asctime)s - %(message)slog_cli_date_format控制台日志的日期格式。%Y-%m-%d %H:%M:%Slog_file指定日志文件的路径。test.loglog_file_level设置日志文件的输出级别。INFO, WARNINGlog_file_format文件日志的格式。%(levelname)s - %(message)slog_file_date_format文件日志的日期格式。%Y-%m-%d %H:%M:%S
保举组合方式

通过以上方式,可以机动、高效地在 pytest 项目中实现日志管理与显示。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4