Files
clean-architecture-frontend…/tests/component/starter-platform-overview-page.test.tsx
T
DongHyeonka d3ddc8957f feat(contracts): zod 검증기 어댑터를 공유하고 검증 생략을 이름으로 드러낸다 (1101/07-03)
문제
- zod 스키마를 RuntimeValidator로 바꾸는 zodValidator가 참조 기능의
  reference-schemas.ts 안에만 있다. 기능끼리 import가 금지라 새 기능은
  복사하고, 복사본은 이미 갈라졌다(tests/helpers 복사본은 성공 값을
  structuredClone하지 않는다). 참조 기능을 지우면 어댑터도 사라진다.
- RuntimeValidator<T>는 schemaId와 safeParse만 요구한다. 아무것도
  검증하지 않는 검증기도 조립을 통과하고, 검증을 생략했다는 사실이
  타입·이름·조립 결과 어디에도 남지 않는다.

고른 방법 (C: 공유 어댑터 + 생략 표시)
- zodValidator를 src/contracts/zod-validator.ts로 옮긴다. 참조 기능과
  tests/helpers/external-contract-fixture.ts가 이것을 import한다. 동작은
  참조 기능 쪽 원본 그대로다(성공 값 structuredClone, 경로 배열, code
  문자열). tests/helpers도 이제 성공 값을 복사한다.
- unvalidatedPayload(schemaId, reason)를 external-contract-runtime.ts에
  둔다. 만든 검증기에는 validation: "NONE"과 unvalidatedReason이 붙는다.
  zod가 필요 없어서 검증기 프로토콜 옆에 뒀다.
- composeContractContributions가 이 표시가 붙은 검증기를
  unvalidatedPayloads(featureId, contractId, validator, schemaId, reason)로
  내놓는다. HTTP의 input·output·problem과 이벤트의 envelope·payload를 모두
  본다. 표시가 "NONE"이 아니거나 이유가 비어 있으면 조립을 거부한다.
- 플랫폼 개요 화면(스타터 화면)의 계약 절에 "런타임 검증을 생략한 계약"
  표를 둔다. 목록이 비면 그리지 않는다.

버린 대안
- (B) 공유 어댑터만: 검증 생략이 여전히 보이지 않는다.
- (D) 브랜드 타입으로 zodValidator가 만든 검증기만 받기: 외부 패키지의
  자체 검증기까지 막아 §4 설계와 충돌한다.

위험·한계
- 표시 없이 손으로 쓴 통과 검증기(리뷰 실험 L5)는 여전히 조립을
  통과하고 목록에도 없다. 이 변경은 생략을 막지 않는다. 이름 있는 길을
  만들어 그 길로 생략한 것만 드러낸다.
- 공개 계약 추가: RuntimeValidator에 선택 필드 2개,
  ComposedContractContributions에 필드 1개, 새 export zodValidator·
  unvalidatedPayload·UnvalidatedPayloadEntry. 기존 호출자는 바뀌지 않는다.
  ComposedContractContributions를 손으로 만드는 코드는 새 필드를 채워야
  한다(repo 안에는 없다).
- 초기 JS gzip 204,586 → 204,745 B(+159). 예산 204,800까지 55 B 남는다.
  플랫폼 개요 청크 4,625 → 4,750 B.
- 참조 기능은 모든 검증기가 검증하므로 화면 모양은 그대로다. 시각 회귀는
  돌리지 않았다.
- tests/unit/second-api-feature-registries.test.ts의 V2 codec 통과 검증기는
  그대로 둔다(16-01이 그 파일을 넓힌다).

검증
- RED(수정 전): zod-validator.test.ts "Cannot find module
  '../../src/contracts/zod-validator.ts'", external-contract-runtime.test.ts와
  starter-platform-overview-page.test.tsx "unvalidatedPayload is not a
  function". 3파일 모두 실패.
- GREEN: 같은 3파일 33건 통과.
- 회귀: tests/unit·contract·component·runtime-schema·features·platform
  268파일 3,189건, tests/integration 12파일 158건(pnpm을 띄우는
  security-followup-archive 제외), tests/architecture 7파일 33건 통과.
  tsc app·node·test·recipes·web-worker·service-worker 오류 0. 바꾼 파일
  eslint 0. check-registries PASS(compatibility=none), verify-documentation
  PASS_SCOPED, check-adapter-inventory PASS. 아키텍처 그래프 검사(pnpm 대신
  exec stub) 383 모듈 PASS.
- 참조 기능 삭제 모의: scripts/test-sample-removal.ts의 삭제 목록(기능
  폴더, tests/features, reference-context, SAMPLE_EXTRAS)을 복사본에 적용.
  src/contracts/zod-validator.ts가 남고, tsc app·test 오류 0, 어댑터·조립·
  플랫폼 개요·HTTP 시나리오 테스트 4파일 35건 통과.

Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md 07-03, 5.3
2026-11-03 01:34:32 +09:00

246 lines
8.5 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen, waitFor, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import {
composeContractContributions,
unvalidatedPayload,
} from "../../src/contracts/external-contract-runtime.ts";
import { SERVER_STATE_PROFILES } from "../../src/contracts/server-state.ts";
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/loaded-feature-runtimes.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import { PlatformOverviewPage } from "../../src/presentation/examples/platform-overview-page.tsx";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
import { createRuntimeCapabilitiesStub } from "../helpers/runtime-capabilities-stub.ts";
/**
* A starter screen (0929/10-02): a product that replaces `/examples/platform`
* deletes this file with it. Platform tests use the test-only feature's pages.
*
* The page must stay a projection of the installed registries. Every assertion
* below derives its expectation from the same registry the page reads, so a
* template that removes its sample feature still satisfies this suite.
*/
function renderPage() {
return render(
<ApplicationProvider application={createTestApplication()}>
<LocaleProvider>
<PlatformOverviewPage contracts={COMPOSED_CONTRACT_CONTRIBUTIONS} />
</LocaleProvider>
</ApplicationProvider>,
);
}
function tableByCaption(caption: string): HTMLElement {
return screen.getByRole("table", { name: caption });
}
/** A metric is a `dt`/`dd` pair, which carries no ARIA role to query by. */
function metricByLabel(scope: HTMLElement, label: string): HTMLElement {
const term = within(scope).getByText(label).closest(".platform-metric");
if (!(term instanceof HTMLElement)) {
throw new Error(`No metric is labelled ${label}`);
}
return term;
}
describe("platform overview page", () => {
it("renders one route row per installed route registry entry", () => {
renderPage();
const table = tableByCaption("설치된 라우트 목록");
const dataRows = within(table).getAllByRole("row").slice(1);
expect(dataRows).toHaveLength(Object.keys(ROUTE_REGISTRY).length);
for (const definition of Object.values(ROUTE_REGISTRY)) {
expect(
within(table).getByText(definition.routeId),
).toBeInTheDocument();
}
});
it("renders one operation row per installed HTTP contract", () => {
const operationIds = [
...COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.keys(),
];
renderPage();
if (operationIds.length === 0) {
expect(
screen.getByRole("heading", {
name: "설치된 HTTP 오퍼레이션이 없습니다.",
}),
).toBeVisible();
return;
}
const table = tableByCaption("설치된 HTTP 오퍼레이션");
expect(within(table).getAllByRole("row").slice(1)).toHaveLength(
operationIds.length,
);
for (const operationId of operationIds) {
expect(within(table).getByText(operationId)).toBeInTheDocument();
}
});
// 1101/07-03. A skipped validation is shown, not just composed.
it("lists the operations that skip runtime validation, with the reason", () => {
const [listRow, ...rest] = TEST_CONTRACT_CONTRIBUTION.http;
const contracts = composeContractContributions([
Object.freeze({
...TEST_CONTRACT_CONTRIBUTION,
http: Object.freeze([
{
...listRow!,
contract: {
...listRow!.contract,
outputValidator: unvalidatedPayload(
"TestEntityListPayload",
"typed by the package",
),
},
},
...rest,
]),
}),
]);
render(
<ApplicationProvider application={createTestApplication()}>
<LocaleProvider>
<PlatformOverviewPage contracts={contracts} />
</LocaleProvider>
</ApplicationProvider>,
);
const table = tableByCaption("런타임 검증을 생략한 계약");
const [row, ...others] = within(table).getAllByRole("row").slice(1);
expect(others).toHaveLength(0);
expect(within(row!).getByText("TEST_LIST_ENTITIES")).toBeVisible();
expect(within(row!).getByText("typed by the package")).toBeVisible();
});
it("shows no skipped-validation list when every operation validates", () => {
renderPage();
expect(
screen.queryByRole("table", { name: "런타임 검증을 생략한 계약" }),
).toBeNull();
});
it("renders every fixed server-state profile with its own budget", () => {
renderPage();
const table = tableByCaption("서버 상태 프로파일");
for (const profile of Object.values(SERVER_STATE_PROFILES)) {
expect(within(table).getByText(profile.profileId)).toBeInTheDocument();
}
expect(within(table).getAllByRole("row").slice(1)).toHaveLength(
Object.keys(SERVER_STATE_PROFILES).length,
);
});
it("labels a capability that was never selected as unselected", () => {
renderPage();
const region = screen.getByRole("region", { name: "선택적 런타임 능력" });
expect(within(region).getAllByText("미선택")).toHaveLength(4);
expect(within(region).queryByText("운영자가 비활성화함")).toBeNull();
});
it("separates an operator disable from a capability that was never selected", () => {
render(
<ApplicationProvider
application={createTestApplication({
runtimeCapabilities: createRuntimeCapabilitiesStub({
SERVICE_WORKER: { selected: 1, active: 0, override: "DISABLED" },
OFFLINE_COMMANDS: { selected: 1, active: 1 },
}),
})}
>
<LocaleProvider>
<PlatformOverviewPage contracts={COMPOSED_CONTRACT_CONTRIBUTIONS} />
</LocaleProvider>
</ApplicationProvider>,
);
const region = screen.getByRole("region", { name: "선택적 런타임 능력" });
expect(within(region).getByText("운영자가 비활성화함")).toBeVisible();
expect(within(region).getByText("활성 (1)")).toBeVisible();
expect(within(region).getAllByText("미선택")).toHaveLength(2);
});
it("counts installed contract packages separately from template fixtures", () => {
const fixtures = COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.filter(
(contribution) => contribution.source.kind === "TEMPLATE_FIXTURE",
).length;
renderPage();
const summary = screen.getByRole("region", { name: "설치 요약" });
const packages = metricByLabel(summary, "외부 계약 패키지");
expect(
within(packages).getByText(
`${COMPOSED_CONTRACT_CONTRIBUTIONS.externalPackages.length}개`,
),
).toBeVisible();
expect(
within(packages).getByText(`템플릿 픽스처 ${fixtures}개`),
).toBeVisible();
expect(
within(metricByLabel(summary, "라우트")).getByText(
`${Object.keys(ROUTE_REGISTRY).length}개`,
),
).toBeVisible();
});
it("renders the verified release identity once the runtime resolves it", async () => {
renderPage();
const region = screen.getByRole("region", { name: "릴리스 신원" });
await waitFor(() =>
expect(
within(metricByLabel(region, "빌드")).getByText("test-build"),
).toBeVisible(),
);
expect(
within(metricByLabel(region, "릴리스")).getByText("test-release"),
).toBeVisible();
});
it("stops the release metrics from loading forever", async () => {
render(
<ApplicationProvider
application={createTestApplication({
releaseInfo: {
getCurrent: async () => {
throw new Error("manifest unavailable");
},
refresh: async () => {
throw new Error("manifest unavailable");
},
},
})}
>
<LocaleProvider>
<PlatformOverviewPage contracts={COMPOSED_CONTRACT_CONTRIBUTIONS} />
</LocaleProvider>
</ApplicationProvider>,
);
await waitFor(() =>
expect(
screen.getByText("런타임 정보를 확인하지 못했습니다."),
).toBeVisible(),
);
expect(
screen.queryByText("런타임 정보를 확인하고 있습니다."),
).not.toBeInTheDocument();
});
});