문제: FE-GATE-029(check:ci:gating)는 게이트가 닿는 `playwright test` 실행마다 설정의 testDir을 gated로 셌고, `--grep`·`--grep-invert`·파일 필터를 읽지 않았다. FE-GATE-009의 test:a11y에서 Playwright 실행을 빼도 029는 통과했다. test:e2e(FE-GATE-008)가 tests/e2e를 `--grep-invert @a11y`로 돌기 때문에, 시험이 모두 @a11y인 tests/e2e/accessibility.spec.ts는 어느 게이트에서도 돌지 않는다. 설정도 `--config X`만 읽어서 `-c X`·`--config=X` 실행은 e2e 설정의 testDir로 셌다. result-paths 시험은 세 꼴을 따로 읽고 있었다. 고른 방법: 시험 본문이 아니라 게이트가 도는 인자만 본다. testDir 하나는 필터 없는 gated 실행이 있거나, `--grep-invert P` 실행마다 같은 testDir을 `--grep P`(같은 글자)로 도는 gated 실행이 있을 때만 gated다. 파일 필터가 있는 실행, `--grep`·`--grep-invert`를 합쳐 둘 이상 쓴 실행, 설정(또는 그 설정이 상대 경로로 import한 설정)의 글자에 `grep`·`grepInvert` 속성이 있는 실행은 나누지 않는 부분 실행으로 센다. 그런 testDir 아래 게이트 밖 파일은 testDir 한 줄로 알린다: testDir, 실행과 그 script, 빠진 짝. 인자 parser는 `scripts/lib/playwright-test-args.ts` 하나로 두고 029와 result-paths 시험이 같이 쓴다. `docs/operations/ci-quality-gates.md`의 029 설명에 이 규칙을 적는다. 버린 안: - `playwright test --list --reporter=json`으로 Playwright에 묻기: 시험 파일을 in-process로 불러 생성물(`src/features/*` 색인)에 기대고, 실행마다 수 초가 든다. - Babel로 시험 파일을 읽어 Playwright grep 판정을 흉내 내기: 제목 경로, 태그, forceRegExp 같은 Playwright 1.62 내부 규칙을 템플릿 안에 다시 만든다. 버전에 묶이고, 템플릿 리터럴 제목 때문에 파생 서비스에서 거짓 실패가 난다. 위험·한계: 짝은 글자로만 맞춘다. 정규식으로 같은 뜻이라도 글자가 다르면 실패한다(실패 쪽). 모르는 옵션 뒤 맨 토큰은 파일 필터로 센다(실패 쪽). `--project=X`·`--shard=X`처럼 `=`로 붙인 다른 옵션과 설정의 testMatch· testIgnore는 읽지 않는다. 필터는 package script 글자에서만 읽어, 게이트 계약의 `args`로 붙는 인자는 보지 않는다(전에도 읽지 않았다). Playwright 설정 파일의 주석에 `grep:` 꼴을 쓰면 부분 실행으로 센다. 검증: 고치기 전 desktop에서 009의 실행을 뺀 변이로 FE-GATE-029 rc=0, 새 단위 시험 17개 실패(변이 저장소에서 tests/e2e를 셈, -c·--config= 못 읽음, 짝 없는 실행을 셈). 고친 뒤 단위 시험 3파일 61개 통과, 같은 변이에서 FE-GATE-029 rc=1 (「Playwright testDir tests/e2e is only partly run … has no gated `--grep @a11y` run to pair with」). 리뷰에서 나온 `-cX`·`-gP`·`-GP` 꼴: parser만 고치기 전으로 되돌린 변이에서 새 시험 4개 실패, 되돌리면 61개 통과. 확인 리뷰에서 나온 `-xGP` 꼴(값 없는 `-x` 뒤에 붙인 옵션)과 `--grep-invert`를 두 번 쓴 실행: 두 고침을 되돌린 변이에서 새 시험 6개 실패, 되돌리면 67개 통과.
255 lines
11 KiB
TypeScript
255 lines
11 KiB
TypeScript
import { readdir } from "node:fs/promises";
|
|
import path from "node:path";
|
|
|
|
import { z } from "zod";
|
|
|
|
import { SCALE_TIERS, type ScaleTier } from "../scale/run-scale-profile.ts";
|
|
import { reachablePackageScripts } from "./package-script-graph.ts";
|
|
import { type PlaywrightTestRun, playwrightTestRuns } from "./playwright-test-args.ts";
|
|
|
|
/**
|
|
* 12-04. A test file protects nothing unless a CI gate runs it. The gated set
|
|
* is read from the package scripts the CI contract's commands reach: Vitest
|
|
* path filters (`run-vitest.ts run <paths>`), the Vitest steps of a scale tier
|
|
* (`run-scale-profile.ts <tier>`) and Playwright config `testDir`s.
|
|
* A test outside that set needs a reasoned entry in config/ci/ungated-tests.json.
|
|
*
|
|
* fe-ci-next-12. A Playwright testDir is in the set only when the gates run all
|
|
* of it: one gated run has no `--grep`, `--grep-invert` or file filter, or each
|
|
* `--grep-invert P` run has a gated `--grep P` run (the same text P) of the
|
|
* same testDir. It reads the run's arguments, not the tests: matching titles
|
|
* and tags the way Playwright does would tie it to one Playwright version.
|
|
* A file filter, more than one `--grep` or `--grep-invert` in one run, or a
|
|
* config (or a config it imports) that sets `grep` or `grepInvert` makes a
|
|
* partial run it does not split.
|
|
*/
|
|
export const UNGATED_TESTS_PATH = "config/ci/ungated-tests.json";
|
|
|
|
const TEST_FILE = /\.(?:test|spec)\.tsx?$/u;
|
|
// vitest.config.ts includes only the `*.test.ts` and `*.test.tsx` files below tests.
|
|
const VITEST_TEST_FILE = /\.test\.tsx?$/u;
|
|
|
|
/**
|
|
* 0929/12-06. A gated path and the runner that reaches it. A Vitest path
|
|
* runs its `*.test.*` files only; a Playwright `testDir` runs what the
|
|
* Playwright default `testMatch` takes, `*.spec.*` and `*.test.*`.
|
|
*/
|
|
export type GatedTestTarget = Readonly<{ path: string; runner: "vitest" | "playwright" }>;
|
|
|
|
/** A `playwright test` run a gate command reaches, with the testDir its config names. */
|
|
export type GatedPlaywrightRun = PlaywrightTestRun &
|
|
Readonly<{ script: string; testDir: string | undefined; configSetsGrep: boolean }>;
|
|
|
|
/** A testDir the gates run only part of, and the runs that leave the rest out. */
|
|
export type PlaywrightTestDirGap = Readonly<{ testDir: string; runs: readonly string[] }>;
|
|
|
|
const ungatedTestsSchema = z
|
|
.object({
|
|
schemaVersion: z.literal(1),
|
|
entries: z.array(
|
|
z
|
|
.object({
|
|
path: z.string().regex(/^tests\/\S+$/u),
|
|
reason: z.string().trim().min(1, "exclusion reason is required"),
|
|
})
|
|
.strict(),
|
|
),
|
|
})
|
|
.strict();
|
|
|
|
export type UngatedTestExclusion = Readonly<{ path: string; reason: string }>;
|
|
|
|
export function parseUngatedTestExclusions(value: unknown): readonly UngatedTestExclusion[] {
|
|
return ungatedTestsSchema.parse(value).entries;
|
|
}
|
|
|
|
/** Repository-relative test files below tests/, fixtures excluded. */
|
|
export async function listTestFiles(root: string): Promise<string[]> {
|
|
const entries = await readdir(path.join(root, "tests"), { recursive: true, withFileTypes: true });
|
|
return entries
|
|
.filter((entry) => entry.isFile() && TEST_FILE.test(entry.name))
|
|
.map((entry) =>
|
|
path.relative(root, path.join(entry.parentPath, entry.name)).split(path.sep).join("/"),
|
|
)
|
|
.filter((file) => !file.startsWith("tests/fixtures/"))
|
|
.sort();
|
|
}
|
|
|
|
export function gatedTestPaths(
|
|
scripts: Readonly<Record<string, string>>,
|
|
entryScripts: readonly string[],
|
|
readConfig: (file: string) => string,
|
|
): string[] {
|
|
return [...new Set(gatedTestTargets(scripts, entryScripts, readConfig).map(({ path: target }) => target))].sort();
|
|
}
|
|
|
|
export function gatedTestTargets(
|
|
scripts: Readonly<Record<string, string>>,
|
|
entryScripts: readonly string[],
|
|
readConfig: (file: string) => string,
|
|
): GatedTestTarget[] {
|
|
const targets = new Map<string, GatedTestTarget>();
|
|
const add = (target: string, runner: GatedTestTarget["runner"]) => {
|
|
const normalized = target.replace(/\/$/u, "");
|
|
targets.set(`${runner} ${normalized}`, { path: normalized, runner });
|
|
};
|
|
const addVitestPaths = (tokens: readonly string[]) => {
|
|
const vitestRun = tokens.findIndex(
|
|
(token, index) => token === "run" && /(?:run-vitest\.ts|vitest)$/u.test(tokens[index - 1] ?? ""),
|
|
);
|
|
if (vitestRun < 0) return;
|
|
for (const token of tokens.slice(vitestRun + 1)) {
|
|
if (!token.startsWith("-")) add(token, "vitest");
|
|
}
|
|
};
|
|
for (const script of reachablePackageScripts(scripts, entryScripts)) {
|
|
for (const segment of scripts[script]!.split("&&")) {
|
|
const tokens = segment.trim().split(/\s+/u);
|
|
addVitestPaths(tokens);
|
|
const scaleProfile = tokens.findIndex((token) => /run-scale-profile\.ts$/u.test(token));
|
|
if (scaleProfile >= 0) {
|
|
for (const step of SCALE_TIERS[tokens[scaleProfile + 1] as ScaleTier] ?? []) addVitestPaths(step.command);
|
|
}
|
|
}
|
|
}
|
|
for (const testDir of playwrightCoverage(gatedPlaywrightRuns(scripts, entryScripts, readConfig)).gated) {
|
|
add(testDir, "playwright");
|
|
}
|
|
return [...targets.values()].sort(
|
|
(left, right) => left.path.localeCompare(right.path) || left.runner.localeCompare(right.runner),
|
|
);
|
|
}
|
|
|
|
/** Each `playwright test` run the entry scripts reach, in the order they reach them. */
|
|
export function gatedPlaywrightRuns(
|
|
scripts: Readonly<Record<string, string>>,
|
|
entryScripts: readonly string[],
|
|
readConfig: (file: string) => string,
|
|
): GatedPlaywrightRun[] {
|
|
return reachablePackageScripts(scripts, entryScripts).flatMap((script) =>
|
|
playwrightTestRuns(scripts[script]!).map((run) => ({
|
|
...run,
|
|
script,
|
|
testDir: /testDir:\s*["']\.?\/?([^"']+)["']/u.exec(readConfig(run.config))?.[1]?.replace(/\/$/u, ""),
|
|
configSetsGrep: configSetsGrep(run.config, readConfig, new Set()),
|
|
})),
|
|
);
|
|
}
|
|
|
|
export function playwrightTestDirGaps(
|
|
scripts: Readonly<Record<string, string>>,
|
|
entryScripts: readonly string[],
|
|
readConfig: (file: string) => string,
|
|
): PlaywrightTestDirGap[] {
|
|
return playwrightCoverage(gatedPlaywrightRuns(scripts, entryScripts, readConfig)).gaps;
|
|
}
|
|
|
|
/** The config or a config it imports by a relative path names `grep` or `grepInvert`. */
|
|
function configSetsGrep(config: string, readConfig: (file: string) => string, seen: Set<string>): boolean {
|
|
if (seen.has(config)) return false;
|
|
seen.add(config);
|
|
const text = readConfig(config);
|
|
// A property, not a word in a comment: `grep: …`, `grep,` or `grep }`.
|
|
if (/\bgrep(?:Invert)?\s*[:,}]/u.test(text)) return true;
|
|
return [...text.matchAll(/\bfrom\s+["'](\.{1,2}\/[^"']+\.config\.[cm]?[jt]s)["']/gu)].some(([, specifier]) =>
|
|
configSetsGrep(path.posix.join(path.posix.dirname(config), specifier!), readConfig, seen),
|
|
);
|
|
}
|
|
|
|
type RunFilter =
|
|
| Readonly<{ kind: "none" }>
|
|
| Readonly<{ kind: "grep" | "grepInvert"; pattern: string }>
|
|
| Readonly<{ kind: "partial"; why: string }>;
|
|
|
|
function runFilter(run: GatedPlaywrightRun): RunFilter {
|
|
if (run.files.length > 0) return { kind: "partial", why: `file filter ${run.files.join(" ")}` };
|
|
if (run.configSetsGrep) {
|
|
return { kind: "partial", why: `${run.config} or a config it imports sets grep or grepInvert` };
|
|
}
|
|
if (run.grep.length + run.grepInvert.length > 1) {
|
|
return { kind: "partial", why: "more than one --grep or --grep-invert" };
|
|
}
|
|
if (run.grep[0] !== undefined) return { kind: "grep", pattern: run.grep[0] };
|
|
if (run.grepInvert[0] !== undefined) return { kind: "grepInvert", pattern: run.grepInvert[0] };
|
|
return { kind: "none" };
|
|
}
|
|
|
|
function playwrightCoverage(runs: readonly GatedPlaywrightRun[]): { gated: string[]; gaps: PlaywrightTestDirGap[] } {
|
|
const byTestDir = new Map<string, { run: GatedPlaywrightRun; filter: RunFilter }[]>();
|
|
for (const run of runs) {
|
|
if (run.testDir === undefined) continue;
|
|
byTestDir.set(run.testDir, [...(byTestDir.get(run.testDir) ?? []), { run, filter: runFilter(run) }]);
|
|
}
|
|
const gated: string[] = [];
|
|
const gaps: PlaywrightTestDirGap[] = [];
|
|
for (const [testDir, dirRuns] of byTestDir) {
|
|
const patterns = (kind: "grep" | "grepInvert") =>
|
|
new Set(dirRuns.flatMap(({ filter }) => (filter.kind === kind ? [filter.pattern] : [])));
|
|
const greps = patterns("grep");
|
|
const inverts = patterns("grepInvert");
|
|
const unpaired = [...inverts].filter((pattern) => !greps.has(pattern));
|
|
if (dirRuns.some(({ filter }) => filter.kind === "none") || (inverts.size > 0 && unpaired.length === 0)) {
|
|
gated.push(testDir);
|
|
continue;
|
|
}
|
|
const named = ({ run }: { run: GatedPlaywrightRun }) => `\`${run.segment}\` (${run.script})`;
|
|
gaps.push({
|
|
testDir,
|
|
runs: dirRuns.flatMap((dirRun) => {
|
|
const { filter } = dirRun;
|
|
if (filter.kind === "grepInvert" && unpaired.includes(filter.pattern)) {
|
|
return [`${named(dirRun)} has no gated \`--grep ${filter.pattern}\` run to pair with`];
|
|
}
|
|
if (filter.kind === "grep" && inverts.size === 0) {
|
|
return [`${named(dirRun)} has no gated \`--grep-invert ${filter.pattern}\` run to pair with`];
|
|
}
|
|
if (filter.kind === "partial") return [`${named(dirRun)} is a partial run FE-GATE-029 does not read: ${filter.why}`];
|
|
return [];
|
|
}),
|
|
});
|
|
}
|
|
return { gated, gaps };
|
|
}
|
|
|
|
export function ungatedTestFailures(input: Readonly<{
|
|
testFiles: readonly string[];
|
|
/** A bare string is a Vitest path. */
|
|
gatedPaths: readonly (string | GatedTestTarget)[];
|
|
exclusions: readonly UngatedTestExclusion[];
|
|
/** Named once for the files they leave ungated, instead of once per file. */
|
|
playwrightGaps?: readonly PlaywrightTestDirGap[];
|
|
}>): string[] {
|
|
const targets = input.gatedPaths.map((target): GatedTestTarget =>
|
|
typeof target === "string" ? { path: target, runner: "vitest" } : target,
|
|
);
|
|
const gated = (file: string) =>
|
|
targets.some(
|
|
({ path: gatedPath, runner }) =>
|
|
(file === gatedPath || file.startsWith(`${gatedPath}/`)) &&
|
|
(runner === "playwright" || VITEST_TEST_FILE.test(file)),
|
|
);
|
|
const excluded = new Set(input.exclusions.map(({ path: file }) => file));
|
|
const ungated = input.testFiles.filter((file) => !gated(file) && !excluded.has(file));
|
|
// The deepest testDir a file is in names it.
|
|
const gaps = [...(input.playwrightGaps ?? [])].sort((left, right) => right.testDir.length - left.testDir.length);
|
|
const gapOf = (file: string) => gaps.find(({ testDir }) => file.startsWith(`${testDir}/`));
|
|
const failures = ungated
|
|
.filter((file) => gapOf(file) === undefined)
|
|
.map((file) =>
|
|
`test file is not run by any CI gate command and is not in ${UNGATED_TESTS_PATH}: ${file}`
|
|
);
|
|
for (const gap of gaps) {
|
|
const files = ungated.filter((file) => gapOf(file) === gap).length;
|
|
if (files === 0) continue;
|
|
failures.push(
|
|
`Playwright testDir ${gap.testDir} is only partly run by the CI gate commands, so none of its ${files} test file${files === 1 ? "" : "s"} counts as gated: ${gap.runs.join("; ")}. Gate one run of it with no --grep, --grep-invert or file filter, or a \`--grep P\` run for each \`--grep-invert P\` run (package.json scripts)`,
|
|
);
|
|
}
|
|
// An entry for a file a removal deleted is harmless; one for a file a gate
|
|
// now runs would hide the next regression, so it has to go.
|
|
for (const { path: file } of input.exclusions) {
|
|
if (gated(file)) failures.push(`ungated test exclusion is stale; a CI gate runs it: ${file}`);
|
|
}
|
|
return failures;
|
|
}
|