如何在运行时更新pytest.ini并让当前测试实例生效?
解决pytest运行时动态配置日志文件名(含当前时间)的问题
你遇到的问题核心原因是:pytest在启动初期就已加载并解析了pytest.ini配置文件,后续修改文件内容不会触发当前测试实例重新读取配置,所以修改ini文件无法在本次运行中生效。
正确的做法是直接操作pytest_configure钩子传入的config对象,动态修改配置项,而非修改物理文件。
修改后的实现代码
import datetime from configparser import ConfigParser, ExtendedInterpolation def pytest_configure(config): current_time = datetime.datetime.now() log_file_path = f"./logs/{current_time.strftime('%Y_%m_%d')}.txt" # 直接修改pytest当前实例的配置,立即生效 config.option.log_cli = True config.option.log_level = "DEBUG" config.option.log_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(funcName)s:%(lineno)s)" config.option.log_date_format = "%Y-%m-%d %H:%M:%S" config.option.log_file = log_file_path config.option.log_file_date_format = "%Y-%m-%d %H:%M:%S" config.option.log_file_mode = "a" config.option.addopts = "-rA" # 可选:如果需要持久化配置到pytest.ini(供后续测试运行使用),保留以下代码 config_parser = ConfigParser(interpolation=ExtendedInterpolation()) config_parser['pytest'] = { 'log_cli': 'true', 'log_level': 'DEBUG', 'log_format': '%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(funcName)s:%(lineno)s)', 'log_date_format': '%Y-%m-%d %H:%M:%S', 'log_file': log_file_path, 'log_file_date_format': '%Y-%m-%d %H:%M:%S', 'log_file_mode': 'a', 'addopts': '-rA', 'logging_on': 'TRUE' } with open('pytest.ini', 'w') as configfile: config_parser.write(configfile)
关键说明
pytest_configure钩子中的config参数是当前测试实例的核心配置对象,直接修改它的option属性会立即生效,无需重启测试。- 注意配置项的类型匹配:比如
log_cli需要传入布尔值True,而非字符串"true",pytest的config对象对参数类型有明确要求。 - 如果不需要持久化配置到
pytest.ini,可以完全去掉写入文件的代码块,只保留修改config.option的部分即可。
内容的提问来源于stack exchange,提问作者Kaayenat
相关产品推荐
相关产品推荐

