如何在保留teardown日志的同时让Pytest测试摘要无需滚动可见?
解决方案
这里有几种可行的方法,既能保留teardown日志,又能直接在终端末尾看到测试摘要:
方法1:在teardown后重复打印测试摘要
修改你的conftest.py,通过pytest钩子捕获原始测试摘要,在大量teardown日志输出完成后重新打印:
# 存储测试摘要内容 _test_summary = [] def pytest_terminal_summary(terminalreporter, exitstatus, config): # 捕获终端报告中的摘要部分 global _test_summary # 提取summary区域的所有行 _test_summary = terminalreporter._sections.get("summary", []) def pytest_unconfigure(config): # 输出原有的teardown日志 for _ in range(100): print('some teardown log msg') # 在日志末尾重复打印测试摘要 print("\n" + "-"*60) print("测试摘要(重复显示)") print("-"*60) for line in _test_summary: print(line)
运行pytest -v后,100条teardown日志输出完毕,终端最后会再次打印测试摘要,无需向上滚动查看。
方法2:将teardown日志定向到文件
如果不需要teardown日志在终端显示,可将其写入文件,终端只保留测试摘要,同时日志完整保留:
修改conftest.py,使用logging模块替代print输出日志:
import logging def pytest_unconfigure(config): # 配置日志处理器,将teardown日志写入文件 teardown_logger = logging.getLogger("teardown_logs") teardown_logger.setLevel(logging.INFO) file_handler = logging.FileHandler("teardown_logs.txt") file_handler.setFormatter(logging.Formatter("%(message)s")) teardown_logger.addHandler(file_handler) # 输出teardown日志到文件 for _ in range(100): teardown_logger.info('some teardown log msg') # 移除处理器防止后续重复输出 teardown_logger.removeHandler(file_handler)
运行pytest -v时,终端仅显示测试摘要,teardown日志全部保存在teardown_logs.txt文件中,需要查看时直接打开文件即可。
方法3:自定义终端报告顺序(进阶)
通过编写pytest插件,修改终端报告的输出时机,让测试摘要在teardown日志之后输出。不过这种方法需要重写部分pytest的终端报告逻辑,复杂度较高,前两种方法更适合快速解决问题。
内容的提问来源于stack exchange,提问作者flonk
相关产品推荐
相关产品推荐

