architecture-governance.test.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import assert from "node:assert/strict";
  2. import { mkdir, mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { test } from "node:test";
  7. import { execFile } from "node:child_process";
  8. import { promisify } from "node:util";
  9. import {
  10. changedFilesFromGit,
  11. checkArchitecture,
  12. loadPolicy,
  13. updateBaseline,
  14. } from "../architecture/index.mjs";
  15. const execFileAsync = promisify(execFile);
  16. async function git(cwd, ...args) {
  17. return execFileAsync("git", args, { cwd });
  18. }
  19. async function initializeGit(cwd) {
  20. await git(cwd, "init");
  21. await git(cwd, "config", "user.name", "Architecture Test");
  22. await git(cwd, "config", "user.email", "architecture-test@example.invalid");
  23. await git(cwd, "config", "commit.gpgsign", "false");
  24. await git(cwd, "-c", "core.hooksPath=", "commit", "--allow-empty", "-m", "fixture");
  25. }
  26. async function fixture(files, fn) {
  27. const cwd = await mkdtemp(join(tmpdir(), "zcode-architecture-"));
  28. try {
  29. for (const [relative, content] of Object.entries(files)) {
  30. const target = join(cwd, relative);
  31. await mkdir(join(target, ".."), { recursive: true });
  32. await writeFile(target, content);
  33. }
  34. return await fn(cwd);
  35. } finally {
  36. // Windows 上刚退出的 git.exe 释放目录句柄有延迟,rmdir 会间歇性 EBUSY,重试吸收。
  37. await rm(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
  38. }
  39. }
  40. const POLICY = `version: 1
  41. modules:
  42. - id: alpha
  43. roots: [src/alpha]
  44. managed: true
  45. requires: [beta]
  46. publicEntrypoints: [src/alpha/contract.ts]
  47. - id: beta
  48. roots: [src/beta]
  49. managed: true
  50. requires: []
  51. publicEntrypoints: [src/beta/contract.ts]
  52. global:
  53. maxFileLines: 20
  54. maxContractLines: 10
  55. `;
  56. const POLICY_UNDECLARED = POLICY.replace("requires: [beta]", "requires: []");
  57. test("managed module documents satisfy artifacts without being checked as source", async () => {
  58. const files = { "architecture-policy.yaml": POLICY };
  59. for (const module of ["alpha", "beta"]) {
  60. for (const name of ["module.ts", "contract.ts", "contract.example.ts", "contract.test.ts"]) {
  61. files[`src/${module}/${name}`] = "export {};\n";
  62. }
  63. // 文档示例故意超过源码行数限制且含 import;它们不是可执行的跨模块依赖。
  64. files[`src/${module}/CONTRACT.md`] = 'import "../beta/internal.js";\n'.repeat(30);
  65. }
  66. await fixture(files, async (cwd) => {
  67. assert.deepEqual((await checkArchitecture({ cwd })).violations, []);
  68. await rm(join(cwd, "src/alpha/CONTRACT.md"));
  69. const missing = (await checkArchitecture({ cwd })).violations;
  70. assert.equal(missing.length, 1);
  71. assert.equal(missing[0].rule, "missing-module-artifact");
  72. assert.equal(missing[0].module, "alpha");
  73. assert.equal(missing[0].detail, "CONTRACT.md");
  74. });
  75. });
  76. test("repository policy discovers both refactored provider modules", async () => {
  77. const root = fileURLToPath(new URL("../../", import.meta.url));
  78. const policy = await loadPolicy(root);
  79. for (const id of ["provider", "provider-node"]) {
  80. // 新门禁若沿用旧仓库目录,会漏掉重构后的模块,使 context 无法找到其源码。
  81. const module = policy.modules.find((item) => item.id === id);
  82. assert.ok(module, `missing module: ${id}`);
  83. assert.deepEqual(module.roots, [join(root, "packages", id, "src")]);
  84. }
  85. });
  86. test("changed files exclude CI caches but retain tracked and untracked source paths", async () => {
  87. const ignore = await readFile(new URL("../../.gitignore", import.meta.url), "utf8");
  88. await fixture({ ".gitignore": ignore, "tracked.ts": "before" }, async (cwd) => {
  89. await initializeGit(cwd);
  90. await git(cwd, "add", ".gitignore", "tracked.ts");
  91. await git(cwd, "-c", "core.hooksPath=", "commit", "-m", "tracked files");
  92. await writeFile(join(cwd, "tracked.ts"), "after");
  93. const paths = [" 新文件 name.ts", "staged.ts"];
  94. if (process.platform !== "win32") paths.push('line\nbreak".ts');
  95. for (const file of paths) await writeFile(join(cwd, file), "export {};\n");
  96. await git(cwd, "add", "staged.ts");
  97. for (const cache of [
  98. ".electron-builder-cache",
  99. ".electron-cache",
  100. ".pnpm-store",
  101. ".npm-cache",
  102. ]) {
  103. await mkdir(join(cwd, cache));
  104. await writeFile(join(cwd, cache, "cached.ts"), "export {};\n");
  105. }
  106. assert.deepEqual((await changedFilesFromGit(cwd)).sort(), ["tracked.ts", ...paths].sort());
  107. });
  108. });
  109. test("changed files support Git output larger than 1 MiB for untracked and tracked files", async () => {
  110. await fixture({}, async (cwd) => {
  111. await initializeGit(cwd);
  112. await mkdir(join(cwd, "src"));
  113. const paths = Array.from(
  114. { length: 8192 },
  115. (_, i) => `src/${String(i).padStart(5, "0")}-${"x".repeat(120)}.ts`,
  116. );
  117. // 真 Git 输出跨过原缓冲区上限;不能用忽略缓存或截断列表假装修复。
  118. for (let offset = 0; offset < paths.length; offset += 100) {
  119. await Promise.all(
  120. paths.slice(offset, offset + 100).map((file) => writeFile(join(cwd, file), "")),
  121. );
  122. }
  123. assert.deepEqual((await changedFilesFromGit(cwd)).sort(), paths);
  124. await git(cwd, "add", "src");
  125. await git(cwd, "-c", "core.hooksPath=", "commit", "--quiet", "-m", "large tracked tree");
  126. await rm(join(cwd, "src"), { recursive: true });
  127. assert.deepEqual((await changedFilesFromGit(cwd)).sort(), paths);
  128. });
  129. });
  130. test("Git enumeration failures reject instead of reporting an empty changed set", async () => {
  131. await fixture({}, async (cwd) => {
  132. await assert.rejects(changedFilesFromGit(cwd), /git/i);
  133. });
  134. });
  135. test("undeclared cross-module import is reported", async () => {
  136. await fixture(
  137. {
  138. "architecture-policy.yaml": POLICY_UNDECLARED,
  139. "src/alpha/contract.ts": "export type Alpha = string;\n",
  140. "src/alpha/index.ts": 'import { beta } from "../beta/index.js";\nexport { beta };\n',
  141. "src/beta/contract.ts": "export const beta = 1;\n",
  142. "src/beta/index.ts": "export const beta = 1;\n",
  143. },
  144. async (cwd) => {
  145. const result = await checkArchitecture({ cwd });
  146. assert.ok(result.violations.some((v) => v.rule === "module-dependency"));
  147. },
  148. );
  149. });
  150. test("deep import and cycle are reported with stable fingerprints", async () => {
  151. await fixture(
  152. {
  153. "architecture-policy.yaml": POLICY,
  154. "src/alpha/contract.ts": "export type Alpha = string;\n",
  155. "src/alpha/a.ts": 'import "../beta/internal.js";\n',
  156. "src/alpha/b.ts": 'import "./a.js";\n',
  157. "src/beta/contract.ts": "export type Beta = string;\n",
  158. "src/beta/internal.ts": 'import "../alpha/b.js";\n',
  159. },
  160. async (cwd) => {
  161. const result = await checkArchitecture({ cwd });
  162. const rules = new Set(result.violations.map((v) => v.rule));
  163. assert.ok(rules.has("deep-import"));
  164. assert.ok(rules.has("cycle"));
  165. for (const violation of result.violations) {
  166. assert.match(violation.fingerprint, /^[a-f0-9]{16}$/);
  167. }
  168. },
  169. );
  170. });
  171. test("baseline suppresses existing violations but rejects new ones", async () => {
  172. await fixture(
  173. {
  174. "architecture-policy.yaml": POLICY,
  175. "src/alpha/contract.ts": "export type Alpha = string;\n",
  176. "src/alpha/index.ts": 'import "../beta/internal.js";\n',
  177. "src/beta/contract.ts": "export type Beta = string;\n",
  178. "src/beta/internal.ts": "export const value = 1;\n",
  179. },
  180. async (cwd) => {
  181. const initial = await checkArchitecture({ cwd });
  182. await updateBaseline({ cwd, violations: initial.violations });
  183. const baseline = JSON.parse(await readFile(join(cwd, ".architecture-baseline.json"), "utf8"));
  184. assert.equal(baseline.violations.length, initial.violations.length);
  185. await writeFile(join(cwd, "src/alpha/new.ts"), 'import "../beta/internal.js";\n');
  186. const changed = await checkArchitecture({ cwd, changedFiles: ["src/alpha/new.ts"] });
  187. assert.ok(changed.newViolations.length >= 1);
  188. assert.equal(changed.baselineViolations.length, 0);
  189. },
  190. );
  191. });
  192. test("managed modules require contract artifacts and enforce layer and domain boundaries", async () => {
  193. const policy = `version: 1
  194. modules:
  195. - id: alpha
  196. roots: [src/alpha]
  197. managed: true
  198. layers:
  199. contract: contract
  200. domain: domain
  201. ui: ui
  202. layerOrder: [contract, domain, ui]
  203. publicEntrypoints: [contract.ts]
  204. global:
  205. maxFileLines: 100
  206. maxContractLines: 20
  207. `;
  208. await fixture(
  209. {
  210. "architecture-policy.yaml": policy,
  211. "src/alpha/module.ts": "export const alphaModule = { id: 'alpha' } as const;\n",
  212. "src/alpha/contract.ts": "export type Alpha = string;\n",
  213. "src/alpha/domain/value.ts":
  214. "import { readFile } from 'node:fs';\nimport '../ui/view.js';\nexport const value = readFile;\n",
  215. "src/alpha/ui/view.ts": "import '../domain/value.js';\n",
  216. },
  217. async (cwd) => {
  218. const result = await checkArchitecture({ cwd });
  219. const rules = new Set(result.violations.map((v) => v.rule));
  220. assert.ok(rules.has("missing-module-artifact"));
  221. assert.ok(rules.has("domain-io"));
  222. assert.ok(rules.has("layer-direction"));
  223. },
  224. );
  225. });
  226. test("relative public entrypoints resolve from a module root", async () => {
  227. await fixture(
  228. {
  229. "architecture-policy.yaml": POLICY,
  230. "src/alpha/contract.ts": "export type Alpha = string;\n",
  231. "src/alpha/index.ts": 'import { beta } from "../beta/contract.js";\nexport { beta };\n',
  232. "src/beta/contract.ts": "export const beta = 1;\n",
  233. },
  234. async (cwd) => {
  235. const result = await checkArchitecture({ cwd });
  236. assert.equal(result.violations.filter((v) => v.rule === "deep-import").length, 0);
  237. },
  238. );
  239. });
  240. test("expired exceptions are global blocking violations", async () => {
  241. const policy = `${POLICY}\nexceptions:\n - id: old\n rule: deep-import\n paths: [src/**]\n expires: 2020-01-01\n`;
  242. await fixture(
  243. {
  244. "architecture-policy.yaml": policy,
  245. "src/alpha/contract.ts": "export type Alpha = string;\n",
  246. "src/beta/contract.ts": "export type Beta = string;\n",
  247. },
  248. async (cwd) => {
  249. const result = await checkArchitecture({ cwd, changedFiles: [] });
  250. assert.ok(result.newViolations.some((v) => v.rule === "expired-exception"));
  251. },
  252. );
  253. });