pytest-reportlog 是第三方插件,用于输出每行一个 json 对象的结构化日志(json lines 格式),包含 test_report/collect_report 等事件,支持细粒度分析;而 --junitxml 仅生成汇总式 xml。它需 pip install 安装,且必须通过 pyproject.toml 配置 report_log = "report.json" 启用,不再支持 --report-log= 命令行参数。

pytest-reportlog 是什么,它和 pytest --junitxml 有啥区别?
它不是 pytest 内置插件,而是第三方插件 pytest-reportlog,专门用来输出结构化、细粒度的 JSON 日志(每条测试用例的开始/结束/失败详情都独立成行),不像 --junitxml 那样只生成汇总式 XML。如果你需要做实时日志消费、对接 ELK、或做失败用例的精准归因分析,pytest-reportlog 更合适。
注意:它默认不安装,必须显式 pip 安装;且从 pytest 7.0+ 开始,它的行为有变化——不再支持旧版 --report-log=xxx.json 写法,改用 --report-log + 配置文件方式。
如何正确安装并启用 pytest-reportlog?
直接运行 pip install pytest-reportlog 即可。但启用时不能只加命令行参数——必须配合配置文件,否则会静默失效或报错 ValueError: report_log_path is required。
- 在项目根目录新建
pytest.ini或pyproject.toml(推荐后者) - 在
pyproject.toml中写入:
[tool.pytest.ini_options] report_log = "report.json"
然后运行 pytest 就会自动生成 report.json,每行是一个 JSON 对象(JSON Lines 格式),不是单个大 JSON。
别用 --report-log=report.json 命令行参数——它已被弃用,只会触发警告且不生效。
report.json 每行是什么结构?怎么解析才不踩坑?
每行是独立的 JSON 对象,包含 event 字段标识类型:"test_report" 表示用例执行结果,"collect_report" 表示收集阶段信息。真正关心的测试结果都在 "test_report" 类型里。
关键字段包括:nodeid(测试路径)、outcome("passed"/"failed"/"skipped")、duration(秒级浮点数)、longrepr(失败堆栈,是字符串而非对象,需 json.loads() 二次解析)。
-
longrepr是 base64 编码的字符串,不是原始 traceback;解码后才是可读错误信息 -
duration精确到微秒,但值很小(如0.001234),别误当成毫秒 - 同一用例可能出现多行:比如 setup 失败会先出一行
outcome="error",再出outcome="failed",要按nodeid+when字段去重或合并
想实时看失败详情,怎么快速 grep 或解析 report.json?
因为是 JSON Lines,不能直接 cat report.json | jq ——jq 默认期望单个 JSON,会报错。得加 -r 和 --slurp 或逐行处理。
- 查所有失败用例:
grep '"outcome":"failed"' report.json | jq -r '.nodeid' - 提取失败堆栈(需解码):先用 Python 脚本更稳妥,例如:
import json, base64
for line in open("report.json"):
d = json.loads(line)
if d.get("outcome") == "failed" and "longrepr" in d:
raw = base64.b64decode(d["longrepr"]).decode()
print(d["nodeid"], "\n", raw)
别试图用 shell 工具直接 decode base64 —— longrepr 里可能含换行和双引号,shell 解析容易截断或报错。
report.json 文件本身不压缩、不校验、不轮转,跑完就全量覆盖,如果并发执行或多次 run,记得重命名或加时间戳,否则前一次日志会被冲掉。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










