Files
clean-architecture-frontend…/tests/unit/removal-fixture.test.ts
T
DongHyeonka e6b2a4f6bf fix(manual): 짝 백엔드 OIDC 설정 키 예시의 FE-REG-ENV 행에 defaultValue를 적는다
문제
매뉴얼 04 §3.2의 PRODUCT_ENV_REGISTRY 예시 두 행(OIDC_ISSUER,
OIDC_CLIENT_ID)에 defaultValue가 없다. 행 타입은 defaultValue를 필수 칸으로
가진다(src/contracts/env.ts). 그래서 제품이 그대로 붙이면 check:types:app이
env.ts에서 TS2322로, env-registry-coverage가 `row {"required":false}`로
실패한다(리뷰 14-R3). 매뉴얼 03 C절과 product-contracts.ts 주석은
defaultValue를 쓴다.

고른 방법
- 두 행에 `defaultValue: null`을 더하고(.optional() 키), 행 칸의 규칙을
  예시 아래 한 줄로 적었다.
- 테스트 tests/unit/manual-paired-backend-settings.test.ts: 매뉴얼 §3.2의 ts
  블록을 그대로 저장소 사본의 새 파일로 두고, 사본의 product-contracts.ts가
  제품 자신의 파일(옆에 보존)에 그 키를 더해 내보낸다. 그 사본에서
  tsconfig.app.json 타입 검사와, env-registry-coverage와 같은 행 대조(키가
  없을 때 스키마가 내는 required·defaultValue)를 node로 돌린다. 제품 파일을
  덮어쓰지 않으므로 다운스트림에서도 그대로 돈다(1105/09-01과 같은 방식).
- 문서를 읽는 테스트라 REMOVAL_FIXTURE_DOCUMENT_TESTS에 더했다. 그 목록의
  항목이 문서를 읽는지 보는 removal-fixture.test.ts 정규식에 `docs/`를
  더했다. 문서 대상(REMOVAL_FIXTURE_DOCUMENT_TARGETS)에 docs가 있어 README나
  CHANGELOG를 읽지 않는 문서 테스트도 있을 수 있다. 목록의 뜻은 그대로다.
- 버린 대안: 예시 행을 recipe에서 export하고 recipe 테스트가 그것으로
  조립하기(리뷰 ②). contracts가 recipe를 import할 수 없어 매뉴얼이 다시
  복사를 시킨다. 이번 테스트가 매뉴얼 블록 자체를 지킨다.

위험·한계
- 행 대조는 env-registry-coverage의 schemaDeclaration을 이 테스트 안에 다시
  적었다(사본에서 vitest를 띄우지 않으려고). 규칙이 바뀌면 둘을 함께 고친다.
- §3.3·§4.3의 코드 예시는 여전히 컴파일하지 않는다(recipe를 복사한 뒤의
  모양이라 사본 구성이 더 크다).
- 테스트가 저장소 사본을 만들고 tsc app 프로그램을 돈다. test:unit이 몇 초
  는다.

검증
- desktop batch에서 확인: node scripts/run-vitest.ts run
  tests/unit/manual-paired-backend-settings.test.ts
  tests/unit/removal-fixture.test.ts, corepack pnpm verify:documentation

Refs: 1105/14-02
2026-11-06 02:59:02 +09:00

252 lines
11 KiB
TypeScript

import { existsSync } from "node:fs";
import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts";
import {
assertNoRuntimeImports,
pruneRemovalFixtureCiContract,
REMOVAL_FIXTURE_COPY_TARGETS,
REMOVAL_FIXTURE_DOCUMENT_TARGETS,
REMOVAL_FIXTURE_DOCUMENT_TESTS,
removalFixtureExcludedTests,
removeRuntimeDependentTests,
renderRemovalJunit,
runtimeImportGraph,
} from "../../scripts/lib/removal-fixture.ts";
const temporaryRoots: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
it("rejects an empty scanned module universe", async () => {
const root = await mkdtemp(path.join(tmpdir(), "removal-fixture-empty-modules-"));
temporaryRoots.push(root);
await expect(runtimeImportGraph(root, ["src/runtime"])).rejects.toThrow(
/scanned module universe is empty/i,
);
});
it("rejects a runtime removal scan that discovers no dependent tests", async () => {
const root = await mkdtemp(path.join(tmpdir(), "removal-fixture-zero-dependent-tests-"));
temporaryRoots.push(root);
await mkdir(path.join(root, "src/runtime"), { recursive: true });
await mkdir(path.join(root, "tests"), { recursive: true });
await writeFile(path.join(root, "src/runtime/index.ts"), "export const runtime = true;\n");
await writeFile(path.join(root, "tests/unrelated.test.ts"), "export const unrelated = true;\n");
await expect(removeRuntimeDependentTests(root, ["src/runtime"])).rejects.toThrow(
/no runtime-dependent tests discovered/i,
);
});
it("allows zero runtime imports after the runtime has been removed", async () => {
const root = await mkdtemp(path.join(tmpdir(), "removal-fixture-post-removal-"));
temporaryRoots.push(root);
await mkdir(path.join(root, "tests"), { recursive: true });
await writeFile(path.join(root, "tests/unrelated.test.ts"), "export const unrelated = true;\n");
await expect(
assertNoRuntimeImports(root, ["src/runtime"], "fixture runtime"),
).resolves.toBeUndefined();
});
async function copyCiContract(prefix: string): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), prefix));
temporaryRoots.push(root);
await mkdir(path.join(root, "config/ci"), { recursive: true });
for (const file of ["config/ci/gates.json", "config/ci/contract-baseline.json", "package.json"]) {
await writeFile(path.join(root, file), await readFile(file));
}
return root;
}
// D-13: a removal takes the same step a downstream project takes — it records
// the reduced contract as the new baseline — and then loads canonically.
it("prunes removed command and evidence references and re-baselines the contract", async () => {
const root = await copyCiContract("removal-fixture-contract-");
await pruneRemovalFixtureCiContract({
root,
removedScripts: new Set(["test:reference-feature"]),
removedEvidencePathFragments: ["reference-feature.xml"],
});
const contract = await loadCiGateContract(root);
expect(contract.commands.some(({ script }) => script === "test:reference-feature")).toBe(false);
expect(contract.artifacts.some(({ path }) => path.includes("reference-feature.xml"))).toBe(false);
expect(contract.gates.some(({ commandIds }) => commandIds.includes("test-reference-feature"))).toBe(false);
expect(contract.gates.some(({ evidenceArtifactIds }) =>
evidenceArtifactIds.includes("artifact-artifacts-tests-reference-feature-xml")
)).toBe(false);
const baseline = JSON.parse(
await readFile(path.join(root, "config/ci/contract-baseline.json"), "utf8"),
) as Record<string, unknown>;
expect(baseline).toMatchObject({ commands: contract.commands.length, owner: "removal-fixture" });
const packageDocument = JSON.parse(await readFile(path.join(root, "package.json"), "utf8")) as {
scripts: Record<string, string>;
};
expect(packageDocument.scripts["check:ci"]).not.toMatch(/reduced/u);
});
// 1103/16-02. A product feature owns no CI script, so its removal prunes
// nothing. The baseline reason then ended in a blank ("removal fixture pruned
// ") and the baseline schema refused it before any gate ran.
it("re-baselines a removal that prunes no CI script", async () => {
const root = await copyCiContract("removal-fixture-no-scripts-");
await pruneRemovalFixtureCiContract({
root,
removedScripts: new Set(),
removedEvidencePathFragments: [],
});
const baseline = JSON.parse(
await readFile(path.join(root, "config/ci/contract-baseline.json"), "utf8"),
) as Record<string, unknown>;
expect(baseline["reason"]).toBe("removal fixture pruned no CI scripts");
await expect(loadCiGateContract(root)).resolves.toBeDefined();
});
it("rejects a contract that no longer matches its committed baseline", async () => {
const root = await copyCiContract("removal-fixture-baseline-drift-");
const baselinePath = path.join(root, "config/ci/contract-baseline.json");
const baseline = JSON.parse(await readFile(baselinePath, "utf8")) as Record<string, number>;
await writeFile(baselinePath, JSON.stringify({ ...baseline, commands: baseline.commands! + 1 }));
await expect(loadCiGateContract(root)).rejects.toThrow(
/contract-baseline\.json[\s\S]*commands[\s\S]*update:ci-contract-baseline/u,
);
});
it("rejects pruning that leaves a reduced gate without commands", async () => {
const root = await copyCiContract("removal-fixture-empty-gate-");
await expect(pruneRemovalFixtureCiContract({
root,
removedScripts: new Set(["test:runtime-schema"]),
removedEvidencePathFragments: ["runtime-schema.xml"],
})).rejects.toThrow(/commandIds|too small|at least 1/i);
});
// 1103/02-06. Three FE-GATE-020 drills copied the repository without its
// documents and still ran the tests that read them, so each failed its `test`
// check on ENOENT whatever it removed. Only the sample drill excluded them.
describe("document tests in a removal fixture", () => {
it("leaves the document tests out exactly when the documents are not copied", () => {
expect(removalFixtureExcludedTests(REMOVAL_FIXTURE_COPY_TARGETS))
.toEqual(REMOVAL_FIXTURE_DOCUMENT_TESTS);
expect(removalFixtureExcludedTests([
...REMOVAL_FIXTURE_COPY_TARGETS,
...REMOVAL_FIXTURE_DOCUMENT_TARGETS,
])).toEqual([]);
});
// This file also runs inside the capability fixtures, which hold neither
// the documents nor these tests; the two go together.
it("names tests that read the documents, present exactly where the documents are", async () => {
const documentsPresent = REMOVAL_FIXTURE_DOCUMENT_TARGETS.every((target) => existsSync(target));
for (const test of REMOVAL_FIXTURE_DOCUMENT_TESTS) {
expect(existsSync(test), test).toBe(documentsPresent);
if (documentsPresent) {
// 1105/14-02. docs/ is one of the document targets too.
await expect(readFile(test, "utf8")).resolves.toMatch(/README\.md|CHANGELOG\.md|docs\//u);
}
}
});
it("is the only exclusion list: every drill prepares its fixture through it", async () => {
const drills: string[] = [];
for (const name of await readdir("scripts")) {
if (!/^test-.*\.ts$/u.test(name)) continue;
const source = await readFile(path.join("scripts", name), "utf8");
if (!source.includes("./lib/removal-fixture.ts")) continue;
drills.push(name);
expect(source, name).toContain("prepareRemovalFixture(");
for (const test of REMOVAL_FIXTURE_DOCUMENT_TESTS) {
expect(source, name).not.toContain(test);
}
}
expect(drills).toEqual(expect.arrayContaining(["test-sample-removal.ts", "test-feature-scaffold.ts"]));
});
});
describe("release evidence fixture copy", () => {
it("keeps the release evidence and leaves the regenerated trees behind", async () => {
const { copyReleaseEvidenceTree, RELEASE_EVIDENCE_REGENERATED_TREES } =
await import("../../scripts/lib/removal-fixture.ts");
const { RELEASE_CANDIDATE_EVIDENCE_PATHS } = await import(
"../../scripts/lib/release-candidate.ts"
);
const { access, readdir } = await import("node:fs/promises");
// The source is a fake checkout, not process.cwd(): release evidence is
// git-ignored, so a fresh clone has none of it and the copy would be
// checked against nothing.
const source = await mkdtemp(path.join(tmpdir(), "release-evidence-source-"));
const target = await mkdtemp(path.join(tmpdir(), "release-evidence-target-"));
temporaryRoots.push(source, target);
const evidencePaths = RELEASE_CANDIDATE_EVIDENCE_PATHS.filter((evidence) =>
evidence.startsWith("artifacts/")
);
expect(evidencePaths.length).toBeGreaterThan(0);
for (const relative of [
...evidencePaths,
...RELEASE_EVIDENCE_REGENERATED_TREES.map((tree) => `${tree}/trace.zip`),
]) {
await mkdir(path.dirname(path.join(source, relative)), { recursive: true });
await writeFile(path.join(source, relative), "{}\n");
}
await copyReleaseEvidenceTree(source, target);
// Every release artifact has to survive the copy; a fixture missing one
// cannot build a candidate at all, and every provider suite then fails
// while constructing its own fixture.
for (const evidence of evidencePaths) {
await expect(access(path.join(target, evidence)), evidence).resolves.toBeUndefined();
}
// The regenerated trees are why this is a filter and not a plain copy: they
// are tens of megabytes of traces and coverage HTML. They still exist,
// because the repository inventory expects the directories.
for (const tree of RELEASE_EVIDENCE_REGENERATED_TREES) {
await expect(readdir(path.join(target, tree)), tree).resolves.toEqual([]);
}
});
});
describe("removal JUnit report (14-08)", () => {
it("counts every failure and gives each check its own cause", () => {
const xml = renderRemovalJunit("reference-feature-removal", [
{ name: "typecheck", passed: false, failure: "corepack pnpm check:types exited 2" },
{ name: "architecture", passed: true },
{ name: "build", passed: false, failure: "corepack pnpm build exited 1" },
{
name: "fixture-id-residue",
passed: false,
failure: "residue: tests/a.test.ts, tests/<b>&c.ts",
},
]);
expect(xml).toContain('tests="4" failures="3"');
expect(xml).toContain(
'<testcase name="typecheck"><failure message="corepack pnpm check:types exited 2" /></testcase>',
);
expect(xml).toContain('<testcase name="architecture"></testcase>');
expect(xml).toContain(
'<failure message="corepack pnpm build exited 1" />',
);
expect(xml).toContain(
'message="residue: tests/a.test.ts, tests/&lt;b&gt;&amp;c.ts"',
);
expect(xml.match(/residue:/gu)).toHaveLength(1);
});
});