Files
clean-architecture-frontend…/tests/integration/http-scenario-catalog.test.ts
DongHyeonka 5d064b8ace test(features): 기능을 더해도 기능 밖 테스트와 시나리오 하네스가 깨지지 않게 한다 (16-02)
문제: 기능 하나를 더하면(리뷰 16 실험 E) 기능 밖 테스트 3개가 깨진다.
① installed-context-routing은 context 목록이 정확히
["reference-context"]이고 첫 context가 참조 context라고 단정한다.
② product-feature-switch는 정렬 첫 기능(INSTALLED_PRODUCT_FEATURE_IDS[0])을
끄고 참조 라우트를 본다. 새 기능이 앞에 정렬되면 깨진다.
③ release-manifest fixture가 contractSet.packages: []로 고정이다.
EXTERNAL_PACKAGE를 쓰는 첫 기능에서 반드시 깨진다.
또 시나리오 하네스의 operation ID 타입이 테스트 계약 3개 리터럴이고
시나리오 응답 함수가 /api/test-entities 핸들러 안에 묶여 있다. 새 기능
테스트가 자기 operation에 실패 시나리오를 쓰려면 카탈로그를 고쳐야 한다
(안 고치면 TS2345, 실행하면 catalog.ts:469 TypeError).

방법: 리뷰의 (b) 최소 개선.
① "목록에 reference-context가 있다"로 바꾸고, 라우트 검사는 id로 찾은
  context에서 한다.
② REFERENCE_FEATURE_ID를 쓴다.
③ fixture의 packages와 setDigest를 EXPECTED_CONTRACT_SET_PACKAGES에서
  만든다.
하네스: HttpScenarioOperationId를 string으로 넓혔다. 시나리오 사실(명령
여부, 응답 상한, 성공 status)은 httpScenarioOperationFacts가 설치된 V3
descriptor에서 읽는다. 시나리오 응답은 tests/mocks/handlers/
http-scenarios.ts의 createHttpScenarioHandler로 옮겼다. 경로와 method도
descriptor에서 만든다. test-entities 핸들러는 이 함수를 쓰고 카탈로그
확인(assertOperationScenario)을 그대로 거친다. 카탈로그 기대값 57개는
계속 테스트 계약 3개에만 있고, 그 타입도 3개로 둔다. 카탈로그에 없는
operation을 assertOperationScenario에 넘기면 TypeError 대신 그 사실을
말하는 오류가 난다. test-entities 핸들러는 요청의 이름·id를 되돌려 주던
응답을 카탈로그 payload로 고정했다(기대값과 같은 값이다).
새 기능 테스트의 MSW 시나리오: server.use(createHttpScenarioHandler(
<자기 설치 계약>, { scenario: "server-terminal-503", payload }))
버린 대안: (a) 현상 유지는 기능마다 4곳을 고친다. (c) 하네스를 기능별로
나누면 변경이 크고 test-evidence.json의 증거 경로가 바뀐다. 기능
operation을 카탈로그에 더하는 방식은 기능 추가를 공유 파일 수정으로
만든다.
test-evidence.json은 바꾸지 않았다(sourceContracts 토큰이 test-entities.ts에
그대로 있다). 제거 드릴의 플랫폼 보존 목록에 http-scenarios.ts를 더했고,
테스트 전략 문서 11절에 사용법을 적었다.

위험·한계:
- 앱 전체를 렌더하는 테스트에서 response-too-large는 끝나지 않는다.
  실행기가 MSW가 넘긴 본문을 cancel하는 promise가 끝나지 않는 기존
  제약이다. 카탈로그 통합 테스트는 프록시 fetcher로 우회한다.
- 같은 실험에서 기능 밖 테스트가 더 깨진다. 이 발견 범위 밖이라 두었다.
  http-operation-v2-v3-parity는 스키마 ID "NoRequest"를 센티널로 고정한다.
  스키마 ID는 전역이라 두 번째 기능은 다른 이름을 써야 하고, 그러면 이
  테스트가 깨진다. manual-a11y-evidence·documentation-readiness(라우트별
  a11y 기록, 16-01)와 second-api-feature-registries(무효화 그래프 추가가
  breaking, 16-01)도 깨진다.
- test:sample-removal, test:http-scenario-evidence는 pnpm이 필요해 돌리지
  않았다.

검증:
RED: 참조 기능을 토큰 경계로 order로 바꾼 복사본(order-context,
EXTERNAL_PACKAGE 출처 포함, 커밋 안 함)을 넣고 tests/features
tests/component tests/runtime-schema를 돌렸다. 5파일 8개 실패. 기능 밖은
① 2개(["order-context","reference-context"]), ② 2개(order-feature를 꺼서
참조 링크가 남음), ③ 1개(ReleaseManifestError)다. 나머지 3개는 복사한
테스트다. 하네스 probe는 TS2345 2건, 실행 시 TypeError(catalog.ts:469).
새 통합 테스트는 기준 하네스에서 모듈 없음으로 실패하고, 기준
assertOperationScenario는 미등록 operation에 TypeError를 낸다.
GREEN: 같은 복사본으로 같은 폴더와 카탈로그 통합 테스트를 돌렸다. 78파일
중 실패는 출처를 바꾼 복사본 provenance 1파일뿐이고 ①~③은 통과한다.
order 테스트가 createHttpScenarioHandler(LIST_ORDER_RESOURCES_CONTRACT)로
content-type-mismatch·schema-mismatch·server-terminal-503을 화면에서
확인했다(카탈로그 수정 없음).
복사본을 지운 뒤: tests/features·component·runtime-schema·unit·
integration(security-followup-archive 제외)·contract 250파일 3111개 통과,
카탈로그 57/57, check-test-evidence --scenario-only·--source-only PASS,
tsc app·test·node 통과, verify-documentation-readiness PASS_SCOPED,
check-ci-contract PASS, 바꾼 파일 eslint 통과.

Refs: docs/reviews/2026-11-01-maturity-review/16-structure-patterns.md 16-02
2026-11-03 01:49:11 +09:00

462 lines
15 KiB
TypeScript

import { mkdir, rm } from "node:fs/promises";
import path from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { readBoundedBytes } from "../../src/adapters/http/bounded-body-reader.ts";
import {
createContractHttpExecutor,
type HttpExecutionObservation,
} from "../../src/adapters/http/http-execution-v3.ts";
import {
type InstalledHttpContract,
} from "../../src/contracts/external-contract-runtime.ts";
import type { CacheScopeSnapshot } from "../../src/contracts/server-state-scope.ts";
import {
computeHttpScenarioCatalogDigest,
httpScenarioReceiptSchema,
type AttemptStatus,
type BodyDisposition,
type HttpScenarioAssertionGroups,
type RetryReason,
} from "../../scripts/lib/http-scenario-evidence.ts";
import { writeValidatedJsonArtifact } from "../../scripts/lib/validated-json-artifact.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
import { createHttpScenarioHandler } from "../mocks/handlers/http-scenarios.ts";
import { createTestEntityScenarioHandlers } from "../mocks/handlers/test-entities.ts";
import { createStrictMockServer } from "../mocks/server.ts";
import {
assertOperationScenario,
HTTP_SCENARIO_CONTRACTS,
HTTP_SCENARIO_EXECUTION_IDS,
HTTP_SCENARIO_EXPECTATIONS,
HTTP_SCENARIO_RECEIPT_SCHEMA_VERSION,
OPERATION_SCENARIO_CATALOG,
type HttpScenarioExpectation,
} from "../mocks/scenarios/catalog.ts";
/** A low-cardinality route identity, as a feature binding passes it. */
const ROUTE_ID = "TEST_ENTITY_ROUTE";
const RECEIPT_PATH = path.resolve(
"artifacts/tests/http-scenario-executions.json",
);
const mockApi = createStrictMockServer();
beforeAll(mockApi.listen);
afterAll(mockApi.close);
type AttemptTrace = {
status: AttemptStatus;
media: string | null;
pulledBytes: number;
appliedCeiling: number | null;
completed: boolean;
cancelled: boolean;
};
type CatalogOperationId = HttpScenarioExpectation["operationId"];
function operationFor(operationId: CatalogOperationId) {
return HTTP_SCENARIO_CONTRACTS[operationId] as InstalledHttpContract<
unknown,
unknown,
unknown
>;
}
function inputFor(operationId: CatalogOperationId): unknown {
if (operationId === "TEST_LIST_ENTITIES") return { limit: 20 };
if (operationId === "TEST_GET_ENTITY") return { entityId: "entity-1" };
return { name: "Created" };
}
function normalizeMedia(response: Response): string | null {
const value = response.headers.get("content-type");
return value?.split(";", 1)[0]?.trim().toLowerCase() || null;
}
function tracingFetcher(attempts: AttemptTrace[]): typeof fetch {
return async (input, init) => {
const trace: AttemptTrace = {
status: "PENDING_ABORT",
media: null,
pulledBytes: 0,
appliedCeiling: null,
completed: false,
cancelled: false,
};
attempts.push(trace);
let response: Response;
try {
response = await fetch(input, init);
} catch (error) {
trace.status = init?.signal?.aborted
? "PENDING_ABORT"
: "NETWORK_REJECTION";
throw error;
}
trace.status = response.status;
trace.media = normalizeMedia(response);
if (!response.body) return response;
const reader = response.body.getReader();
const proxy = new ReadableStream<Uint8Array>(
{
async pull(controller) {
try {
const chunk = await reader.read();
if (chunk.done) {
trace.completed = true;
controller.close();
return;
}
trace.pulledBytes += chunk.value.byteLength;
controller.enqueue(chunk.value);
} catch (error) {
controller.error(error);
}
},
cancel(reason) {
trace.cancelled = true;
// MSW-transferred oversized bodies leave the original cancel promise
// permanently pending. Record and request cancellation without making
// the proxy response less responsive than the real executor contract.
void reader.cancel(reason).catch(() => {});
},
},
{ highWaterMark: 0 },
);
return new Response(proxy, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
};
}
function outcomeDetail(outcome: Readonly<Record<string, unknown>>): string | null {
if (outcome.kind === "CONTRACT_VIOLATION") {
return String((outcome.violation as Readonly<{ kind: string }>).kind);
}
if (outcome.kind === "TRANSPORT_FAILURE") {
return String((outcome.failure as Readonly<{ kind: string }>).kind);
}
if (outcome.kind === "PROBLEM") {
return String((outcome.metadata as Readonly<{ status: number }>).status);
}
return null;
}
function retryReason(status: AttemptStatus): RetryReason {
if (status === "NETWORK_REJECTION") return "NETWORK_FAILURE";
if (status === 429) return "HTTP_429";
if (status === 503) return "HTTP_503";
throw new Error(`Sleep followed a non-retryable attempt: ${String(status)}`);
}
function bodyDisposition(
trace: AttemptTrace,
outcome: Readonly<Record<string, unknown>>,
): BodyDisposition {
if (trace.status === "NETWORK_REJECTION" || trace.status === "PENDING_ABORT") {
return "NO_RESPONSE";
}
if (
outcome.kind === "CONTRACT_VIOLATION" &&
outcomeDetail(outcome) === "RESPONSE_TOO_LARGE" &&
trace.cancelled
) {
return "REJECTED_LIMIT";
}
if (trace.completed) return "FULLY_READ_WITHIN_BOUND";
if (trace.cancelled) return "CANCELLED_WITHOUT_READ";
throw new Error(`Response body was neither consumed nor cancelled: ${trace.status}`);
}
async function waitForHandler(
ready: Promise<void>,
executionId: string,
): Promise<void> {
let watchdog: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
ready,
new Promise<never>((_resolve, reject) => {
watchdog = setTimeout(
() => reject(new Error(`Handler readiness timed out: ${executionId}`)),
2_000,
);
}),
]);
} finally {
if (watchdog !== undefined) clearTimeout(watchdog);
}
}
async function executeScenario(
entry: HttpScenarioExpectation,
): Promise<HttpScenarioAssertionGroups> {
const physicalAttempts: AttemptTrace[] = [];
const sleeps: RetryReason[] = [];
const observations: HttpExecutionObservation[] = [];
const caller = new AbortController();
const scopeLifetime = new AbortController();
let scopeCurrent = true;
let handlerReady!: () => void;
const ready = new Promise<void>((resolve) => {
handlerReady = resolve;
});
const scope: CacheScopeSnapshot = Object.freeze({
generation: 1,
fingerprint: "scenario-scope-1",
identities: Object.freeze({}) as CacheScopeSnapshot["identities"],
signal: scopeLifetime.signal,
isCurrent: () => scopeCurrent,
});
const baseOperation = operationFor(entry.operationId);
const operation =
entry.testDeadlineOverrideMs === null
? baseOperation
: Object.freeze({
...baseOperation,
frontend: Object.freeze({
...baseOperation.frontend,
totalDeadlineMs: entry.testDeadlineOverrideMs,
}),
});
const fetcher = tracingFetcher(physicalAttempts);
const executor = createContractHttpExecutor({
baseUrl: "https://api.test",
maxRetryAttempts: 2,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher,
random: () => 0,
readBoundedResponseBytes: async (response, maximumBytes) => {
const trace = physicalAttempts.at(-1);
if (!trace) throw new Error("Body reader ran before a physical attempt");
if (trace.appliedCeiling !== null) {
throw new Error("Body reader ran more than once for one attempt");
}
trace.appliedCeiling = maximumBytes;
return readBoundedBytes(response, maximumBytes);
},
sleep: async () => {
const prior = physicalAttempts.at(-1);
if (!prior) throw new Error("Retry sleep occurred before an attempt");
sleeps.push(retryReason(prior.status));
},
observe: (observation) => observations.push(observation),
});
mockApi.server.use(
...createTestEntityScenarioHandlers({
scenarios: { [entry.operationId]: entry.scenarioId },
onAttempt(attempt) {
if (
attempt.operationId === entry.operationId &&
attempt.scenarioId === entry.scenarioId
) {
handlerReady();
}
},
}),
);
try {
const execution = executor.execute(operation, inputFor(entry.operationId), {
routeId: ROUTE_ID,
scope,
signal: caller.signal,
...(entry.operationId === "TEST_CREATE_ENTITY"
? {
intent: Object.freeze({
intentId: `intent-${entry.scenarioId}`,
operationId: entry.operationId,
canonicalInputIdentity: "scenario-input",
idempotencyKey: `scenario-${entry.scenarioId}`,
createdAtMonotonicMs: 1,
}),
}
: {}),
});
if (entry.scenarioId === "timeout" || entry.scenarioId === "aborted") {
await waitForHandler(ready, entry.executionId);
if (entry.scenarioId === "aborted") {
if (entry.operationId === "TEST_LIST_ENTITIES") {
caller.abort();
} else {
scopeCurrent = false;
scopeLifetime.abort();
}
}
}
const outcome = (await execution) as unknown as Readonly<Record<string, unknown>>;
expect(observations, `${entry.executionId} observer count`).toHaveLength(1);
const observation = observations[0]!;
const observedSignal = scopeLifetime.signal.aborted ? "ABORTED" : "ACTIVE";
const cancellationOwner =
observation.terminalReason === "TIMEOUT"
? "DEADLINE"
: caller.signal.aborted
? "CALLER"
: scopeLifetime.signal.aborted
? "SCOPE_FENCE"
: "NONE";
const observed: HttpScenarioAssertionGroups = Object.freeze({
status: Object.freeze({
attempts: Object.freeze(physicalAttempts.map((attempt) => attempt.status)),
final: physicalAttempts.at(-1)!.status,
}),
outcome: Object.freeze({
kind: String(outcome.kind),
detail: outcomeDetail(outcome),
}),
effect: Object.freeze({
outcome: String(outcome.effect),
observer: observation.terminalReason,
}),
retry: Object.freeze({ count: sleeps.length, reasons: Object.freeze(sleeps) }),
fetch: Object.freeze({
count: physicalAttempts.length,
observerAttempts: observation.attemptCount,
agrees: physicalAttempts.length === observation.attemptCount,
}),
media: Object.freeze({
attempts: Object.freeze(physicalAttempts.map((attempt) => attempt.media)),
final: physicalAttempts.at(-1)?.media ?? null,
}),
body: Object.freeze({
attempts: Object.freeze(
physicalAttempts.map((attempt) =>
Object.freeze({
disposition: bodyDisposition(attempt, outcome),
pulledBytes: attempt.pulledBytes,
ceiling: attempt.appliedCeiling ?? 0,
}),
),
),
}),
scope: Object.freeze({
start: "CURRENT",
end: scopeCurrent ? "CURRENT" : "STALE",
signal: observedSignal,
cancellationOwner,
}),
});
return observed;
} finally {
caller.abort();
scopeLifetime.abort();
mockApi.reset();
}
}
describe("HTTP scenario catalog execution evidence", () => {
it("declares exactly the 57 behaviorally distinct operation scenarios", () => {
const executionIds = Object.entries(OPERATION_SCENARIO_CATALOG).flatMap(
([operationId, scenarioIds]) =>
scenarioIds.map((scenarioId) => `${operationId}::${scenarioId}`),
);
expect(OPERATION_SCENARIO_CATALOG.TEST_LIST_ENTITIES).toHaveLength(20);
expect(OPERATION_SCENARIO_CATALOG.TEST_GET_ENTITY).toHaveLength(19);
expect(OPERATION_SCENARIO_CATALOG.TEST_CREATE_ENTITY).toHaveLength(18);
expect(executionIds).toHaveLength(57);
expect(new Set(executionIds)).toHaveLength(57);
expect(executionIds).toEqual(HTTP_SCENARIO_EXECUTION_IDS);
});
it("executes every declared scenario and publishes one complete receipt", async () => {
await rm(RECEIPT_PATH, { force: true });
const rows: Array<Readonly<{
executionId: string;
expected: HttpScenarioAssertionGroups;
observed: HttpScenarioAssertionGroups;
testDeadlineOverrideMs: number | null;
}>> = [];
for (const entry of HTTP_SCENARIO_EXPECTATIONS) {
const observed = await executeScenario(entry);
expect(observed, entry.executionId).toEqual(entry.expected);
rows.push(
Object.freeze({
executionId: entry.executionId,
expected: entry.expected,
observed,
testDeadlineOverrideMs: entry.testDeadlineOverrideMs,
}),
);
}
const sortedRows = [...rows].sort((left, right) =>
left.executionId.localeCompare(right.executionId),
);
await mkdir(path.dirname(RECEIPT_PATH), { recursive: true });
await writeValidatedJsonArtifact({
path: RECEIPT_PATH,
schema: httpScenarioReceiptSchema,
value: {
schemaVersion: HTTP_SCENARIO_RECEIPT_SCHEMA_VERSION,
catalogDigest: computeHttpScenarioCatalogDigest(
HTTP_SCENARIO_RECEIPT_SCHEMA_VERSION,
HTTP_SCENARIO_EXPECTATIONS,
),
catalogTotal: 57,
executedIds: sortedRows.map((row) => row.executionId),
rows: sortedRows,
},
});
}, 30_000);
});
describe("HTTP scenario handler for an operation outside the catalog", () => {
// 16-02. A feature test passes its own installed contract; the catalog has
// no entry for it. The ceiling is larger than the catalog's, so the
// oversized body shows it was read from this descriptor.
const featureList = Object.freeze({
...TEST_LIST_HTTP_CONTRACT,
contract: Object.freeze({
...TEST_LIST_HTTP_CONTRACT.contract,
operationId: "FEATURE_LIST_ITEMS",
pathTemplate: "/api/feature-groups/{groupId}/items",
}),
frontend: Object.freeze({
...TEST_LIST_HTTP_CONTRACT.frontend,
responseByteLimit: 65_536,
}),
});
it("answers on the descriptor's route with the descriptor's ceiling", async () => {
const attempts: unknown[] = [];
mockApi.server.use(
createHttpScenarioHandler(featureList, {
scenario: "response-too-large",
payload: [],
onAttempt: (attempt) => attempts.push(attempt),
}),
);
try {
const response = await fetch("https://api.test/api/feature-groups/g-1/items");
expect(response.status).toBe(200);
expect((await response.arrayBuffer()).byteLength).toBe(65_537);
expect(attempts).toEqual([
{
operationId: "FEATURE_LIST_ITEMS",
scenarioId: "response-too-large",
attempt: 1,
},
]);
} finally {
mockApi.reset();
}
});
it("keeps the catalog's evidence to its own operations", () => {
expect(() =>
assertOperationScenario("FEATURE_LIST_ITEMS", "success"),
).toThrow("FEATURE_LIST_ITEMS is not a catalog operation");
});
});