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
This commit is contained in:
@@ -708,6 +708,10 @@ feature 제거 시 해당 contribution도 함께 제거할 수 있고 공통 evi
|
||||
sample feature가 아니라 `tests/helpers/external-contract-fixture.ts`의 테스트
|
||||
계약 3개(조회 목록, 조회 단건, 명령)로 돌므로 sample을 지워도 남는다(0929/10-02).
|
||||
바이트 상한·명령 여부·성공 status는 계약에서 읽는다.
|
||||
feature 테스트는 catalog를 고치지 않는다. 자기 설치 계약을
|
||||
`tests/mocks/handlers/http-scenarios.ts`의
|
||||
`createHttpScenarioHandler(<계약>, { scenario, payload })`에 넘기면 그 operation의
|
||||
경로·성공 status·응답 상한으로 시나리오 응답을 받는다(16-02).
|
||||
|
||||
### 11.1 목표 구조
|
||||
|
||||
|
||||
@@ -140,6 +140,8 @@ const commonTestPaths = [
|
||||
"tests/integration/http-scenario-catalog.test.ts",
|
||||
"tests/mocks/scenarios/catalog.ts",
|
||||
"tests/mocks/handlers/test-entities.ts",
|
||||
// 16-02. Feature tests answer their own operations with it.
|
||||
"tests/mocks/handlers/http-scenarios.ts",
|
||||
"tests/fixtures/typecheck/fixture-feature-contract.ts",
|
||||
"tests/fixtures/typecheck/invalid-feature-input.ts",
|
||||
"tests/fixtures/typecheck/invalid-reference-operation.ts",
|
||||
|
||||
@@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
|
||||
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
|
||||
import { INSTALLED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts";
|
||||
import { REFERENCE_FEATURE_ID } from "../../src/features/reference-feature/contracts/reference-feature-contract.ts";
|
||||
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
|
||||
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
|
||||
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
|
||||
@@ -21,7 +21,9 @@ import { createProductFeaturesStub } from "../helpers/runtime-capabilities-stub.
|
||||
* here, on the same render, so the switch cannot be half-wired.
|
||||
*/
|
||||
|
||||
const FEATURE_ID = INSTALLED_PRODUCT_FEATURE_IDS[0]!;
|
||||
// 16-02. The feature that owns FEATURE_ROUTE, not whichever installed feature
|
||||
// sorts first.
|
||||
const FEATURE_ID = REFERENCE_FEATURE_ID;
|
||||
const FEATURE_ROUTE = ROUTE_REGISTRY.REFERENCE_RESOURCE_LIST;
|
||||
|
||||
function renderAt(path: string, disabled: boolean) {
|
||||
|
||||
@@ -3,15 +3,21 @@ import { describe, expect, it } from "vitest";
|
||||
import { TEMPLATE_APP_MODULE } from "../../../src/apps/template-app.ts";
|
||||
import { createAppRouteModules } from "../../../src/platform/routing/context-route-module.ts";
|
||||
|
||||
// 16-02. Other installed features bring their own contexts; only the
|
||||
// reference context is this sample's to check.
|
||||
const REFERENCE_CONTEXT_ID = "reference-context";
|
||||
|
||||
describe("installed context routing", () => {
|
||||
it("boots one bounded-context entry instead of flattening feature routes", () => {
|
||||
const modules = createAppRouteModules(TEMPLATE_APP_MODULE);
|
||||
expect(modules.map((module) => module.id)).toEqual(["reference-context"]);
|
||||
expect(modules.map((module) => module.id)).toContain(REFERENCE_CONTEXT_ID);
|
||||
expect(modules.some((module) => module.id === "REFERENCE_RESOURCE_LIST")).toBe(false);
|
||||
});
|
||||
|
||||
it("loads the reference feature routes lazily without changing public URLs", async () => {
|
||||
const [context] = createAppRouteModules(TEMPLATE_APP_MODULE);
|
||||
const context = createAppRouteModules(TEMPLATE_APP_MODULE).find(
|
||||
(module) => module.id === REFERENCE_CONTEXT_ID,
|
||||
);
|
||||
expect(context).toBeDefined();
|
||||
const routes = await context!.loadRoutes();
|
||||
expect(routes.map((route) => [route.id, route.path])).toEqual([
|
||||
|
||||
@@ -21,16 +21,18 @@ import {
|
||||
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,
|
||||
type HttpScenarioOperationId,
|
||||
} from "../mocks/scenarios/catalog.ts";
|
||||
|
||||
/** A low-cardinality route identity, as a feature binding passes it. */
|
||||
@@ -53,7 +55,9 @@ type AttemptTrace = {
|
||||
cancelled: boolean;
|
||||
};
|
||||
|
||||
function operationFor(operationId: HttpScenarioOperationId) {
|
||||
type CatalogOperationId = HttpScenarioExpectation["operationId"];
|
||||
|
||||
function operationFor(operationId: CatalogOperationId) {
|
||||
return HTTP_SCENARIO_CONTRACTS[operationId] as InstalledHttpContract<
|
||||
unknown,
|
||||
unknown,
|
||||
@@ -61,7 +65,7 @@ function operationFor(operationId: HttpScenarioOperationId) {
|
||||
>;
|
||||
}
|
||||
|
||||
function inputFor(operationId: HttpScenarioOperationId): 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" };
|
||||
@@ -406,3 +410,52 @@ describe("HTTP scenario catalog execution evidence", () => {
|
||||
});
|
||||
}, 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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { delay, http, HttpResponse, type JsonBodyType } from "msw";
|
||||
|
||||
import {
|
||||
httpScenarioOperationFacts,
|
||||
type HttpScenarioContract,
|
||||
type HttpScenarioId,
|
||||
type HttpScenarioOperationId,
|
||||
} from "../scenarios/catalog.ts";
|
||||
|
||||
/**
|
||||
* 16-02. One MSW handler that answers an installed HTTP operation with one
|
||||
* catalog scenario. The route, the success status and the response ceiling
|
||||
* come from the operation's own descriptor, so a feature test passes its
|
||||
* contract and needs no catalog entry:
|
||||
*
|
||||
* server.use(createHttpScenarioHandler(LIST_X_CONTRACT, {
|
||||
* scenario: "server-terminal-503", payload: [...],
|
||||
* }));
|
||||
*/
|
||||
export type HttpScenarioHandlerOptions = Readonly<{
|
||||
baseUrl?: string;
|
||||
scenario?: HttpScenarioId;
|
||||
/** The success body; `empty` answers `[]` instead. */
|
||||
payload: JsonBodyType;
|
||||
onAttempt?(attempt: Readonly<{
|
||||
operationId: HttpScenarioOperationId;
|
||||
scenarioId: HttpScenarioId;
|
||||
attempt: number;
|
||||
}>): void;
|
||||
}>;
|
||||
|
||||
export function createHttpScenarioHandler(
|
||||
installed: HttpScenarioContract,
|
||||
options: HttpScenarioHandlerOptions,
|
||||
) {
|
||||
const { operationId, method, pathTemplate } = installed.contract;
|
||||
const scenarioId = options.scenario ?? "success";
|
||||
const facts = httpScenarioOperationFacts(installed);
|
||||
// MSW path params are `:name`; descriptors write `{name}`.
|
||||
const url = `${options.baseUrl ?? "https://api.test"}${pathTemplate.replace(
|
||||
/\{([^}]+)\}/gu,
|
||||
":$1",
|
||||
)}`;
|
||||
let attempt = 0;
|
||||
return http[method.toLowerCase() as Lowercase<typeof method>](url, () => {
|
||||
attempt += 1;
|
||||
options.onAttempt?.({ operationId, scenarioId, attempt });
|
||||
return scenarioResponse(
|
||||
scenarioId,
|
||||
scenarioId === "empty" ? [] : options.payload,
|
||||
attempt,
|
||||
facts,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function scenarioResponse(
|
||||
scenario: HttpScenarioId,
|
||||
payload: JsonBodyType,
|
||||
attempt: number,
|
||||
{ ceiling, successStatus }: ReturnType<typeof httpScenarioOperationFacts>,
|
||||
) {
|
||||
if (scenario === "slow") await delay(50);
|
||||
if (scenario === "timeout" || scenario === "aborted") {
|
||||
await delay("infinite");
|
||||
}
|
||||
if (scenario === "network-error") return HttpResponse.error();
|
||||
if (scenario === "content-type-mismatch") {
|
||||
return new HttpResponse("<html>not json</html>", {
|
||||
status: successStatus,
|
||||
headers: { "Content-Type": "text/html" },
|
||||
});
|
||||
}
|
||||
if (scenario === "malformed-json") {
|
||||
return new HttpResponse("{invalid", {
|
||||
status: successStatus,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
if (scenario === "envelope-mismatch") {
|
||||
return HttpResponse.json({ data: payload }, { status: successStatus });
|
||||
}
|
||||
if (scenario === "schema-mismatch") {
|
||||
return HttpResponse.json({ unexpected: true }, { status: successStatus });
|
||||
}
|
||||
if (scenario === "unauthenticated-401") {
|
||||
return HttpResponse.json(problem(401, "AUTH_REQUIRED"), { status: 401 });
|
||||
}
|
||||
if (scenario === "forbidden-403") {
|
||||
return HttpResponse.json(problem(403, "FORBIDDEN"), { status: 403 });
|
||||
}
|
||||
if (scenario === "not-found-404") {
|
||||
return HttpResponse.json(problem(404, "NOT_FOUND"), { status: 404 });
|
||||
}
|
||||
if (scenario === "conflict-409") {
|
||||
return HttpResponse.json(problem(409, "CONFLICT"), { status: 409 });
|
||||
}
|
||||
if (scenario === "in-flight-409") {
|
||||
return HttpResponse.json(problem(409, "IDEMPOTENT_IN_FLIGHT"), {
|
||||
status: 409,
|
||||
});
|
||||
}
|
||||
if (scenario === "validation-422") {
|
||||
return HttpResponse.json(problem(422, "VALIDATION_REJECTED"), {
|
||||
status: 422,
|
||||
});
|
||||
}
|
||||
if (scenario === "rate-limited-429") {
|
||||
return HttpResponse.json(problem(429, "RATE_LIMITED"), {
|
||||
status: 429,
|
||||
headers: { "Retry-After": "1" },
|
||||
});
|
||||
}
|
||||
if (
|
||||
scenario === "server-terminal-503" ||
|
||||
(scenario === "server-retry-success" && attempt === 1)
|
||||
) {
|
||||
return HttpResponse.json(problem(503, "SERVER_FAILURE"), { status: 503 });
|
||||
}
|
||||
if (scenario === "response-too-large") {
|
||||
const bytes = new Uint8Array(ceiling + 1).fill(0x20);
|
||||
bytes[0] = 0x5b;
|
||||
bytes[bytes.length - 1] = 0x5d;
|
||||
return new HttpResponse(
|
||||
new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(bytes);
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{
|
||||
status: successStatus,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": String(bytes.byteLength),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
return HttpResponse.json(payload, { status: successStatus });
|
||||
}
|
||||
|
||||
function problem(status: number, code: string) {
|
||||
return Object.freeze({
|
||||
type: `https://api.test/problems/${code.toLowerCase()}`,
|
||||
title: code,
|
||||
status,
|
||||
code,
|
||||
});
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import { delay, http, HttpResponse, type JsonBodyType } from "msw";
|
||||
|
||||
import {
|
||||
assertOperationScenario,
|
||||
httpScenarioOperationFacts,
|
||||
HTTP_SCENARIO_ENTITY,
|
||||
HTTP_SCENARIO_CONTRACTS,
|
||||
HTTP_SCENARIO_OPERATION_IDS,
|
||||
HTTP_SCENARIO_PAYLOADS,
|
||||
type HttpScenarioId,
|
||||
type HttpScenarioOperationId,
|
||||
} from "../scenarios/catalog.ts";
|
||||
import {
|
||||
createHttpScenarioHandler,
|
||||
type HttpScenarioHandlerOptions,
|
||||
} from "./http-scenarios.ts";
|
||||
|
||||
/**
|
||||
* MSW handlers for the test contracts in `tests/helpers/external-contract-fixture.ts`
|
||||
@@ -16,144 +19,19 @@ import {
|
||||
type ScenarioOptions = Readonly<{
|
||||
baseUrl?: string;
|
||||
scenarios?: Partial<Record<HttpScenarioOperationId, HttpScenarioId>>;
|
||||
onAttempt?(attempt: Readonly<{
|
||||
operationId: HttpScenarioOperationId;
|
||||
scenarioId: HttpScenarioId;
|
||||
attempt: number;
|
||||
}>): void;
|
||||
onAttempt?: HttpScenarioHandlerOptions["onAttempt"];
|
||||
}>;
|
||||
|
||||
async function scenarioResponse(
|
||||
operationId: HttpScenarioOperationId,
|
||||
scenario: HttpScenarioId,
|
||||
payload: JsonBodyType,
|
||||
attempt: number,
|
||||
) {
|
||||
const { ceiling, successStatus } = httpScenarioOperationFacts(operationId);
|
||||
if (scenario === "slow") await delay(50);
|
||||
if (scenario === "timeout" || scenario === "aborted") {
|
||||
await delay("infinite");
|
||||
}
|
||||
if (scenario === "network-error") return HttpResponse.error();
|
||||
if (scenario === "content-type-mismatch") {
|
||||
return new HttpResponse("<html>not json</html>", {
|
||||
status: successStatus,
|
||||
headers: { "Content-Type": "text/html" },
|
||||
});
|
||||
}
|
||||
if (scenario === "malformed-json") {
|
||||
return new HttpResponse("{invalid", {
|
||||
status: successStatus,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
if (scenario === "envelope-mismatch") {
|
||||
return HttpResponse.json({ data: payload }, { status: successStatus });
|
||||
}
|
||||
if (scenario === "schema-mismatch") {
|
||||
return HttpResponse.json({ unexpected: true }, { status: successStatus });
|
||||
}
|
||||
if (scenario === "unauthenticated-401") {
|
||||
return HttpResponse.json(problem(401, "AUTH_REQUIRED"), { status: 401 });
|
||||
}
|
||||
if (scenario === "forbidden-403") {
|
||||
return HttpResponse.json(problem(403, "FORBIDDEN"), { status: 403 });
|
||||
}
|
||||
if (scenario === "not-found-404") {
|
||||
return HttpResponse.json(problem(404, "NOT_FOUND"), { status: 404 });
|
||||
}
|
||||
if (scenario === "conflict-409") {
|
||||
return HttpResponse.json(problem(409, "CONFLICT"), { status: 409 });
|
||||
}
|
||||
if (scenario === "in-flight-409") {
|
||||
return HttpResponse.json(problem(409, "IDEMPOTENT_IN_FLIGHT"), {
|
||||
status: 409,
|
||||
});
|
||||
}
|
||||
if (scenario === "validation-422") {
|
||||
return HttpResponse.json(problem(422, "VALIDATION_REJECTED"), {
|
||||
status: 422,
|
||||
});
|
||||
}
|
||||
if (scenario === "rate-limited-429") {
|
||||
return HttpResponse.json(problem(429, "RATE_LIMITED"), {
|
||||
status: 429,
|
||||
headers: { "Retry-After": "1" },
|
||||
});
|
||||
}
|
||||
if (
|
||||
scenario === "server-terminal-503" ||
|
||||
(scenario === "server-retry-success" && attempt === 1)
|
||||
) {
|
||||
return HttpResponse.json(problem(503, "SERVER_FAILURE"), { status: 503 });
|
||||
}
|
||||
if (scenario === "response-too-large") {
|
||||
const bytes = new Uint8Array(ceiling + 1).fill(0x20);
|
||||
bytes[0] = 0x5b;
|
||||
bytes[bytes.length - 1] = 0x5d;
|
||||
return new HttpResponse(
|
||||
new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(bytes);
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{
|
||||
status: successStatus,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": String(bytes.byteLength),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
return HttpResponse.json(payload, { status: successStatus });
|
||||
}
|
||||
|
||||
function problem(status: number, code: string) {
|
||||
return Object.freeze({
|
||||
type: `https://api.test/problems/${code.toLowerCase()}`,
|
||||
title: code,
|
||||
status,
|
||||
code,
|
||||
});
|
||||
}
|
||||
|
||||
export function createTestEntityScenarioHandlers(options: ScenarioOptions = {}) {
|
||||
const baseUrl = options.baseUrl ?? "https://api.test";
|
||||
const attempts = new Map<HttpScenarioOperationId, number>();
|
||||
const answer = (operationId: HttpScenarioOperationId, payload: JsonBodyType) => {
|
||||
const scenarioId = assertOperationScenario(
|
||||
operationId,
|
||||
options.scenarios?.[operationId] ?? "success",
|
||||
);
|
||||
const attempt = (attempts.get(operationId) ?? 0) + 1;
|
||||
attempts.set(operationId, attempt);
|
||||
options.onAttempt?.({ operationId, scenarioId, attempt });
|
||||
return scenarioResponse(
|
||||
operationId,
|
||||
scenarioId,
|
||||
scenarioId === "empty" ? [] : payload,
|
||||
attempt,
|
||||
);
|
||||
};
|
||||
|
||||
return [
|
||||
http.get(`${baseUrl}/api/test-entities`, () =>
|
||||
answer("TEST_LIST_ENTITIES", [{ ...HTTP_SCENARIO_ENTITY }]),
|
||||
),
|
||||
http.post(`${baseUrl}/api/test-entities`, async ({ request }) => {
|
||||
const body = (await request.json()) as Readonly<Record<string, unknown>>;
|
||||
return answer("TEST_CREATE_ENTITY", {
|
||||
id: "entity-created",
|
||||
name: String(body.name ?? "Created"),
|
||||
});
|
||||
return HTTP_SCENARIO_OPERATION_IDS.map((operationId) =>
|
||||
createHttpScenarioHandler(HTTP_SCENARIO_CONTRACTS[operationId], {
|
||||
baseUrl: options.baseUrl,
|
||||
scenario: assertOperationScenario(
|
||||
operationId,
|
||||
options.scenarios?.[operationId] ?? "success",
|
||||
),
|
||||
payload: HTTP_SCENARIO_PAYLOADS[operationId],
|
||||
onAttempt: options.onAttempt,
|
||||
}),
|
||||
http.get(`${baseUrl}/api/test-entities/:entityId`, ({ params }) =>
|
||||
answer("TEST_GET_ENTITY", {
|
||||
...HTTP_SCENARIO_ENTITY,
|
||||
id: String(params.entityId),
|
||||
}),
|
||||
),
|
||||
] as const;
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { JsonBodyType } from "msw";
|
||||
|
||||
import type {
|
||||
AttemptStatus,
|
||||
BodyDisposition,
|
||||
@@ -11,6 +13,7 @@ export type {
|
||||
HttpScenarioAssertionGroups,
|
||||
RetryReason,
|
||||
} from "../../../scripts/lib/http-scenario-evidence.ts";
|
||||
import type { InstalledHttpContract } from "../../../src/contracts/external-contract-runtime.ts";
|
||||
import {
|
||||
TEST_CLASSIFIED_CREATE_HTTP_CONTRACT,
|
||||
TEST_DETAIL_HTTP_CONTRACT,
|
||||
@@ -56,10 +59,32 @@ export const HTTP_SCENARIO_CONTRACTS = Object.freeze({
|
||||
TEST_CREATE_ENTITY: TEST_CLASSIFIED_CREATE_HTTP_CONTRACT,
|
||||
});
|
||||
|
||||
export type HttpScenarioOperationId = keyof typeof HTTP_SCENARIO_CONTRACTS;
|
||||
/**
|
||||
* 16-02. Any installed operation, not only the catalog's: a feature test
|
||||
* answers its own operation with `createHttpScenarioHandler`
|
||||
* (`tests/mocks/handlers/http-scenarios.ts`) without editing this file.
|
||||
*/
|
||||
export type HttpScenarioOperationId = string;
|
||||
|
||||
/**
|
||||
* The part of an installed (V3) descriptor a scenario reads. Every
|
||||
* `InstalledHttpContract` fits it, whatever its input and output types.
|
||||
*/
|
||||
export type HttpScenarioContract = Readonly<{
|
||||
contract: Readonly<
|
||||
Pick<
|
||||
InstalledHttpContract<unknown, unknown, unknown>["contract"],
|
||||
"operationId" | "method" | "pathTemplate" | "acceptedStatuses"
|
||||
> & { commandEffect: unknown }
|
||||
>;
|
||||
frontend: Readonly<{ responseByteLimit: number }>;
|
||||
}>;
|
||||
|
||||
/** The operations this catalog's evidence (FE-GATE-007) is recorded for. */
|
||||
type CatalogOperationId = keyof typeof HTTP_SCENARIO_CONTRACTS;
|
||||
|
||||
export const HTTP_SCENARIO_OPERATION_IDS = Object.freeze(
|
||||
Object.keys(HTTP_SCENARIO_CONTRACTS) as HttpScenarioOperationId[],
|
||||
Object.keys(HTTP_SCENARIO_CONTRACTS) as CatalogOperationId[],
|
||||
);
|
||||
|
||||
for (const operationId of HTTP_SCENARIO_OPERATION_IDS) {
|
||||
@@ -70,11 +95,11 @@ for (const operationId of HTTP_SCENARIO_OPERATION_IDS) {
|
||||
}
|
||||
|
||||
export type HttpScenarioExecutionId =
|
||||
`${HttpScenarioOperationId}::${HttpScenarioId}`;
|
||||
`${CatalogOperationId}::${HttpScenarioId}`;
|
||||
|
||||
export type HttpScenarioExpectation = Readonly<{
|
||||
executionId: HttpScenarioExecutionId;
|
||||
operationId: HttpScenarioOperationId;
|
||||
operationId: CatalogOperationId;
|
||||
scenarioId: HttpScenarioId;
|
||||
expected: HttpScenarioAssertionGroups;
|
||||
testDeadlineOverrideMs: number | null;
|
||||
@@ -92,19 +117,21 @@ export const HTTP_SCENARIO_CREATED_ENTITY = Object.freeze({
|
||||
name: "Created",
|
||||
});
|
||||
|
||||
/** What a scenario's answer depends on, from the operation's contract. */
|
||||
export function httpScenarioOperationFacts(operationId: HttpScenarioOperationId) {
|
||||
const installed = HTTP_SCENARIO_CONTRACTS[operationId];
|
||||
/** The success body each catalog operation answers with. */
|
||||
export const HTTP_SCENARIO_PAYLOADS: Readonly<
|
||||
Record<CatalogOperationId, JsonBodyType>
|
||||
> = Object.freeze({
|
||||
TEST_LIST_ENTITIES: Object.freeze([HTTP_SCENARIO_ENTITY]),
|
||||
TEST_GET_ENTITY: HTTP_SCENARIO_ENTITY,
|
||||
TEST_CREATE_ENTITY: HTTP_SCENARIO_CREATED_ENTITY,
|
||||
});
|
||||
|
||||
/** What a scenario's answer depends on, read from the installed descriptor. */
|
||||
export function httpScenarioOperationFacts(installed: HttpScenarioContract) {
|
||||
return Object.freeze({
|
||||
command: installed.contract.commandEffect !== null,
|
||||
ceiling: installed.frontend.responseByteLimit,
|
||||
successStatus: installed.contract.acceptedStatuses[0]!,
|
||||
payload:
|
||||
operationId === "TEST_LIST_ENTITIES"
|
||||
? [HTTP_SCENARIO_ENTITY]
|
||||
: operationId === "TEST_GET_ENTITY"
|
||||
? HTTP_SCENARIO_ENTITY
|
||||
: HTTP_SCENARIO_CREATED_ENTITY,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -126,11 +153,13 @@ function attemptBody(
|
||||
}
|
||||
|
||||
function expectationFor(
|
||||
operationId: HttpScenarioOperationId,
|
||||
operationId: CatalogOperationId,
|
||||
scenarioId: HttpScenarioId,
|
||||
): HttpScenarioExpectation {
|
||||
const { command, ceiling, successStatus, payload } =
|
||||
httpScenarioOperationFacts(operationId);
|
||||
const { command, ceiling, successStatus } = httpScenarioOperationFacts(
|
||||
HTTP_SCENARIO_CONTRACTS[operationId],
|
||||
);
|
||||
const payload = HTTP_SCENARIO_PAYLOADS[operationId];
|
||||
let statuses: AttemptStatus[] = [successStatus];
|
||||
let kind = "SUCCESS";
|
||||
let detail: string | null = null;
|
||||
@@ -432,7 +461,7 @@ const OPERATION_SCENARIOS = Object.freeze({
|
||||
),
|
||||
),
|
||||
} satisfies Readonly<
|
||||
Record<HttpScenarioOperationId, readonly HttpScenarioId[]>
|
||||
Record<CatalogOperationId, readonly HttpScenarioId[]>
|
||||
>);
|
||||
|
||||
export const HTTP_SCENARIO_EXPECTATIONS = Object.freeze(
|
||||
@@ -458,7 +487,7 @@ export const OPERATION_SCENARIO_CATALOG = Object.freeze(
|
||||
),
|
||||
]),
|
||||
) as Readonly<
|
||||
Record<HttpScenarioOperationId, readonly HttpScenarioId[]>
|
||||
Record<CatalogOperationId, readonly HttpScenarioId[]>
|
||||
>,
|
||||
);
|
||||
|
||||
@@ -466,7 +495,15 @@ export function assertOperationScenario(
|
||||
operationId: HttpScenarioOperationId,
|
||||
scenario: HttpScenarioId,
|
||||
) {
|
||||
if (!OPERATION_SCENARIO_CATALOG[operationId].includes(scenario)) {
|
||||
const catalog: Readonly<Partial<Record<string, readonly HttpScenarioId[]>>> =
|
||||
OPERATION_SCENARIO_CATALOG;
|
||||
const declared = catalog[operationId];
|
||||
if (declared === undefined) {
|
||||
throw new Error(
|
||||
`${operationId} is not a catalog operation; answer it with createHttpScenarioHandler`,
|
||||
);
|
||||
}
|
||||
if (!declared.includes(scenario)) {
|
||||
throw new Error(`Scenario ${scenario} is not declared for ${operationId}`);
|
||||
}
|
||||
return scenario;
|
||||
|
||||
@@ -5,8 +5,14 @@ import {
|
||||
ReleaseManifestError,
|
||||
} from "../../src/bootstrap/load-release-manifest.ts";
|
||||
import { computeContractSetDigest } from "../../src/contracts/contract-set-canonical.ts";
|
||||
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../../src/features/installed-contract-contributions.ts";
|
||||
|
||||
const EMPTY_SET_DIGEST = await computeContractSetDigest([]);
|
||||
// 16-02. The build compiles the installed features' packages, so a coherent
|
||||
// manifest carries exactly that set, whatever is installed.
|
||||
const INSTALLED_SET_DIGEST = await computeContractSetDigest(
|
||||
EXPECTED_CONTRACT_SET_PACKAGES,
|
||||
);
|
||||
|
||||
const runtime: Parameters<typeof loadReleaseManifest>[0] = {
|
||||
build: {
|
||||
@@ -49,8 +55,8 @@ const manifest = {
|
||||
routeChunks: { "route-home": "assets/home.js" },
|
||||
contractSet: {
|
||||
setAlgorithm: "CA_CONTRACT_SET_V1",
|
||||
setDigest: EMPTY_SET_DIGEST,
|
||||
packages: [],
|
||||
setDigest: INSTALLED_SET_DIGEST,
|
||||
packages: EXPECTED_CONTRACT_SET_PACKAGES,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user