Files
clean-architecture-frontend…/tests/unit/v8-coverage-counter-semantics.test.ts
T
DongHyeonka 0c3c9d3351
frontend-quality-gates / merge / static checks (pull_request) Canceled after 0s
frontend-quality-gates / merge / tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / browser tests (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Canceled after 0s
frontend-quality-gates / external-vulnerability-provider (pull_request) Canceled after 0s
frontend-quality-gates / external-provenance-provider (pull_request) Canceled after 0s
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Canceled after 0s
frontend-quality-gates / deploy-promoted-release (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Canceled after 0s
frontend-quality-gates / main / checker self-tests (pull_request) Canceled after 0s
fix(coverage): 위험 커버리지가 "use strict" 밖의 지시문을 문장으로 센다
문제: 0bb1f0af에서 모듈을 Babel AST로 읽게 바꾼 뒤, 파일 맨 위의
지시문(`"use client";`)을 세지 않는다. Babel은 지시문을
`program.directives`에 두고 `body`에 넣지 않는다(ESTree 변환은 body에
넣었다). V8 coverage는 `"use client"`를 문장 1개로 세고 `"use strict"`는
세지 않는다(desktop에서 실제 V8 실행으로 확인). 그래서 지시문과 타입만
있는 모듈이 counterless로 분류되고 coverage에는 문장이 잡혀, 파생
프로젝트에서 risk-coverage가 거짓으로 실패한다. 지금 `src/`에는
지시문이 없어 375개 대조에서 보이지 않았다. 새 눈 리뷰(fe-testing
렌즈)가 찾았다.

고른 방법: `"use strict"`가 아닌 지시문이 있으면 counter-bearing이다.
check:v8-coverage-counter-semantics의 fixture에 지시문 모듈 둘
(`use client`는 counter-bearing, `use strict`는 counterless)을 더해,
분류기가 기대는 V8 동작을 실제 실행으로 고정한다. risk-coverage 시험도
같은 두 모듈을 분류한다.

위험·한계: 예전 분류(ESTree)는 `"use strict"`만 있는 모듈을
counter-bearing으로 봤다. 이제 V8과 같이 counterless다.

검증(desktop): risk-coverage·risk-coverage-files·counter-semantics 시험
통과, check:v8-coverage-counter-semantics PASS(2 counter-bearing,
8 counterless), check:types·eslint rc=0. 변이: 지시문 규칙을 빼면
「matches the observed V8 counterless …」가 `directive-use-client.ts`를
counterless로 받아 실패. 로그 /tmp/claude-gates/w2fe2-dir1·2·4/.

Fixes: 0bb1f0afc0 ("perf(coverage): 위험 커버리지 모듈 목록을 Babel 파서와 동기 fs로 만든다")
2026-11-12 22:45:48 +09:00

254 lines
8.4 KiB
TypeScript

import { execFile } from "node:child_process";
import {
access,
mkdtemp,
readFile,
rm,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import {
assertV8CoverageCounterSemantics,
checkV8CoverageCounterSemantics,
} from "../../scripts/lib/v8-coverage-counter-semantics.ts";
import { rootAnchoredGlobs } from "../../scripts/lib/coverage-scope.ts";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
const roots: string[] = [];
const execFileAsync = promisify(execFile);
const zeroCounter = Object.freeze({
total: 0,
covered: 0,
skipped: 0,
pct: 100,
});
const zeroMetrics = Object.freeze({
lines: zeroCounter,
statements: zeroCounter,
functions: zeroCounter,
branches: zeroCounter,
});
const counterlessPaths = Object.freeze([
"src/directive-use-strict.ts",
"src/import-empty.ts",
"src/import-side-effect.ts",
"src/import-type-empty.ts",
"src/import-value.ts",
"src/reexport-named.ts",
"src/reexport-star.ts",
"src/type-only.ts",
]);
function fixtureSummary(root: string): Record<string, unknown> {
return Object.fromEntries([
[
"total",
{
lines: { total: 1, covered: 1, skipped: 0, pct: 100 },
statements: { total: 1, covered: 1, skipped: 0, pct: 100 },
functions: zeroCounter,
branches: zeroCounter,
},
],
...["src/directive-use-client.ts", "src/runtime.ts"].map((modulePath) => [
path.join(root, modulePath),
{
lines: { total: 1, covered: 1, skipped: 0, pct: 100 },
statements: { total: 1, covered: 1, skipped: 0, pct: 100 },
functions: zeroCounter,
branches: zeroCounter,
},
]),
...counterlessPaths.map((modulePath) => [path.join(root, modulePath), zeroMetrics]),
]);
}
async function captureFailure(operation: Promise<unknown>): Promise<Error> {
try {
await operation;
} catch (error) {
if (error instanceof Error) return error;
throw error;
}
throw new Error("expected operation to fail");
}
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
describe("V8 coverage counter semantics", () => {
it("accepts one counter-bearing row and seven exact counterless rows", () => {
const root = "/owned-fixture";
expect(assertV8CoverageCounterSemantics(fixtureSummary(root), root)).toEqual({
counterBearingModules: ["src/directive-use-client.ts", "src/runtime.ts"],
counterlessModules: counterlessPaths,
});
});
it("rejects a missing or additional producer row", () => {
const root = "/owned-fixture";
const missing = fixtureSummary(root);
delete missing[path.join(root, "src/import-empty.ts")];
expect(() => assertV8CoverageCounterSemantics(missing, root)).toThrow(
/row set.*missing.*import-empty/u,
);
const additional = fixtureSummary(root);
additional[path.join(root, "src/unexpected.ts")] = zeroMetrics;
expect(() => assertV8CoverageCounterSemantics(additional, root)).toThrow(
/row set.*additional.*unexpected/u,
);
});
it("rejects counterless nonzero and runtime all-zero drift", () => {
const root = "/owned-fixture";
const counterlessDrift = fixtureSummary(root);
counterlessDrift[path.join(root, "src/import-value.ts")] = {
...zeroMetrics,
lines: { total: 1, covered: 1, skipped: 0, pct: 100 },
};
expect(() =>
assertV8CoverageCounterSemantics(counterlessDrift, root),
).toThrow(/counterless.*exact all-zero.*import-value/u);
const runtimeDrift = fixtureSummary(root);
runtimeDrift[path.join(root, "src/runtime.ts")] = zeroMetrics;
expect(() => assertV8CoverageCounterSemantics(runtimeDrift, root)).toThrow(
/not counter-bearing: src\/runtime\.ts/u,
);
const directiveDrift = fixtureSummary(root);
directiveDrift[path.join(root, "src/directive-use-client.ts")] = zeroMetrics;
expect(() => assertV8CoverageCounterSemantics(directiveDrift, root)).toThrow(
/not counter-bearing: src\/directive-use-client\.ts/u,
);
});
it("rejects producer percentages that do not exactly match their counts", () => {
const root = "/owned-fixture";
const totalDrift = fixtureSummary(root);
totalDrift["total"] = {
...totalDrift["total"] as Record<string, unknown>,
lines: { total: 1, covered: 1, skipped: 0, pct: -500 },
};
expect(() => assertV8CoverageCounterSemantics(totalDrift, root)).toThrow(
/total\.lines.*invalid coverage counters/u,
);
const runtimeDrift = fixtureSummary(root);
runtimeDrift[path.join(root, "src/runtime.ts")] = {
...runtimeDrift[path.join(root, "src/runtime.ts")] as Record<
string,
unknown
>,
lines: { total: 1, covered: 1, skipped: 0, pct: 99.99 },
};
expect(() => assertV8CoverageCounterSemantics(runtimeDrift, root)).toThrow(
/runtime.*lines.*invalid coverage counters/u,
);
});
it("bounds child diagnostics and cleans its owned root on child exit", async () => {
const ownedRoot = await mkdtemp(path.join(tmpdir(), "v8-counter-exit-"));
roots.push(ownedRoot);
const childFailure = Object.assign(new Error("child exit 1"), {
stdout: "o".repeat(20_000),
stderr: "e".repeat(20_000),
});
const failure = await captureFailure(
checkV8CoverageCounterSemantics({
repositoryRoot: process.cwd(),
createOwnedRoot: async () => ownedRoot,
runVitest: async () => Promise.reject(childFailure),
}),
);
expect(failure.message).toMatch(/child Vitest failed/u);
expect(failure.message).toMatch(/truncated/u);
expect(failure.message.length).toBeLessThan(5_000);
await expect(access(ownedRoot)).rejects.toMatchObject({ code: "ENOENT" });
});
it("fails closed on a missing summary and cleans its owned root", async () => {
const ownedRoot = await mkdtemp(path.join(tmpdir(), "v8-counter-summary-"));
roots.push(ownedRoot);
await expect(
checkV8CoverageCounterSemantics({
repositoryRoot: process.cwd(),
createOwnedRoot: async () => ownedRoot,
runVitest: async () => ({ stdout: "", stderr: "" }),
}),
).rejects.toThrow(/coverage summary is missing/u);
await expect(access(ownedRoot)).rejects.toMatchObject({ code: "ENOENT" });
});
it("copies the fixture under a src-suffixed folder with root-anchored patterns", async () => {
const ownedRoot = await mkdtemp(path.join(tmpdir(), "v8-counter-scope-"));
roots.push(ownedRoot);
let child: { fixtureRoot: string; config: string } | undefined;
await expect(
checkV8CoverageCounterSemantics({
repositoryRoot: process.cwd(),
createOwnedRoot: async () => ownedRoot,
runVitest: async (input) => {
child = {
fixtureRoot: input.fixtureRoot,
config: await readFile(input.configPath, "utf8"),
};
await access(path.join(input.fixtureRoot, "outside-src.ts"));
return { stdout: "", stderr: "" };
},
}),
).rejects.toThrow(/coverage summary is missing/u);
expect(child?.fixtureRoot.startsWith(`${ownedRoot}${path.sep}`)).toBe(true);
expect(path.basename(child?.fixtureRoot ?? "")).toMatch(/[()].*src$/u);
const config = JSON.parse(
(child?.config ?? "").replace(/^export default /u, "").replace(/;\s*$/u, ""),
) as { test: { coverage: { include: string[] } } };
expect(config.test.coverage.include).toEqual(
rootAnchoredGlobs(child?.fixtureRoot ?? "", ["src/**/*.ts"]),
);
});
it("keeps the child fixture outside main Vitest discovery", async () => {
const outputRoot = await mkdtemp(path.join(tmpdir(), "v8-counter-list-"));
roots.push(outputRoot);
const outputPath = path.join(outputRoot, "listed.json");
await execFileAsync(
process.execPath,
[
path.join(process.cwd(), "node_modules/vitest/vitest.mjs"),
"list",
"tests/fixtures/v8-coverage-counter-semantics",
"--config",
path.join(process.cwd(), "vitest.config.ts"),
"--filesOnly",
"--passWithNoTests",
"--json",
outputPath,
"--no-color",
],
{
cwd: process.cwd(),
encoding: "utf8",
timeout: 30_000,
maxBuffer: 256 * 1024,
},
);
expect(JSON.parse(await readFile(outputPath, "utf8"))).toEqual([]);
}, childProcessTimeout(1_104));
});