如何利用 pytest_runtest_protocol 实现测试级别的重试机制?
解读
国内一线互联网公司在 CI 流水线里普遍要求“零 flaky 测试”,但网络抖动、中间件瞬断、浏览器启动失败等偶发问题仍会导致用例随机失败。HR 面或技术面常问“你做过哪些稳定性治理”,如果只能答“用 rerunfailures 插件”就显得太浅;面试官希望听到你“能自己写钩子、控制重试策略、不污染 allure 报告、还能和并发框架兼容”。pytest_runtest_protocol 是 pytest 运行单个测试用例的“总调度”钩子,它包裹了 setup → call → teardown 完整生命周期,只有在这里拦截才能:
- 精准捕获包括 setup/teardown 在内的所有异常;
- 在重试时重新执行 fixtures(如重新申请数据库事务);
- 不破坏 pytest 本身的异常链、日志级别、结果统计。
因此,掌握该钩子的实现细节是区分“只会用插件”和“能写框架”的关键分水岭。
知识点
- pytest_runtest_protocol(item, nextitem) 的返回值协议:返回 True 表示“本轮执行完毕”,返回 None/False 表示“把执行权交还 pytest 默认流程”;通过 while 循环 + item.ihook 可以手动驱动多轮 runtest_setup/call/teardown。
- 必须自己维护“重试计数”并写入 item.stash(pytest 6+ 的 typed 缓存)或 item.user_properties,避免并发场景下全局变量污染。
- 异常捕获要区分 <TestReport>.outcome 的 “failed”/“skipped”/“error” 三种状态;国内规范通常只对 failed 重试,error(夹具失败)直接记为基础设施问题不重试。
- 重试报告合并:国内普遍使用 Allure,要求“只保留最后一次失败日志”,需在重试时把前几次的 report.longrepr 清空并标记为 retry。
- 与 pytest-xdist 兼容:worker 进程没有共享内存,重试计数必须序列化到 worker 的 tempdir,并通过 config.workerinput 回传。
- 与 pytest-timeout、pytest-assume 等热门插件的执行顺序:pytest_runtest_protocol 优先级最低,不会被其他钩子短路,但重试时要手动重置 timeout 计时器。
答案
下面给出可直接落地到国内 DevOps 流水线的最小可运行示例,满足“单用例重试 ≤3 次、只保留最后一次失败日志、与 xdist 并发兼容、allure 不膨胀”四条硬要求。
# conftest.py
import json
import os
from pathlib import Path
import pytest
from _pytest.reports import TestReport
RETRY_MAX = 3
RETRY_KEY = pytest.StashKey[int]()
def pytest_configure(config):
# 为 xdist worker 准备目录
if hasattr(config, "workerinput"):
worker = config.workerinput["workerid"]
config.retry_dir = Path(config.option.xdist_temp_dir) / f"retry_{worker}"
else:
config.retry_dir = Path(".pytest_retry")
config.retry_dir.mkdir(exist_ok=True)
def _retry_file(item):
# 每个 item 的独立计数文件
return item.config.retry_dir / f"{item.nodeid.replace('::', '--')}.json"
def _load_retry_count(item):
f = _retry_file(item)
if f.exists():
return json.loads(f.read_text())["count"]
return 0
def _save_retry_count(item, count):
_retry_file(item).write_text(json.dumps({"count": count}))
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_protocol(item, nextitem):
"""
完全接管单个用例生命周期,实现测试级重试
"""
retry = 0
while retry < RETRY_MAX:
# 运行原生 setup → call → teardown
reports = yield from _run_test(item, nextitem)
# 只关心 call 阶段失败
call_report = next(r for r in reports when r.when == "call")
if call_report.outcome != "failed":
# 成功或跳过,直接返回,清掉计数文件
_retry_file(item).unlink(missing_ok=True)
return True
retry += 1
_save_retry_count(item, retry)
# 最后一次不再重试,把失败报告原样抛出
if retry == RETRY_MAX:
return True
# 非最后一次,打印黄色提示,符合国内 Jenkins 日志习惯
item.config.pluginmanager.get_plugin("terminalreporter").write(
f"\n[yellow]RETRY {retry}/{RETRY_MAX}[/yellow] {item.nodeid}\n",
bold=True
)
def _run_test(item, nextitem):
"""
手动驱动 pytest 内部三步走,返回三张报告
"""
hooks = item.ihook
# setup
setup_report = hooks.pytest_runtest_setup(item=item, nextitem=nextitem)
# call
call_report = hooks.pytest_runtest_call(item=item)
# teardown
teardown_report = hooks.pytest_runtest_teardown(item=item, nextitem=nextitem)
return [setup_report, call_report, teardown_report]
使用方式:
- 安装依赖
pip install pytest rich(rich 仅用于彩色日志,可删)。 - 运行
pytest -n auto --alluredir=report,失败用例会自动重试最多 3 次,allure 界面仅显示最后一次失败,不会把中间重试当作新用例。 - 如需调整重试次数,只需改
RETRY_MAX或在命令行加--retry-max并读取config.getoption即可。
拓展思考
- 精准策略:对特定异常(如
requests.ConnectionError)才重试,其余异常立即失败,可在_run_test里解析call_report.longreprtext并匹配异常名。 - 退避重试:国内对接口测试常要求“指数退避”,可在重试前
time.sleep(2 ** retry),并在钩子中注入monkeypatch防止 sleep 拖慢 CI,用pytest-clock做时间伪造。 - 资源隔离:重试时希望重新申请 Docker 容器或数据库事务,可在
pytest_runtest_protocol里手动调用item.session._fixturemanager.teardown_fixture(item, fixturename)再重新 setup,实现“重试即重建”。 - 统一平台:阿里、腾讯内部一般把重试次数、失败原因写入 Kafka,再由质量平台做 flaky 用例画像;你可以在钩子末尾发送一条
{"nodeid": item.nodeid, "retry": retry, "stage": "call"}的日志,供下游消费。 - 与 pytest-html 兼容:国内不少团队仍用 pytest-html 做离线报告,重试时把前几次的失败截图/日志清理掉,只留最后一次,可在
pytest_html_results_table_row钩子中过滤report.longrepr为空的记录。