affected-engineering-test-cli.test.mjs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import assert from "node:assert/strict";
  2. import { execFile } from "node:child_process";
  3. import { mkdtemp, writeFile, readFile, rm, symlink } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join, resolve } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { promisify } from "node:util";
  8. import test from "node:test";
  9. const exec = promisify(execFile);
  10. const entry = fileURLToPath(new URL("../run-affected-engineering-tests.mjs", import.meta.url));
  11. const zero = "0".repeat(40);
  12. async function fixture(t) {
  13. const root = await mkdtemp(join(tmpdir(), "affected-official-"));
  14. t.after(() => rm(root, { recursive: true, force: true }));
  15. // 外层 hook 的 SHA 和 Git local env 不属于夹具,必须用环境副本隔离。
  16. const env = { ...process.env };
  17. for (const key of Object.keys(env))
  18. if (
  19. key.startsWith("GIT_") ||
  20. key.startsWith("ZCODE_PRE_PUSH_") ||
  21. key === "ZCODE_AFFECTED_TEST_BASE"
  22. )
  23. delete env[key];
  24. await symlink(
  25. resolve("node_modules"),
  26. join(root, "node_modules"),
  27. process.platform === "win32" ? "junction" : "dir",
  28. );
  29. const write = (path, content) => writeFile(join(root, path), content);
  30. const git = async (...args) =>
  31. (
  32. await exec(
  33. "git",
  34. [
  35. "-c",
  36. "user.name=Test",
  37. "-c",
  38. "user.email=test@example.invalid",
  39. "-c",
  40. "commit.gpgsign=false",
  41. ...args,
  42. ],
  43. { cwd: root, env },
  44. )
  45. ).stdout.trim();
  46. await write(".gitignore", "node_modules\nselected\n");
  47. await write("package.json", '{"type":"module"}');
  48. await write(
  49. "vitest.config.mjs",
  50. 'export default {test:{name:"engineering",include:["*.test.mjs"],maxWorkers:1,setupFiles:["./vitest.setup.ts"],forceRerunTriggers:["**/package.json/**","**/{vitest,vite}.config.*/**","**/{vitest,vite}.config.*","**/vitest.setup.ts"]}}',
  51. );
  52. await write("vitest.setup.ts", "// shared setup\n");
  53. await write("source.mjs", "export const value = 1;");
  54. await write(
  55. "a.test.mjs",
  56. 'import {test,expect} from "vitest"; import {value} from "./source.mjs"; import {writeFile} from "node:fs/promises"; test("selected",async()=>{expect(value).toBe(2);await writeFile(new URL("./selected",import.meta.url),"yes")});',
  57. );
  58. await write("other.test.mjs", 'throw new Error("UNSELECTED_TEST_EXECUTED");');
  59. await git("init", "-b", "main");
  60. await git("add", ".");
  61. await git("commit", "-m", "base");
  62. const base = await git("rev-parse", "HEAD");
  63. const invoke = async (args = [], overrides = {}, script = entry) => {
  64. try {
  65. return {
  66. code: 0,
  67. ...(await exec(process.execPath, [script, ...args], {
  68. cwd: root,
  69. env: { ...env, ...overrides },
  70. maxBuffer: 2_000_000,
  71. })),
  72. };
  73. } catch (error) {
  74. return { code: error.code, stdout: error.stdout, stderr: error.stderr };
  75. }
  76. };
  77. const hook = (remote = base, local = "HEAD") =>
  78. git("rev-parse", local).then((sha) => ({
  79. ZCODE_PRE_PUSH_STDIN: `refs/heads/main ${sha} refs/heads/main ${remote}`,
  80. }));
  81. return { root, write, git, base, invoke, hook, env };
  82. }
  83. const paths = (result) => JSON.parse(result.stdout).map((spec) => spec.path);
  84. test("官方预览与执行一致,不加载无关文件,不改写源码或 index", async (t) => {
  85. const { root, write, git, invoke } = await fixture(t);
  86. await write("source.mjs", "export const value = 2;");
  87. const index = await git("ls-files", "--stage");
  88. const preview = await invoke(["--dry-run", "--json"]);
  89. assert.equal(preview.code, 0, preview.stderr);
  90. assert.deepEqual(paths(preview), ["a.test.mjs"]);
  91. await assert.rejects(readFile(join(root, "selected")), { code: "ENOENT" });
  92. const run = await invoke();
  93. assert.equal(run.code, 0, run.stderr + run.stdout);
  94. assert.equal(await readFile(join(root, "selected"), "utf8"), "yes");
  95. assert.equal(await git("ls-files", "--stage"), index);
  96. assert.equal(await readFile(join(root, "source.mjs"), "utf8"), "export const value = 2;");
  97. });
  98. for (const file of ["vitest.config.mjs", "package.json", "vitest.setup.ts"]) {
  99. test(`${file} 由官方触发全量,预览与执行均成功跳过且不加载测试`, async (t) => {
  100. const { root, write, invoke } = await fixture(t);
  101. await write(file, (await readFile(join(root, file), "utf8")) + "\n");
  102. for (const args of [[], ["--dry-run"], ["--dry-run", "--json"]]) {
  103. const result = await invoke(args);
  104. assert.equal(result.code, 0, result.stdout + result.stderr);
  105. assert.match(result.stderr, /跳过工程测试/u);
  106. assert.ok(!result.stdout.includes("UNSELECTED_TEST_EXECUTED"));
  107. }
  108. await assert.rejects(readFile(join(root, "selected")), { code: "ENOENT" });
  109. });
  110. }
  111. test("共同源码依赖选中全部测试时成功跳过,不只检查配置文件", async (t) => {
  112. const { root, write, git, invoke } = await fixture(t);
  113. await write(
  114. "other.test.mjs",
  115. 'import "./source.mjs"; throw new Error("UNSELECTED_TEST_EXECUTED");',
  116. );
  117. await git("add", ".");
  118. await git("commit", "-m", "shared dependency");
  119. await write("source.mjs", "export const value = 2;");
  120. const result = await invoke();
  121. assert.equal(result.code, 0, result.stdout + result.stderr);
  122. assert.match(result.stderr, /跳过工程测试/u);
  123. await assert.rejects(readFile(join(root, "selected")), { code: "ENOENT" });
  124. });
  125. test("任务起点覆盖已提交改动,旧 WIP、staged 和新增测试正常纳入", async (t) => {
  126. const { write, git, base, invoke } = await fixture(t);
  127. await write("source.mjs", "export const value = 2;");
  128. await git("add", "source.mjs");
  129. await git("commit", "-m", "task change");
  130. assert.deepEqual(paths(await invoke(["--base", base, "--dry-run", "--json"])), ["a.test.mjs"]);
  131. assert.deepEqual(paths(await invoke(["--dry-run", "--json"])), []);
  132. await write("new.test.mjs", 'import {test} from "vitest";test("new",()=>{});');
  133. assert.deepEqual(paths(await invoke(["--dry-run", "--json"])), ["new.test.mjs"]);
  134. await git("add", "new.test.mjs");
  135. assert.deepEqual(paths(await invoke(["--base", base, "--dry-run", "--json"])), [
  136. "a.test.mjs",
  137. "new.test.mjs",
  138. ]);
  139. });
  140. test("无改动、无关联、Node 测试都不执行,说明并成功退出", async (t) => {
  141. const { root, write, invoke } = await fixture(t);
  142. assert.match((await invoke()).stdout, /无选中测试/u);
  143. await write("resource.txt", "unrelated");
  144. await write(
  145. "tool.test.mjs",
  146. 'import test from "node:test";test("node",()=>{throw new Error("NODE_EXECUTED")});',
  147. );
  148. // 夹具 root include 会包括此文件,放入 scripts/ 才符合根 Node 测试边界。
  149. const { mkdir, rename } = await import("node:fs/promises");
  150. await mkdir(join(root, "scripts"));
  151. await rename(join(root, "tool.test.mjs"), join(root, "scripts/tool.test.mjs"));
  152. const result = await invoke();
  153. assert.equal(result.code, 0, result.stderr);
  154. assert.match(result.stdout, /无选中测试/u);
  155. });
  156. for (const kind of ["unstaged", "staged", "untracked"]) {
  157. test(`Push 阻止 ${kind} 改动,忽略 Git 已忽略的文件`, async (t) => {
  158. const { root, write, git, invoke, hook } = await fixture(t);
  159. await write("selected", "ignored");
  160. const clean = await invoke(["--scope", "push", "--dry-run"], await hook());
  161. assert.equal(clean.code, 0, clean.stderr);
  162. await write(kind === "untracked" ? "untracked.txt" : "source.mjs", "export const value = 2;");
  163. if (kind === "staged") await git("add", "source.mjs");
  164. const result = await invoke(["--scope", "push"], await hook());
  165. assert.equal(result.code, 2, result.stderr);
  166. assert.match(result.stderr, /工作区.*不干净/u);
  167. assert.equal(await readFile(join(root, "selected"), "utf8"), "ignored");
  168. });
  169. }
  170. test("Push 使用 remote SHA;新分支使用 staging 共同祖先;手动模式使用 upstream", async (t) => {
  171. const { write, git, base, invoke, hook } = await fixture(t);
  172. await git("update-ref", "refs/remotes/origin/staging", base);
  173. await git("update-ref", "refs/remotes/origin/main", base);
  174. await git("config", "branch.main.remote", "origin");
  175. await git("config", "branch.main.merge", "refs/heads/main");
  176. await git("config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*");
  177. await write("source.mjs", "export const value = 2;");
  178. await git("add", ".");
  179. await git("commit", "-m", "task");
  180. for (const overrides of [await hook(), await hook(zero), {}]) {
  181. const result = await invoke(["--scope", "push", "--dry-run", "--json"], overrides);
  182. assert.equal(result.code, 0, result.stderr);
  183. assert.deepEqual(paths(result), ["a.test.mjs"]);
  184. }
  185. });
  186. test("无基线、无效基线、非 HEAD 推送均报错;删除 ref 不测试", async (t) => {
  187. const { invoke, hook, base } = await fixture(t);
  188. for (const [args, env] of [
  189. [["--scope", "push"], {}],
  190. [["--base", "missing"], {}],
  191. [["--scope", "push"], await hook("1".repeat(40))],
  192. [
  193. ["--scope", "push"],
  194. { ZCODE_PRE_PUSH_STDIN: `refs/heads/x ${"1".repeat(40)} refs/heads/x ${base}` },
  195. ],
  196. [["--scope", "invalid"], {}],
  197. ])
  198. assert.equal((await invoke(args, env)).code, 2);
  199. const deleted = await invoke(["--scope", "push"], {
  200. ZCODE_PRE_PUSH_STDIN: `(delete) ${zero} refs/heads/x ${base}`,
  201. });
  202. assert.equal(deleted.code, 0, deleted.stderr);
  203. assert.match(deleted.stdout, /无选中测试/u);
  204. });
  205. test("合并集成带入的改动正常参与官方选择", async (t) => {
  206. const { write, git, base, invoke } = await fixture(t);
  207. await git("checkout", "-b", "integration");
  208. await write("source.mjs", "export const value = 2;");
  209. await git("add", ".");
  210. await git("commit", "-m", "integration change");
  211. await git("update-ref", "refs/remotes/origin/staging", "HEAD");
  212. await git("checkout", "main");
  213. await write("feature.txt", "feature");
  214. await git("add", ".");
  215. await git("commit", "-m", "feature");
  216. await git("merge", "--no-ff", "integration", "-m", "merge integration");
  217. const result = await invoke(["--base", base, "--dry-run", "--json"]);
  218. assert.equal(result.code, 0, result.stderr);
  219. assert.deepEqual(paths(result), ["a.test.mjs"]);
  220. });
  221. test("实际选中测试失败返回 1,无关测试不执行", async (t) => {
  222. const { write, invoke } = await fixture(t);
  223. await write("source.mjs", "export const value = 3;");
  224. const result = await invoke();
  225. assert.equal(result.code, 1, result.stdout + result.stderr);
  226. assert.ok(!result.stdout.includes("UNSELECTED_TEST_EXECUTED"));
  227. });
  228. test("pre-push retains the engineering runner and the E2E provider seed regression", async () => {
  229. const root = resolve(fileURLToPath(new URL("../..", import.meta.url)));
  230. const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
  231. assert.match(pkg.scripts["verify:pre-push"], /test:engineering:affected --scope push/);
  232. const files = JSON.parse(
  233. await readFile(join(root, "scripts/engineering-test-files.json"), "utf8"),
  234. );
  235. const seed = "packages/desktop/test/modelProviderRestartConfig.test.ts";
  236. assert.ok(files.includes(seed));
  237. await readFile(join(root, seed));
  238. });
  239. test("official selection never loads a CUA project sharing the same source", async (t) => {
  240. const { write, git, invoke } = await fixture(t);
  241. await write(
  242. "vitest.config.mjs",
  243. `export default {test:{projects:[
  244. {test:{name:"engineering",include:["a.test.mjs","other.test.mjs"],maxWorkers:1}},
  245. {test:{name:"cua",include:["cua.test.mjs"]}}
  246. ]}}`,
  247. );
  248. await write("cua.test.mjs", 'import "./source.mjs"; throw new Error("CUA_EXECUTED");');
  249. await git("add", ".");
  250. await git("commit", "-m", "projects");
  251. await write("source.mjs", "export const value = 2;");
  252. const preview = await invoke(["--dry-run", "--json"]);
  253. assert.equal(preview.code, 0, preview.stderr);
  254. assert.deepEqual(paths(preview), ["a.test.mjs"]);
  255. const run = await invoke();
  256. assert.equal(run.code, 0, run.stdout + run.stderr);
  257. assert.ok(!run.stdout.includes("CUA_EXECUTED"));
  258. });
  259. test("根配置的公共 setup 通过官方 trigger 选中整个套件并成功跳过", async () => {
  260. const result = await exec(process.execPath, [entry, "--files", "vitest.setup.ts", "--dry-run"], {
  261. cwd: resolve("."),
  262. maxBuffer: 2_000_000,
  263. });
  264. assert.match(result.stderr, /跳过工程测试/u);
  265. assert.ok(!result.stdout.includes("RUN v"));
  266. });
  267. test("多个 Push ref 的官方选择合并去重,完整并集成功跳过", async (t) => {
  268. const { write, git, base, invoke, hook } = await fixture(t);
  269. await write("source.mjs", "export const value = 2;");
  270. await git("add", ".");
  271. await git("commit", "-m", "first");
  272. const middle = await git("rev-parse", "HEAD");
  273. await write("other.test.mjs", 'import {test} from "vitest";test("other",()=>{});');
  274. await git("add", ".");
  275. await git("commit", "-m", "second");
  276. const first = await hook(base);
  277. const second = await hook(middle);
  278. const result = await invoke(["--scope", "push", "--dry-run", "--json"], {
  279. ZCODE_PRE_PUSH_STDIN: `${first.ZCODE_PRE_PUSH_STDIN}\n${second.ZCODE_PRE_PUSH_STDIN}`,
  280. });
  281. assert.equal(result.code, 0, result.stderr);
  282. assert.match(result.stderr, /跳过工程测试/u);
  283. assert.deepEqual(paths(result), ["a.test.mjs", "other.test.mjs"]);
  284. const notHead = await invoke(["--scope", "push"], await hook(base, middle));
  285. assert.equal(notHead.code, 2, notHead.stderr);
  286. assert.match(notHead.stderr, /不是当前 HEAD/u);
  287. });
  288. test("显式文件走官方模块关系,不再分析 readFile 字面量或自动选择 Node 测试", async (t) => {
  289. const { write, git, invoke } = await fixture(t);
  290. await write("resource.txt", "before");
  291. await write(
  292. "a.test.mjs",
  293. 'import {test} from "vitest";import {readFile} from "node:fs/promises";test("resource",()=>readFile(new URL("./resource.txt",import.meta.url)));',
  294. );
  295. await git("add", ".");
  296. await git("commit", "-m", "resource test");
  297. await write("resource.txt", "after");
  298. const result = await invoke(["--files", "resource.txt", "--dry-run", "--json"]);
  299. assert.equal(result.code, 0, result.stderr);
  300. assert.deepEqual(paths(result), []);
  301. });
  302. test("hook Git local env 不污染真实 index,选择仍使用实际工作区", async (t) => {
  303. const { root, write, git, invoke } = await fixture(t);
  304. await write("source.mjs", "export const value = 2;");
  305. const index = await git("ls-files", "--stage");
  306. const result = await invoke(["--dry-run", "--json"], {
  307. GIT_INDEX_FILE: join(root, "missing-index"),
  308. });
  309. assert.equal(result.code, 0, result.stderr);
  310. assert.deepEqual(paths(result), ["a.test.mjs"]);
  311. assert.equal(await git("ls-files", "--stage"), index);
  312. });
  313. test("真实 git push 在配置触发全量时继续推送,不执行工程测试", async (t) => {
  314. const { root, write, git } = await fixture(t);
  315. const remote = await mkdtemp(join(tmpdir(), "affected-push-"));
  316. t.after(() => rm(remote, { recursive: true, force: true }));
  317. await git("init", "--bare", remote);
  318. await git("remote", "add", "origin", remote);
  319. await git("push", "-u", "origin", "main");
  320. const quote = (value) => `'${value.replaceAll("\\", "/").replaceAll("'", "'\\''")}'`;
  321. await writeFile(
  322. join(root, ".git/hooks/pre-push"),
  323. `#!/bin/sh\npre_push_stdin=$(cat)\nZCODE_PRE_PUSH_STDIN="$pre_push_stdin" ${quote(process.execPath)} ${quote(entry)} --scope push\n`,
  324. { mode: 0o755 },
  325. );
  326. await write("vitest.setup.ts", "// changed shared setup\n");
  327. await git("add", ".");
  328. await git("commit", "-m", "setup change");
  329. const output = await git("push", "origin", "main");
  330. assert.match(output, /选中 2\/2/u);
  331. assert.equal(await git("rev-parse", "origin/main"), await git("rev-parse", "HEAD"));
  332. await assert.rejects(readFile(join(root, "selected")), { code: "ENOENT" });
  333. });
  334. test("Push 显式 ref 优先于 hook 基线,首次推送也不依赖 staging", async (t) => {
  335. const { write, git, base, invoke, hook } = await fixture(t);
  336. await git("branch", "comparison-ref", base);
  337. await write("source.mjs", "export const value = 2;");
  338. await git("add", ".");
  339. await git("commit", "-m", "source change");
  340. const head = await git("rev-parse", "HEAD");
  341. for (const remote of [head, zero]) {
  342. const input = await hook(remote);
  343. for (const [args, override] of [
  344. [[], { ZCODE_AFFECTED_TEST_BASE: "comparison-ref" }],
  345. [[], { ZCODE_PRE_PUSH_BASE: base }],
  346. [["--base", base], { ZCODE_AFFECTED_TEST_BASE: "missing" }],
  347. [[], { ZCODE_AFFECTED_TEST_BASE: base, ZCODE_PRE_PUSH_BASE: "missing" }],
  348. ]) {
  349. const result = await invoke(["--scope", "push", "--dry-run", "--json", ...args], {
  350. ...input,
  351. ...override,
  352. });
  353. assert.equal(result.code, 0, result.stderr);
  354. assert.deepEqual(paths(result), ["a.test.mjs"]);
  355. }
  356. }
  357. const invalid = await invoke(["--scope", "push"], {
  358. ...(await hook(head)),
  359. ZCODE_AFFECTED_TEST_BASE: "missing",
  360. });
  361. assert.equal(invalid.code, 2);
  362. assert.match(invalid.stderr, /missing/u);
  363. const notHead = await invoke(["--scope", "push"], {
  364. ...(await hook(head, base)),
  365. ZCODE_AFFECTED_TEST_BASE: base,
  366. });
  367. assert.equal(notHead.code, 2);
  368. assert.match(notHead.stderr, /不是当前 HEAD/u);
  369. await write("source.mjs", "export const value = 3;");
  370. const dirty = await invoke(["--scope", "push"], {
  371. ...(await hook(head)),
  372. ZCODE_AFFECTED_TEST_BASE: base,
  373. });
  374. assert.equal(dirty.code, 2);
  375. assert.match(dirty.stderr, /工作区.*不干净/u);
  376. });
  377. test("真实 git push 消费任意显式基线,而不是 remote SHA", async (t) => {
  378. const { root, write, git, env } = await fixture(t);
  379. const remote = await mkdtemp(join(tmpdir(), "affected-push-base-"));
  380. t.after(() => rm(remote, { recursive: true, force: true }));
  381. await git("init", "--bare", remote);
  382. await git("remote", "add", "origin", remote);
  383. await write("source.mjs", "export const value = 2;");
  384. await git("add", ".");
  385. await git("commit", "-m", "source change");
  386. await git("branch", "comparison-ref", "HEAD");
  387. await git("push", "-u", "origin", "main");
  388. const quote = (value) => `'${value.replaceAll("\\", "/").replaceAll("'", "'\\''")}'`;
  389. await writeFile(
  390. join(root, ".git/hooks/pre-push"),
  391. `#!/bin/sh\npre_push_stdin=$(cat)\nZCODE_PRE_PUSH_STDIN="$pre_push_stdin" ${quote(process.execPath)} ${quote(entry)} --scope push\n`,
  392. { mode: 0o755 },
  393. );
  394. await write("vitest.setup.ts", "// setup changed on remote\n");
  395. await git("add", ".");
  396. await git("commit", "-m", "setup change");
  397. await git("push", "origin", "main");
  398. await write("feature.txt", "feature");
  399. await git("add", ".");
  400. await git("commit", "-m", "unrelated feature");
  401. // remote SHA 的范围只有无关联文本;显式 comparison-ref 的范围含公共 setup,应选中整个套件并跳过。
  402. const result = await exec("git", ["push", "origin", "main"], {
  403. cwd: root,
  404. env: { ...env, ZCODE_AFFECTED_TEST_BASE: "comparison-ref" },
  405. });
  406. assert.match(result.stdout, /选中 2\/2/u);
  407. assert.match(result.stderr, /跳过工程测试/u);
  408. assert.equal(await git("rev-parse", "origin/main"), await git("rev-parse", "HEAD"));
  409. await assert.rejects(readFile(join(root, "selected")), { code: "ENOENT" });
  410. });
  411. for (const file of ["vitest.config.ts", "scripts/engineering-test-files.json"]) {
  412. test(`real worktree trigger selects all engineering tests for ${file}`, async () => {
  413. const result = await exec(process.execPath, [entry, "--files", file, "--dry-run"], {
  414. cwd: resolve("."),
  415. maxBuffer: 2_000_000,
  416. });
  417. assert.match(result.stderr, /跳过工程测试/);
  418. });
  419. }