如何在pytest中创建与测试脚本同名的带时间戳日志文件
解决方法
方案一:利用Pytest自带日志系统生成指定格式日志
这种方式无需在测试脚本中手动配置logging,直接复用Pytest的日志配置,自动生成与测试脚本同名的带时间戳日志文件。
修改conftest.py
更新pytest_configure函数,动态获取测试脚本名称并生成目标格式的日志文件名:
import time import logging def pytest_configure(config): """自动生成与测试脚本同名的带时间戳日志文件""" if not config.option.log_file: # 提取运行的测试脚本文件名(支持单个测试文件运行场景) test_files = [arg for arg in config.args if arg.endswith('.py')] if test_files: # 从路径中提取文件名,移除.py后缀 test_name = test_files[0].split('/')[-1].replace('.py', '') else: # 未指定测试文件时使用默认前缀 test_name = 'test' timestamp = time.strftime('%Y-%m-%d_%H-%M-%S') config.option.log_file = f'{test_name}.{timestamp}.log' def pytest_assertrepr_compare(op, left, right): """断言失败时记录日志""" logging.error(f'Comparing Foo instances: vals: {left} != {right}') return ["Comparing Foo instances:", f" vals: {left} != {right}"]
简化test_support.py
移除手动配置的logging.basicConfig,直接使用Pytest的日志系统:
import pytest import logging logger = logging.getLogger(__name__) class Test_support(): def test_procedure(self): logger.info("We are into the support call") assert True
方案二:直接在测试脚本中指定日志文件名
如果希望保留测试脚本中的logging配置,只需修改日志文件名的定义即可:
import pytest import time import logging # 直接生成目标格式的日志文件名 LOG_FILENAME = f'test_support.{time.strftime("%Y-%m-%d_%H-%M-%S")}.log' logging.basicConfig( filename=LOG_FILENAME, level=logging.INFO, format='%(asctime)s.%(msecs)03d %(levelname)s %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) logger = logging.getLogger(__name__) class Test_support(): def test_procedure(self): logger.info("We are into the support call") assert True
注意事项
- 方案一的优势是统一使用Pytest的日志配置,同时支持控制台和文件日志输出,避免重复配置冲突。
- 方案二更适合需要自定义日志格式且不需要Pytest统一日志管理的场景。
- 原
pytest_assertrepr_compare函数中存在未定义的log变量,已修改为logging.error避免报错。
内容的提问来源于stack exchange,提问作者user1652137
相关产品推荐
相关产品推荐

