문제 조립기와 선언 검증의 쓰기 API 규칙 5개는 지워도 관련 테스트가 모두 통과한다(리뷰 변이 MX1·MX2·MX5·MX6·MX9). - MX1 읽기 operation의 command descriptor 금지 (external-contract-runtime.ts). 실행기는 쓰기 여부를 메서드가 아니라 commandEffect !== null로 정하므로 GET이 쓰기로 처리되는 것을 막는 유일한 경계다. - MX9 KEYED 쓰기의 복구 descriptor 필수 - MX6 NEVER 재시도와 재시도 예산 1 이상의 모순 거부 - MX5 V2 KEYED_COMMAND의 idempotencyKeyPolicy REQUIRED 정합 (api-operations.ts) - MX2 mapper 레지스트리 키 = mapperId (boundary-mapper.ts) 조립기는 여러 번 다시 쓰인 파일이라 규칙 줄이 빠져도 CI가 모른다. 고른 방법 규칙마다 그 규칙만 어긴 행 하나로 실패 사례를 둔다. 오류 메시지는 기능 작성자가 쓰기 API 규칙을 배우는 통로라 reason 문자열을 그대로 단언한다. 정상 대조군은 기존 사례(TEST_CONTRACT_CONTRIBUTION 조립, command() 정의, 키가 맞는 mapper 등록)를 쓰거나 같은 테스트 안에 둔다. 코드 변경은 없다. 버린 대안 - 메시지 대신 ContractContributionError 종류만 단언: 다른 규칙이 먼저 실패해도 통과해서 변이를 놓칠 수 있다. 위험·한계 - 메시지 문구를 바꾸면 테스트도 바꿔야 한다. 의도한 결합이다. - MX6은 실행기(http-retry-lifecycle)가 한 번 더 막는다. 이 테스트는 조립 단계의 안내 메시지를 지킨다. 검증 - RED: 변이 5개를 하나씩 넣고 바꾼 3파일을 돌렸다. 이 커밋 전 테스트로는 5개 모두 살아남음(26/26 통과). 새 테스트로는 5개 모두 죽음, 각 변이마다 해당 사례 1건만 실패(30/31). - GREEN: 변이 없이 31/31 통과. - 회귀: tsc test rc=0, 바꾼 파일 eslint rc=0. Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md
192 lines
6.5 KiB
TypeScript
192 lines
6.5 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
|
|
import {
|
|
ContractContributionError,
|
|
composeContractContributions,
|
|
invokeValidator,
|
|
type InstalledContractContribution,
|
|
type RuntimeValidator,
|
|
} from "../../src/contracts/external-contract-runtime.ts";
|
|
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
|
|
|
|
function contribution(
|
|
contributionId: string,
|
|
http: InstalledContractContribution["http"],
|
|
): InstalledContractContribution & Readonly<{ contributionId: string }> {
|
|
return Object.freeze({
|
|
...TEST_CONTRACT_CONTRIBUTION,
|
|
contributionId,
|
|
http: Object.freeze([...http]),
|
|
});
|
|
}
|
|
|
|
function captureContributionError(operation: () => unknown): ContractContributionError {
|
|
try {
|
|
operation();
|
|
} catch (error) {
|
|
expect(error).toBeInstanceOf(ContractContributionError);
|
|
return error as ContractContributionError;
|
|
}
|
|
throw new Error("Expected contract composition to fail.");
|
|
}
|
|
|
|
describe("external contract contribution composition", () => {
|
|
it("allows one feature to install multiple uniquely identified contributions", () => {
|
|
const operations = TEST_CONTRACT_CONTRIBUTION.http;
|
|
const composed = composeContractContributions([
|
|
contribution("test-read-contracts", operations.slice(0, 2)),
|
|
contribution("test-command-contracts", operations.slice(2)),
|
|
]);
|
|
|
|
expect(composed.contributions).toHaveLength(2);
|
|
expect(composed.httpByOperationId.size).toBe(3);
|
|
});
|
|
|
|
it("rejects duplicate contribution identities even across different feature entries", () => {
|
|
const first = contribution(
|
|
"test-contracts",
|
|
TEST_CONTRACT_CONTRIBUTION.http.slice(0, 1),
|
|
);
|
|
const second = contribution(
|
|
"test-contracts",
|
|
TEST_CONTRACT_CONTRIBUTION.http.slice(1),
|
|
);
|
|
|
|
const error = captureContributionError(() =>
|
|
composeContractContributions([first, second]),
|
|
);
|
|
expect(error.reason).toContain("duplicate contributionId");
|
|
});
|
|
|
|
it("maps malformed source values to the closed composition error", () => {
|
|
const malformed = {
|
|
...contribution("malformed-source", []),
|
|
source: null,
|
|
} as unknown as InstalledContractContribution;
|
|
|
|
const error = captureContributionError(() =>
|
|
composeContractContributions([malformed]),
|
|
);
|
|
expect(error.reason).toContain("source");
|
|
});
|
|
|
|
it("rejects method and body vocabulary outside the runtime protocol", () => {
|
|
const installed = TEST_CONTRACT_CONTRIBUTION.http[0]!;
|
|
const malformedOperation = {
|
|
...installed,
|
|
contract: { ...installed.contract, method: "TRACE" },
|
|
} as unknown as InstalledContractContribution["http"][number];
|
|
|
|
const error = captureContributionError(() =>
|
|
composeContractContributions([
|
|
contribution("invalid-http-vocabulary", [malformedOperation]),
|
|
]),
|
|
);
|
|
expect(error.reason).toContain("method");
|
|
});
|
|
});
|
|
|
|
// 07-06 (MX1, MX9, MX6). The write-API rules the composer teaches through its
|
|
// error messages. TEST_CONTRACT_CONTRIBUTION composing in the first block is
|
|
// the valid control.
|
|
describe("write operation rules", () => {
|
|
const [listRow, , createRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [
|
|
InstalledContractContribution["http"][number],
|
|
InstalledContractContribution["http"][number],
|
|
InstalledContractContribution["http"][number],
|
|
];
|
|
|
|
function reasonFor(row: object): string {
|
|
return captureContributionError(() =>
|
|
composeContractContributions([
|
|
contribution("write-rule", [
|
|
row as InstalledContractContribution["http"][number],
|
|
]),
|
|
]),
|
|
).reason;
|
|
}
|
|
|
|
// The executor decides "write" by `commandEffect !== null`, not by method,
|
|
// so this rule is the only thing keeping a GET from running as a command.
|
|
it("rejects command descriptors on a read operation", () => {
|
|
expect(
|
|
reasonFor({
|
|
...listRow,
|
|
contract: { ...listRow.contract, commandEffect: createRow.contract.commandEffect },
|
|
}),
|
|
).toBe("test-feature/TEST_LIST_ENTITIES: read operations carry no command descriptors");
|
|
});
|
|
|
|
it("requires a recovery descriptor on a KEYED command", () => {
|
|
expect(
|
|
reasonFor({
|
|
...createRow,
|
|
contract: { ...createRow.contract, commandRecovery: null },
|
|
}),
|
|
).toBe("test-feature/TEST_CREATE_ENTITY: KEYED commands require a recovery descriptor");
|
|
});
|
|
|
|
it("rejects a retry budget on a NEVER-retry operation", () => {
|
|
expect(
|
|
reasonFor({
|
|
...createRow,
|
|
contract: { ...createRow.contract, retrySemantics: "NEVER" },
|
|
frontend: { ...createRow.frontend, retryBudget: 1 },
|
|
}),
|
|
).toBe("test-feature/TEST_CREATE_ENTITY: retry budget contradicts NEVER retry semantics");
|
|
});
|
|
});
|
|
|
|
// The sample feature's own cases (its fixture composes, a second one does not)
|
|
// live in tests/features so they leave with the sample.
|
|
describe("template fixture provenance (07-04, §4.8)", () => {
|
|
it("rejects a fixture copied into a product feature, which would leave the contract set silently", () => {
|
|
const copied = Object.freeze({
|
|
...contribution("order-http-v1", TEST_CONTRACT_CONTRIBUTION.http),
|
|
featureId: "order",
|
|
source: Object.freeze({
|
|
kind: "TEMPLATE_FIXTURE" as const,
|
|
fixtureId: "REFERENCE_FEATURE_V1" as const,
|
|
revision: 1 as const,
|
|
}),
|
|
});
|
|
const error = captureContributionError(() =>
|
|
composeContractContributions([copied]),
|
|
);
|
|
expect(error.reason).toMatch(
|
|
/^order: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to .+ only; pin an EXTERNAL_PACKAGE$/u,
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("validator invocation (07-06)", () => {
|
|
const returning = (result: unknown): RuntimeValidator<unknown> => ({
|
|
schemaId: "Malformed",
|
|
safeParse: () => result as never,
|
|
});
|
|
|
|
it.each([
|
|
["non-array issues", { success: false, issues: 5 }],
|
|
["object issues", { success: false, issues: {} }],
|
|
["non-boolean success", { success: "no", data: "unchecked" }],
|
|
["throwing issues getter", {
|
|
success: false,
|
|
get issues(): never {
|
|
throw new Error("hostile");
|
|
},
|
|
}],
|
|
])("reports THROWN for a result with %s", (_label, result) => {
|
|
expect(invokeValidator(returning(result), {})).toEqual({ outcome: "THROWN" });
|
|
});
|
|
|
|
it("keeps well-formed results", () => {
|
|
expect(invokeValidator(returning({ success: true, data: 1 }), {})).toEqual({
|
|
outcome: "VALID",
|
|
value: 1,
|
|
});
|
|
expect(
|
|
invokeValidator(returning({ success: false, issues: [{ path: [], code: "X" }] }), {}),
|
|
).toEqual({ outcome: "INVALID", issues: [{ path: [], code: "X" }] });
|
|
});
|
|
});
|