如何根据 pytest-benchmark 的结果自动将测试分为“慢”与“快”两组?
解读
国内一线互联网公司在做性能回归时,普遍要求“单测耗时 < 50 ms、集成测 < 200 ms”,超过阈值即触发“慢测试”告警,并自动打入独立 CI 阶段,防止拖慢 MR 流水线。
面试官想确认两点:
- 你能否把 pytest-benchmark 的原始数据(JSON + stats)取出来;
- 你能否在不改业务代码的前提下,用 pytest 的钩子把“慢/快”标签动态打到测试项上,并配套提供命令行参数与失败策略,做到“零人工维护”。
答出“解析 JSON→计算分位→item.add_marker→hook 过滤”这一完整闭环,才能体现你对 pytest 插件体系与 CI 集成的深度理解。
知识点
- pytest-benchmark 结果存储:
--benchmark-json=report.json会输出含machine_info/commit_info/tests三段的 JSON,其中tests[*].stats字段里有mean、median、iqr、stddev等耗时统计。 - 动态打标:
pytest_itemcollected(item)钩子中调用item.add_marker(pytest.mark.slow)即可把标记写入item.keywords,后续可用-m "not slow"直接过滤。 - 阈值策略:
国内常用“中位数 + 3×IQR”或“P95”作为慢速判定,避免偶发毛刺;也可把阈值写进pyproject.toml供团队统一维护。 - 缓存加速:
把上一轮 JSON 缓存到.pytest/benchmark.json,下次收集阶段直接读缓存,避免重复跑基准。 - 失败门禁:
在pytest_terminal_summary里统计慢速用例占比,>5 % 就让 exit code=1,阻断 MR 合并,符合国内“质量红线”规范。
答案
- 在项目根目录新建
benchmark_classifier.py:
import json, pathlib, pytest
from typing import List, Dict, Any
THRESHOLD = 50 # 单位 ms,可放配置中心
def load_last_report() -> Dict[str, float]:
p = pathlib.Path(".pytest/benchmark.json")
if not p.exists():
return {}
data = json.loads(p.read_text(encoding="utf8"))
# 用“模块::函数”当 key,取 median 耗时(秒转毫秒)
return {
f"{t['group']}::{t['name']}": t['stats']['median'] * 1000
for t in data.get("benchmarks", [])
}
def pytest_addoption(parser):
parser.addoption("--classify-benchmark", action="store_true",
help="根据历史 benchmark 结果自动打 slow 标记")
def pytest_configure(config):
if config.getoption("--classify-benchmark"):
config._benchmark_times = load_last_report()
def pytest_itemcollected(item: pytest.Item):
config = item.config
if not hasattr(config, "_benchmark_times"):
return
key = f"{item.module.__name__}::{item.name}"
median_ms = config._benchmark_times.get(key, 0)
if median_ms > THRESHOLD:
item.add_marker(pytest.mark.slow)
def pytest_terminal_summary(terminalreporter, exitstatus, config):
if not hasattr(config, "_benchmark_times"):
return
slow = [x for x in terminalreporter.stats.get("passed", [])
if "slow" in x.keywords]
total = len(terminalreporter.stats.get("passed", []))
ratio = len(slow) / max(total, 1)
if ratio > 0.05:
terminalreporter.write_sep("=", "FAIL: 慢测试占比 {:.1%},超过 5% 红线".format(ratio), red=True)
config.exitstatus = 1
- 在
conftest.py里导入上述模块即可生效。 - 流水线脚本:
# 第一轮:生成基准
pytest --benchmark-json=.pytest/benchmark.json --benchmark-only
# 第二轮:日常测试,自动打标并拦截慢测试
pytest --classify-benchmark -m "not slow" --benchmark-disable
至此,无需改动任何业务用例,就能根据历史性能数据把测试自动分为“快/慢”两组,并能在 CI 中直接 -m "not slow" 过滤,保障 MR 阶段耗时 < 2 min 的国内交付标准。
拓展思考
- 多环境阈值:
在pyproject.toml里按env = ci/local区分阈值,本地调试放宽到 100 ms,CI 保持 50 ms,避免开发者频繁被打断。 - 增量判定:
若 Git 工作区仅改动某几个模块,可在钩子中只读取这些模块的历史基准,其余用默认 0 ms,实现“增量慢测试检测”,进一步提速。 - 与分布式执行结合:
使用pytest-xdist时,只在master节点做 JSON 解析与打标,再把标记同步到worker,避免每个进程重复 IO;同时把慢测试集中到一个worker,降低调度碎片。 - 可视化回溯:
把 nightly 跑出的 benchmark.json 上传到内部 Grafana,通过group维度做 P95 趋势图,出现性能回退时自动 @代码所有者,形成“测试左移”闭环。