Files
clean-architecture-frontend…/tests/scripts/generate-product-feature-index.test.ts
DongHyeonka 91962e24e3 test(setup): 자식 프로세스를 띄우는 시험이 잰 시간으로 timeout을 정한다
자식 프로세스를 띄우는 Vitest 시험 91개(24파일)가 기본 timeout 10초에
기대고 있었다. 셋은 FE-GATE-013에서만 도는 tests/system 시험이다.
기본값은 프로세스 안에서 도는 시험에 맞춘 값이다. 부하가 높은
desktop에서는 자식 프로세스 시험이 평소보다 크게 느려진다.
FE-GATE-020 drill 사본에서 평소 0.4~1.2초인 문서 시험이 10.6초 걸려
실패했다(2026-11-12). 가장 위험한 것은 tests/architecture/app-build-input
.test.ts로, desktop에서 이미 5.7초까지 걸렸다.

무엇을 고칠지는 desktop 계측으로 정했다.
- test:coverage 묶음(maxWorkers=4)과 test:unit을 세 번씩 돌렸다. 시험마다
  띄운 자식 프로세스는 child_process 함수를 감싸 기록했고, 소요 시간은
  JSON reporter로 받았다.
- 시험마다 실제 timeout은 task.timeout으로 기록했다.
- 자식 프로세스를 띄우는 시험 140개 중 88개가 기본값이었다. tests/system은
  그 묶음에 없어서, 아래 검사가 잡은 셋을 따로 세 번 쟀다.

고친 것:
- tests/helpers/child-process-timeout.ts의 childProcessTimeout(<잰 최대
  ms>)는 그 15배를 30초 단위로 올린 값이다. 15배는 위 0.7초 → 10.6초에서
  왔다. 시험마다 자기가 잰 최대값을 인자로 적어 근거가 호출 자리에 남는다.
- describe 안의 기본값 시험이 모두 자식 프로세스를 띄우면 describe에,
  일부만 띄우면 그 시험에 준다. 프로세스 안에서 도는 시험의 hang을 늦게
  잡지 않으려는 것이다.
- tests/setup.ts가 child_process 함수를 감싼다. 기본 timeout인 시험이
  자식 프로세스를 띄우면 그 호출에서 실패시키고, helper 이름을 알린다.
  helper나 시험이 import한 스크립트가 띄워도 잡는다. util.promisify가
  읽는 속성은 원래 함수에서 옮긴다.
- docs/work/reference/testing.md 2절에 값 정하는 법과 이 검사를 적었다.

버린 것:
- 전역 testTimeout 올리기: 프로세스 안 시험의 hang을 늦게 잡는다.
- 시험마다 손으로 정한 숫자: 근거가 남지 않고, 이미 있는 값도
  60_000·120_000처럼 근거가 없었다.
- 자식 프로세스를 띄우지 않게 바꾸기: 검사 스크립트를 CLI 그대로 시험하는
  것이 이 시험들의 목적이라 범위가 커진다.
- 파일에 timeout 선언이 있는지만 보는 정적 검사: helper가 띄우는 경우와
  같은 파일의 다른 시험을 놓친다.

위험:
- hook(beforeAll 등)에서 띄우는 프로세스는 검사하지 않는다. 계측에서
  hook이 띄운 곳은 둘이고, 둘 다 180초를 선언했다.
- 같은 파일 안에서 it.concurrent로 도는 시험이 섞이면 어느 시험의
  timeout인지 틀릴 수 있다. 지금은 그런 시험이 없다.
- 다운스트림 시험이 기본값으로 자식 프로세스를 띄우면 test:unit 등이
  실패한다. 메시지가 helper를 알린다.

검증(desktop):
- 다섯 검사(test:unit·check:types·check:ci·lint·verify:documentation)
  rc=0.
- 자식 프로세스를 띄우는 시험 파일 40개와 tests/scale: rc=0, 검사 위반 0.
- tests/system: 115개 중 18개 실패. 모두 bwrap 호스트 제약이고 검사
  위반은 0이다.
- 변이: 검사를 끄면 tests/unit/child-process-timeout.test.ts가 실패한다.
  tracked-artifacts describe의 timeout을 지우면 그 시험이 검사 메시지로
  실패한다.
- 재현: CPU 10% 제한에서 app-build-input·registry-governance·hosting-probe
  ·design-system-rules를 돌렸다. main 650d22fa는 11개가 10초 timeout으로
  실패했다. 이 커밋은 71개 모두 통과했고, 가장 긴 시험은 17.7초였다.
2026-11-12 11:22:59 +09:00

281 lines
12 KiB
TypeScript

import { rm } from "node:fs/promises";
import { afterEach, describe, expect, it } from "vitest";
import {
generateAppIndexes,
renderContextIndex,
renderFeatureIndex,
selectAppIndexes,
type TopologyDeclarationSource,
} from "../../scripts/generate-product-feature-index.ts";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
describe("feature index generator", () => {
it("is deterministic by normalized id", () => {
const first = renderFeatureIndex([
{ id: "zeta", importPath: "../features/zeta/feature-module.ts" },
{ id: "alpha", importPath: "../features/alpha/feature-module.ts" },
]);
const second = renderFeatureIndex([
{ id: "alpha", importPath: "../features/alpha/feature-module.ts" },
{ id: "zeta", importPath: "../features/zeta/feature-module.ts" },
]);
expect(first).toBe(second);
expect(first.indexOf("alpha")).toBeLessThan(first.indexOf("zeta"));
});
it("emits a base feature module fallback for an empty product", () => {
const rendered = renderFeatureIndex([]);
expect(rendered).toContain(
'import type { FeatureModule } from "../features/feature-module.ts";',
);
expect(rendered).toContain("type GeneratedProductFeatureModule =");
expect(rendered).toContain(
"[GeneratedProductFeatureModule] extends [never]",
);
expect(rendered).toContain("? FeatureModule");
});
it("groups feature route executables behind one lazy context loader", () => {
const rendered = renderContextIndex([
{
id: "catalog-search",
importPath: "../features/catalog-search/feature-module.ts",
directory: "catalog-search",
contextId: "catalog",
contextRoutePath: "catalog/*",
contextMaxFeatures: 200,
},
{
id: "catalog-detail",
importPath: "../features/catalog-detail/feature-module.ts",
directory: "catalog-detail",
contextId: "catalog",
contextRoutePath: "catalog/*",
contextMaxFeatures: 200,
},
]);
expect(rendered.match(/defineBoundedContextModule\(\{/gu)).toHaveLength(1);
expect(rendered).toContain(
'import("../features/catalog-search/context-routes.ts")',
);
expect(rendered).toContain(
'import("../features/catalog-detail/context-routes.ts")',
);
expect(rendered).not.toContain(
'from "../features/catalog-search/context-routes.ts"',
);
expect(rendered).not.toContain(
'from "../features/catalog-detail/context-routes.ts"',
);
});
it("emits no context loader for an empty product", () => {
expect(renderContextIndex([])).toBe(
"// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\n" +
"export const PRODUCT_CONTEXT_MODULES = Object.freeze([] as const);\n",
);
});
});
describe("app-scoped selection from ownership declarations", () => {
// 00-03. The fake repositories used to stay in /tmp.
const temporaryRoots: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
async function repo(files: Record<string, string>) {
const { mkdtemp, mkdir, writeFile } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const path = await import("node:path");
const root = await mkdtemp(path.join(tmpdir(), "generator-"));
temporaryRoots.push(root);
for (const [file, content] of Object.entries(files)) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
}
return root;
}
const app = (id: string, max = 20) =>
`export const APP_MODULE_ID = "${id}";\nexport const APP_MAX_CONTEXTS = ${max};\n`;
const context = (id: string, appId: string, max = 200) =>
`export const CONTEXT_MODULE_ID = "${id}";\nexport const CONTEXT_APP_ID = "${appId}";\n` +
`export const CONTEXT_ROUTE_PATH = "${id}/*";\nexport const CONTEXT_MAX_FEATURES = ${max};\n`;
const feature = (id: string, contextId: string) =>
`export const FEATURE_MODULE_ID = "${id}";\nexport const FEATURE_CONTEXT_ID = "${contextId}";\n`;
it("rejects a feature owned by an undeclared context", async () => {
const root = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/features/f/feature-module.ts": feature("f", "missing"),
});
await expect(generateAppIndexes(root, "a")).rejects.toThrow(/undeclared context missing/);
});
it("rejects a context owned by an undeclared app", async () => {
const root = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/contexts/c/context-module.ts": context("c", "ghost"),
});
await expect(generateAppIndexes(root, "a")).rejects.toThrow(/undeclared app ghost/);
});
it("enforces the context feature budget and the app context budget", async () => {
const overFeatures = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/contexts/c/context-module.ts": context("c", "a", 1),
"src/features/f1/feature-module.ts": feature("f1", "c"),
"src/features/f2/feature-module.ts": feature("f2", "c"),
});
await expect(generateAppIndexes(overFeatures, "a")).rejects.toThrow(/c feature cardinality 2 exceeds budget 1/);
const overContexts = await repo({
"src/apps/a/app-module.ts": app("a", 1),
"src/contexts/c1/context-module.ts": context("c1", "a"),
"src/contexts/c2/context-module.ts": context("c2", "a"),
"src/features/f1/feature-module.ts": feature("f1", "c1"),
"src/features/f2/feature-module.ts": feature("f2", "c2"),
});
await expect(generateAppIndexes(overContexts, "a")).rejects.toThrow(/App a context cardinality 2 exceeds budget 1/);
});
it("refuses a feature directory without a declaration (09-07)", async () => {
const files = {
"src/apps/a/app-module.ts": app("a"),
"src/contexts/c/context-module.ts": context("c", "a"),
"src/features/f/feature-module.ts": feature("f", "c"),
// A misspelt declaration file used to drop the feature without a word.
"src/features/typo/feature-modul.ts": feature("typo", "c"),
};
await expect(generateAppIndexes(await repo(files), "a")).rejects.toThrow(
/src\/features\/typo has no feature-module\.ts; add one, or keep code that is no feature outside src\/features/u,
);
});
it("reads a marker file as a missing declaration", async () => {
// The local-draft sample used to skip the check with a NOT_A_FEATURE
// file; it is a test fixture now and the marker is gone.
const root = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/contexts/c/context-module.ts": context("c", "a"),
"src/features/sample/NOT_A_FEATURE": "Composed only by tests.\n",
});
await expect(generateAppIndexes(root, "a")).rejects.toThrow(
/src\/features\/sample has no feature-module\.ts/u,
);
});
it("skips contexts without features and never imports another app's features", async () => {
const root = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/apps/b/app-module.ts": app("b"),
"src/contexts/empty/context-module.ts": context("empty", "a"),
"src/contexts/ca/context-module.ts": context("ca", "a"),
"src/contexts/cb/context-module.ts": context("cb", "b"),
"src/features/fa/feature-module.ts": feature("fa", "ca"),
"src/features/fb/feature-module.ts": feature("fb", "cb"),
});
const selected = await generateAppIndexes(root, "a");
expect(selected.entries.map((entry) => entry.id)).toEqual(["fa"]);
expect(selected.contextIndex).not.toContain("empty");
expect(selected.featureIndex).not.toContain("features/fb/");
expect(selected.appIndex).toContain('id: "a"');
});
it("loads a context's own layout lazily when it has a context-layout.tsx (09-03)", async () => {
const layout = "export const CONTEXT_LAYOUT = () => null;\n";
const selected = await generateAppIndexes(
await repo({
"src/apps/a/app-module.ts": app("a"),
"src/contexts/site-dir/context-module.ts": context("site", "a"),
"src/contexts/site-dir/context-layout.tsx": layout,
"src/contexts/topics/context-module.ts": context("topics", "a"),
"src/contexts/topics/context-layout.tsx": layout,
"src/contexts/shop/context-module.ts": context("shop", "a"),
"src/features/fs/feature-module.ts": feature("fs", "site"),
"src/features/ft/feature-module.ts": feature("ft", "topics"),
"src/features/fp/feature-module.ts": feature("fp", "shop"),
}),
"a",
);
const index = selected.contextIndex;
expect(index).toContain(
'loadLayout: async () => (await import("../contexts/site-dir/context-layout.tsx")).CONTEXT_LAYOUT,',
);
expect(index).toContain('import("../contexts/topics/context-layout.tsx")');
expect(index).not.toMatch(/from "\.\.\/contexts\/[^"]+\/context-layout\.tsx"/u);
// The shop context has none and stays under AppShell.
expect(index.match(/loadLayout:/gu)).toHaveLength(2);
});
});
describe("build-time product selection (09-02)", () => {
const source: TopologyDeclarationSource = Object.freeze({
appIds: () => ["a"],
app: (appId: string) =>
appId === "a" ? Object.freeze({ id: "a", maxContexts: 20 }) : undefined,
contextsOf: () => [
Object.freeze({ id: "c", appId: "a", routePath: "c/*", maxFeatures: 200 }),
],
featuresOf: () => [
Object.freeze({ id: "f1", contextId: "c", directory: "f1" }),
Object.freeze({ id: "f2", contextId: "c", directory: "f2" }),
],
});
const declared =
'DECLARED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze(["f1", "f2"])';
it("keeps every declared feature when nothing is selected", () => {
for (const selection of [undefined, "", " "]) {
const selected = selectAppIndexes(source, "a", selection);
expect(selected.entries.map((entry) => entry.id)).toEqual(["f1", "f2"]);
expect(selected.featureIndex).toBe(selectAppIndexes(source, "a").featureIndex);
expect(selected.featureIndex).toContain(declared);
}
});
it("imports only the selected features and still declares the rest", () => {
const selected = selectAppIndexes(source, "a", "f2");
expect(selected.entries.map((entry) => entry.id)).toEqual(["f2"]);
expect(selected.featureIndex).not.toContain("features/f1/");
expect(selected.contextIndex).not.toContain("features/f1/");
expect(selected.contextIndex).toContain("features/f2/context-routes.ts");
expect(selected.featureIndex).toContain(declared);
});
it("imports nothing for an explicit none", () => {
const selected = selectAppIndexes(source, "a", "none");
expect(selected.entries).toEqual([]);
expect(selected.featureIndex).not.toMatch(/features\/f[12]\//u);
expect(selected.contextIndex).toBe(renderContextIndex([]));
expect(selected.featureIndex).toContain(declared);
});
it("fails generation on an id the app does not declare", () => {
expect(() => selectAppIndexes(source, "a", "f1,f3")).toThrow(
/VITE_PRODUCT_FEATURES names features this build does not contain: f3/u,
);
});
it("fails the generator command, the first build step, on a misspelt id", async () => {
const { spawnSync } = await import("node:child_process");
const run = spawnSync(
process.execPath,
["scripts/generate-product-feature-index.ts", "--check"],
{
encoding: "utf8",
env: { ...process.env, VITE_PRODUCT_FEATURES: "reference-featrue" },
},
);
expect(run.status).not.toBe(0);
expect(run.stderr).toMatch(/does not contain: reference-featrue/u);
}, childProcessTimeout(157));
});