Files
clean-architecture-frontend…/tests/unit/run-isolation.test.ts
T
DongHyeonka 0e72c0c116 fix(test-run): Playwright 서버가 빈 포트를 고르고 dev 서버를 재사용하지 않는다
문제: 다섯 Playwright 설정의 서버 포트가 고정이다(e2e 4173, visual과
capability가 둘 다 4174, storybook 6006, dev 5173). 한 checkout이든 같은
기계의 두 worktree든 두 번째 실행은 `http://127.0.0.1:4173 is already
used`로 시작하지 못한다(00-R1). dev 설정만 `reuseExistingServer: true`라
5173에 다른 checkout·브랜치의 dev 서버가 떠 있으면 말없이 그 서버를
검사한다. vite는 `--strictPort` 없이 떠서, 포트가 그 사이 잡히면 다음
포트로 옮기고 Playwright는 원래 URL의 남의 서버를 검사할 수 있다
(1105/12-04).

고른 방법: 설정마다 `reservePort(TEST_<이름>_PORT)`로 빈 포트를 고른다
(`scripts/lib/run-isolation.ts`). 커널이 port 0에 준 포트를 받고 바로
닫는다. 고른 포트를 그 변수에 써 둔다. Playwright는 worker마다 설정을
다시 평가하고 worker는 runner 환경을 물려받으므로, worker의 평가가 같은
포트를 읽어 `baseURL`이 어디서나 같다. 변수를 미리 주면 그 포트를 쓴다
(디버깅용 고정). vite 서버 넷 모두 `--strictPort`로 띄우고, dev 설정은
`reuseExistingServer: false`로 바꿨다. run ID가 없어도 빈 포트를 쓴다.
두 worktree는 출력 경로가 이미 다르고 포트만 부딪히기 때문이다. 고정
번호를 읽는 곳은 없다. spec은 `baseURL`에서 origin을 얻는다
(`resumable-upload.spec.ts`, `production-csp.spec.ts`).
버린 대안: 포트 범위를 run ID에서 계산하기. 두 checkout이 같은 run ID를
쓰거나 다른 프로그램이 그 포트를 쓰면 다시 부딪힌다. Playwright
`webServer.wait`로 서버가 고른 포트를 stdout에서 읽기: `use.baseURL`은
설정을 읽을 때 정해져서 쓸 수 없다.

위험·한계: 포트를 고른 뒤 서버가 잡기 전에 다른 프로세스가 같은 포트를
잡을 수 있다. 그때는 `--strictPort`/serve-static의 listen 실패나
Playwright의 "already used"로 시작이 실패한다. 남의 서버로 검사가 새지
않는다. 기본 실행의 포트 번호가 매번 달라진다. 고정이 필요하면
`TEST_E2E_PORT=4173`처럼 준다. `test:e2e:dev`는 이제 떠 있는 dev 서버를
쓰지 않고 자기 서버를 띄운다. capability 설정이 없는 사본
(test:browser-file-storage-removal)에서는 그 설정의 포트 테스트를 돌리지 않는다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/run-isolation.test.ts tests/unit/playwright-run-isolation.test.ts
corepack pnpm test:browser-file-storage-removal

Refs: 1105/12-04
2026-11-06 02:58:00 +09:00

148 lines
5.3 KiB
TypeScript

import { createServer, type Server } from "node:net";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
findFreePort,
moduleSpecifier,
reservePort,
runOutputPath,
runOutputRoot,
testRunPath,
testRunRoot,
} from "../../scripts/lib/run-isolation.ts";
const servers: Server[] = [];
afterEach(async () => {
await Promise.all(
servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))),
);
});
async function listen(port: number): Promise<number> {
const server = createServer();
servers.push(server);
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(port, "127.0.0.1", () => resolve());
});
const address = server.address();
return typeof address === "object" && address !== null ? address.port : -1;
}
/**
* 1105/12-04. Builds and Playwright runs wrote to fixed paths (`dist`,
* `artifacts/tests/*`), so a second run in one checkout emptied the first
* one's dist and deleted its results. These are the path rules every config
* and build step uses.
*/
describe("test run paths (TEST_RUN_ID)", () => {
it("are the checkout's own paths without a run ID", () => {
for (const environment of [{}, { TEST_RUN_ID: "" }]) {
expect(testRunRoot(environment)).toBe(".");
expect(testRunPath("artifacts/tests/e2e/results", environment)).toBe(
"artifacts/tests/e2e/results",
);
expect(testRunPath("dist", environment)).toBe("dist");
}
});
it("give each run ID its own folder under .tmp/runs", () => {
const a = { TEST_RUN_ID: "gate-008.a" };
const b = { TEST_RUN_ID: "gate-008.b" };
expect(testRunRoot(a)).toBe(".tmp/runs/gate-008.a");
expect(testRunPath("artifacts/tests/e2e/results", a)).toBe(
".tmp/runs/gate-008.a/artifacts/tests/e2e/results",
);
expect(testRunPath("dist", b)).toBe(".tmp/runs/gate-008.b/dist");
expect(testRunPath("dist", a)).not.toBe(testRunPath("dist", b));
});
it("refuse a run ID that is not one folder name", () => {
for (const runId of ["../dist", "a/b", ".hidden", "-a", "a b", "x".repeat(65), "a\\b"]) {
expect(() => testRunRoot({ TEST_RUN_ID: runId }), runId).toThrow(/TEST_RUN_ID/u);
}
});
});
describe("build output root (RUN_OUTPUT_ROOT)", () => {
it("is the checkout without a root", () => {
for (const environment of [{}, { RUN_OUTPUT_ROOT: "" }, { RUN_OUTPUT_ROOT: "." }]) {
expect(runOutputRoot(environment)).toBe(".");
expect(runOutputPath("dist", environment)).toBe("dist");
expect(runOutputPath(".generated/frontend-runtime", environment)).toBe(
".generated/frontend-runtime",
);
}
});
it("puts every build output under a root in .tmp", () => {
const environment = { RUN_OUTPUT_ROOT: "./.tmp/runs/a/" };
expect(runOutputRoot(environment)).toBe(".tmp/runs/a");
expect(runOutputPath("dist/config.json", environment)).toBe(".tmp/runs/a/dist/config.json");
expect(runOutputPath("artifacts/release/build-manifest.json", environment)).toBe(
".tmp/runs/a/artifacts/release/build-manifest.json",
);
});
it("refuses a root outside .tmp, which git, Tailwind and the watchers do not ignore", () => {
for (const root of ["dist", "out/a", "/tmp/a", ".tmp", ".tmp/../dist", "../other", ".tmp\\a"]) {
expect(() => runOutputRoot({ RUN_OUTPUT_ROOT: root }), root).toThrow(/RUN_OUTPUT_ROOT/u);
}
});
});
describe("server ports", () => {
it("finds a port a server can listen on right away", async () => {
const port = await findFreePort();
expect(port).toBeGreaterThan(0);
expect(await listen(port)).toBe(port);
});
it("never offers a port another run's server holds", async () => {
const taken = await listen(0);
for (let attempt = 0; attempt < 20; attempt += 1) {
expect(await findFreePort()).not.toBe(taken);
}
});
it("keeps the port it picked in the variable, so the next evaluation reuses it", async () => {
const environment: Record<string, string | undefined> = {};
const find = vi.fn(async () => 41_234);
expect(await reservePort("TEST_E2E_PORT", environment, find)).toBe(41_234);
expect(environment["TEST_E2E_PORT"]).toBe("41234");
// A Playwright worker: same config, the runner's environment.
expect(await reservePort("TEST_E2E_PORT", environment, find)).toBe(41_234);
expect(find).toHaveBeenCalledTimes(1);
});
it("uses a port the caller pinned and refuses one that is not a port", async () => {
const find = vi.fn(async () => 41_234);
expect(await reservePort("TEST_DEV_PORT", { TEST_DEV_PORT: "5173" }, find)).toBe(5173);
expect(find).not.toHaveBeenCalled();
for (const value of ["0", "65536", "-1", "4173x", "abc", "41.5"]) {
await expect(reservePort("TEST_DEV_PORT", { TEST_DEV_PORT: value }, find), value)
.rejects.toThrow(/TEST_DEV_PORT/u);
}
});
});
describe("generated module specifiers", () => {
it("keep today's specifier in .generated and reach src from a deeper root", () => {
expect(
moduleSpecifier(".generated/frontend-runtime/contract-set.ts", "src/contracts/contract-set.ts"),
).toBe("../../src/contracts/contract-set.ts");
expect(
moduleSpecifier(
".tmp/runs/a/.generated/frontend-runtime/contract-set.ts",
"src/contracts/contract-set.ts",
),
).toBe("../../../../../src/contracts/contract-set.ts");
});
});