只有 pytest_runtest_makereport 能修改测试结果,且仅当 report.when == "call" 时有效;需同步设置 report.outcome、report.skipped、report.failed 等字段并清空 failure 相关状态,否则统计错误。

pytest中哪些Hook能改测试结果?
只有 pytest_runtest_makereport 和 pytest_runtest_logreport 能拿到完整测试报告对象,但真正可修改结果的只有前者——它返回的 TestReport 实例在 pytest 内部尚未被最终判定为“失败/跳过/通过”。pytest_runtest_logreport 是只读通知,改了也没用。
注意:pytest_runtest_makereport 在每个测试项的 setup/call/teardown 阶段各调用一次,你必须判断 report.when == "call" 才是执行阶段的结果,否则会误改 setup 失败的报告。
- 只对
report.when == "call"的报告做修改 - 不能在
pytest_exception_interact或pytest_sessionfinish里改结果——它们发生得太晚或太早 - 修改
report.outcome不生效,必须改report.longrepr+report.wasxfail+report.failed等组合字段
怎么让失败测试变成跳过(skip)?
最常用场景:某些环境不满足时自动跳过已失败的测试,而不是报错。关键不是设 report.outcome = "skipped",而是模拟 pytest 内部 skip 的行为。
def pytest_runtest_makereport(item, call, report):
if report.when == "call" and report.failed:
# 检查是否符合跳过条件,例如环境变量缺失
if not item.config.getoption("--allow-fail", False):
report.outcome = "skipped"
report.wasxfail = None
report.longrepr = "Skipped due to missing env: MY_SERVICE_URL"
# 必须清空 failure 相关字段,否则 pytest 仍当它是 failed
report.failed = False
report.passed = False
report.skipped = True
漏掉 report.failed = False 或 report.skipped = True 会导致 pytest 统计错误(比如 -x 退出仍触发),这是最常见的坑。
如何动态标记 xfail 并覆盖原始失败信息?
当测试本应失败但当前环境让它意外通过时,需要强制标记为 xfail;反之,若本该失败却因 bug 修复而通过,也要能取消 xfail。核心是操作 report.wasxfail 和 report.keywords。
快速生成专业的 Python 脚本和应用代码。一键创建完整项目结构,支持CLI、API、爬虫、Bot、Django等多种项目类型,包含完整的项目结构、配置文件、依赖管理、测试、README和文档。
-
report.wasxfail = "reason text"表示该失败是预期的(即 xfail 成功) -
report.wasxfail = None表示该失败非预期(即 xfail 失败) - 如果测试通过但
"xfail" in report.keywords,说明它本该失败却通过了,此时应设report.wasxfail = "unexpectedly passed" - 修改
report.longrepr只影响控制台输出,不影响 pytest 的统计逻辑
别直接删 report.keywords["xfail"]——pytest 不认这个操作,要用 item.add_marker("xfail(strict=False)") 提前干预,Hook 里只能靠 wasxfail 控制最终判定。
为什么修改后 pytest --tb=short 还显示原始 traceback?
因为 report.longrepr 默认是 ExceptionInfo 对象,不是字符串。直接赋值字符串会让 pytest 忽略它,继续用原始 traceback。
正确做法是用 py.code.ExceptionInfo 构造新异常表示,或更简单:用 report.longrepr = report.longrepr.reprcrash(提取简短描述),再拼接自定义信息:
if report.when == "call" and report.failed:
short_msg = str(report.longrepr.reprcrash.message) if hasattr(report.longrepr, "reprcrash") else "Unknown error"
report.longrepr = f"[HOOK MODIFIED] {short_msg} | Env: {os.getenv('ENV_NAME', 'dev')}"
但要注意:这样改完后 --tb=long 就看不到原始 traceback 了。如果既要保留原始堆栈又要加标识,得用 report.longrepr.toterminal() 配合自定义输出器——这已经超出 Hook 能力范围,建议改用自定义 TerminalReporter。
Hook 修改结果这事,边界很窄:能动 outcome、skipped、failed、wasxfail、longrepr,但不能动日志、不能重跑测试、不能改 fixture 行为。越往深处走,就越容易和 pytest 自身调度冲突。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










