← 中文资源

简体中文版本

如何并行化与分片测试套件

通过按稳定分布、隔离数据库与确定性顺序把测试分片到多 worker,加速 CI 而不掩盖失败。

阅读英文原文

引言

串行跑三十分钟的测试套件是工程师不再本地运行的套件,也会拖慢每次合并。并行通过多 worker 跑测试削减墙钟时间,但幼稚并行引入自身失败:worker 争抢共享数据库、单独通过却一起失败的测试、以及让一个 worker 干所有活的失衡分片。有效分片均匀分配测试、隔离每个 worker 的资源、保持套件确定,使速度提升而不产生新抖动。

分片与并行

单机并行在独立进程跑若干测试文件、用可用核心。分片把套件拆到独立机器或 CI 任务,每个跑一个子集。两者组合:若干分片,每个内部跨核心并行。分片是超出单机扩展、让大套件几分钟跑完的东西。

两个层面都有分配问题:若工作不均,一些 worker 空闲而一个苦干。按文件数拆分假设每个文件成本相同,那是错的;含一个慢集成测试的文件比含二十个快单元测试的文件贵。按实测时长分布,而非按数量。

均匀分配测试

用历史时长构建总时间大致相等的分片。把最慢的测试先分给当前总时长最少的分片,一种贪心装箱使最大分片时间最小。周期性重算拆分,因为随测试增加时长会变。

测试框架与 CI 提供基于时长的拆分:Vitest、Jest、Playwright 与 pytest 都支持按索引或时长文件分片。给它们来自前次运行的时长缓存并定期刷新,分片便保持平衡而无需手工记账。

隔离共享资源

共享数据库的并行测试互相破坏:一个测试的写出现在另一个的读中、事务冲突、唯一约束意外触发。给每个 worker 自己的数据库或 schema,worker 启动前创建、结束后销毁。这是并行测试套件最重要的隔离。

同样适用于文件、端口、临时目录与任何共享缓存。把每个 worker 绑定到自己的端口范围、临时目录与缓存命名空间。假设固定端口或共享文件路径的测试串行通过、并行失败,修复是使资源按 worker 而非全局。

确定性顺序与随机化

并行执行天然使顺序非确定,因此测试不得依赖顺序。按计划以随机顺序运行套件(测试顺序随机化)来检测顺序依赖;只在某些顺序失败的测试是顺序依赖的,必须修复而非仅重跑。

随机化也是防意外耦合的防御:若测试通过模块级变量或数据库行共享状态,以不同顺序运行会暴露它。把随机种子留在失败输出中使失败顺序可本地复现,并把任何顺序依赖失败当作测试隔离的真实 bug。

保持失败报告清晰

分片拆分报告,因此第三分片的失败必须与第一分片的一样易找。把所有分片结果收集进一份报告、各标注其分片、任一失败则整体流水线失败。不要让“尽力而为”的分片静默通过。

若真有重试只在整个套件层面做,并把重试当作抖动信号跟踪。只在第二次尝试通过的分片在掩盖抖动。分别报告首次尝试与重试结果保持信号诚实,使分片的速度不以结果为代价。

衡量改进

跟踪每分片与总墙钟时间,并观察最慢分片。总时间由最慢分片决定,因此不均拆分浪费其他 worker。当最慢分片明显慢于平均时重新平衡,通常意味着分布过时。

也看排队时间与安装开销:若每个 worker 花两分钟配数据库,该开销可能主导五分钟套件。缓存依赖、复用容器、高效配 schema,使并行收益真实而非被每 worker 安装吃掉。

常见陷阱与小结

不要按文件数而非时长拆分。不要跨 worker 共享数据库。不要依赖执行顺序。不要让重试的分片隐藏失败。也不要在隔离资源前并行,否则你以慢换抖。

分片通过跨 worker 以均匀、基于时长的分布与每 worker 资源隔离运行测试,把长套件变短。按实测时间分布、给每个 worker 自己的数据库与端口、使顺序无关紧要、清晰报告每个分片的失败、并衡量最慢分片。做得好时,套件变快而不变得更不可信。

代码示例

# sharding shapes
1 machine, N processes   -> run files in parallel on N cores
M machines, N processes  -> split suite into M shards, each parallel within
# distribute by duration, not file count:
# a 1-test slow file and a 20-test fast file are not equal units of work
# Playwright: split across 4 shards using recorded timing.
npx playwright test --shard=1/4
npx playwright test --shard=2/4
# in CI, run the four shards as separate jobs in parallel:
#   matrix: shard: [1, 2, 3, 4]
#   command: npx playwright test --shard=${{ matrix.shard }}/4

# Vitest: similar sharding
npx vitest run --shard=1/4
// Each worker gets its own schema, derived from the worker id.
import { test as base } from '@playwright/test';
import { Client } from 'pg';

export const test = base.extend<{ db: Client }>({
  db: async ({}, use, workerInfo) => {
    const schema = `test_w${workerInfo.workerIndex}`;
    const client = new Client({ connectionString: process.env.DATABASE_URL });
    await client.connect();
    await client.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);
    await client.query(`SET search_path TO ${schema}`);
    await client.query('BEGIN');                 // roll back per test
    await use(client);
    await client.query('ROLLBACK');
    await client.query(`DROP SCHEMA ${schema} CASCADE`);
    await client.end();
  },
});
# Randomize order to expose hidden coupling; seed is printed on failure.
npx vitest run --sequence.shuffle --sequence.seed=1700000000
npx jest --randomize --seed=1700000000
# a test that fails only under some orders is order-dependent: fix it
# CI sharding with honest reporting
[ ] run shards in parallel jobs (matrix)
[ ] upload each shard's results (junit/json)
[ ] merge into a single report, tagged by shard
[ ] fail the pipeline if ANY shard fails on the first attempt
[ ] record retry counts as a flakiness signal (don't hide them)
# metrics to watch
wall-clock per shard        total time = max(shard times)
max/avg shard ratio         > ~1.3 => rebalance the split
per-worker setup time       high setup can eat the parallel gain
retry rate                  rising retries => hidden flakes from isolation
# rebalance using fresh duration data; stale splits drift uneven