Files
clean-architecture-frontend…/tests/unit/schema-metadata-policy.test.ts
DongHyeonka efe11f1581 test(contracts): 탐침이 닿지 않는 스키마는 방향만 요구한다
문제: e7b1b01 뒤 정책 테스트는 HTTP 자리 스키마의 행이
unknownFieldPolicy를 빼면 실패하고, 적으면 탐침 결과와 비교한다. 탐침이
객체에 닿지 못하는 검증기(두 탐침을 모두 루트에서 거절: `responseBody:
"NONE"` 출력의 z.undefined(), 문자열·null 본문)는 결과가 UNREACHED다.
행 타입은 REJECT_UNKNOWN·STRIP_UNKNOWN만 받으므로, 그런 operation은 행을
어떻게 적어도 통과하지 못한다. 칸을 빼면 `row states no
unknownFieldPolicy`, STRIP_UNKNOWN을 적으면 `row STRIP_UNKNOWN, validator
UNREACHED`다. 템플릿에는 그런 operation이 없어 다운스트림에서 난다.

고른 방법: 리뷰의 가장 작은 방향. 탐침 결과가 UNREACHED인 자리는 정책
비교에서만 빼고, direction은 그대로 요구한다. 두 검사를 슬롯·행을 받는
함수(directionProblems, policyProblems)로 꺼내, 설치된 descriptor 검사와
가짜 스키마 검사가 같은 함수를 쓴다. 새 describe가 z.undefined() 같은
NoContent 검증기로 탐침이 UNREACHED인지, 행이 direction을 빼면 실패하는지,
정책을 빼거나 적어도 통과하는지 본다. 매뉴얼 01, errors.md, CHANGELOG
1106 절의 먼저 할 일 1과 07-02 행에 적었다.
검사를 느슨하게 한 것이 아닌 이유: 탐침은 객체가 없는 스키마의 모르는
필드 정책을 판정할 수 없다. 그 자리의 비교는 맞는 답이 없는 질문이었다.
e7b1b01 전에는 칸을 빼면 이 자리 전체를 건너뛰었다. 지금은 direction을
요구하므로 그때보다 넓다. 객체에 닿는 스키마의 정책 비교는 그대로다.
버린 대안: 행 타입에 객체가 아닌 본문용 값을 더한다. src/contracts의
SchemaDefinition 모양, 분류기, 기준선이 함께 바뀐다.

위험·한계: 행이 UNREACHED 스키마에 적은 정책 값은 아무도 검사하지 않는다.
루트에서 이슈 하나로 거절하는 union(zod `invalid_union`, 예:
strict 객체 | null)도 UNREACHED가 되어 정책 비교에서 빠진다(추론, 실행하지
않음). 고친 곳이 테스트 파일 자신이라 RED는 테스트 파일만으로
만들 수 없다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/schema-metadata-policy.test.ts

Refs: 1106/07-02 (diff review DR-04)
2026-11-06 07:58:07 +09:00

244 lines
9.0 KiB
TypeScript

import { describe, expect, it } from "vitest";
import type { RuntimeValidator } from "../../src/contracts/external-contract-runtime.ts";
import type { SchemaDefinition } from "../../src/contracts/schema-registry.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import {
COMPOSED_CONTRACT_CONTRIBUTIONS,
SCHEMA_REGISTRY,
} from "../../src/features/loaded-feature-runtimes.ts";
/**
* 1103/07-03. FE-REG-SCHEMA rows state each HTTP schema's direction and
* unknown-field policy, and `docs/contracts/compatibility.md` builds the
* "adding a response field is additive" rule on `STRIP_UNKNOWN`. Nothing at
* run time reads those two fields, so they are checked here against the
* validators the installed HTTP descriptors run.
*
* The probe is an object with one key no schema declares, and the same object
* as the only item of an array, so it reaches the first object level of an
* object or list payload. A validator that rejects it with
* `unrecognized_keys` rejects unknown fields; one that reaches the object
* without that issue tolerates them. A nested object below that level is not
* probed.
*
* 1106/07-02. Both fields are optional in the row type, and a row that left
* them out used to be skipped here. 1105/07-02 grades a response row whose
* policy turns `REJECT_UNKNOWN` as breaking, but a row with no policy does not
* change when its DTO turns `.strict()`, so nothing saw it. A schema an HTTP
* operation uses now fails here without them; the policy only where the probe
* reaches an object (`policyProblems`). Route-only rows (`NotFoundSplat`) are
* not in `slots` and still need neither.
*/
const PROBE_KEY = "__unknownFieldProbe";
type ProbedPolicy = "REJECT_UNKNOWN" | "STRIP_UNKNOWN" | "UNREACHED";
function probeUnknownFieldPolicy(validator: RuntimeValidator<unknown>): ProbedPolicy {
const probe = { [PROBE_KEY]: true };
for (const [value, objectPath] of [
[probe, []],
[[probe], [0]],
] as const) {
const result = validator.safeParse(value);
if (result.success) return "STRIP_UNKNOWN";
const atObject = (path: readonly (string | number)[]) =>
JSON.stringify(path) === JSON.stringify(objectPath);
if (
result.issues.some(
(issue) => issue.code === "unrecognized_keys" && atObject(issue.path),
)
) {
return "REJECT_UNKNOWN";
}
// Every issue sits at or above the probed object (wrong type, wrong
// shape): the validator never looked inside it, so try the next probe.
const unreached = result.issues.every(
(issue) =>
issue.path.length <= objectPath.length &&
issue.path.every((segment, index) => segment === objectPath[index]),
);
if (!unreached) return "STRIP_UNKNOWN";
}
return "UNREACHED";
}
const slots = COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.flatMap(
({ http }) =>
http.flatMap(({ contract }) => [
{
operationId: contract.operationId,
direction: "REQUEST" as const,
validator: contract.inputValidator,
},
{
operationId: contract.operationId,
direction: "RESPONSE" as const,
validator: contract.outputValidator,
},
// 1103/16-04. The failure body is read as a response too.
{
operationId: contract.operationId,
direction: "RESPONSE" as const,
validator: contract.problemValidator,
},
]),
);
type Slot = Readonly<{
operationId: string;
direction: "REQUEST" | "RESPONSE";
validator: RuntimeValidator<unknown>;
}>;
type Rows = Readonly<Record<string, SchemaDefinition | undefined>>;
function directionProblems(used: readonly Slot[], rows: Rows): string[] {
return used.flatMap(({ operationId, direction, validator }) => {
const declared = rows[validator.schemaId]?.direction;
return declared === direction
? []
: [
`${operationId} ${validator.schemaId}: row ${declared ?? "states no direction"}, used as ${direction}`,
];
});
}
/**
* 1106/07-02 (diff review DR-04). A validator the probe cannot reach, one
* that refuses both probes at the root (`z.undefined()` for a
* `responseBody: "NONE"` output, a string or null payload), has no object
* level to judge, and no row value equals `UNREACHED`. Its policy is not
* compared; `directionProblems` still requires its `direction`.
*/
function policyProblems(used: readonly Slot[], rows: Rows): string[] {
return used.flatMap(({ operationId, validator }) => {
const probed = probeUnknownFieldPolicy(validator);
if (probed === "UNREACHED") return [];
const declared = rows[validator.schemaId]?.unknownFieldPolicy;
return probed === declared
? []
: [
`${operationId} ${validator.schemaId}: row ${declared ?? "states no unknownFieldPolicy"}, validator ${probed}`,
];
});
}
type Boundary = SchemaDefinition["boundary"];
/**
* 1103/16-04. Where each installed schema is used: an HTTP input, output or
* failure body, or a route's params or search. The row's `boundary` is
* derived from that set; a schema used in two places that no one boundary
* names (an output that is also an input) has no right answer and is listed.
*/
function usesBySchema(): ReadonlyMap<string, ReadonlySet<string>> {
const uses = new Map<string, Set<string>>();
const add = (schemaId: string | null, use: string) => {
if (schemaId === null) return;
const set = uses.get(schemaId) ?? new Set<string>();
set.add(use);
uses.set(schemaId, set);
};
for (const { http } of COMPOSED_CONTRACT_CONTRIBUTIONS.contributions) {
for (const { contract } of http) {
add(contract.inputValidator.schemaId, "http-input");
add(contract.outputValidator.schemaId, "http-output");
add(contract.problemValidator.schemaId, "http-problem");
}
}
for (const route of Object.values(ROUTE_REGISTRY)) {
add(route.paramsSchema, "route-params");
add(route.searchSchema, "route-search");
}
return uses;
}
function boundaryFor(uses: ReadonlySet<string>): Boundary | undefined {
const key = [...uses].sort().join("+");
const boundaries: Readonly<Record<string, Boundary>> = {
"http-input": "api-request",
"http-output": "api-response",
"http-problem": "api-problem",
"route-params": "route-params",
"http-input+route-params": "route-params",
"route-search": "route-search",
"http-input+route-search": "route-search-api-request",
};
return boundaries[key];
}
// With no installed feature (after the sample is removed) there is nothing to
// probe, and both cases pass empty.
describe("FE-REG-SCHEMA policy of the installed HTTP schemas (1103/07-03)", () => {
it("declares the direction each schema is used in", () => {
expect(directionProblems(slots, SCHEMA_REGISTRY)).toEqual([]);
});
it("gives every schema an operation or route uses a row at the boundary it is used", () => {
const wrong = [...usesBySchema()].flatMap(([schemaId, uses]) => {
const row = SCHEMA_REGISTRY[schemaId];
const expected = boundaryFor(uses);
if (row === undefined) return [`${schemaId}: no FE-REG-SCHEMA row`];
if (expected === undefined) {
return [`${schemaId}: used as ${[...uses].sort().join(" and ")}, which no boundary names`];
}
return row.boundary === expected
? []
: [`${schemaId}: row ${row.boundary}, used as ${expected}`];
});
expect(wrong).toEqual([]);
});
it("declares the unknown-field policy its validator applies", () => {
expect(policyProblems(slots, SCHEMA_REGISTRY)).toEqual([]);
});
});
// 1106/07-02 (diff review DR-04). No row value passed for such a schema: the
// policy check asked for a field and then compared it with `UNREACHED`.
describe("FE-REG-SCHEMA policy of a schema the probe cannot reach (1106/07-02)", () => {
const noContent: RuntimeValidator<unknown> = {
schemaId: "NoContent",
safeParse: (value) =>
value === undefined
? { success: true, data: value }
: { success: false, issues: [{ path: [], code: "invalid_type" }] },
};
const used: readonly Slot[] = [
{ operationId: "DELETE_THING", direction: "RESPONSE", validator: noContent },
];
const rows = (
fields: Pick<SchemaDefinition, "direction" | "unknownFieldPolicy">,
): Rows => ({
NoContent: {
schemaId: "NoContent",
boundary: "api-response",
owner: "test",
runtime: "zod",
...fields,
},
});
it("is a schema the probe cannot reach", () => {
expect(probeUnknownFieldPolicy(noContent)).toBe("UNREACHED");
});
it("still needs its direction", () => {
expect(directionProblems(used, rows({}))).toEqual([
"DELETE_THING NoContent: row states no direction, used as RESPONSE",
]);
expect(directionProblems(used, rows({ direction: "RESPONSE" }))).toEqual([]);
});
it("is not held to an unknown-field policy", () => {
expect(policyProblems(used, rows({ direction: "RESPONSE" }))).toEqual([]);
expect(
policyProblems(
used,
rows({ direction: "RESPONSE", unknownFieldPolicy: "STRIP_UNKNOWN" }),
),
).toEqual([]);
});
});