Files
clean-architecture-frontend…/tests/unit/create-feature.test.ts
T
DongHyeonka 7db32e1343 fix(http): V3 실행기가 짝 백엔드 Envelope를 operation 단위로 읽는다
문제
create:feature가 만든 기능과 참조 기능이 쓰는 V3 실행기
(http-execution-v3.ts, feature-http-binding.ts)는 성공 본문을 DTO로,
실패 본문을 problem details(최상위 code)로 바로 검증한다. 짝 백엔드는
모든 JSON 응답을 Envelope {success, data|error, meta}로 보내고 null 필드는
키째 뺀다(백엔드 docs/web/http-contract.md 1절). 그래서 생성한 기능은 짝
백엔드의 성공을 SCHEMA_MISMATCH로, 실패를 PROBLEM_SCHEMA_INVALID(쓰기는
결과 불명)로 읽는다. 백엔드 맞추기(969979d~64e98ee)는 V2 클라이언트에만
들어갔다.

고른 방법: (가) V3 실행기에 operation 단위 Envelope 읽기
- V3 descriptor에 선택 필드 responseEnvelope("NONE" | "ENVELOPE_V1")를
  둔다. 조립은 이 키를 허용하고 모르는 값을 거부한다. 값이 없으면 지금과
  같다.
- ENVELOPE_V1이면 실행기가 바이트 상한·구조 예산을 Envelope 전체에 건 뒤
  프레임을 확인한다. outputValidator는 data(키가 없으면 null),
  problemValidator는 error를 받는다. 성공 status에 Envelope가 아닌 본문은
  새 위반 ENVELOPE_MISMATCH다. 실패 Envelope의 바이트 상한은
  min(64 KiB, responseByteLimit)이다.
- V2 client.ts의 멱등성 거절 표·필드 검증 판정·gateway status 규칙을
  backend-envelope.ts로 옮기고 V2, V3 실행기, feature binding이 함께
  읽는다. 실행기는 그 표의 판정(422·400 거절, 필드 목록 400은 적용 안 됨,
  409 IDEMPOTENT_IN_FLIGHT·503 IDEMPOTENCY_UNAVAILABLE은 결과 불명)을
  classifyProblem보다 먼저 쓴다. binding은 mapProblem이 답하지 않으면 V2와
  같은 kind·code·validationIssues로 읽는다. V2 출력은 바뀌지 않았다.
- create:feature 뼈대: contribution이 ENVELOPE_V1을 선언하고 problem
  스키마가 Envelope error(code 필수)다. 백엔드 본문을 그대로 적은
  <base>-http-gateway.test.ts를 생성한다.
- MSW createHttpScenarioHandler는 descriptor가 ENVELOPE_V1이면 Envelope로
  답한다.

버린 대안
- provider 단위(실행기 전체): V3 실행기는 baseUrl 하나라 앱 전체가 바뀐다.
  참조 기능·테스트 계약의 problem details fixture가 모두 깨지고 한 앱이 두
  모양의 API를 쓸 수 없다.
- (나) 백엔드 problem+json·DTO 모드: 백엔드 소유자 결정 2(JSON은 모두
  Envelope)와 반대이고 백엔드가 두 모양을 계속 유지해야 한다.
- (다) 기능 스키마가 Envelope를 감쌈: 기능마다 null 생략·success 판별·
  멱등성 판정을 다시 쓰고, V2 행(data 스키마)과 V3 스키마 ID가 갈라진다.

위험·한계
- HttpContractViolationKind에 ENVELOPE_MISMATCH가 더해졌다. default 없는
  exhaustive switch는 분기를 더해야 한다.
- 실행기가 ENVELOPE_V1 operation의 위 판정을 classifyProblem보다 먼저
  정한다. 패키지가 409 IDEMPOTENT_IN_FLIGHT를 적용 안 됨이라 해도 결과
  불명이다.
- V2와 남은 차이: 64 KiB를 넘는 실패 Envelope는 V3만 읽지 않는다. 보낸
  KEYED 요청의 503은 V2만 같은 키로 자동 재시도한다(판정은 같다). 구조
  예산은 V3에만 있다.
- 참조 기능은 그대로 DTO·problem details다. tests/e2e/accessibility.spec.ts는
  모든 API에 []로 답하므로 생성한 기능 라우트는 오류 화면이 검사된다(e2e는
  돌리지 않았다).
- 초기 JS 202,770 → 203,321 B(+551 B, 예산 204,800 B).

검증
- RED: tests/integration/http-execution-v3-envelope.test.ts 19건 중 17건
  실패(성공 → SCHEMA_MISMATCH, 실패 → PROBLEM_SCHEMA_INVALID·MAYBE_APPLIED,
  조립 → unexpected key: responseEnvelope). 크기 2건은 처음부터 통과(동작
  고정).
- GREEN: 같은 파일 25건 통과. 같은 응답을 V2와 V3에 보내 kind·code·
  httpStatus·effect·retryAfterMs·validationIssues가 같음을 7가지 응답으로
  비교한다.
- check:types, lint, check:architecture, check:adapter-inventory,
  check:registries, check:diagnostics, check:i18n, check:ci 통과.
  test:unit 2,604, test:component 244, test:integration 200 통과.
  tests/features·tests/contract 124건 통과.
  test:feature-scaffold 16개 검사 통과(생성한 gateway 테스트 5건,
  Envelope로 답하는 목록 화면 테스트 3건 포함).
  test:sample-removal 23개 검사 통과.
  check:bundle 통과(203,321 / 204,800 B).

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.3, 14.6
2026-11-03 20:10:51 +09:00

255 lines
9.7 KiB
TypeScript

import { access, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
CreateFeatureError,
planFeature,
randomTopicSuffix,
writeFeatureFiles,
type FeatureRequest,
type InstalledFacts,
} from "../../scripts/create-feature.ts";
import { PLACEHOLDER_CONTRACT_PACKAGE_DIGEST } from "../../src/contracts/deployment-admission.ts";
/**
* U7. What `pnpm create:feature` renders, checked without touching the
* repository. test:feature-scaffold writes a feature into a copy and runs the
* gates on it; this file covers the ids, the topic, the order and the refusals.
*/
const INSTALLED: InstalledFacts = Object.freeze({
appIds: ["template-app"],
featureIds: ["orders-feature", "drafts-feature"],
contexts: [
{ id: "orders-context", routePath: "orders/*" },
{ id: "billing-context", routePath: "billing/*" },
],
contextDirectories: ["orders-context", "billing-context"],
routes: [
{ routeId: "APP_HOME", path: "/", chunkId: "route-home", navigationOrder: 10 },
{ routeId: "ORDERS_LIST", path: "/orders", chunkId: "route-orders-list", navigationOrder: 50 },
{ routeId: "NOT_FOUND", path: "*", chunkId: "route-not-found", navigationOrder: null },
],
topics: ["qinv.0000000000000000000000000a"],
messageKeys: ["route.APP_HOME.title", "home.list.title"],
});
const TOPIC_SUFFIX = "abcdefghjkmnpqrstvwxyz0123";
function plan(request: FeatureRequest, installed: InstalledFacts = INSTALLED) {
return planFeature(request, installed, () => TOPIC_SUFFIX);
}
function rendered(request: FeatureRequest): string {
return [...plan(request).files.values()].join("\n");
}
describe("create:feature rendering", () => {
it("prefixes every global id with the feature and carries no sample token", () => {
const text = rendered({ id: "invoice-feature" });
expect(text).not.toMatch(/reference/iu);
const ids = [
...text.matchAll(
/\b(?:schemaId|inputSchemaId|operationId|mapperId|outputContractId|policyId|diagnosticsOperation|definitionId|chunkId|routeId|moduleId|loadingSurface|contributionId|owner)\s*:\s*"([^"]+)"/gu,
),
...text.matchAll(/\bzodValidator\(\s*"([^"]+)"/gu),
...text.matchAll(/defineQueryNamespaceIdentity\(\s*"([^"]+)"/gu),
...text.matchAll(/kind: "([a-z][^"]*\.[^"]*)"/gu),
...text.matchAll(/^\s+"((?:route\.)?[A-Za-z_.]+)": "/gmu),
].map((match) => match[1] ?? "");
expect(ids.length).toBeGreaterThan(30);
for (const id of ids) {
expect(id).toMatch(
/^(?:INVOICE_|Invoice|invoice[.-]|route\.INVOICE_LIST\.|route-invoice-|feature-frontend-invoice-feature$)/u,
);
}
expect(text).not.toMatch(/"NoRequest"/u);
});
it("names the route, context and topic it creates", () => {
const created = plan({ id: "invoice-feature" });
expect(created).toMatchObject({
contextId: "invoice-context",
newContext: true,
routeId: "INVOICE_LIST",
routePath: "/invoice",
topic: `qinv.${TOPIC_SUFFIX}`,
placeholder: true,
});
expect([...created.files.keys()]).toEqual(
expect.arrayContaining([
"src/contexts/invoice-context/context-module.ts",
"src/features/invoice-feature/feature-module.ts",
"tests/features/invoice-feature/invoice-feature-input.test.ts",
"tests/features/invoice-feature/invoice-list-page.test.tsx",
"artifacts/tests/a11y-manual/INVOICE_LIST.md",
]),
);
expect([...created.files.keys()].some((file) => file.includes("/domain/"))).toBe(false);
expect(created.files.get("src/contexts/invoice-context/context-module.ts")).toContain(
'CONTEXT_ROUTE_PATH = "invoice/*"',
);
expect(created.files.get("artifacts/tests/a11y-manual/INVOICE_LIST.md")).toMatch(
/^Status: pending-manual-review$/mu,
);
});
it("generates a fresh lower-case 26-character topic and refuses an installed one", () => {
const first = randomTopicSuffix();
expect(first).toMatch(/^[0-9a-hjkmnp-tv-z]{26}$/u);
expect(randomTopicSuffix()).not.toBe(first);
expect(() =>
planFeature({ id: "invoice-feature" }, INSTALLED, () => "0000000000000000000000000a"),
).toThrow(/qinv\.0000000000000000000000000a is already installed/u);
});
it("places the route after the last navigation entry", () => {
expect(rendered({ id: "invoice-feature" })).toContain("navigationOrder: 60,");
});
it("adds the route under an existing context's root", () => {
const created = plan({ id: "invoice-feature", context: "billing-context" });
expect(created).toMatchObject({ newContext: false, routePath: "/billing/invoice" });
expect([...created.files.keys()].some((file) => file.startsWith("src/contexts/"))).toBe(false);
});
it("pins the placeholder through its exported constant, or the given package", () => {
expect(rendered({ id: "invoice-feature" })).toContain(
"digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,",
);
const digest = `sha256:${"ab".repeat(32)}`;
const pinned = plan({
id: "invoice-feature",
contractPackage: {
packageId: "@org-contracts/invoice",
version: "1.4.2",
digest,
sourceRevision: "0a1b2c3d",
},
});
const contract = pinned.files.get(
"src/features/invoice-feature/contracts/invoice-feature-contract.ts",
);
expect(pinned.placeholder).toBe(false);
expect(contract).toContain(`digest: "${digest}",`);
expect(contract).not.toContain("PLACEHOLDER");
expect(digest).not.toBe(PLACEHOLDER_CONTRACT_PACKAGE_DIGEST);
});
// 1101 README 14.3. test:feature-scaffold runs the gateway test this renders.
it("reads the paired backend's Envelope and tests it with the backend's own bodies", () => {
const { files } = plan({ id: "invoice-feature" });
const contracts = "src/features/invoice-feature/contracts";
expect(files.get(`${contracts}/invoice-contract-contribution.ts`)).toContain(
'responseEnvelope: "ENVELOPE_V1" as const,',
);
expect(files.get(`${contracts}/invoice-schemas.ts`)).toMatch(
/invoiceProblemSchema = z\s*\.object\(\{\s*code: z\.string\(\)\.regex/u,
);
expect(
files.get("tests/features/invoice-feature/invoice-http-gateway.test.ts"),
).toContain('success: true, data: [{ id: "item-1", name: "First item" }]');
});
});
describe("create:feature refusals", () => {
it.each(["Invoice", "invoice_feature", "-invoice", "invoice--x", "invoice-", "", "a".repeat(41)])(
"refuses the id %j",
(id) => {
expect(() => plan({ id })).toThrow(/kebab-case/u);
},
);
it.each([
[{ id: "orders-feature" }, /already a feature or context/u],
[{ id: "orders-context" }, /already a feature or context/u],
[{ id: "orders" }, /prefix its ids with "orders", which orders-feature already uses/u],
[{ id: "billing-feature" }, /pass --context billing-context/u],
[{ id: "invoice-feature", context: "orders" }, /already owns the route root orders\/\*/u],
[{ id: "invoice-feature", context: "drafts-feature" }, /is a feature id/u],
[{ id: "home-feature" }, /message keys already exist: home\.list\.title/u],
[
{
id: "invoice-feature",
contractPackage: {
packageId: "@org-contracts/invoice",
version: "1.4.2",
digest: "sha256:abc",
sourceRevision: "0a1b2c3d",
},
},
/not a pinned identity: invoice-feature: package digest/u,
],
] as const)("refuses %j", (request, reason) => {
expect(() => plan(request)).toThrow(reason);
});
it("refuses a route that collides with an installed one", () => {
expect(() =>
plan(
{ id: "invoice-feature" },
{
...INSTALLED,
routes: [
...INSTALLED.routes,
{ routeId: "LEGACY", path: "/invoice", chunkId: "route-legacy", navigationOrder: null },
],
},
),
).toThrow(/collides with installed route LEGACY/u);
});
});
describe("create:feature writing", () => {
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
async function emptyRoot(): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), "create-feature-"));
roots.push(root);
return root;
}
it("refuses to overwrite and writes nothing when one target exists", async () => {
const root = await emptyRoot();
const files = plan({ id: "invoice-feature" }).files;
await mkdir(path.join(root, "artifacts/tests/a11y-manual"), { recursive: true });
await writeFile(path.join(root, "artifacts/tests/a11y-manual/INVOICE_LIST.md"), "kept\n");
await expect(writeFeatureFiles(root, files)).rejects.toThrow(
/refusing to overwrite: artifacts\/tests\/a11y-manual\/INVOICE_LIST\.md/u,
);
expect(await readdir(root)).toEqual(["artifacts"]);
});
it("refuses an existing feature directory", async () => {
const root = await emptyRoot();
await mkdir(path.join(root, "src/features/invoice-feature"), { recursive: true });
await expect(
writeFeatureFiles(root, plan({ id: "invoice-feature" }).files, [
"src/features/invoice-feature",
]),
).rejects.toThrow(CreateFeatureError);
});
it("removes what it wrote when a later write fails", async () => {
const root = await emptyRoot();
const files = new Map([
["src/features/broken/first.ts", "export {};\n"],
// A file cannot be a directory, so this write fails after the first.
["src/features/broken/first.ts/second.ts", "export {};\n"],
]);
await expect(writeFeatureFiles(root, files)).rejects.toThrow();
await expect(access(path.join(root, "src"))).rejects.toThrow();
});
});