Files
clean-architecture-frontend…/tests/unit/playwright-flaky-judgement.test.ts
DongHyeonka c1e258bb81 test(playwright): CI 판정용 재시도로 흔들림을 가리고 실패로 남긴다
Playwright가 재시도하지 않아 실패가 흔들림인지 회귀인지 run에 남지
않는다. CI=true에서만 한 번 더 돌고, 재시도에서 통과해도 실패로
끝낸다. 설정 helper로만 주고 검사기가 설정 객체의 key를 거절한다.

failOnFlakyTests만으로는 재시도에서만 test.fail()에 닿은 시험의 첫
실패가 통과로 바뀐다. helper의 reporter가 실패한 시도를 따로 판정하고
다른 보고에 없는 원인을 색 코드 없이 찍는다. e2e 공유 fixture 빌드는 재시도에서 앞
시도의 실패 기록을 다시 쓰지 않는다(카드 C9). package script와 게이트
args는 029 파서와 이어 쓴 script 때문에 버렸다. CI 판별은 러너 정책이라
CI env를 읽는다.

위험·한계: 많이 깨진 run은 브라우저 게이트가 최대 약 두 배 걸린다
(추정). 명령줄 --reporter는 이 판정 reporter를 뺀다. JUnit에서 실패한
시험의 시간과 failure/error 분류는 첫 시도 기준이 된다. 검사기는 spec
안의 describe.configure({ retries })를 보지 않는다. 빌드가 실패 기록
없이 끊기면(worker 종료, hook 시간 초과) 재시도도 기다리다 실패한다.

검증: main으로 옮기기 전 트리 c8df70ab에서 test:unit 3632개, types,
lint, FE-GATE-029, verify:documentation rc=0, 변이 30개 검출. desktop
실제 브라우저: 일시 빌드 실패는 6 flaky, 계속 실패는 3 failed, 숨은
실패는 rc=1과 원인 출력. 트리 3dea9c06에서 숨은 expect 실패의 색 코드
시험이 고치기 전 1개 실패, 고친 뒤 35개 통과.

Refs: CI-FE-0001
2026-11-23 00:45:11 +09:00

410 lines
16 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { spawnSync } from "node:child_process";
import { readdirSync } from "node:fs";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it, vi } from "vitest";
import { formatGateFailure } from "../../scripts/lib/ci-gate-failure.ts";
import { flakyJudgementReporter } from "../../scripts/lib/playwright-flaky-judgement.ts";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
import { loadConfigFile, releaseRuns } from "../helpers/playwright-run-isolation.ts";
/**
* FLAKY-3. In CI a failed Playwright test runs once more to tell a flaky test
* from a broken one, and the run fails either way. The first block runs the
* real Playwright on a config with no browser and no server. The second reads
* what each config of this repository evaluates to.
*
* The probe specs are written at run time, so no runner, lint or typecheck
* picks them up. They are below .tmp/ so `@playwright/test` resolves.
*/
const HELPER = pathToFileURL(path.resolve("scripts/lib/playwright-flaky-judgement.ts")).href;
const PLAYWRIGHT_CLI = createRequire(import.meta.url).resolve("@playwright/test/cli");
/**
* Longest desktop run of a test in the first block and in the last one, over
* four runs of this file, two of them with coverage (2026-11-22).
*/
const RUN_MS = 3_584;
const CHECK_MS = 694;
const folders: string[] = [];
afterEach(async () => {
vi.unstubAllEnvs();
await releaseRuns();
await Promise.all(folders.splice(0).map((folder) => rm(folder, { recursive: true, force: true })));
});
function count(text: string, pattern: RegExp): number {
return [...text.matchAll(pattern)].length;
}
/** Runs `body` as a spec, in each of `projects`, that records the retry number of each attempt. */
async function runProbe(body: string, ci: string | undefined, projects: readonly string[] = []) {
await mkdir(".tmp", { recursive: true });
const root = await mkdtemp(path.resolve(".tmp/flaky-judgement-"));
folders.push(root);
const attempts = path.join(root, "attempts");
const junit = path.join(root, "results.xml");
await writeFile(
path.join(root, "probe.config.ts"),
`import { defineConfig } from "@playwright/test";
import { flakyJudgement, flakyJudgementReporter } from ${JSON.stringify(HELPER)};
export default defineConfig({
testDir: ".",
testMatch: "probe.spec.ts",
...flakyJudgement(),
${projects.length === 0 ? "" : `projects: ${JSON.stringify(projects.map((name) => ({ name })))},`}
workers: 1,
outputDir: "results",
reporter: [["list"], flakyJudgementReporter, ["junit", { outputFile: ${JSON.stringify(junit)}, includeRetries: true }]],
});
`,
);
await writeFile(
path.join(root, "probe.spec.ts"),
`import { appendFileSync } from "node:fs";
import { expect, test as base } from "@playwright/test";
const test = base.extend({
attempt: async ({}, use, testInfo) => {
appendFileSync(${JSON.stringify(attempts)}, String(testInfo.retry));
await use(testInfo.retry);
},
failsOnFirstSetup: async ({ attempt }, use) => {
if (attempt === 0) throw new Error("setup failed", { cause: new Error("port taken") });
await use(attempt);
},
});
${body}
`,
);
// The child's environment is this test's: not the CI, reporter or color
// variables of whoever runs Vitest.
const environment = {
PATH: process.env["PATH"],
HOME: process.env["HOME"],
TMPDIR: process.env["TMPDIR"],
FORCE_COLOR: "0",
...(ci === undefined ? {} : { CI: ci }),
};
const result = spawnSync(
process.execPath,
[PLAYWRIGHT_CLI, "test", "--config", path.join(root, "probe.config.ts")],
{ cwd: root, env: environment as unknown as NodeJS.ProcessEnv, encoding: "utf8" },
);
const xml = await readFile(junit, "utf8").catch(() => "");
return {
status: result.status,
output: `${result.stdout}${result.stderr}`,
attempts: await readFile(attempts, "utf8").catch(() => ""),
xml,
};
}
const FLAKY = `test("probe", async ({ attempt }) => {
expect(attempt).toBe(1);
});`;
describe("Playwright flaky judgement", { timeout: childProcessTimeout(RUN_MS) }, () => {
it("reports a test that passes on its retry as flaky and fails the run in CI", async () => {
const run = await runProbe(FLAKY, "true");
expect(run.status, run.output).not.toBe(0);
expect(run.attempts).toBe("01");
expect(run.output).toMatch(/^\s*1 flaky$/mu);
expect(run.output).toContain("(retry #1)");
// The list reporter prints why this one failed. The judgement does not again.
expect(run.output).not.toContain("failed an attempt");
expect(count(run.xml, /<testcase\b/gu)).toBe(1);
expect(count(run.xml, /<flakyFailure\b/gu)).toBe(1);
expect(run.xml).not.toMatch(/<failure\b/u);
});
// What JUnit leaves of a flaky test. Counting <flakyFailure> alone misses most.
it.each([
["a failed expect", FLAKY, ["flakyFailure"]],
[
"a timeout",
`test("probe", async ({ attempt }) => {\n if (attempt === 1) return;\n test.setTimeout(200);\n await new Promise(() => {});\n});`,
["flakyError"],
],
["a throw", `test("probe", async ({ attempt }) => {\n if (attempt === 0) throw new Error("boom");\n});`, ["flakyError"]],
["a crash", `test("probe", async ({ attempt }) => {\n if (attempt === 0) process.exit(3);\n});`, ["flakyError"]],
[
"an expected failure that passed",
`test("probe", async ({ attempt }) => {\n test.fail();\n expect(attempt).toBe(0);\n});`,
[],
],
])("records in JUnit a flaky test that began with %s", async (_, body, children) => {
const run = await runProbe(body, "true");
expect(run.status, run.output).not.toBe(0);
expect(run.output).toMatch(/^\s*1 flaky$/mu);
expect([...run.xml.matchAll(/<(flaky\w+)\b/gu)].map((match) => match[1])).toEqual(children);
expect(run.xml).not.toMatch(/<(?:failure|error)\b/u);
});
it("runs a test that always fails twice in CI and reports it failed", async () => {
const run = await runProbe(`test("probe", async ({ attempt }) => {\n expect(attempt).toBe(-1);\n});`, "true");
expect(run.status, run.output).not.toBe(0);
expect(run.attempts).toBe("01");
expect(run.output).toMatch(/^\s*1 failed$/mu);
expect(run.output).toContain("Retry #1");
expect(count(run.xml, /<testcase\b/gu)).toBe(1);
expect(count(run.xml, /<failure\b/gu)).toBe(1);
});
it.each([
["no CI", undefined],
["an empty CI", ""],
["CI=false", "false"],
])("does not retry with %s", async (_, ci) => {
const run = await runProbe(FLAKY, ci);
expect(run.status, run.output).not.toBe(0);
expect(run.attempts).toBe("0");
expect(run.output).toMatch(/^\s*1 failed$/mu);
expect(run.output).not.toMatch(/retry #1/iu);
});
// Playwright judges every attempt by the expected status of the last one.
// A test.fail() only the retry reaches turns the first failure into an
// expected one: the test ends "expected", not flaky, so failOnFlakyTests
// alone passes a run that fails without a retry. preload-use.spec.ts calls
// test.fail() in the body, after its fixtures.
it.each([
[
"a fixture fails before the test.fail() its body calls",
`test("probe", async ({ failsOnFirstSetup }) => {\n test.fail();\n expect(failsOnFirstSetup).toBe(-1);\n});`,
],
[
"the expected failure passes and only that attempt expects one",
`test("probe", async ({ attempt }) => {\n test.fail(attempt === 0);\n});`,
],
])("fails the run in CI, as without a retry, when %s", async (_, body) => {
expect((await runProbe(body, undefined)).status).not.toBe(0);
const run = await runProbe(body, "true");
expect(run.attempts).toBe("01");
expect(run.status, run.output).not.toBe(0);
expect(run.output).toContain("failed an attempt before the retry changed what it expects");
});
// For these the list reporter prints "3 passed" and no error, and the JUnit
// file has no failure: what the judgement prints is all the gate log has.
it.each([
[
"a fixture failed",
`test("probe", async ({ failsOnFirstSetup }) => {\n test.fail();\n expect(failsOnFirstSetup).toBe(-1);\n});`,
[/Error: setup failed/u, /^\s+at .*probe\.spec\.ts:\d+:\d+/mu, /port taken/u],
],
[
"an expect failed",
`test("probe", async ({ attempt }) => {\n if (attempt === 0) expect(attempt).toBe(2);\n test.fail();\n expect(attempt).toBe(-1);\n});`,
[/expect\(received\)\.toBe\(expected\)/u, /^\s*Expected: 2$/mu],
],
[
"the expected failure passed",
`test("probe", async ({ attempt }) => {\n test.fail(attempt === 0);\n});`,
[/Expected to fail, but passed\./u],
],
[
"what was thrown is not an Error",
`test("probe", async ({ attempt }) => {\n if (attempt === 0) throw "the port was taken";\n test.fail();\n expect(attempt).toBe(-1);\n});`,
[/the port was taken/u],
],
])("names the project and why the hidden attempt failed when %s", async (_, body, causes) => {
const projects = ["first", "second", "third"];
const run = await runProbe(body, "true", projects);
expect(run.status, run.output).not.toBe(0);
expect(run.output).toMatch(/^\s*3 passed\b/mu);
// Playwright records errors with color codes; the list reporter strips them.
expect(run.output).not.toContain("\u001b");
const header = /^ *\d+\) \[(\w+)\] › .*probe\.spec\.ts:\d+:\d+ › probe/gmu;
const blocks = [...run.output.matchAll(header)].map((match, index, all) => ({
project: match[1]!,
text: run.output.slice(match.index, all[index + 1]?.index),
}));
expect(blocks.map((block) => block.project).sort(), run.output).toEqual(projects);
for (const block of blocks) {
for (const cause of causes) expect(block.text, block.project).toMatch(cause);
}
// ci:gate quotes the first failure block, not only the last lines of the log.
const command = "$ corepack pnpm test:e2e";
const summary = formatGateFailure({
gateId: "FE-GATE-008",
gateName: "e2e",
logPath: "gate.txt",
failedCommand: command,
output: [command, run.output],
tailLines: 1,
});
expect(summary).toContain("first failure in the log:");
expect(summary).toContain(`[${blocks[0]!.project}]`);
for (const cause of causes) expect(summary).toMatch(cause);
});
it("says why the hidden attempt failed when another test fails the run", async () => {
const run = await runProbe(
`test("hidden", async ({ failsOnFirstSetup }) => {
test.fail();
expect(failsOnFirstSetup).toBe(-1);
});
test("broken", async ({ attempt }) => {
expect(attempt).toBe(-1);
});`,
"true",
);
expect(run.status, run.output).not.toBe(0);
expect(run.output).toMatch(/^\s*1 failed$/mu);
expect(run.output).toContain("Error: setup failed");
expect(count(run.output, /failed an attempt/gu)).toBe(1);
});
// This one is flaky, but the list reporter has no line for it: the last
// attempt expects a skip and the first one left no error.
it("says why when the retry skips a test whose expected failure passed", async () => {
const run = await runProbe(
`test("probe", async ({ attempt }) => {\n test.fail(attempt === 0);\n test.skip(attempt === 1);\n});`,
"true",
);
expect(run.status, run.output).not.toBe(0);
expect(run.output).toMatch(/^\s*1 flaky$/mu);
expect(run.output).toContain("Expected to fail, but passed.");
});
it("fails the run in CI when the retry skips the test that failed", async () => {
const run = await runProbe(
`test("probe", async ({ attempt }) => {\n test.skip(attempt === 1);\n expect(attempt).toBe(1);\n});`,
"true",
);
expect(run.status, run.output).not.toBe(0);
expect(run.attempts).toBe("01");
expect(run.output).toMatch(/^\s*1 flaky$/mu);
});
it("passes a run whose tests all end as expected on the first attempt", async () => {
const run = await runProbe(
`test("passes", async ({ attempt }) => {
expect(attempt).toBe(0);
});
test("fails on purpose", async ({ attempt }) => {
test.fail();
expect(attempt).toBe(1);
});
test("is left out", async ({ attempt }) => {
test.skip(attempt === 0);
});`,
"true",
);
expect(run.status, run.output).toBe(0);
expect(run.attempts).toBe("000");
expect(run.output).not.toContain("failed an attempt");
});
});
// Every config at the root, read from disk: a config added later is held to
// the same judgement, and a checkout without the capabilities config is not
// asked for it.
describe("Playwright configs", () => {
const configs = readdirSync(".").filter((file) => /^playwright.*\.config\.ts$/u.test(file));
it("are found", () => {
expect(configs).toContain("playwright.config.ts");
expect(configs.length).toBeGreaterThan(1);
});
it.each(configs)("%s retries once in CI only, fails on a flaky test and records the retry", async (file) => {
vi.stubEnv("CI", "true");
const inCi = await loadConfigFile(file);
vi.stubEnv("CI", "");
const outsideCi = await loadConfigFile(file);
for (const [config, retries] of [
[inCi, 1],
[outsideCi, 0],
] as const) {
expect(config.retries).toBe(retries);
expect(config.failOnFlakyTests).toBe(retries === 1);
// A project's own value wins over the config's.
for (const project of config.projects ?? []) expect(project.retries ?? config.retries).toBe(retries);
expect(config.reporter).toContainEqual(flakyJudgementReporter);
expect(config.reporter).toContainEqual([
"junit",
expect.objectContaining({ includeRetries: true }) as unknown,
]);
}
});
});
describe("check-test-evidence on retries", { timeout: childProcessTimeout(CHECK_MS) }, () => {
const FIXTURES = "tests/fixtures/test-evidence/playwright-config";
// The fixture is also the source root, so the run reads no other file.
const check = async (config: string) => {
await mkdir(".tmp", { recursive: true });
const root = await mkdtemp(path.resolve(".tmp/flaky-judgement-check-"));
folders.push(root);
return spawnSync(
process.execPath,
[
"scripts/check-test-evidence.ts",
"--source-only",
"--source-root",
config,
"--playwright-config",
config,
"--artifact",
path.join(root, "report.json"),
],
{ encoding: "utf8" },
);
};
it.each([
"literal-retries.fixture",
"literal-fail-on-flaky-tests.fixture",
"quoted-retries.fixture",
"computed-retries.fixture",
"shorthand-retries.fixture",
])("rejects %s", async (fixture) => {
const result = await check(`${FIXTURES}/${fixture}`);
expect(result.status).toBe(1);
expect(result.stderr).toContain(
`${FIXTURES}/${fixture}: retries come only from ...flakyJudgement(), so a test that passes on its retry still fails the gate`,
);
});
it("rejects a config it cannot read", async () => {
await mkdir(".tmp", { recursive: true });
const root = await mkdtemp(path.resolve(".tmp/flaky-judgement-unreadable-"));
folders.push(root);
const config = path.join(root, "unreadable.fixture");
await writeFile(config, "export default { forbidOnly: true, retries: 1\n");
const result = await check(config);
expect(result.status).toBe(1);
expect(result.stderr).toContain(`${config}: cannot parse to look for retries`);
});
it.each(["flaky-judgement.fixture", "retries-named-elsewhere.fixture"])("accepts %s", async (fixture) => {
const result = await check(`${FIXTURES}/${fixture}`);
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
});
});