Files
clean-architecture-frontend…/tests/unit/pr-gate-selection.test.ts
DongHyeonka 89e187c893
frontend-quality-gates / merge / static checks (pull_request) Successful in 1m31s
frontend-quality-gates / merge / tests (pull_request) Successful in 13m55s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 5m18s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) In progress
frontend-quality-gates / main / self-tests and removal drills (pull_request) Waiting to run
test(ci): PR 경로표 계약 시험이 생성기의 상대 import를 풀어 읽게 한다
문제: 계약 시험은 따옴표 바로 뒤에 src/·tests/가 오는 경로만 읽었다.
생성기 템플릿은 "../../../contracts/server-state.ts"처럼 상대 경로로 써서,
생성 코드가 import하는 src 파일 26개 중 24개가 scaffold 행(FE-GATE-020)
밖에 있었다(REV-FE-0007).

방법: 시험이 planFeature로 --with-create·--keyed·--context·--package
조합 18개를 실제로 렌더하고, 상대 경로를 렌더된 파일 위치에서 푼다.
파일이 아닌 경로와 어느 렌더에도 안 나오는 경로는 unresolved로 실패하고,
scaffold 행의 정확한 src 경로를 생성 코드가 import하지 않아도 실패한다.
scaffold 행에는 정확한 파일 경로 24개를 더했다. 버린 안: src/** 같은 넓은
glob, application 행에 020 더하기(2026-11-13 경로표 결정의 목적을 없앤다).

위험: 시험은 직접 import만 본다. 배럴 안쪽 파일만 바뀐 PR은 020을 돌지
않는다. drill 스크립트 자신의 ../src import는 범위 밖이라 다루지 않았다.
CI-FE-0005가 020을 main 단계로 옮기면 이 24줄과 시험을 다시 손본다.

검증(desktop): 시험만 고친 트리 RED rc=1(drills name 1개 실패, 24개),
고친 뒤 15/15 rc=0. 변이 8개 모두 rc=1 뒤 되돌려 rc=0. 최근 병합 30개에서
020이 새로 걸리는 병합 0개. check:types·lint·test:unit·verify:documentation
rc=0, FE-GATE-010 rc=0(CI env).

Refs: REV-FE-0007
2026-11-23 07:11:17 +09:00

308 lines
14 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts";
import { planFeature, type InstalledFacts } from "../../scripts/create-feature.ts";
import {
loadPrGateSelectionTable,
pathPatternRegExp,
prChangedFiles,
prGateSkipReason,
PR_BASE_REF_VARIABLE,
selectPrGates,
SKIPPED_GATE_LINE,
skippedGateLine,
} from "../../scripts/lib/pr-gate-selection.ts";
const table = loadPrGateSelectionTable(process.cwd());
/** Longest desktop run of the `git ls-files` test (2026-11-13, three runs at load 17 to 23). */
const GIT_LS_FILES_MS = 48;
/** Longest desktop run of the shallow-clone test (2026-11-13, three runs at load 24). */
const SHALLOW_CLONE_MS = 291;
const ALWAYS = ["FE-GATE-001", "FE-GATE-002", "FE-GATE-003", "FE-GATE-010"];
function covered(file: string): boolean {
const patterns = [...table.global, ...table.rules.flatMap((rule) => rule.paths)];
return patterns.some((pattern) => pathPatternRegExp(pattern).test(file));
}
function selected(files: readonly string[]): readonly string[] | "all" {
const selection = selectPrGates(table, files);
return selection.kind === "all" ? "all" : [...selection.gates].sort();
}
function relativePaths(text: string): string[] {
return [...text.matchAll(/["'`](\.\.?\/[^"'`\s]*)/gu)].map((match) => match[1]!);
}
function isRepositoryFile(target: string): boolean {
return !target.startsWith("../") && statSync(target, { throwIfNoEntry: false })?.isFile() === true;
}
/** What `planFeature` renders for each combination of create:feature's options. */
function generatorPlans() {
const installed: InstalledFacts = {
appIds: ["template-app"],
featureIds: [],
contexts: [{ id: "installed-context", routePath: "installed/*" }],
contextDirectories: ["installed-context"],
routes: [],
topics: [],
messageKeys: [],
};
const contractPackage = {
packageId: "@org-contracts/path-table",
version: "1.0.0",
digest: `sha256:${"ab".repeat(32)}`,
sourceRevision: "0a1b2c3d",
};
return ([undefined, "NEVER", "KEYED"] as const).flatMap((write) =>
[undefined, "installed-context", "named-context"].flatMap((context) =>
[undefined, contractPackage].map((pinned) =>
planFeature({ id: "path-table-feature", write, context, contractPackage: pinned }, installed),
),
),
);
}
/**
* REV-FE-0007. The generator's templates import relative to the file they
* render, so each path is resolved from that file in the rendered plan. A path
* that is no file is `unresolved`, and so is a path in the generator's source
* that no render shows (an option `generatorPlans` does not pass) and that is
* not the script's own import.
*/
function generatorImports(templates: readonly string[]) {
const named = new Set<string>();
const rendered = new Set<string>();
const unresolved = new Set<string>();
for (const { files } of generatorPlans()) {
for (const [file, content] of files) {
for (const specifier of relativePaths(content)) {
rendered.add(specifier);
const target = path.posix.join(path.posix.dirname(file), specifier);
if (files.has(target)) continue;
if (isRepositoryFile(target)) named.add(target);
else unresolved.add(`${file}: ${specifier}`);
}
}
}
for (const script of templates) {
for (const specifier of relativePaths(readFileSync(script, "utf8"))) {
if (isRepositoryFile(path.posix.join(path.posix.dirname(script), specifier))) continue;
const shape = pathPatternRegExp(specifier.replace(/\$\{[^}]*\}/gu, "*"));
if (![...rendered].some((shown) => shape.test(shown))) unresolved.add(`${script}: ${specifier}`);
}
}
return { named, unresolved: [...unresolved] };
}
type GitCall = readonly string[];
function fakeGit(answers: Readonly<Record<string, Readonly<{ status?: number; stdout?: string; stderr?: string }>>>) {
const calls: GitCall[] = [];
const git = (args: readonly string[]) => {
calls.push(args);
const answer = answers[args[0]!] ?? {};
return { status: answer.status ?? 0, stdout: answer.stdout ?? "", stderr: answer.stderr ?? "" };
};
return { git, calls };
}
describe("PR path table (contract)", () => {
it("puts every merge gate on a row or in always", async () => {
const contract = await loadCiGateContract(process.cwd());
const merge = contract.stages.find((stage) => stage.id === "merge")!.gateIds;
const listed = new Set([...table.always, ...table.rules.flatMap((rule) => rule.gates)]);
expect(merge.filter((gate) => !listed.has(gate))).toEqual([]);
expect([...listed].filter((gate) => !merge.includes(gate))).toEqual([]);
});
// FE-6 (decisions.md): FE-GATE-008 leaves the @a11y browser tests to
// FE-GATE-009, so a PR that runs 008 without 009 would run them nowhere.
it("runs FE-GATE-009 wherever it runs FE-GATE-008", () => {
expect(table.always.includes("FE-GATE-008")).toBe(table.always.includes("FE-GATE-009"));
const with008 = table.rules.filter((rule) => rule.gates.includes("FE-GATE-008"));
expect(with008.length).toBeGreaterThan(0);
for (const rule of with008) expect(rule.gates, rule.id).toContain("FE-GATE-009");
});
it("matches every tracked file with a row or the global list", () => {
const tracked = spawnSync("git", ["ls-files"], { encoding: "utf8" }).stdout.split("\n").filter(Boolean);
expect(tracked.length).toBeGreaterThan(100);
expect(tracked.filter((file) => !covered(file))).toEqual([]);
}, childProcessTimeout(GIT_LS_FILES_MS));
it("covers every repository path the scaffold and removal drills name with the scaffold row", () => {
const scaffold = table.rules.find((rule) => rule.id === "scaffold")!;
const templates = ["scripts/create-feature.ts", "scripts/create-feature-write-slice.ts"];
const drills = [
...templates,
"scripts/lib/generated-feature.ts",
"scripts/lib/feature-scaffold-drill.ts",
"scripts/test-feature-scaffold.ts",
"scripts/test-sample-removal.ts",
];
const named = new Set(
drills.flatMap((file) =>
[...readFileSync(file, "utf8").matchAll(/["'`]((?:src|tests)\/[\w./-]+)/gu)].map((match) => match[1]!),
),
);
expect(named.size).toBeGreaterThan(5);
const imports = generatorImports(templates);
expect(imports.unresolved).toEqual([]);
expect(imports.named.size).toBeGreaterThan(5);
for (const imported of imports.named) named.add(imported);
const uncovered = [...named].filter(
(name) =>
!scaffold.paths.some((pattern) =>
[name, `${name.replace(/\/$/u, "")}/x`].some((candidate) => pathPatternRegExp(pattern).test(candidate)),
),
);
expect(uncovered).toEqual([]);
// The other way: an exact src path on the row is one a render imports, so
// a path the generator stopped importing does not keep FE-GATE-020 on it.
const notImported = scaffold.paths.filter(
(pattern) => pattern.startsWith("src/") && !/[*?]/u.test(pattern) && !imports.named.has(pattern),
);
expect(notImported).toEqual([]);
});
});
describe("PR gate selection", () => {
it("runs the static gates and the unit gate for documents only", () => {
expect(selected(["docs/work/README.md", "README.md", "src/presentation/AGENTS.md", ".claude/rules/tests.md"])).toEqual(
[...ALWAYS, "FE-GATE-005"].sort(),
);
});
it("adds the accessibility gate and the removal drill for the accessibility records", () => {
expect(selected(["docs/accessibility/route-reviews/APP_HOME.md"])).toEqual(
[...ALWAYS, "FE-GATE-005", "FE-GATE-009", "FE-GATE-020"].sort(),
);
});
it("runs the application gates but not the scaffold drill for code outside its inputs", () => {
const gates = selected(["src/presentation/pages/home-page.tsx", "tests/e2e/app-shell.spec.ts"]);
expect(gates).not.toBe("all");
expect(gates).toContain("FE-GATE-008");
expect(gates).toContain("FE-GATE-013");
expect(gates).not.toContain("FE-GATE-020");
});
it("runs the scaffold drill when its inputs change", () => {
expect(selected(["src/features/reference/index.ts"])).toContain("FE-GATE-020");
expect(selected(["src/features/reference/index.ts"])).toContain("FE-GATE-008");
expect(selected(["tests/mocks/scenarios/catalog.ts"])).toContain("FE-GATE-020");
});
it("runs every gate for a global file, an unknown file or an empty diff", () => {
expect(selectPrGates(table, ["package.json"])).toEqual({ kind: "all", reason: "전역 파일 package.json이 바뀜" });
expect(selected(["scripts/verify.sh", "docs/x.md"])).toBe("all");
expect(selected(["playwright.visual.config.ts"])).toBe("all");
expect(selectPrGates(table, ["new-root-file.txt"])).toMatchObject({ kind: "all" });
expect(selectPrGates(table, [])).toMatchObject({ kind: "all" });
});
it("reads path patterns as segments", () => {
expect(pathPatternRegExp("**/*.md").test("README.md")).toBe(true);
expect(pathPatternRegExp("**/*.md").test("docs/a/b.md")).toBe(true);
expect(pathPatternRegExp("docs/**").test("docs/a/b.txt")).toBe(true);
expect(pathPatternRegExp("docs/**").test("docsx/a")).toBe(false);
expect(pathPatternRegExp("tsconfig*.json").test("tsconfig.app.json")).toBe(true);
expect(pathPatternRegExp("tsconfig*.json").test("src/tsconfig.json")).toBe(false);
expect(pathPatternRegExp("index.html").test("indexXhtml")).toBe(false);
});
});
describe("skipped gate log line", () => {
it("has the fixed form of design-docs ci/manual.md 4.1", () => {
const line = skippedGateLine("FE-GATE-020", "바뀐 파일 3개가 경로표에서 이 게이트에 안 걸림");
expect(line).toBe("건너뜀: FE-GATE-020 — 바뀐 파일 3개가 경로표에서 이 게이트에 안 걸림");
expect(SKIPPED_GATE_LINE.test(line)).toBe(true);
expect(SKIPPED_GATE_LINE.test("건너뜀: merge / tests — 트리 abc1234가 PR #12 run 34에서 초록")).toBe(true);
expect(SKIPPED_GATE_LINE.test("skipped: FE-GATE-020")).toBe(false);
expect(SKIPPED_GATE_LINE.test("건너뜀: FE-GATE-020 —")).toBe(false);
});
});
describe("PR diff and the skip decision", () => {
it("unshallows the checkout, fetches the base and diffs from the merge base", () => {
const { git, calls } = fakeGit({
"rev-parse": { stdout: "true\n" },
"merge-base": { stdout: "abc123\n" },
diff: { stdout: "docs/a.md\nsrc/b.ts\n" },
});
expect(prChangedFiles("main", git)).toEqual({ files: ["docs/a.md", "src/b.ts"] });
expect(calls[1]).toEqual(["fetch", "--no-tags", "--quiet", "--unshallow", "origin", "+refs/heads/main:refs/remotes/origin/main"]);
expect(calls[2]).toEqual(["merge-base", "refs/remotes/origin/main", "HEAD"]);
expect(calls[3]).toEqual(["diff", "--name-only", "--no-renames", "abc123", "HEAD"]);
});
it("reads a shallow PR checkout's changes from the merge base with real git", () => {
const root = mkdtempSync(path.join(tmpdir(), "pr-gate-selection-"));
try {
const git = (cwd: string, ...args: string[]) => {
const result = spawnSync(
"git",
["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "init.defaultBranch=main", ...args],
{ cwd, encoding: "utf8" },
);
if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`);
return result;
};
const origin = path.join(root, "origin");
mkdirSync(origin);
git(origin, "init", "--quiet");
writeFileSync(path.join(origin, "a.ts"), "1\n");
git(origin, "add", ".");
git(origin, "commit", "--quiet", "-m", "base");
git(origin, "switch", "--quiet", "-c", "pr");
mkdirSync(path.join(origin, "docs"));
writeFileSync(path.join(origin, "docs", "x.md"), "x\n");
git(origin, "add", ".");
git(origin, "commit", "--quiet", "-m", "pr");
git(origin, "switch", "--quiet", "main");
writeFileSync(path.join(origin, "a.ts"), "2\n");
git(origin, "commit", "--quiet", "-am", "main moves on");
git(root, "clone", "--quiet", "--depth", "1", "--branch", "pr", `file://${origin}`, "checkout");
const checkout = path.join(root, "checkout");
const inCheckout = (args: readonly string[]) => {
const result = spawnSync("git", args, { cwd: checkout, encoding: "utf8" });
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
};
// main's own later change (a.ts) is not the PR's.
expect(prChangedFiles("main", inCheckout)).toEqual({ files: ["docs/x.md"] });
} finally {
rmSync(root, { recursive: true, force: true });
}
}, childProcessTimeout(SHALLOW_CLONE_MS));
it("reports a fetch failure or an odd base name instead of guessing", () => {
expect(prChangedFiles("main", fakeGit({ fetch: { status: 128, stderr: "denied" } }).git)).toEqual({
error: "base 브랜치를 받지 못함: denied",
});
expect(prChangedFiles("main; rm -rf /", fakeGit({}).git)).toMatchObject({ error: expect.stringContaining("이상함") });
});
it("skips only in a pull_request run, only gates the diff does not reach", () => {
const docsOnly = () =>
fakeGit({ "rev-parse": { stdout: "false\n" }, "merge-base": { stdout: "abc\n" }, diff: { stdout: "docs/a.md\n" } }).git;
const root = process.cwd();
expect(prGateSkipReason("FE-GATE-020", {}, root, docsOnly())).toBeUndefined();
expect(prGateSkipReason("FE-GATE-020", { [PR_BASE_REF_VARIABLE]: "" }, root, docsOnly())).toBeUndefined();
expect(prGateSkipReason("FE-GATE-020", { [PR_BASE_REF_VARIABLE]: "main" }, root, docsOnly())).toMatch(
/^바뀐 파일 1개가 경로표/u,
);
expect(prGateSkipReason("FE-GATE-005", { [PR_BASE_REF_VARIABLE]: "main" }, root, docsOnly())).toBeUndefined();
expect(
prGateSkipReason("FE-GATE-020", { [PR_BASE_REF_VARIABLE]: "main" }, root, fakeGit({ fetch: { status: 1 } }).git),
).toBeUndefined();
});
});