affected-unit-test-cli.test.mjs 18 KB

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