ci(gates): FE-GATE-005가 unit·contract 시험을 coverage 실행에서 한 번만 돈다 #76

Merged
donghyeon.kang merged 2 commits from donghyeon.kang/ci/tests-run-once AGit into main 2026-11-20 10:55:51 +00:00
15 changed files with 334 additions and 27 deletions
+1 -1
View File
@@ -56,7 +56,7 @@ paths:
pnpm·브라우저는 desktop에서만 돈다(`docs/work/operate.md` 4.1절). 노트북에서는 `scripts/verify.sh`로 보낸다.
- 작업 중: `scripts/verify.sh exec -- node scripts/run-vitest.ts run <파일>`, 브라우저 spec 하나는 `scripts/verify.sh exec -- corepack pnpm exec playwright test <spec>`
- 층별 게이트: FE-GATE-004(runtime-schema), FE-GATE-005(unit·contract·coverage·scale pr), FE-GATE-006(component), FE-GATE-007(integration·HTTP 시나리오 증거·recipes), FE-GATE-008(e2e·browser-capabilities·storybook·visual·시험 증거), FE-GATE-009(a11y). 예: `scripts/verify.sh gate FE-GATE-006`
- 층별 게이트: FE-GATE-004(runtime-schema), FE-GATE-005(coverage 한 번이 unit·contract도 돈다, scale pr), FE-GATE-006(component), FE-GATE-007(integration·HTTP 시나리오 증거·recipes), FE-GATE-008(e2e·browser-capabilities·storybook·visual·시험 증거), FE-GATE-009(a11y). 예: `scripts/verify.sh gate FE-GATE-006`
- FE-GATE-013(system)은 `scripts/verify.sh`가 시스템 컨테이너(`scripts/run-in-system-container.sh`) 안에서 돌린다. 컨테이너를 띄울 수 없는 호스트에서만 `docs/work/reference/gates.md` 3절 조건과 문구로 적는다.
- 시험 기반 자체(음성 fixture가 정해진 오류로 실패해야 통과, `check:ci:gating`): `scripts/verify.sh gate FE-GATE-029`
- 커밋 전 묶음은 `docs/work/reference/gates.md` 2절 표, merge 가능 판정은 `scripts/verify.sh merge`.
+2
View File
@@ -23,6 +23,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
- devDependencies에서 `dependency-cruiser`가 빠진다. 그 CLI를 따로 쓰고 있었으면 다시 더한다.
- 선택 runtime 제거 드릴 셋이 merge의 FE-GATE-020에서 main 단계의 새 게이트 FE-GATE-030으로 옮는다. main job 이름이 `main / self-tests and removal drills`로 바뀐다. 그 이름을 필수 검사로 걸었으면 바꾼다. 선택 runtime을 바꾸는 PR은 `scripts/verify.sh gate FE-GATE-030`을 직접 돌린다.
- merge job 셋과 main job(`main / self-tests and removal drills`)이 runner의 actions/cache 저장소에서 Node·corepack·pnpm store와 메타데이터 캐시를 복원하고, main run만 저장한다. runner에 캐시 서버가 없으면 복원 단계가 경고만 내고 설치가 그대로 돈다. 자기 runner의 캐시 크기 상한을 확인한다(항목 하나가 압축 전 약 0.7GB, lockfile이 바뀔 때마다 새 항목).
- FE-GATE-005가 `test:unit`·`test:contract`를 따로 돌지 않는다. `tests/unit`·`tests/contract`는 `test:coverage`에서 한 번 돌고, 같은 실행이 `artifacts/tests/unit.xml`·`contract.xml`을 쓴다(`scripts/lib/coverage-bundle-junit-reporter.ts`). 계약에서 command `test-unit`·`test-contract`가 빠진다. 자기 `config/ci/gates.json`의 게이트가 그 id를 부르면 지운다. `test:coverage`의 경로에서 두 폴더 중 하나를 빼거나 그 reporter를 빼면 FE-GATE-005가 실패한다. 두 package script는 작업 중에 쓰는 명령으로 남는다.
- 수동 접근성 기록(`docs/accessibility/route-reviews/`)에 WCAG 2.2 칸 둘이 생기고, `Release ID`를 릴리스 태그와 대조한다.
- 옮기기 전: 자기 기록에 `M8`·`M9` 줄이 없으면 FE-GATE-009 형식 검사가 그 필드 이름을 대며 실패한다. release 단계를 태그 없이(브랜치에서 수동으로) 돌리면 FE-GATE-028이 `missing required environment: RELEASE_TAG`로 멈춘다.
- 옮기는 법: 기록마다 `M8 Focus not obscured: pending`, `M9 Target size: pending` 두 줄을 더한다. 서명하는 기록의 `Release ID`는 다음 release부터 그 릴리스 태그(예 `v1.4.0`)로 적는다. release 단계는 태그 run에서 돈다.
@@ -107,6 +108,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
| [계약] | 브라우저 job 컨테이너가 `--shm-size=2g`로 뜨고, Firefox 시험 프로필을 RAM 파일시스템(`/dev/shm`)에 둔다. Firefox가 시험 context의 저장소를 디스크 프로필에 두어, 디스크가 붐비면 첫 화면 5초 대기를 넘겼다. 자리가 모자라면 디스크 프로필로 돌고 이유를 한 줄 찍는다 | `scripts/generate-ci-workflow.ts`, `.gitea/workflows/quality-gates.yml`, `tests/support/browser/browser-test.ts`, `docs/operations/ci-quality-gates.md` | `f81dda49`, `c239bdf4` |
| [계약] | FE-GATE-008의 `test:e2e`가 이름에 `@a11y`가 붙은 시험을 빼고 돈다(`playwright test --grep-invert @a11y`). 그 시험은 FE-GATE-009의 `test:a11y`만 돈다. 두 실행은 같은 Playwright 설정이라 project(세 엔진)도 같다. FE-GATE-008만 돌리면 axe 스캔과 생성 기능 목록의 빈·오류 상태 화면은 돌지 않는다. 제품이 e2e spec에 `@a11y`를 붙인 시험도 009에서만 돈다. 시험 둘이 두 script의 짝과 PR 경로표의 008·009 짝을 지킨다. round9 R9-D11을 바꾼다(decisions.md FE-6) | `package.json`, `tests/unit/ci-workflow-generation.test.ts`, `tests/unit/pr-gate-selection.test.ts`, `docs/work/reference/decisions.md`, `docs/testing/taxonomy.md`, `.claude/skills/fe-qa/SKILL.md` | `d254d70a` |
| [계약] | `dependency-cache` 단계를 main job(`main_gate`)에도 둔다. 키·경로·main run만 저장·frozen install은 merge job과 같다. release·promotion·provider job은 그대로 거절한다. 위 `7ed0af3d` 행의 「merge job 셋에만」을 바꾼다(decisions.md FE-7) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `.gitea/workflows/quality-gates.yml`, `tests/unit/ci-workflow-generation.test.ts`, `docs/operations/ci-quality-gates.md` | `d254d70a` |
| [계약] | FE-GATE-005의 명령이 `test:coverage`·`check:scale:pr` 둘이 된다. `tests/unit`·`tests/contract`의 JUnit 증거(`unit.xml`·`contract.xml`, 이름·형식 그대로)는 coverage 실행 안의 reporter가 쓰고, 두 증거의 producer는 `test-coverage`다. 한 폴더에서 시험 파일이 하나도 돌지 않거나 보고서가 그 폴더에서 돈 파일과 다른 파일을 담으면 그 실행이 실패한다. unit·contract 시험은 이제 coverage 계측 아래에서만 돈다. FE-GATE-004·006·007은 자기 실행을 그대로 둔다(decisions.md FE-4) | `config/ci/gates.json`, `package.json`, `scripts/lib/coverage-bundle-junit-reporter.ts`, `scripts/lib/feature-scaffold-drill.ts`, `tests/unit/coverage-bundle-junit-reporter.test.ts`, `docs/operations/ci-quality-gates.md` | `6cba1f50` |
### 그 밖의 변경
+2 -14
View File
@@ -32,16 +32,6 @@
"script": "test:runtime-schema",
"expect": "pass"
},
{
"id": "test-unit",
"script": "test:unit",
"expect": "pass"
},
{
"id": "test-contract",
"script": "test:contract",
"expect": "pass"
},
{
"id": "test-coverage",
"script": "test:coverage",
@@ -755,7 +745,7 @@
"schemaId": "junit",
"production": "command-generated",
"producerCommandIds": [
"test-unit"
"test-coverage"
]
},
{
@@ -764,7 +754,7 @@
"schemaId": "junit",
"production": "command-generated",
"producerCommandIds": [
"test-contract"
"test-coverage"
]
},
{
@@ -1642,8 +1632,6 @@
"id": "FE-GATE-005",
"name": "unit",
"commandIds": [
"test-unit",
"test-contract",
"test-coverage",
"check-scale-pr"
],
+1 -1
View File
@@ -153,7 +153,7 @@ node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write
## 이 명령을 지키는 검사
- `tests/unit/create-feature.test.ts` (`test:unit`, FE-GATE-005)
- `tests/unit/create-feature.test.ts` (`test:coverage`, FE-GATE-005)
- 렌더 결과만 본다. 저장소를 건드리지 않는다.
- 접두어, 예전 참조 샘플 이름이 없음, topic 형식과 충돌, `navigationOrder`, 거부 조건, 덮어쓰기 거부와 되돌리기.
- 백엔드 경로 규칙, `--with-create`·`--keyed`의 descriptor 값, 모든 operation의 Envelope 선언.
+8 -1
View File
@@ -505,6 +505,13 @@ FE-RB-005 drill을 돌렸으므로 폐기했다(`scripts/contracts/ci-gates.ts`
실행한다. 그래서 route 동작, reflow, 기본 dialog 동작, theme 유지, 자동 접근성 검사는
Chromium에서만 보는 smoke check가 아니라 엔진 전체에 걸친 계약이 된다.
`FE-GATE-005`는 `tests/unit`·`tests/contract`를 `test:coverage`에서 한 번만 돈다.
같은 실행에서 `scripts/lib/coverage-bundle-junit-reporter.ts`가 두 폴더의 결과를
`artifacts/tests/unit.xml`·`contract.xml`로 쓴다(2026-11-20 FE-4, 총괄). 그 전에는
`test:unit`·`test:contract`가 같은 파일을 한 번 더 돌았다. 두 script는 작업 중에
쓰는 명령으로 남고 게이트는 부르지 않는다. 두 폴더 중 하나라도 시험 파일이 하나도
돌지 않거나, 쓴 보고서가 그 폴더에서 돈 파일과 다른 파일을 담으면 그 실행이 실패한다.
`FE-GATE-005`의 unit suite에는 client cache/storage의 deterministic contract가
포함된다. `storage-registry.test.ts`는 key별 codec, schema/TTL, 16,384-byte
상한, quota/security/corrupt cleanup과 memory fallback을,
@@ -512,7 +519,7 @@ Chromium에서만 보는 smoke check가 아니라 엔진 전체에 걸친 계약
self/duplicate/out-of-order/gap, BroadcastChannel → localStorage → local-only
degrade와 cleanup을 검증한다. `tanstack-cache-coordinator.test.ts`는 topic을
local namespace로만 resolve하고 query key/data를 wire에 보내지 않으며 mutation
중 remote hint를 coalesce하는지 검증한다. 결과는 기존
중 remote hint를 coalesce하는지 검증한다. 결과는
`artifacts/tests/unit.xml`과 coverage evidence에 포함된다.
`FE-GATE-006`과 runtime adapter unit은
+1 -1
View File
@@ -39,7 +39,7 @@
- `scripts/contracts/release-artifacts.ts`의 스키마
- 생성 workflow와 ci-workflow-generation 스냅샷
- CI 계약 기준선(승인자·사유). 2026-11-08에 지웠다
- **실패를 보고하는 게이트가 바뀐다**: `tests/unit`은 test:unit과 test:coverage(FE-GATE-005)에서 돈다. `tests/architecture`는 test:coverage에서만 돈다(package.json:51,82). 따라서 FE-GATE-010·013에 있던 확인을 테스트로 옮기면 그 게이트 로그에서 빠지고 FE-GATE-005로 간다.
- **실패를 보고하는 게이트가 바뀐다**: `tests/unit`은 merge 단계에서 test:coverage(FE-GATE-005)에서만 돈다(2026-11-20 FE-4 전에는 test:unit에서도 돌았다). `tests/architecture`는 test:coverage에서만 돈다(package.json:51,82). 따라서 FE-GATE-010·013에 있던 확인을 테스트로 옮기면 그 게이트 로그에서 빠지고 FE-GATE-005로 간다.
- **ESLint 설정**: flat config는 같은 규칙 이름의 옵션을 합치지 않고 덮어쓴다(`eslint.config.ts:909-910` 주석). 새 금지 규칙을 레이어별 `no-restricted-*` 옵션에 끼워 넣으면 서로 덮어쓴다. `build-env/*`, `browser-data-boundary/*`처럼 로컬 규칙 이름으로 따로 둔다. 또 금지 fixture는 ignores(`:500-511`)에 걸린다. 테스트에서는 `new ESLint({ ignore: false })`를 쓰거나 `lintText(source, { filePath })`에 가상 경로를 줘서 돌린다.
- **script 이름을 부르는 곳**: 삭제 드릴과 스케일 검증이 package script를 이름으로 부른다. 옮길 때 이 목록도 같이 고친다.
- `test-sample-removal.ts:475-482`
+2 -2
View File
@@ -8,8 +8,8 @@ script로 낮추지 않는다.
| 단계 | 명령 | 담당 범위 / 전제 조건 | 증거 |
| --- | --- | --- | --- |
| runtime schema | `pnpm test:runtime-schema` | 순수 runtime schema 계약 | `artifacts/tests/runtime-schema.xml` |
| unit | `pnpm test:unit` | Node만 쓰는 domain·application·순수 정책·runtime 단위. systemd·bwrap·cgroup 전제 조건 없음 | `artifacts/tests/unit.xml` |
| capability contract | `pnpm test:contract` | 재사용하는 capability의 소비자 계약 | `artifacts/tests/contract.xml` |
| unit | `pnpm test:unit` | Node만 쓰는 domain·application·순수 정책·runtime 단위. systemd·bwrap·cgroup 전제 조건 없음. CI(FE-GATE-005)에서는 `test:coverage`가 이 폴더를 돈다 | `artifacts/tests/unit.xml`(CI에서는 `test:coverage`의 같은 실행이 쓴다) |
| capability contract | `pnpm test:contract` | 재사용하는 capability의 소비자 계약. CI(FE-GATE-005)에서는 `test:coverage`가 이 폴더를 돈다 | `artifacts/tests/contract.xml`(CI에서는 `test:coverage`의 같은 실행이 쓴다) |
| component | `pnpm test:component` | React·hook·UI 동작 | `artifacts/tests/component.xml` |
| integration | `pnpm test:integration` | HTTP/MSW, IndexedDB, 조립된 browser-runtime 경계, 자식 프로세스·파일 시스템·IPC 통합 | `artifacts/tests/integration.xml` |
| system / CI runner | `pnpm test:system` | systemd, bubblewrap, cgroup v2, CI provider 프로세스 통제를 갖춘 호환 Linux host. 그 host에서 bubblewrap이 권한 없는 user namespace와 network namespace를 만들 수 있어야 한다. CI와 `scripts/verify.sh`는 FE-GATE-013을 `scripts/run-in-system-container.sh`가 띄우는 컨테이너 안에서 돌린다 | `artifacts/tests/system.xml` |
+1
View File
@@ -75,6 +75,7 @@
| PR은 바뀐 범위의 merge 게이트만 | 2026-11-13 | PR run의 merge job은 `config/ci/pr-gate-selection.json` 경로표로 바뀐 파일이 닿는 게이트만 돌고, 안 도는 게이트는 `건너뜀: <게이트 ID> — <이유>` 한 줄을 남긴다. 전역 파일·표에 없는 파일·빈 diff·diff를 못 읽음이면 전부 돈다. main·release run은 늘 전부 돈다. 판정은 `scripts/lib/pr-gate-selection.ts`, 계약 시험은 `tests/unit/pr-gate-selection.test.ts`다 | 소유자 결정(2026-11-13 18:3x, design-docs `ci/manual.md` 4절). PR 경로표가 놓친 것은 main이 잡는다. main push에서 선택 때문에 놓친 실패가 나오면 경로표를 고친다 |
| FE-6 `@a11y` 시험은 FE-GATE-009에서만 | 2026-11-20 | round9 R9-D11을 바꾼다. FE-GATE-008의 `test:e2e`는 이름에 `@a11y`가 붙은 시험을 빼고(`--grep-invert @a11y`) 돈다. 그 시험은 FE-GATE-009의 `test:a11y`가 자기 실행으로 돈다. 두 실행은 같은 Playwright 설정을 써서, 그 시험이 도는 project(chromium·firefox·webkit)도 같다. 전제(게이트마다 증거를 새로 만든다)는 그대로다. 버린 안(FE-GATE-009가 FE-GATE-008 결과를 읽기)도 계속 버린다. 이유: merge browser job이 같은 `@a11y` 시험 33개를 두 번 돌았다. 대가: FE-GATE-008만 돌리면 `@a11y` 시험(axe 스캔, 생성 기능 목록의 빈·오류 상태 화면)은 돌지 않는다 | 총괄(2026-11-20): 소유자 2026-11-19 CI 속도 지시, design-docs `ci/06-frontend-ci-speed-handoff.md` 4.1절 |
| FE-7 main job도 의존성 캐시 | 2026-11-20 | 2026-11-13 「의존성 캐시는 merge job만」을 바꾼다. main job(`main_gate`, FE-GATE-029·030)도 merge job 셋과 같은 키·경로로 캐시를 복원한다. 저장은 그대로 main run만 하고, 설치는 그대로 `--frozen-lockfile`이다. release·promotion·provider job은 그대로 매번 새로 설치한다. 이유: main job만 install이 15~24초였다(merge job은 1~2초). main job은 공급망 증거를 만들지 않는다 | 총괄(2026-11-20): design-docs `ci/06-frontend-ci-speed-handoff.md` 4.2절 |
| FE-4 005 안 일반 실행 빼기 | 2026-11-20 | FE-GATE-005는 `tests/unit`·`tests/contract`를 `test:coverage`에서 한 번만 돈다. `test:unit`·`test:contract` 명령을 게이트에서 빼고, 같은 coverage 실행에서 `scripts/lib/coverage-bundle-junit-reporter.ts`가 `artifacts/tests/unit.xml`·`contract.xml`을 쓴다. 증거 이름과 게이트 ID는 그대로이고, 두 증거는 FE-GATE-005의 명령이 그 실행 중에 새로 만든다. 전제(게이트마다 증거를 새로 만든다)는 그대로다. 버린 안: coverage 실행 한 번이 FE-GATE-004·006·007의 증거까지 내기(design-docs `ci/04-…` R-3 (가), 약 −1:30). 그 세 게이트가 FE-GATE-005의 결과를 읽게 되어 FE-6에서 버린 꼴과 같다: coverage 실행이 죽으면 세 게이트도 판정을 못 내고, 혼자 돌릴 수 없다. 004는 005보다 앞이라 차례도 바꿔야 했다. 이유: FE-GATE-005 안에서 같은 시험 파일을 두 번 돌았다(약 0:57). 대가: unit·contract 시험은 이제 coverage 계측 아래에서만 돈다. 시간에 기대는 시험이 가려질 수 있다. 004·006·007의 묶음은 coverage에서 한 번 더 돈다(약 0:33). 재검토: coverage 실행에서 안 보이고 일반 실행에서만 보이는 unit·contract 실패가 나오면 일반 실행을 되돌린다. Vitest를 올릴 때는 reporter가 그 JUnit reporter에 기대므로 분할한 보고서를 일반 실행과 다시 대조한다 | 총괄(2026-11-20): 소유자 2026-11-19 CI 속도 지시, design-docs `ci/06-frontend-ci-speed-handoff.md` 4.3·6.2절 |
| 구조·기술 결정 기록 | 2026-07-26~ | `VD-01`~(빈 번호 있음) | `docs/adr/` |
## 3. 결정 대기 쓰는 법
+1 -1
View File
@@ -63,7 +63,7 @@
"test:browser-file-storage-removal": "node scripts/test-browser-file-storage-runtime-removal.ts",
"test:realtime-removal": "node scripts/test-realtime-runtime-removal.ts",
"check:v8-coverage-counter-semantics": "node scripts/check-v8-coverage-counter-semantics.ts",
"test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && node scripts/run-vitest.ts run tests/runtime-schema tests/unit tests/contract tests/component tests/integration tests/features tests/platform tests/architecture tests/release tests/scripts tests/scale/browser-soak.contract.test.ts --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts",
"test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && node scripts/run-vitest.ts run tests/runtime-schema tests/unit tests/contract tests/component tests/integration tests/features tests/platform tests/architecture tests/release tests/scripts tests/scale/browser-soak.contract.test.ts --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml --reporter=./scripts/lib/coverage-bundle-junit-reporter.ts && node scripts/check-risk-coverage.ts",
"check:coverage:fixture": "node scripts/check-risk-coverage.ts --summary tests/fixtures/coverage/below-threshold.json --artifact artifacts/quality/risk-coverage-fixture.json",
"test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:contract && corepack pnpm test:component && corepack pnpm test:integration && node scripts/run-vitest.ts run tests/features tests/scripts tests/scale/browser-soak.contract.test.ts --reporter=default && corepack pnpm test:platform && corepack pnpm check:release-coherence && corepack pnpm test:recipes",
"verify:lockfile": "corepack pnpm install --frozen-lockfile --ignore-scripts",
@@ -0,0 +1,100 @@
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"));
}
}
+2 -2
View File
@@ -26,14 +26,14 @@ const DRILL =
* The drill runs FE-GATE-005's test:coverage in the same copy, and its paths
* hold every path of these suites (tests/unit/removal-drill-test-paths.test.ts).
* Running them plain as well found nothing more and cost about 80 s a drill.
* tests/unit and tests/contract are not here: the merge stage runs them only in
* test:coverage (FE-4, scripts/lib/coverage-bundle-junit-reporter.ts).
*/
const COVERED =
"test:coverage runs the same test files in this copy " +
"(tests/unit/removal-drill-test-paths.test.ts checks the paths).";
export const SCAFFOLD_DRILL_COVERED_SUITES: readonly string[] = Object.freeze([
"test:runtime-schema",
"test:unit",
"test:contract",
"test:component",
"test:integration",
]);
+1 -1
View File
@@ -12,5 +12,5 @@
## 검사
- 판정은 `check:architecture`(FE-GATE-010)다. 편집 직후 훅(N3)이 이 폴더 파일의 import를 같은 규칙에 대 본다.
- `test:unit`(FE-GATE-005)
- `test:coverage`(FE-GATE-005). 작업 중에는 `test:unit`으로 `tests/unit`만 돌린다
- 돌리는 곳은 desktop이다(`scripts/verify.sh`). 테스트는 `tests/unit`, 포트 소비자 계약은 `tests/contract`에 둔다(`.claude/rules/tests.md`).
+1 -1
View File
@@ -11,5 +11,5 @@
## 검사
- 판정은 `check:architecture`(FE-GATE-010)다. 편집 직후 훅(N3)이 이 폴더 파일의 import를 같은 규칙에 대 본다.
- `test:unit`(FE-GATE-005)
- `test:coverage`(FE-GATE-005). 작업 중에는 `test:unit`으로 `tests/unit`만 돌린다
- 돌리는 곳은 desktop이다(`scripts/verify.sh`). 테스트는 `tests/unit`에 둔다(`.claude/rules/tests.md`).
@@ -0,0 +1,208 @@
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&amp;b.test.ts" timestamp="x" tests="1">',
' <testcase classname="tests/unit/a&amp;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"]);
}
});
});
+3 -2
View File
@@ -27,8 +27,9 @@ describe("feature scaffold drill commands", () => {
commandId,
).toBe(true);
}
// test:unit, test:contract and the other plain suites run inside
// test:coverage (tests/unit/removal-drill-test-paths.test.ts).
// The plain suites the merge stage still runs (runtime-schema, component,
// integration) run inside test:coverage
// (tests/unit/removal-drill-test-paths.test.ts).
expect(commands.map(({ script }) => script)).toEqual(expect.arrayContaining([
"check:types", "lint", "test:coverage", "build", "check:bundle",
"check:request-fanout", "build:release-candidate",