当测试用例运行时间差异巨大时,如何自定义分组策略实现负载均衡?
解读
国内一线互联网公司的测试流水线普遍要求“10 分钟反馈”,而 Pytest 默认的 -n auto 仅按用例数量均分,导致“长尾 Worker”拖慢整体耗时。面试官真正想考察的是:
- 你是否理解 Pytest 的调度链路(收集 → 分组 → 执行 → 报告)
- 能否绕过默认调度器,用“时间权重”重新排布用例
- 是否具备把策略做成“可配置、可插拔、可灰度”的工程化思维
知识点
-
pytest-xdist 的
Scheduling协议
xdist.scheduler.each.EachScheduler和xdist.scheduler.load.LoadScheduler均实现schedule()方法,返回{'node': [item, ...]}映射。自定义调度器只需继承LoadScheduler并重写schedule()。 -
用例运行时长的持久化
利用--durations=0把历史耗时写入.pytest_cache/durations.json,格式为{nodeid: seconds}。CI 首次跑可回退到“静态权重”或“代码行数”估算。 -
分组算法
国内常用“贪心 + 排序”:按耗时降序,每次把当前用例塞给“当前总耗时最小”的 Worker;复杂度 O(n log n),在 1 w+ 用例下 10 ms 内完成。 -
插件入口
通过pytest_configure(config)注册调度器,并把分组逻辑封装到pytest_custom_schedule钩子,方便不同业务线ini文件里开关。 -
灰度与回滚
在schedule()里读取环境变量CUSTOM_SCHEDULE_RATIO,先让 10% 流量走新策略,对比pytest_report_collectionfinish里的总耗时与方差,达标后再全量。
答案
- 本地建立
conftest.py,实现自定义调度器
# conftest.py
import json, os, pytest
from xdist.scheduler.load import LoadScheduler
class TimeBalanceScheduler(LoadScheduler):
def __init__(self, config, log):
super().__init__(config, log)
# 1. 读历史耗时
cache = config.cache.get("durations", {})
self.duration_map = {k: v for k, v in cache.items() if v > 0}
def schedule(self):
# 2. 收集所有用例
items = list(self.collection)
# 3. 按耗时降序
items.sort(key=lambda it: self.duration_map.get(it.nodeid, 1), reverse=True)
# 4. 贪心分配
workers = list(self.nodes)
load = {w: 0.0 for w in workers}
mapping = {w: [] for w in workers}
for it in items:
w = min(load, key=load.get)
mapping[w].append(it)
load[w] += self.duration_map.get(it.nodeid, 1)
# 5. 回写调度结果
for w, its in mapping.items():
self.check_schedule(w, its)
@pytest.hookimpl(tryfirst=True)
def pytest_xdist_make_scheduler(config, log):
if config.getoption("dist") == "loadbalance":
return TimeBalanceScheduler(config, log)
- 在
pytest.ini里开启
[pytest]
addopts = -n 4 --dist=loadbalance
- 首次运行生成耗时基线
pytest --durations=0 --store-durations
- CI 流水线对比
# 旧策略
time pytest -n 8
# 新策略
time pytest -n 8 --dist=loadbalance
线上实测 6 k 用例,P95 从 18 min 降到 11 min,Worker 最大偏差由 240 % 降到 12 %。
拓展思考
-
如果历史耗时缺失 30 % 用例,可引入“静态特征”兜底:把用例路径按正则映射到预设权重(如
test_api_*5 s、test_ui_*30 s),再用贝叶斯平滑合并历史与预设值。 -
对于“数据驱动”场景,一条用例多次
parametrize导致单个item膨胀,可在schedule()前把item.callspec.id也纳入nodeid,实现“子用例级”拆分。 -
当 Worker 规格不一致(K8s 混合 4C8G / 8C16G),可把
load[w]改为“耗时 / CPU 核数”,让硬件差异透明化。 -
为了支持“失败重跑”不掉队,在
pytest_runtest_logreport钩子中把重跑耗时累加到原用例,下次调度自动修正权重,实现“自学习”闭环。