Files
clean-architecture-frontend…/tests/unit/playwright-result-paths.test.ts
DongHyeonka 32982e5547 ci(gates): FE-GATE-029가 --grep-invert 실행마다 같은 testDir의 --grep 짝을 요구한다
문제: 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개 통과.
2026-11-21 00:36:39 +09:00

211 lines
9.7 KiB
TypeScript

import { readFile } from "node:fs/promises";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts";
import { reachablePackageScripts } from "../../scripts/lib/package-script-graph.ts";
import { playwrightTestRuns } from "../../scripts/lib/playwright-test-args.ts";
import { RELEASE_EVIDENCE_REGENERATED_TREES } from "../../scripts/lib/removal-fixture.ts";
import { loadConfigFile, outputs, releaseRuns } from "../helpers/playwright-run-isolation.ts";
/**
* 1106 review 11. test:a11y (FE-GATE-009) ran with playwright.config.ts as it
* was, so it wrote the e2e results folder, HTML report and results.xml. The
* merge browser job runs FE-GATE-008 and then FE-GATE-009 in one checkout and
* uploads artifacts/: the e2e evidence it uploaded was the a11y run's, and
* FE-GATE-009 kept no JUnit file or report of its own. test:e2e:dev (no gate)
* spread the same paths, so a local run replaced the gate's results too.
*
* The configs are the ones the package scripts name, loaded without a run ID:
* the paths the gates and the CI upload read.
*/
const scripts = (JSON.parse(await readFile("package.json", "utf8")) as { scripts: Record<string, string> })
.scripts;
afterEach(releaseRuns);
type Writer = Readonly<{ name: string; paths: readonly string[] }>;
/**
* The config of each `playwright test` a script runs, following the scripts it
* calls. FE-GATE-029 reads the runs with the same parser (fe-ci-next-12).
*/
function playwrightConfigs(script: string, packageScripts: Readonly<Record<string, string>> = scripts): string[] {
return reachablePackageScripts(packageScripts, [script]).flatMap((reached) =>
playwrightTestRuns(packageScripts[reached]!).map(({ config }) => config),
);
}
const relative = (absolute: string) => path.relative(process.cwd(), absolute);
async function resultPaths(config: string): Promise<readonly string[]> {
const { results, report, junit } = outputs(await loadConfigFile(config));
return [results, report, junit].map(relative);
}
/** Playwright empties its results folder at start, so a path inside another's is a clash too. */
function overlap(left: string, right: string): boolean {
return left === right || left.startsWith(`${right}/`) || right.startsWith(`${left}/`);
}
function clashes(writers: readonly Writer[]): string[] {
const found: string[] = [];
writers.forEach((left, index) => {
for (const right of writers.slice(index + 1)) {
for (const leftPath of left.paths) {
const rightPath = right.paths.find((candidate) => overlap(leftPath, candidate));
if (rightPath !== undefined) found.push(`${left.name} writes ${leftPath}, ${right.name} writes ${rightPath}`);
}
}
});
return found;
}
/** Every config a package script runs. */
function namedConfigs(): string[] {
return [...new Set(Object.keys(scripts).flatMap((script) => playwrightConfigs(script)))].sort();
}
async function gatedWriters(): Promise<Writer[]> {
const contract = await loadCiGateContract(process.cwd());
const gated = new Set(contract.gates.flatMap(({ commandIds }) => commandIds));
const writers: Writer[] = [];
for (const command of contract.commands) {
if (!gated.has(command.id)) continue;
for (const [run, config] of playwrightConfigs(command.script).entries()) {
writers.push({ name: `${command.id} run ${run + 1} (${config})`, paths: await resultPaths(config) });
}
}
return writers;
}
describe("Playwright result paths", () => {
// The three checks below pass on an empty list, so the helpers that build
// it have to find what they are given.
it("finds every config a script runs, through the scripts it calls, and none in a script that runs none", () => {
const fake = {
gate: "corepack pnpm build && corepack pnpm browser",
browser:
"playwright test --config playwright.a11y.config.ts --grep @a11y && playwright test -c other.config.ts && playwright test --config=third.config.ts && playwright test --grep-invert @a11y",
build: "node scripts/build.ts && playwright show-report",
};
expect(playwrightConfigs("gate", fake)).toEqual([
"playwright.a11y.config.ts",
"other.config.ts",
"third.config.ts",
"playwright.config.ts",
]);
expect(playwrightConfigs("build", fake)).toEqual([]);
});
it("reports a writer pair that writes one path or a path inside the other's, and not a pair that shares a name prefix", () => {
expect(
clashes([
{ name: "inner", paths: ["artifacts/tests/e2e/results/nested"] },
{ name: "e2e", paths: ["artifacts/tests/e2e/results", "artifacts/tests/e2e/results.xml"] },
{ name: "junit", paths: ["artifacts/tests/e2e/results.xml"] },
{ name: "dev", paths: ["artifacts/tests/e2e-dev/results", "artifacts/tests/e2e/results.xml.bak"] },
{ name: "trace", paths: ["artifacts/tests/e2e/results/trace.zip"] },
]),
).toEqual([
"inner writes artifacts/tests/e2e/results/nested, e2e writes artifacts/tests/e2e/results",
"e2e writes artifacts/tests/e2e/results.xml, junit writes artifacts/tests/e2e/results.xml",
"e2e writes artifacts/tests/e2e/results, trace writes artifacts/tests/e2e/results/trace.zip",
]);
});
it("are each config's own: no two configs the package scripts name write the same results, report or JUnit file", async () => {
const configs = namedConfigs();
expect(configs).toContain("playwright.config.ts");
expect(configs.length).toBeGreaterThan(1);
const writers: Writer[] = [];
for (const config of configs) writers.push({ name: config, paths: await resultPaths(config) });
expect(clashes(writers)).toEqual([]);
});
it("are each gate command's own, so a gate that runs after another in one job keeps the first one's results", async () => {
const writers = await gatedWriters();
expect(writers.map(({ name }) => name)).toEqual(
expect.arrayContaining([expect.stringMatching(/^test-e2e /u), expect.stringMatching(/^test-a11y /u)]),
);
expect(clashes(writers)).toEqual([]);
});
it("are the evidence of the gate that runs the command, with that command as the producer", async () => {
const contract = await loadCiGateContract(process.cwd());
const failures: string[] = [];
let checked = 0;
for (const gate of contract.gates) {
for (const commandId of gate.commandIds) {
const command = contract.commands.find(({ id }) => id === commandId)!;
for (const config of playwrightConfigs(command.script)) {
const { report, junit } = outputs(await loadConfigFile(config));
for (const file of [relative(junit), relative(path.join(report, "index.html"))]) {
checked += 1;
const artifact = contract.artifacts.find((candidate) => candidate.path === file);
if (artifact === undefined) {
failures.push(`${gate.id} ${commandId} (${config}) writes ${file}, which config/ci/gates.json has no artifact for`);
continue;
}
if (!gate.evidenceArtifactIds.includes(artifact.id)) {
failures.push(`${gate.id} ${commandId} (${config}) writes ${file}, which is not in ${gate.id}'s evidence`);
}
if (artifact.production !== "command-generated" || !artifact.producerCommandIds.includes(commandId)) {
failures.push(`${gate.id} ${commandId} (${config}) writes ${file}, whose producer is not ${commandId}`);
}
}
}
}
}
expect(checked).toBeGreaterThan(2);
expect(failures).toEqual([]);
});
// fe-ci-next-9. The removal fixtures copy artifacts/ less the regenerated
// trees (copyReleaseEvidenceTree). Out of artifacts/tests/e2e/, the a11y and
// dev results and reports went into every fixture, traces included: a local
// verify.sh merge runs FE-GATE-009 before FE-GATE-013 and FE-GATE-020 in one
// checkout.
it("are trees the removal fixture copy leaves behind", async () => {
const failures: string[] = [];
for (const config of namedConfigs()) {
const { results, report } = outputs(await loadConfigFile(config));
for (const folder of [relative(results), relative(report)]) {
if (!RELEASE_EVIDENCE_REGENERATED_TREES.some((tree) => folder === tree || folder.startsWith(`${tree}/`))) {
failures.push(`${config} writes ${folder}, which the removal fixture copy keeps (scripts/lib/removal-fixture.ts)`);
}
}
}
expect(failures).toEqual([]);
});
// FE-6 (decisions.md): every @a11y browser test runs once, in FE-GATE-009,
// on the projects, build and server FE-GATE-008 runs every other one on.
it("are all the a11y config changes from the e2e config, and test:e2e and test:a11y split the browser tests on @a11y", async () => {
const playwrightRuns = (script: string) =>
script.split("&&").map((part) => part.trim()).filter((part) => part.startsWith("playwright test"));
expect(playwrightRuns(scripts["test:e2e"]!)).toEqual(["playwright test --grep-invert @a11y"]);
expect(playwrightRuns(scripts["test:a11y"]!)).toEqual([
"playwright test --config playwright.a11y.config.ts --grep @a11y",
]);
// One pinned port, so the two loads start the same server.
const samePort = { TEST_E2E_PORT: "41731" };
const withoutResultPaths = (config: Awaited<ReturnType<typeof loadConfigFile>>) => {
const rest = { ...config };
delete rest.outputDir;
delete rest.reporter;
return rest;
};
const e2eConfig = await loadConfigFile("playwright.config.ts", samePort);
const a11yConfig = await loadConfigFile("playwright.a11y.config.ts", samePort);
expect(e2eConfig.projects?.length).toBeGreaterThan(1);
expect(withoutResultPaths(a11yConfig)).toEqual(withoutResultPaths(e2eConfig));
});
});