更换网站服务器,网站建设的语言与工具,杭州公司注册代理公司,冰桶挑战是什么网络营销方式在 pytest 中#xff0c;可以通过 钩子函数 和 配置文件 pytest.ini 配置日志的显示方式#xff0c;实现对日志的灵活控制。以下是常用实现方式及配置说明。 方式一#xff1a;使用 conftest.py 钩子函数自定义日志显示
通过 conftest.py 文件中的钩子函数#xff0c;实现…在 pytest 中可以通过 钩子函数 和 配置文件 pytest.ini 配置日志的显示方式实现对日志的灵活控制。以下是常用实现方式及配置说明。 方式一使用 conftest.py 钩子函数自定义日志显示
通过 conftest.py 文件中的钩子函数实现日志记录并自定义显示。
实现步骤
import pytest
import logging# 配置日志格式和输出
def pytest_configure(config):log_format %(asctime)s - %(levelname)s - %(message)slogging.basicConfig(levellogging.INFO, # 设置日志级别formatlog_format,filenametest.log, # 日志文件保存路径filemodew # 每次运行时重写日志文件)console logging.StreamHandler() # 控制台输出console.setLevel(logging.INFO) # 控制台日志级别console.setFormatter(logging.Formatter(log_format))logging.getLogger().addHandler(console)logging.info(Logging setup complete.)# 钩子函数记录每个测试的开始和结束
pytest.hookimpl(tryfirstTrue, hookwrapperTrue)
def pytest_runtest_protocol(item, nextitem):logging.info(fTest started: {item.name})outcome yieldresult PASSED if outcome.get_result().passed else FAILEDlogging.info(fTest finished: {item.name} - {result})运行效果
运行测试时日志会记录在 test.log 文件中同时在控制台实时输出。 方式二通过 pytest.ini 配置文件管理日志显示
使用 pytest.ini 文件设置全局日志配置省去手动编写 logging 的代码。
配置示例
创建或编辑项目中的 pytest.ini 文件
[pytest]
log_cli true # 启用控制台日志输出
log_cli_level INFO # 设置日志级别
log_cli_format %(asctime)s - %(levelname)s - %(message)s # 日志格式
log_cli_date_format %Y-%m-%d %H:%M:%S # 日期格式log_file test.log # 日志文件保存路径
log_file_level INFO # 文件日志级别
log_file_format %(asctime)s - %(levelname)s - %(message)s # 文件日志格式
log_file_date_format %Y-%m-%d %H:%M:%S # 文件日期格式运行效果
控制台输出的日志格式与级别按照配置显示。所有日志信息保存到 test.log 文件。 方式三在测试代码中使用 caplog 捕获日志
使用 pytest 提供的内置 caplog 功能捕获日志适用于验证日志输出的测试场景。
测试用例示例
import loggingdef test_logging_example(caplog):logging.info(This is an info log.)logging.error(This is an error log.)assert info log in caplog.text # 验证日志内容assert error log in caplog.text运行效果
caplog 捕获到的日志信息可以用于断言和分析。 常见日志配置说明
配置项描述示例值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.ini 配置统一管理日志级别、格式和输出路径。适用于简单、稳定的项目日志需求。 细粒度控制 在 conftest.py 中结合钩子函数针对用例或阶段添加特定的日志逻辑。适用于复杂场景的动态日志需求。 日志验证 使用 caplog 在特定测试用例中捕获日志内容便于断言和调试。
通过以上方式可以灵活、高效地在 pytest 项目中实现日志管理与显示。