pytest的pytest_runtest_makereport钩子通过判断report.when == "call"且not report.passed来精准捕获失败用例,避免误捕setup/teardown异常;应使用report.longreprtext获取堆栈,弃用已废弃的report.outcome。

pytest的pytest_runtest_makereport钩子怎么捕获失败用例
这个钩子是获取测试结果最直接的方式,它在每个测试项执行完后触发,返回一个 TestReport 对象。关键不是等所有测试跑完再汇总,而是每跑完一个用例就立刻拿到它的状态——report.passed、report.failed、report.skipped 都是布尔值,但要注意:失败(fail)和报错(error)都走 report.when == "call" 分支;而 setup/teardown 阶段出问题则对应 "setup" 或 "teardown"。
常见错误是只判断 report.failed,漏掉 report.when == "call" 条件,导致 setup 失败也被当成用例失败发通知;或者把 report.outcome 当成可靠字段,其实它在 pytest 7+ 已被弃用,应以 report.passed/report.failed/report.skipped 为准。
- 只在
report.when == "call"时处理用例执行结果,跳过 setup/teardown - 用
report.failed or report.failed不对,正确写法是not report.passed and report.when == "call" - 用
report.longreprtext取完整 traceback,比report.caplog更稳定(后者依赖--log-cli-level)
飞书机器人 Webhook 怎么发带格式的测试摘要消息
飞书卡片消息比纯文本更易读,但官方 Python SDK 对卡片 schema 支持弱,直接用 requests.post 构造 JSON 更可控。重点在于 msg_type 设为 "interactive",然后在 card 字段里组织元素:标题用 header,失败用例列表用 elements + div + text,错误堆栈建议折叠(tag: "collapse"),避免刷屏。
容易踩的坑是忽略飞书对卡片字段长度限制:单个 text.content 超过 2000 字会截断,堆栈过长必须截取关键行(比如最后 5 行 + "... (truncated)");另外 Webhook URL 必须带 timestamp 和 sign 签名(如果启用了安全设置),否则返回 400 错误。
立即学习“Python免费学习笔记(深入)”;
- 构造请求头:
{"Content-Type": "application/json; charset=utf-8"} - 错误信息截断示例:
report.longreprtext.splitlines()[-5:] if report.longreprtext else [] - 签名计算需用
hmac.new+base64.b64encode,密钥来自飞书机器人后台,不可硬编码在代码里
如何避免重复发送或干扰正常 pytest 输出
钩子函数本身不阻塞 pytest 流程,但发网络请求可能超时或失败,必须加异常捕获;更重要的是,不能让通知逻辑影响 pytest 的退出码——即使飞书发送失败,测试本身成功也该返回 0。另一个问题是并发执行(-n auto)下多个 worker 同时调用钩子,会导致同一用例被多次通知。
根本解法是只在主进程发通知:通过 pytest_configure 判断是否为主节点(config.option.numprocesses is None 或检查 os.environ.get("PYTEST_XDIST_WORKER") 是否为空),非主进程跳过所有通知逻辑。
- 用
try/except requests.RequestException包裹飞书请求,记录 warning 日志但不抛出 - 在
pytest_configure中设全局标记:config._lark_notifier_enabled = is_master,后续钩子里先检查该标记 - 不要在
pytest_sessionfinish里汇总发送——它拿不到单个用例的longreprtext,且 session 级异常无法区分是测试失败还是环境问题
本地调试时怎么模拟失败用例又不真发飞书
硬编码开关(如 if os.getenv("NOTIFY_LARK") == "1")太粗糙,容易提交到 CI;推荐用 pytest 的 --lark-webhook 自定义命令行参数,配合 addoption 注册。这样本地跑时加 --lark-webhook=none 就跳过发送,CI 环境才填真实 URL。
调试阶段最实用的是把消息内容打到 stdout 或写入临时文件,而不是发出去。注意别用 print(),会被 pytest 捕获进日志,改用 sys.stderr.write() 或 logging.getLogger("lark").info() 配合 --log-cli-level=INFO。
- 注册参数:
parser.addoption("--lark-webhook", action="store", default=None) - 在钩子中判断:
if webhook_url and webhook_url != "none": send_to_lark(...) - 消息体打印示例:
logging.getLogger("lark").debug(f"Would send: {json.dumps(card, ensure_ascii=False)[:200]}...")


















