fix(test): 파일 존재로 정하던 run 격리·빌드 입력 검사를 소유자로 정한다
문제: 두 테스트가 검사 대상을 "파일이 있으면"으로 정한다. - `playwright-run-isolation.test.ts`는 capabilities 설정이 있을 때만 그 설정의 검사 8개를 정의한다(`existsSync`). browser-file-storage 드릴 사본에서 33개가 25개로 줄었는데 skip 보고가 없다. 템플릿에서 설정 이름을 바꾸고 테스트의 문자열만 놓쳐도 같이 빠진다. - `vite-build-inputs.test.ts`는 목록 소비자 둘을 `existsSync`로 거른다. 어느 제거 목록에도 없는 `product-feature-selection-build.test.ts`의 이름이 바뀌어도 검사가 빈 반복으로 통과한다. - 주석의 skip 차단 ID가 0929/10-04로 틀렸다. 1101/10-04다. 고른 방법(리뷰 문서 ⓐ): - capabilities 검사 8개를 `playwright-capabilities-run-isolation.test.ts`로 옮기고 설정을 이름으로 import한다. browser-file-storage 드릴이 설정과 이 파일을 이름으로 함께 지운다. 같은 드릴이 `ci-workflow-generation` 테스트를 지우는 방식이다. `force` 없이 지워, 이름이 바뀐 파일은 드릴이 그 자리에서 멈춘다. - 두 파일이 같은 검사를 쓰도록 불러오기·포트·결과 폴더 검사를 `tests/helpers/playwright-run-isolation.ts`로 뺐다. 단언은 그대로다. - `vite-build-inputs`는 빌드 테스트를 늘 읽는다. 측정 스크립트는 그 파일을 가진 제거 가능 기능(`removable-template-features.ts`)이 설치돼 있을 때(feature-module.ts가 있을 때, verify:documentation과 같은 규칙) 읽는다. 그 소유 기능이 없으면 실패한다. 기능 ID를 테스트에 쓰지 않는 것은 샘플 드릴의 residue 검사가 `src`·`tests`의 샘플 이름을 잡기 때문이다. - 틀린 ID 주석은 옮긴 검사와 함께 없어지고, 새 파일 머리말에 1101/10-04로 적었다. 버린 대안: 드릴이 표시를 넘기고 테스트가 읽는 방식(ⓑ). 드릴과 테스트 사이 계약이 늘고, capability를 지우는 제품이 테스트를 고쳐야 한다. 주석 ID만 고치기(ⓒ)는 공백이 남는다. 위험·한계: - 테스트 수는 템플릿 33개(25 + 8)로 같다. browser-file-storage 사본에서는 25개가 돌고 8개는 파일째 지워진다(드릴 코드에 적힘). - 측정 스크립트의 조건은 여전히 파일 존재(소유 기능의 feature-module.ts)다. 대상이 지울 수 있다고 등록된 소유자로 바뀌었다. - 이 노트북에서는 실행하지 못했다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/unit/playwright-run-isolation.test.ts tests/unit/playwright-capabilities-run-isolation.test.ts tests/unit/vite-build-inputs.test.ts 이름 바꾸기 변이 둘(capabilities 설정, product-feature-selection-build 테스트), check:types, lint, ci:gate FE-GATE-020 Refs: 1106/10-01
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
import { createServer, type Server } from "node:net";
|
||||
import path from "node:path";
|
||||
|
||||
import type { PlaywrightTestConfig } from "@playwright/test";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* 1105/12-04. The run-isolation checks every Playwright config shares, for
|
||||
* tests/unit/playwright-run-isolation.test.ts (the four configs every project
|
||||
* has) and tests/unit/playwright-capabilities-run-isolation.test.ts (the
|
||||
* capabilities config, which goes with the browser file/storage runtime).
|
||||
*
|
||||
* 1106/10-01. Each file imports its configs by name and passes them here, so
|
||||
* no check depends on which config files a checkout happens to have.
|
||||
*/
|
||||
export type ConfigName = "e2e" | "visual" | "capabilities" | "storybook" | "dev";
|
||||
export type ConfigLoaders = Readonly<
|
||||
Partial<Record<ConfigName, () => Promise<{ default: PlaywrightTestConfig }>>>
|
||||
>;
|
||||
|
||||
const PORT_VARIABLES: Readonly<Record<ConfigName, string>> = {
|
||||
e2e: "TEST_E2E_PORT",
|
||||
visual: "TEST_VISUAL_PORT",
|
||||
capabilities: "TEST_CAPABILITIES_PORT",
|
||||
storybook: "TEST_STORYBOOK_PORT",
|
||||
dev: "TEST_DEV_PORT",
|
||||
};
|
||||
const RUN_VARIABLES = ["TEST_RUN_ID", "RUN_OUTPUT_ROOT", ...Object.values(PORT_VARIABLES)];
|
||||
const held: Server[] = [];
|
||||
|
||||
/** For afterEach: forgets the loaded configs and frees the ports `hold` took. */
|
||||
export async function releaseRuns(): Promise<void> {
|
||||
vi.resetModules();
|
||||
await Promise.all(
|
||||
held.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))),
|
||||
);
|
||||
}
|
||||
|
||||
type ConfigProcess = Readonly<{
|
||||
config: PlaywrightTestConfig;
|
||||
after: Readonly<Record<string, string | undefined>>;
|
||||
}>;
|
||||
|
||||
export type ConfigRuns = Readonly<{
|
||||
/** The config as one process sees it, and what it left in that environment. */
|
||||
loadProcess(
|
||||
name: ConfigName,
|
||||
environment?: Readonly<Record<string, string>>,
|
||||
): Promise<ConfigProcess>;
|
||||
load(name: ConfigName, environment?: Readonly<Record<string, string>>): Promise<PlaywrightTestConfig>;
|
||||
}>;
|
||||
|
||||
/** Each load evaluates the config again with the environment of one process. */
|
||||
export function configRuns(loaders: ConfigLoaders): ConfigRuns {
|
||||
async function loadProcess(
|
||||
name: ConfigName,
|
||||
environment: Readonly<Record<string, string>> = {},
|
||||
): Promise<ConfigProcess> {
|
||||
const loader = loaders[name];
|
||||
if (loader === undefined) throw new TypeError(`no loader for the ${name} config`);
|
||||
const saved = RUN_VARIABLES.map((variable) => [variable, process.env[variable]] as const);
|
||||
for (const variable of RUN_VARIABLES) delete process.env[variable];
|
||||
Object.assign(process.env, environment);
|
||||
vi.resetModules();
|
||||
try {
|
||||
const config = (await loader()).default;
|
||||
return {
|
||||
config,
|
||||
after: Object.fromEntries(RUN_VARIABLES.map((variable) => [variable, process.env[variable]])),
|
||||
};
|
||||
} finally {
|
||||
for (const [variable, value] of saved) {
|
||||
if (value === undefined) delete process.env[variable];
|
||||
else process.env[variable] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
loadProcess,
|
||||
load: async (name, environment = {}) => (await loadProcess(name, environment)).config,
|
||||
};
|
||||
}
|
||||
|
||||
export function portOf(config: PlaywrightTestConfig): number {
|
||||
return Number(new URL(String(config.use?.baseURL)).port);
|
||||
}
|
||||
|
||||
/** Listens on `port` the way the first run's server does. */
|
||||
export async function hold(port: number): Promise<void> {
|
||||
const server = createServer();
|
||||
held.push(server);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, "127.0.0.1", () => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function reporterOption(config: PlaywrightTestConfig, reporter: string, option: string): string {
|
||||
const reporters: readonly unknown[] = Array.isArray(config.reporter) ? config.reporter : [];
|
||||
const entry = reporters.find(
|
||||
(candidate) => Array.isArray(candidate) && candidate[0] === reporter,
|
||||
) as readonly [string, Record<string, unknown>] | undefined;
|
||||
return String(entry?.[1][option]);
|
||||
}
|
||||
|
||||
function outputs(config: PlaywrightTestConfig) {
|
||||
return {
|
||||
results: path.resolve(String(config.outputDir)),
|
||||
report: path.resolve(reporterOption(config, "html", "outputFolder")),
|
||||
junit: path.resolve(reporterOption(config, "junit", "outputFile")),
|
||||
};
|
||||
}
|
||||
|
||||
export function webServer(config: PlaywrightTestConfig) {
|
||||
const server = config.webServer;
|
||||
if (!server || Array.isArray(server)) throw new TypeError("expected one web server");
|
||||
return server;
|
||||
}
|
||||
|
||||
/** Each config's results, report and JUnit file, by its folder under artifacts/tests. */
|
||||
export function describeResultFolders(
|
||||
runs: ConfigRuns,
|
||||
folders: readonly (readonly [ConfigName, string])[],
|
||||
): void {
|
||||
describe.each(folders)("the %s config", (name, folder) => {
|
||||
const expected = (root: string) => ({
|
||||
results: path.resolve(root, `artifacts/tests/${folder}/results`),
|
||||
report: path.resolve(root, `artifacts/tests/${folder}/report`),
|
||||
junit: path.resolve(root, `artifacts/tests/${folder}/results.xml`),
|
||||
});
|
||||
|
||||
it("writes where the gates read without a run ID", async () => {
|
||||
expect(outputs(await runs.load(name as ConfigName))).toEqual(expected("."));
|
||||
});
|
||||
|
||||
it("gives each run ID its own results, report and JUnit file", async () => {
|
||||
const a = outputs(await runs.load(name as ConfigName, { TEST_RUN_ID: "a" }));
|
||||
const b = outputs(await runs.load(name as ConfigName, { TEST_RUN_ID: "b" }));
|
||||
|
||||
expect(a).toEqual(expected(".tmp/runs/a"));
|
||||
expect(b).toEqual(expected(".tmp/runs/b"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Inside "the build a run serves": the dev servers' Vite cache. */
|
||||
export function itKeepsTheViteCacheInTheRun(runs: ConfigRuns, names: readonly ConfigName[]): void {
|
||||
it.each(names)("keeps the dev server's Vite cache in the run's folder (%s)", async (name) => {
|
||||
expect(webServer(await runs.load(name)).env?.["RUN_OUTPUT_ROOT"]).toBe(".");
|
||||
expect(webServer(await runs.load(name, { TEST_RUN_ID: "a" })).env?.["RUN_OUTPUT_ROOT"]).toBe(
|
||||
".tmp/runs/a",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function describeServerPorts(runs: ConfigRuns, names: readonly ConfigName[]): void {
|
||||
describe.each(names)("the %s server port", (name) => {
|
||||
it("is a free port the runner hands to its workers", async () => {
|
||||
const runner = await runs.loadProcess(name);
|
||||
const port = portOf(runner.config);
|
||||
const server = webServer(runner.config);
|
||||
|
||||
// Playwright evaluates the config again in each worker, which inherits
|
||||
// the runner's environment: the port is there, so baseURL agrees.
|
||||
expect(runner.after[PORT_VARIABLES[name]]).toBe(String(port));
|
||||
expect(portOf(await runs.load(name, { [PORT_VARIABLES[name]]: String(port) }))).toBe(port);
|
||||
expect(server.url).toBe(`http://127.0.0.1:${port}`);
|
||||
expect(server.command).toMatch(new RegExp(` (?:--port )?${port}(?: |$)`, "u"));
|
||||
expect(server.reuseExistingServer).toBe(false);
|
||||
});
|
||||
|
||||
it("moves for a second run while the first run's server holds its port", async () => {
|
||||
const first = portOf(await runs.load(name));
|
||||
await hold(first);
|
||||
|
||||
expect(portOf(await runs.load(name))).not.toBe(first);
|
||||
});
|
||||
|
||||
it("is the one its variable pins", async () => {
|
||||
const pinned = await runs.load(name, { [PORT_VARIABLES[name]]: "40123" });
|
||||
expect(portOf(pinned)).toBe(40123);
|
||||
expect(webServer(pinned).url).toBe("http://127.0.0.1:40123");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Inside "vite servers": the configs whose server is vite. */
|
||||
export function itExitsWhenItsPortIsTaken(runs: ConfigRuns, names: readonly ConfigName[]): void {
|
||||
it.each(names)(
|
||||
"exit instead of moving to the next port when theirs is taken (%s)",
|
||||
async (name) => {
|
||||
// Without --strictPort vite moved on, and Playwright, waiting on the
|
||||
// configured URL, tested whatever already listened there.
|
||||
expect(webServer(await runs.load(name)).command).toMatch(/ --port \d+ --strictPort(?: |$)/u);
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user