Files
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

384 lines
13 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { access, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import {
SHARED_FIXTURE_BUILD_ROOT_VARIABLE,
sharedFixtureBuild,
startSharedFixtureBuilds,
} from "../e2e/support/shared-fixture-builds.ts";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
async function sharedEnvironment(): Promise<NodeJS.ProcessEnv> {
const root = await mkdtemp(path.join(tmpdir(), "shared-builds-test-"));
roots.push(root);
return { [SHARED_FIXTURE_BUILD_ROOT_VARIABLE]: root };
}
describe("one fixture build per e2e run", () => {
it("builds a key once and hands every caller the same copy", async () => {
const environment = await sharedEnvironment();
let builds = 0;
const create = async (root: string) => {
builds += 1;
await new Promise((resolve) => setTimeout(resolve, 50));
await writeFile(path.join(root, "dist.txt"), "built");
return { dist: path.join(root, "dist.txt") };
};
const results = await Promise.all(
[1, 2, 3].map(() => sharedFixtureBuild("fixture-a", "same", create, environment)),
);
expect(builds).toBe(1);
expect(new Set(results.map((result) => result.root)).size).toBe(1);
for (const result of results) {
expect(result.shared).toBe(true);
expect(result.value).toEqual({ dist: path.join(result.root, "dist.txt") });
}
await access(results[0]!.value.dist);
});
it("refuses a second definition under the same key", async () => {
const environment = await sharedEnvironment();
await sharedFixtureBuild("fixture-b", "first", async () => ({}), environment);
await expect(
sharedFixtureBuild("fixture-b", "second", async () => ({}), environment),
).rejects.toThrow(/fixture-b was built from another definition/u);
});
// The key's folder is the lock, and the call whose mkdir finishes first owns
// it, not the one made first: runner run 235 let the second call build and
// the first wait for its success. The waiter starts once the owner's
// builder runs, that is once the owner holds the lock.
it("fails the waiting callers with the builder's failure", async () => {
const environment = await sharedEnvironment();
let building!: () => void;
const ownerBuilds = new Promise<void>((resolve) => {
building = resolve;
});
const owner = sharedFixtureBuild(
"fixture-c",
"same",
async () => {
building();
await new Promise((resolve) => setTimeout(resolve, 50));
throw new Error("vite build exited 1");
},
environment,
);
await ownerBuilds;
const waiter = sharedFixtureBuild("fixture-c", "same", async () => ({}), environment);
await expect(owner).rejects.toThrow(/vite build exited 1/u);
await expect(waiter).rejects.toThrow(
/fixture-c failed in another worker:[\s\S]*vite build exited 1/u,
);
});
it("builds a private copy and removes it on failure without a shared root", async () => {
const result = await sharedFixtureBuild("fixture-d", "x", async (root) => root, {});
roots.push(result.root);
expect(result).toMatchObject({ shared: false, value: result.root });
expect(path.dirname(result.root)).toBe(tmpdir());
let failedRoot = "";
await expect(
sharedFixtureBuild("fixture-d", "x", async (root) => {
failedRoot = root;
throw new Error("broken copy");
}, {}),
).rejects.toThrow(/broken copy/u);
await expect(access(failedRoot)).rejects.toMatchObject({ code: "ENOENT" });
});
it("refuses a key that is not one lower-case path segment", async () => {
for (const key of ["", "../x", "a/b", "Fixture", `a${"b".repeat(64)}`]) {
await expect(sharedFixtureBuild(key, "x", async () => ({}), {})).rejects.toThrow(
/Invalid fixture build key/u,
);
}
});
it("gives the run a root and removes it with the teardown", async () => {
const environment: NodeJS.ProcessEnv = {};
const teardown = await startSharedFixtureBuilds(environment);
const root = environment[SHARED_FIXTURE_BUILD_ROOT_VARIABLE];
expect(root).toBeTruthy();
await sharedFixtureBuild("fixture-e", "x", async () => ({}), environment);
await teardown();
expect(environment[SHARED_FIXTURE_BUILD_ROOT_VARIABLE]).toBeUndefined();
await expect(access(root!)).rejects.toMatchObject({ code: "ENOENT" });
});
});
// FLAKY-3 (CI-FE-0001 C9). A retry that read the first attempt's failure
// failed without building, so a build that failed once was reported as a
// broken test instead of a flaky one.
describe("a fixture build and the CI retry", () => {
const FIRST = 0;
const RETRY = 1;
const pause = () => new Promise((resolve) => setTimeout(resolve, 50));
/** A run in which the first attempt's build of `key` failed half way. */
async function failedFirstBuild(key: string) {
const environment = await sharedEnvironment();
let root = "";
await expect(
sharedFixtureBuild(
key,
"same",
async (folder) => {
root = folder;
await writeFile(path.join(folder, "half-built"), "");
throw new Error("first build failed");
},
environment,
FIRST,
),
).rejects.toThrow(/first build failed/u);
return { environment, failedRoot: root };
}
it("C9 (가) builds again on a retry, in an empty folder, and returns that build", async () => {
const { environment, failedRoot } = await failedFirstBuild("retry-a");
let found: string[] | undefined;
const result = await sharedFixtureBuild(
"retry-a",
"same",
async (root) => {
found = await readdir(root);
return "built again";
},
environment,
RETRY,
);
expect(result).toMatchObject({ value: "built again", shared: true });
expect(found).toEqual([]);
expect(result.root).not.toBe(failedRoot);
expect(path.dirname(result.root)).toBe(environment[SHARED_FIXTURE_BUILD_ROOT_VARIABLE]);
});
it("C9 (가) builds again when the first attempt's build fails while the retry waits for it", async () => {
const environment = await sharedEnvironment();
let building!: () => void;
const started = new Promise<void>((resolve) => {
building = resolve;
});
const first = sharedFixtureBuild(
"retry-wait",
"same",
async () => {
building();
await pause();
throw new Error("first build failed");
},
environment,
FIRST,
);
await started;
const retry = sharedFixtureBuild("retry-wait", "same", async () => "built again", environment, RETRY);
await expect(first).rejects.toThrow(/first build failed/u);
await expect(retry).resolves.toMatchObject({ value: "built again" });
});
it("C9 (나) fails a retry whose build fails too, and the retries after it", async () => {
const { environment } = await failedFirstBuild("retry-b");
let builds = 0;
const retry = () =>
sharedFixtureBuild(
"retry-b",
"same",
async () => {
builds += 1;
throw new Error("second build failed");
},
environment,
RETRY,
);
await expect(retry()).rejects.toThrow(/^second build failed$/u);
await expect(retry()).rejects.toThrow(/retry-b failed in another worker:[\s\S]*second build failed/u);
expect(builds).toBe(1);
});
it("C9 (다) gives the first attempts one build and its failure", async () => {
const environment = await sharedEnvironment();
let builds = 0;
const first = () =>
sharedFixtureBuild(
"retry-c",
"same",
async () => {
builds += 1;
await pause();
throw new Error("first build failed");
},
environment,
FIRST,
);
const together = await Promise.allSettled([first(), first(), first()]);
const late = await Promise.allSettled([first()]);
expect(builds).toBe(1);
for (const attempt of [...together, ...late]) {
expect(attempt).toMatchObject({
status: "rejected",
reason: { message: expect.stringContaining("first build failed") as unknown },
});
}
});
it.each(["succeeds", "fails"])(
"C9 (라) never builds twice at once in one folder for two retries, when the build %s",
async (outcome) => {
const { environment } = await failedFirstBuild("retry-d");
const building = new Map<string, number>();
let mostAtOnce = 0;
let builds = 0;
const retry = () =>
sharedFixtureBuild(
"retry-d",
"same",
async (root) => {
builds += 1;
building.set(root, (building.get(root) ?? 0) + 1);
mostAtOnce = Math.max(mostAtOnce, building.get(root)!);
await pause();
building.set(root, building.get(root)! - 1);
if (outcome === "fails") throw new Error("second build failed");
return root;
},
environment,
RETRY,
);
const both = await Promise.allSettled([retry(), retry()]);
expect(mostAtOnce).toBe(1);
expect(builds).toBe(1);
expect(both.map((attempt) => attempt.status)).toEqual(
outcome === "fails" ? ["rejected", "rejected"] : ["fulfilled", "fulfilled"],
);
},
);
it("C9 (마) does not build again on a retry when the first attempt's build succeeded", async () => {
const environment = await sharedEnvironment();
const first = await sharedFixtureBuild("retry-e", "same", async () => "built once", environment, FIRST);
let builds = 0;
const retry = await sharedFixtureBuild(
"retry-e",
"same",
async () => {
builds += 1;
return "built twice";
},
environment,
RETRY,
);
expect(builds).toBe(0);
expect(retry).toEqual(first);
});
});
/** Longest desktop run of a test below, over four runs, two of them with coverage (2026-11-22). */
const RUN_MS = 2_264;
// Only Playwright knows which attempt asks: the retry number reaches the
// helper through a describe's beforeAll, as in preload-use.spec.ts.
describe("a fixture build in a Playwright run", { timeout: childProcessTimeout(RUN_MS) }, () => {
it.each([
["once", 1, /^\s*3 flaky$/mu],
["twice", 2, /^\s*3 failed$/mu],
] as const)("C9 judges a build that fails %s by the retry's own build", async (_, failingBuilds, summary) => {
await mkdir(".tmp", { recursive: true });
const root = await mkdtemp(path.resolve(".tmp/shared-builds-run-"));
roots.push(root);
const log = path.join(root, "builds");
const source = (file: string) => JSON.stringify(pathToFileURL(path.resolve(file)).href);
await writeFile(
path.join(root, "probe.config.ts"),
`import { defineConfig } from "@playwright/test";
import { flakyJudgement, flakyJudgementReporter } from ${source("scripts/lib/playwright-flaky-judgement.ts")};
export default defineConfig({
testDir: ".",
testMatch: "probe.spec.ts",
globalSetup: ${JSON.stringify(path.resolve("tests/e2e/support/e2e-global-setup.ts"))},
...flakyJudgement(),
workers: 3,
projects: [{ name: "first" }, { name: "second" }, { name: "third" }],
outputDir: "results",
reporter: [["list"], flakyJudgementReporter],
});
`,
);
await writeFile(
path.join(root, "probe.spec.ts"),
`import { appendFileSync, readFileSync } from "node:fs";
import { test } from "@playwright/test";
import { sharedFixtureBuild } from ${source("tests/e2e/support/shared-fixture-builds.ts")};
test.describe("with a build", () => {
test.beforeAll(async () => {
await sharedFixtureBuild("probe", "same", async () => {
appendFileSync(${JSON.stringify(log)}, "b");
await new Promise((resolve) => setTimeout(resolve, 50));
if (readFileSync(${JSON.stringify(log)}, "utf8").length <= ${failingBuilds}) throw new Error("build failed");
return "built";
});
});
test("uses the build", () => {});
test("uses it again", () => {});
});
test("needs no build", () => {});
`,
);
const result = spawnSync(
process.execPath,
[createRequire(import.meta.url).resolve("@playwright/test/cli"), "test", "--config", path.join(root, "probe.config.ts")],
{
cwd: root,
// The child's environment is this test's, not the runner's.
env: {
PATH: process.env["PATH"],
HOME: process.env["HOME"],
TMPDIR: process.env["TMPDIR"],
FORCE_COLOR: "0",
CI: "true",
} as unknown as NodeJS.ProcessEnv,
encoding: "utf8",
},
);
const output = `${result.stdout}${result.stderr}`;
expect(result.status, output).not.toBe(0);
expect(output).toMatch(summary);
// One build for the first attempts and one for the retries, whatever the projects.
expect(await readFile(log, "utf8"), output).toBe("bb");
});
});