문제:
- FE-GATE-005는 `test:unit`·`test:contract`로 `tests/unit`·`tests/contract`를
돈 뒤, `test:coverage`로 같은 파일을 다시 돈다. coverage의 경로가 두
폴더를 품는다. runner에서 005의 약 3분 가운데 `test:unit`이 31~33%다
(design-docs `ci/06-frontend-ci-speed-handoff.md` 4.3절).
고른 방법:
- 005의 명령에서 `test-unit`·`test-contract`를 빼고, 계약에서도 지운다.
두 package script는 작업 중에 쓰는 명령으로 남는다.
- `scripts/lib/coverage-bundle-junit-reporter.ts`를 `test:coverage`의 reporter로
더한다.
- 같은 coverage 실행에서 두 폴더의 결과를 Vitest의 JUnit reporter로
`artifacts/tests/unit.xml`·`contract.xml`에 쓴다. 폴더마다 그 폴더의
test module만 넘긴다.
- 증거 이름, 형식, 게이트 ID는 그대로다. 두 증거의 producer는
`test-coverage`이고, freshness 검사(`run-ci-gate.ts`)도 그대로
통과한다.
- 한 폴더에서 시험 파일이 하나도 돌지 않으면 그 실행이 실패한다. 일반
실행도 시험 파일이 없는 폴더에서 실패했다. 빈 보고서는 증거 검사를
그대로 통과하기 때문이다.
- 쓴 보고서를 다시 읽어 `<testsuite name>` 목록이 그 폴더에서 돈 파일과
같은지 본다. 다르거나 읽을 수 없으면 실패하고, 남는 파일과 빠진
파일을 앞 3개씩 댄다. Vitest를 올려 JUnit reporter가 넘겨받은 module
대신 전체를 쓰게 바뀌면 여기서 걸린다.
- 드릴의 「coverage가 덮는 묶음」(`SCAFFOLD_DRILL_COVERED_SUITES`)에서
unit·contract를 뺀다. merge 단계가 더는 그 둘을 따로 부르지 않는다.
- 시험(`tests/unit/coverage-bundle-junit-reporter.test.ts`, 9개)이 본다:
- reporter가 폴더마다 그 폴더의 파일만 넘긴다. 빈 폴더면 실패한다.
- 보고서가 넘기지 않은 파일을 담거나, 돈 파일을 빼거나, 써지지 않으면
실패한다. suite 이름을 읽는다.
- 005의 두 증거가 `test:coverage`에서 나온다.
- `test:coverage`가 reporter를 부르고, 그 경로가 두 폴더를 품는다.
- merge 단계에서 두 폴더를 도는 명령이 005의 `test:coverage` 하나뿐이다.
- `docs/work/reference/decisions.md`에 FE-4 행을 더한다. 운영 문서, 시험 층
표, 매뉴얼, 지역 지침 둘, fe-testing 스킬의 005 설명도 고친다.
버린 것:
- coverage 실행 한 번이 FE-GATE-004·006·007의 증거까지 내기(약 −1:30). 세
게이트가 005의 결과를 읽게 된다. coverage 실행이 죽으면 세 게이트도
판정을 못 내고, 혼자 돌릴 수 없다. FE-6에서 버린 꼴과 같다. 004는 005보다
앞이라 차례도 바꿔야 했다. 총괄이 정했다(2026-11-20).
- coverage의 JUnit을 나중에 XML로 나누기: 저장소에 XML 파서가 없다.
Vitest의 reporter로 쓰면 형식이 일반 실행과 같다.
위험·한계:
- unit·contract 시험은 이제 coverage 계측 아래에서만 돈다. 시간에 기대는
시험이 가려질 수 있다. 일반 실행은 기본 worker 수, coverage 실행은
`--maxWorkers=4`로 돈다. environment·setupFiles·pool·include·exclude는
같다.
- 004·006·007의 묶음은 coverage에서 한 번 더 돈다(약 0:33).
- `unit.xml`의 시험 시간은 이제 coverage 실행의 시간이다.
검증(desktop `scripts/verify.sh`):
- 분할한 `unit.xml`·`contract.xml`이 같은 트리의 일반 `test:unit`·
`test:contract` 결과와 파일·testcase·결과까지 같다(unit 242파일 3469,
contract 3파일 26). 기준 main의 일반 실행과는 이 커밋이 더한 시험 파일
하나만 다르다.
- 두 실행의 vitest 설정을 풀어 보니 coverage 켜짐과 maxWorkers만 다르다.
- FE-GATE-005 rc=0. 게이트 로그의 vitest 호출은 `test:coverage` 하나이고,
자기 대조 불만은 0이다.
- `tests/unit` 시험 하나를 깨뜨리면 005 rc=1(`unit.xml` failures=1).
`tests/component` 시험 하나를 깨뜨리면 005·006 rc=1.
- 변이 여덟이 각자 대상 시험에서 실패한다: reporter 인자 빼기, coverage
경로에서 `tests/contract` 빼기(게이트도 「No test file of tests/contract
ran」으로 실패), 005에 `test-unit` 다시 넣기, 폴더 거름을 `includes`로
(두 번), 자기 대조 끄기(두 번), 자기 대조를 남는 이름만 보게 약하게.
- lint·check:types·FE-GATE-010 rc=0.
- 리뷰: 새 눈 1회(Low 2와 확인 못 한 것 1) 반영, 확인 1회(Low 2) 반영, 다시
확인 발견 0.
- merge 단계와 FE-GATE-029·030은 PR 본문에 적는다.
Refs: fe-ci-next (5), FE-4
209 lines
9.1 KiB
TypeScript
209 lines
9.1 KiB
TypeScript
import { readFileSync } from "node:fs";
|
|
import { mkdtemp, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import { indexCiGateContract, loadCiGateContract } from "../../scripts/contracts/ci-gates.ts";
|
|
import CoverageBundleJUnitReporter, {
|
|
COVERAGE_BUNDLE_REPORTS,
|
|
reportedSuiteNames,
|
|
} from "../../scripts/lib/coverage-bundle-junit-reporter.ts";
|
|
import { gatedTestPaths } from "../../scripts/lib/ungated-tests.ts";
|
|
|
|
/**
|
|
* FE-4 (2026-11-20). FE-GATE-005 runs tests/unit and tests/contract once, in
|
|
* test:coverage, and writes their JUnit evidence from that run. These tests
|
|
* keep that true: the reporter hands each report only its folder's files, the
|
|
* gate's evidence comes from test:coverage, and no other merge command runs
|
|
* those folders again.
|
|
*
|
|
* The JUnit reporter below stands in for Vitest's: it writes one <testsuite>
|
|
* per module it is handed, as Vitest's does, plus `junit.extra` if set,
|
|
* leaves the first module out when `junit.dropFirst` is set, and writes
|
|
* nothing when `junit.write` is false.
|
|
*/
|
|
const junit = vi.hoisted(() => ({
|
|
runs: [] as { outputFile: string; modules: string[] }[],
|
|
extra: undefined as string | undefined,
|
|
dropFirst: false,
|
|
write: true,
|
|
}));
|
|
vi.mock("vitest/reporters", async () => {
|
|
const { mkdir: mkdirAsync, writeFile: writeAsync } = await import("node:fs/promises");
|
|
const { dirname, resolve } = await import("node:path");
|
|
return {
|
|
JUnitReporter: class {
|
|
readonly #outputFile: string;
|
|
#root = "";
|
|
constructor(options: { outputFile: string }) {
|
|
this.#outputFile = options.outputFile;
|
|
}
|
|
async onInit(vitest: { config: { root: string } }): Promise<void> {
|
|
this.#root = vitest.config.root;
|
|
}
|
|
async onTestRunEnd(modules: readonly { relativeModuleId: string }[]): Promise<void> {
|
|
const names = modules.map(({ relativeModuleId }) => relativeModuleId);
|
|
junit.runs.push({ outputFile: this.#outputFile, modules: names });
|
|
if (!junit.write) return;
|
|
const file = resolve(this.#root, this.#outputFile);
|
|
await mkdirAsync(dirname(file), { recursive: true });
|
|
await writeAsync(file, [
|
|
"<testsuites>",
|
|
...[...names.slice(junit.dropFirst ? 1 : 0), ...(junit.extra ? [junit.extra] : [])].map((name) => ` <testsuite name="${name}" tests="1">`),
|
|
"</testsuites>",
|
|
].join("\n"));
|
|
}
|
|
},
|
|
};
|
|
});
|
|
|
|
const scripts = (
|
|
JSON.parse(readFileSync("package.json", "utf8")) as { scripts: Record<string, string> }
|
|
).scripts;
|
|
const readConfig = (file: string) => readFileSync(file, "utf8");
|
|
const overlaps = (target: string, directory: string) =>
|
|
target === directory || target.startsWith(`${directory}/`) || directory.startsWith(`${target}/`);
|
|
const testModule = (relativeModuleId: string) => ({ relativeModuleId });
|
|
|
|
const roots: string[] = [];
|
|
|
|
async function runReporter(relativeModuleIds: readonly string[]) {
|
|
junit.runs.length = 0;
|
|
const root = await mkdtemp(path.join(tmpdir(), "coverage-bundle-junit-"));
|
|
roots.push(root);
|
|
const exitCode = process.exitCode;
|
|
const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
|
|
try {
|
|
const reporter = new CoverageBundleJUnitReporter();
|
|
await reporter.onInit({ config: { root } } as never);
|
|
await reporter.onTestRunEnd(relativeModuleIds.map(testModule) as never);
|
|
return {
|
|
exitCode: process.exitCode,
|
|
stderr: stderr.mock.calls.map(([chunk]) => String(chunk)).join(""),
|
|
runs: [...junit.runs],
|
|
};
|
|
} finally {
|
|
process.exitCode = exitCode;
|
|
}
|
|
}
|
|
|
|
describe("coverage bundle JUnit reporter", () => {
|
|
afterEach(async () => {
|
|
junit.runs.length = 0;
|
|
junit.extra = undefined;
|
|
junit.dropFirst = false;
|
|
junit.write = true;
|
|
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
it("hands each bundle's JUnit only the test files of its folder, in run order", async () => {
|
|
const result = await runReporter([
|
|
"tests/unit/b.test.ts",
|
|
"tests/contract/reusable/c.test.ts",
|
|
"tests/unit-extra/d.test.ts",
|
|
"tests/integration/tests/unit/e.test.ts",
|
|
"tests\\unit\\a.test.ts",
|
|
"tests/component/f.test.tsx",
|
|
]);
|
|
expect(result.runs).toEqual([
|
|
{ outputFile: "artifacts/tests/unit.xml", modules: ["tests/unit/b.test.ts", "tests\\unit\\a.test.ts"] },
|
|
{ outputFile: "artifacts/tests/contract.xml", modules: ["tests/contract/reusable/c.test.ts"] },
|
|
]);
|
|
expect(result.exitCode).toBe(process.exitCode);
|
|
expect(result.stderr).toBe("");
|
|
});
|
|
|
|
it("fails the run and names the folder when none of its test files ran", async () => {
|
|
const result = await runReporter(["tests/unit/b.test.ts", "tests/component/f.test.tsx"]);
|
|
expect(result.runs).toEqual([
|
|
{ outputFile: "artifacts/tests/unit.xml", modules: ["tests/unit/b.test.ts"] },
|
|
{ outputFile: "artifacts/tests/contract.xml", modules: [] },
|
|
]);
|
|
expect(result.exitCode).toBe(1);
|
|
expect(result.stderr).toContain("No test file of tests/contract ran");
|
|
});
|
|
|
|
it("fails the run when a written report lists a test file it was not handed", async () => {
|
|
junit.extra = "tests/component/f.test.tsx";
|
|
const result = await runReporter(["tests/unit/b.test.ts", "tests/contract/c.test.ts"]);
|
|
expect(result.exitCode).toBe(1);
|
|
expect(result.stderr).toContain(
|
|
"artifacts/tests/unit.xml does not list exactly the 1 test file(s) of tests/unit that ran (FE-4). " +
|
|
"It lists 2. Not run here: tests/component/f.test.tsx. Ran but missing: none.",
|
|
);
|
|
expect(result.stderr).toContain("artifacts/tests/contract.xml does not list exactly the 1 test file(s) of tests/contract");
|
|
});
|
|
|
|
it("fails the run when a written report leaves out a test file that ran", async () => {
|
|
junit.dropFirst = true;
|
|
const result = await runReporter(["tests/unit/b.test.ts", "tests/unit/a.test.ts", "tests/contract/c.test.ts"]);
|
|
expect(result.exitCode).toBe(1);
|
|
expect(result.stderr).toContain(
|
|
"artifacts/tests/unit.xml does not list exactly the 2 test file(s) of tests/unit that ran (FE-4). " +
|
|
"It lists 1. Not run here: none. Ran but missing: tests/unit/b.test.ts.",
|
|
);
|
|
expect(result.stderr).toContain("Ran but missing: tests/contract/c.test.ts.");
|
|
});
|
|
|
|
it("fails the run when a report was not written", async () => {
|
|
junit.write = false;
|
|
const result = await runReporter(["tests/unit/b.test.ts", "tests/contract/c.test.ts"]);
|
|
expect(result.exitCode).toBe(1);
|
|
expect(result.stderr).toContain("It could not be read.");
|
|
});
|
|
|
|
it("reads each test file's suite name back as Vitest escapes it", () => {
|
|
expect(reportedSuiteNames([
|
|
'<?xml version="1.0" encoding="UTF-8" ?>',
|
|
'<testsuites name="vitest tests" tests="2">',
|
|
' <testsuite name="tests/unit/a&b.test.ts" timestamp="x" tests="1">',
|
|
' <testcase classname="tests/unit/a&b.test.ts" name="runs">',
|
|
' <testsuite name="tests\\unit\\c.test.ts" tests="1">',
|
|
].join("\n"))).toEqual(["tests/unit/a&b.test.ts", "tests/unit/c.test.ts"]);
|
|
});
|
|
});
|
|
|
|
describe("FE-GATE-005 runs tests/unit and tests/contract once, in test:coverage", () => {
|
|
it("writes their JUnit evidence from its test:coverage run, under the files the gate names", async () => {
|
|
const contract = await loadCiGateContract(process.cwd());
|
|
const index = indexCiGateContract(contract);
|
|
const gate = index.gates.get("FE-GATE-005")!;
|
|
const coverageCommandIds = gate.commandIds.filter((id) => index.commands.get(id)?.script === "test:coverage");
|
|
expect(coverageCommandIds).toHaveLength(1);
|
|
for (const { outputFile } of COVERAGE_BUNDLE_REPORTS) {
|
|
const artifact = contract.artifacts.find(({ path }) => path === outputFile);
|
|
expect(artifact, outputFile).toBeDefined();
|
|
expect(gate.evidenceArtifactIds, outputFile).toContain(artifact!.id);
|
|
expect(artifact, outputFile).toMatchObject({
|
|
schemaId: "junit",
|
|
production: "command-generated",
|
|
producerCommandIds: coverageCommandIds,
|
|
});
|
|
}
|
|
});
|
|
|
|
it("names the reporter in test:coverage, whose paths hold each folder", () => {
|
|
expect(scripts["test:coverage"]).toContain("--reporter=./scripts/lib/coverage-bundle-junit-reporter.ts");
|
|
const coverage = gatedTestPaths(scripts, ["test:coverage"], readConfig);
|
|
for (const { directory } of COVERAGE_BUNDLE_REPORTS) {
|
|
expect(coverage, directory).toContain(directory);
|
|
}
|
|
});
|
|
|
|
it("leaves no other merge command running those folders", async () => {
|
|
const contract = await loadCiGateContract(process.cwd());
|
|
const index = indexCiGateContract(contract);
|
|
const merge = contract.stages.find(({ id }) => id === "merge")!;
|
|
for (const { directory } of COVERAGE_BUNDLE_REPORTS) {
|
|
const runners = merge.gateIds.flatMap((gateId) =>
|
|
index.gates.get(gateId)!.commandIds
|
|
.filter((commandId) => gatedTestPaths(scripts, [index.commands.get(commandId)!.script], readConfig)
|
|
.some((target) => overlaps(target, directory)))
|
|
.map((commandId) => `${gateId}:${commandId}`));
|
|
expect(runners, directory).toEqual(["FE-GATE-005:test-coverage"]);
|
|
}
|
|
});
|
|
});
|