Files
clean-architecture-frontend…/scripts/lib/coverage-bundle-junit-reporter.ts
DongHyeonka 6cba1f5056 ci(gates): FE-GATE-005가 unit·contract 시험을 coverage 실행에서 한 번만 돈다
문제:
- 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
2026-11-20 19:10:10 +09:00

101 lines
4.3 KiB
TypeScript

import { readFile } from "node:fs/promises";
import path from "node:path";
import type { Reporter, TestModule, Vitest } from "vitest/node";
import { JUnitReporter } from "vitest/reporters";
/**
* FE-4 (2026-11-20). FE-GATE-005 ran tests/unit and tests/contract twice: plain
* (test:unit, test:contract) and again in test:coverage, whose paths hold
* both. It runs them once now, in test:coverage, which names this reporter.
* From that one run the reporter writes each bundle's JUnit under the name the
* plain run wrote, with Vitest's own JUnit reporter, so the gate's evidence
* (config/ci/gates.json) keeps its files and format.
*
* The run fails when a bundle has no test file in it, as the plain run failed
* on a folder with no test file: an empty report would pass the gate's
* evidence check with no test behind it. It also fails when a written report
* names other test files than the bundle's, which would happen if Vitest's
* JUnit reporter stopped writing only the modules it is handed.
*/
export type CoverageBundleReport = Readonly<{ directory: string; outputFile: string }>;
export const COVERAGE_BUNDLE_REPORTS: readonly CoverageBundleReport[] = Object.freeze([
Object.freeze({ directory: "tests/unit", outputFile: "artifacts/tests/unit.xml" }),
Object.freeze({ directory: "tests/contract", outputFile: "artifacts/tests/contract.xml" }),
]);
const slashed = (file: string) => file.replaceAll("\\", "/");
const firstFew = (files: readonly string[]) =>
files.length === 0
? "none"
: `${files.slice(0, 3).join(", ")}${files.length > 3 ? ` and ${files.length - 3} more` : ""}`;
/** The test files of the run that lie in `directory`, in run order. */
export function bundleModules<Module extends Pick<TestModule, "relativeModuleId">>(
testModules: readonly Module[],
directory: string,
): Module[] {
const prefix = `${directory}/`;
return testModules.filter(({ relativeModuleId }) => slashed(relativeModuleId).startsWith(prefix));
}
const XML_ENTITIES: Readonly<Record<string, string>> = Object.freeze({
amp: "&",
lt: "<",
gt: ">",
quot: "\"",
apos: "'",
});
/** The `name` of every `<testsuite>` (one per test file) in a JUnit report Vitest wrote. */
export function reportedSuiteNames(xml: string): string[] {
return [...xml.matchAll(/<testsuite name="([^"]*)"/gu)].map(([, name = ""]) =>
slashed(name.replace(/&(amp|lt|gt|quot|apos);/gu, (_, entity: string) => XML_ENTITIES[entity]!)));
}
export default class CoverageBundleJUnitReporter implements Reporter {
readonly #reports = COVERAGE_BUNDLE_REPORTS.map((report) => ({
...report,
junit: new JUnitReporter({ outputFile: report.outputFile }),
}));
#root = process.cwd();
async onInit(vitest: Vitest): Promise<void> {
this.#root = vitest.config.root;
for (const { junit } of this.#reports) await junit.onInit(vitest);
}
async onTestRunEnd(testModules: readonly TestModule[]): Promise<void> {
const problems: string[] = [];
for (const { directory, outputFile, junit } of this.#reports) {
const own = bundleModules(testModules, directory);
if (own.length === 0) {
problems.push(
`No test file of ${directory} ran, so ${outputFile} has no test (FE-4). ` +
"FE-GATE-005 runs it only in test:coverage; keep it in that script's paths (package.json).",
);
}
await junit.onTestRunEnd(own);
const expected = own.map(({ relativeModuleId }) => slashed(relativeModuleId)).sort();
const reported = await readFile(path.resolve(this.#root, outputFile), "utf8").then(
(xml) => reportedSuiteNames(xml).sort(),
() => undefined,
);
if (JSON.stringify(reported) !== JSON.stringify(expected)) {
const found = reported === undefined
? "It could not be read."
: `It lists ${reported.length}. Not run here: ${firstFew(reported.filter((file) => !expected.includes(file)))}. ` +
`Ran but missing: ${firstFew(expected.filter((file) => !reported.includes(file)))}.`;
problems.push(
`${outputFile} does not list exactly the ${expected.length} test file(s) of ${directory} that ran (FE-4). ` +
`${found} Check scripts/lib/coverage-bundle-junit-reporter.ts against Vitest's JUnit reporter.`,
);
}
}
if (problems.length === 0) return;
process.exitCode = 1;
process.stderr.write(["", ...problems, ""].join("\n"));
}
}