Files
clean-architecture-frontend…/tests/helpers/external-contract-fixture.ts
T
DongHyeonka dddf6353e0 test(contracts): 이벤트 계약 검증을 실제 이벤트 행으로 고정한다 (10-01)
문제: "정확하지 않은 이벤트 계약을 거부한다" 테스트는 공용 fixture의
events가 빈 배열이라 첫 줄 `if (events.length === 0) return;`에서 끝난다.
단언이 하나도 실행되지 않는다. 그래서 composeContractContributions의
이벤트 snapshot(M17)이나 assertEventContract 호출(M18)을 빼도 관련
테스트가 모두 통과한다. 템플릿 안에는 이벤트를 기여하는 계약이 없어서
이 경로를 지키는 테스트가 따로 없다.

고른 방법:
- tests/helpers/external-contract-fixture.ts에 TEST_EVENT_CONTRACT를
  추가한다. 공용 TEST_CONTRACT_CONTRIBUTION의 events는 그대로 비워 둔다.
  이 fixture를 쓰는 다른 테스트 20여 파일의 전제를 바꾸지 않기 위해서다.
- 빈 배열이면 return하던 테스트를 지우고 "event contracts" 묶음을 둔다.
  정상 행이 snapshot으로 설치되는지(같은 내용, 다른 객체, frozen) 먼저
  확인해서 아래 거부 경우가 다른 이유로 throw하는 것이 아님을 보인다.
  거부 경우는 HTTP 쪽 hostileRows처럼 모양(추가 필드, 다른 prototype,
  accessor)과 내용(빈 eventType, 공백, C1 제어문자, 160바이트 초과,
  validator 없음, 빈 schemaId), 중복 eventType이다.
  ContractContributionError로 던지는지까지 본다.

버린 대안: tests/setup.ts에 전역 expect.hasAssertions()를 두는 방법.
같은 종류의 빈 테스트를 모두 막지만 모든 vitest 프로젝트의 테스트 계약을
바꾸고, 리뷰는 빠른 계층 8개 폴더에서만 확인했다. 이 발견의 범위를
넘는다.

위험·한계: 템플릿 안에서 eventByType을 읽는 코드는 여전히 없다. 이
테스트는 composition 단계의 검증만 고정한다.

검증:
- RED(변경 전 테스트 파일과 새 파일을 함께, 변이 적용):
  M17(snapshotEventContract가 입력을 그대로 반환) — 옛 파일 16개 통과,
  새 파일 4개 실패("installs a well-formed event contract as its own
  snapshot", extra own field, custom prototype, accessor eventType).
  M18(assertEventContract 호출 제거) — 옛 파일 16개 통과, 새 파일 6개
  실패(빈·공백·제어문자·160바이트 초과 eventType, validator 2종).
- GREEN: node scripts/run-vitest.ts run
  tests/unit/contract-registry-immutability.test.ts — 26 passed.
- related tests/helpers/external-contract-fixture.ts
  src/contracts/external-contract-runtime.ts — 97파일 796 passed.
- tsc -p tsconfig.test.json, eslint(바꾼 2파일) 통과.

Refs: docs/reviews/2026-11-01-maturity-review/10-tests-fast-layers.md 10-01
2026-11-01 23:18:45 +09:00

239 lines
6.8 KiB
TypeScript

import { z } from "zod";
import type {
CommandEffectDescriptor,
InstalledContractContribution,
InstalledEventContract,
InstalledHttpContract,
RuntimeValidator,
} from "../../src/contracts/external-contract-runtime.ts";
function zodValidator<T>(
schemaId: string,
schema: z.ZodType<T>,
): RuntimeValidator<T> {
return Object.freeze({
schemaId,
safeParse(value: unknown) {
const result = schema.safeParse(value);
if (result.success) {
return Object.freeze({ success: true as const, data: result.data });
}
return Object.freeze({
success: false as const,
issues: Object.freeze(
result.error.issues.map((issue) =>
Object.freeze({
path: Object.freeze(
issue.path.map((segment) =>
typeof segment === "number" ? segment : String(segment),
),
),
code: String(issue.code),
}),
),
),
});
},
});
}
const entitySchema = z
.object({
id: z.string().min(1),
name: z.string().min(1),
})
.strip();
const problemSchema = z
.object({
type: z.string().min(1),
title: z.string().min(1),
status: z.int().min(100).max(599),
})
.strip();
type TestProblem = z.output<typeof problemSchema>;
const problemValidator = zodValidator("TestProblem", problemSchema);
const readPolicy = Object.freeze({
policyId: "TEST_READ_V1",
requestByteLimit: 0,
responseByteLimit: 32_768,
totalDeadlineMs: 10_000,
retryBudget: 2 as const,
authProfileId: "ANONYMOUS",
diagnosticsOperation: "test.read",
});
export const TEST_LIST_HTTP_CONTRACT: InstalledHttpContract<
Readonly<{ limit: number }>,
readonly z.output<typeof entitySchema>[],
TestProblem
> = Object.freeze({
contract: Object.freeze({
operationId: "TEST_LIST_ENTITIES",
method: "GET" as const,
pathTemplate: "/api/test-entities",
inputValidator: zodValidator(
"TestEntityListQuery",
z
.object({
limit: z.coerce.number().int().min(1).max(100).default(20),
})
.strict(),
),
outputValidator: zodValidator(
"TestEntityListPayload",
z.array(entitySchema).max(100),
),
problemValidator,
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
commandRecovery: null,
commandEffect: null,
projectRequest(input: Readonly<{ limit: number }>) {
return Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze([
Object.freeze(["limit", String(input.limit)] as const),
]),
body: null,
});
},
}),
frontend: readPolicy,
});
export const TEST_DETAIL_HTTP_CONTRACT: InstalledHttpContract<
Readonly<{ entityId: string }>,
z.output<typeof entitySchema>,
TestProblem
> = Object.freeze({
contract: Object.freeze({
operationId: "TEST_GET_ENTITY",
method: "GET" as const,
pathTemplate: "/api/test-entities/{entityId}",
inputValidator: zodValidator(
"TestEntityParams",
z.object({ entityId: z.string().min(1) }).strict(),
),
outputValidator: zodValidator("TestEntityPayload", entitySchema),
problemValidator,
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
commandRecovery: null,
commandEffect: null,
projectRequest(input: Readonly<{ entityId: string }>) {
return Object.freeze({
pathValues: Object.freeze({ entityId: input.entityId }),
queryEntries: Object.freeze([]),
body: null,
});
},
}),
frontend: Object.freeze({
...readPolicy,
policyId: "TEST_DETAIL_V1",
diagnosticsOperation: "test.detail",
}),
});
const commandEffect: CommandEffectDescriptor<TestProblem> = Object.freeze({
successEffect: "APPLIED_CONFIRMED" as const,
classifyProblem({
status,
}: Readonly<{ status: number; problem: TestProblem }>) {
return status === 400 ? "NOT_APPLIED" : "MAYBE_APPLIED";
},
});
export const TEST_CREATE_HTTP_CONTRACT: InstalledHttpContract<
Readonly<{ name: string }>,
z.output<typeof entitySchema>,
TestProblem
> = Object.freeze({
contract: Object.freeze({
operationId: "TEST_CREATE_ENTITY",
method: "POST" as const,
pathTemplate: "/api/test-entities",
inputValidator: zodValidator(
"TestCreateEntityCommand",
z.object({ name: z.string().trim().min(1) }).strict(),
),
outputValidator: zodValidator("TestEntityPayload", entitySchema),
problemValidator,
acceptedStatuses: Object.freeze([201]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "KEYED" as const,
requestBody: "JSON" as const,
responseBody: "REQUIRED_JSON" as const,
commandRecovery: Object.freeze({
mode: "IDEMPOTENCY_REPLAY" as const,
operationIdentityField: "idempotencyKey",
}),
commandEffect,
projectRequest(input: Readonly<{ name: string }>) {
return Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze([]),
body: Object.freeze({ ...input }),
});
},
}),
frontend: Object.freeze({
policyId: "TEST_CREATE_V1",
requestByteLimit: 32_768,
responseByteLimit: 32_768,
totalDeadlineMs: 10_000,
retryBudget: 0 as const,
authProfileId: "ANONYMOUS",
diagnosticsOperation: "test.create",
}),
});
/**
* An event contract an external package could install. The shared
* contribution below keeps `events` empty, so tests that check event
* composition put this row into a copy of it.
*/
export const TEST_EVENT_CONTRACT: InstalledEventContract<
Readonly<{ type: string; payload: unknown }>,
z.output<typeof entitySchema>
> = Object.freeze({
eventType: "test.entity.changed",
envelopeValidator: zodValidator(
"TestEventEnvelope",
z.object({ type: z.string().min(1), payload: z.unknown() }).strip(),
),
payloadValidator: zodValidator("TestEntity", entitySchema),
});
export const TEST_CONTRACT_CONTRIBUTION: InstalledContractContribution =
Object.freeze({
contributionId: "test-http-v1",
featureId: "test-feature",
source: Object.freeze({
kind: "EXTERNAL_PACKAGE" as const,
package: Object.freeze({
packageId: "@test/contracts",
version: "1.0.0",
digest: `sha256:${"a".repeat(64)}`,
runtimeProtocolVersion: 1 as const,
sourceRevision: "abcdef1",
}),
}),
http: Object.freeze([
TEST_LIST_HTTP_CONTRACT,
TEST_DETAIL_HTTP_CONTRACT,
TEST_CREATE_HTTP_CONTRACT,
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
events: Object.freeze([]),
});