Files
clean-architecture-frontend…/tests/unit/runtime-adapters.test.ts
DongHyeonka 00b12b35b9 test(bootstrap): 플랫폼 규칙 테스트 둘을 샘플 밖으로 옮긴다
문제
1103 수정이 더한 플랫폼 규칙 테스트 둘이 참조 샘플에 기댄다. 샘플을
지우면 두 테스트가 사라지거나 비어도 test:all과 제거 드릴이 통과한다.
- MAX_RETRY_ATTEMPTS가 실행기에 닿는다: 유일한 테스트가
  tests/features/reference-feature/reference-runtime-composition.test.ts
  에 있다. createRuntimeAdapters는 설치된 기능의 HTTP로만 실행기에 닿아,
  기능이 없으면 시험할 길이 없다. REQUEST_TIMEOUT_MS도 같은 모양이다.
- 복구 중인 세션은 보호 라우트에서 기다린다:
  tests/unit/navigation-policy.test.ts는 설치된 보호 라우트를 돌며
  단언하는데, 보호 라우트는 모두 샘플 것이라 샘플을 지우면 반복이 0번이다.

고른 방법과 버린 대안
- src/bootstrap/runtime-adapters.ts: 설정 두 값과 auth profile 표로
  실행기를 만드는 부분을 createRuntimeContractHttpExecutor로 뺀다.
  조립 루트는 이 함수로만 실행기를 만든다. tests/unit/runtime-adapters
  .test.ts가 테스트 계약(TEST_LIST, 재시도 예산 2)으로 MAX_RETRY_ATTEMPTS
  0·1·2에 1·2·3번 나가는지, REQUEST_TIMEOUT_MS 5가 10초 계약을 5ms에
  끊는지 본다. 이 파일은 이미 제거 드릴의 공통 테스트 목록에 있다.
- tests/unit/session-route-access.test.ts(새 파일): component 테스트와
  같은 방법으로 생성 index를 mock해 tests/helpers/fixture-feature.tsx를
  설치하고, 보호 라우트 FIXTURE_ITEMS에서 네 세션 상태의 결정을 본다.
  decideRouteAccess에 라우트 정의를 받는 순수 함수를 따로 두는 안(리뷰
  ⓐ)은 버렸다. fixture 기능을 설치하는 방법이 이미 있어서 운영 코드를
  바꾸지 않고 실제 getRoute 경로까지 시험할 수 있다.
- scripts/test-sample-removal.ts: 새 파일을 공통 테스트 목록에 넣어,
  제거 드릴이 그 파일이 남았는지 본다.
- 매뉴얼에 "샘플을 지우면 다시 고정한다"고만 적는 안(ⓒ)은 사람이
  기억해야 해서 버렸다.

위험·한계
- 조립 루트가 이 함수 대신 실행기를 직접 만들도록 바뀌면 새 unit
  테스트는 그걸 모른다. 템플릿 상태에서는 참조 기능 테스트가 계속
  조립 루트 전체를 지킨다.
- 샘플을 지운 복사본에 변이를 넣어 돌리지는 않았다.

검증
- desktop batch에서 확인:
  node scripts/run-vitest.ts run tests/unit/runtime-adapters.test.ts tests/unit/session-route-access.test.ts tests/unit/navigation-policy.test.ts tests/features/reference-feature/reference-runtime-composition.test.ts
- RED: 부모 커밋의 운영 코드에는 createRuntimeContractHttpExecutor가
  없어 runtime-adapters.test.ts의 새 4건이 실패한다.
- 변이: 새 함수의 maxRetryAttempts를 상수 2로 바꾸면 "honours
  MAX_RETRY_ATTEMPTS 0/1"이, navigation-policy.ts의 recovery-pending
  분기를 show-sign-in으로 바꾸면 session-route-access.test.ts의
  "answers a recovery-pending session …"이 실패해야 한다.

Refs: 1105/10-01
2026-11-05 22:07:09 +09:00

596 lines
19 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import {
createRuntimeAdapters,
createRuntimeContractHttpExecutor,
} from "../../src/bootstrap/runtime-adapters.ts";
import { createBrowserMutationIntentFactory } from "../../src/adapters/platform/browser-mutation-intent-factory.ts";
import { createApplication } from "../../src/application/create-application.ts";
import type { ApplicationFeatureId } from "../../src/application/ports/in/application-api.ts";
import { loadFeatureRuntime } from "../../src/features/feature-module.ts";
import { INSTALLED_PRODUCT_FEATURE_MODULES } from "../../src/features/installed-product-manifest.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
import { testRuntimeConfig } from "../helpers/runtime-config.ts";
import { scopeSnapshot } from "../helpers/traffic-test-kit.ts";
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
type Release = Parameters<typeof createRuntimeAdapters>[0]["release"];
const runtime: Runtime = {
config: testRuntimeConfig({
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
REQUEST_TIMEOUT_MS: 4321,
MAX_RETRY_ATTEMPTS: 0,
RELEASE_MANIFEST_URL: "/release-manifest.json",
CONFIG_SCHEMA_VERSION: "2.0",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
}),
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
};
const release: Release = {
schemaVersion: 2,
appVersion: "0.1.0",
buildId: "build-a",
commitSha: "abc123",
configSchemaVersion: "2.0",
contractSet: {
setAlgorithm: "CA_CONTRACT_SET_V1",
setDigest: `sha256:${"0".repeat(64)}`,
packages: [],
},
assetManifestHash: "hash-a",
releaseId: "release-a",
builtAt: "2026-07-25T00:00:00Z",
routeChunks: { "route-home": "assets/home.js" },
};
/**
* 1103/09-04. The installed features that contribute an application API. The
* template's example screens call none: loading them
* installs no input.
*/
const API_FEATURE_IDS: readonly string[] = (
await Promise.all(
INSTALLED_PRODUCT_FEATURE_MODULES.map(async (module) =>
(await loadFeatureRuntime(module)).adapters.length > 0 ? [module.id] : [],
),
)
).flat();
describe("runtime adapter composition", () => {
it("creates validated intent and idempotency identities with independent UUID calls", () => {
const randomUUID = vi
.fn<() => string>()
.mockReturnValueOnce("intent-uuid")
.mockReturnValueOnce("idempotency-uuid");
const factory = createBrowserMutationIntentFactory({
randomUUID,
monotonicNow: () => 12.5,
});
const intent = factory.create({
operationId: "CREATE_ENTITY",
canonicalInputIdentity: "opaque-canonical-input",
requiresIdempotencyKey: true,
});
expect(intent).toEqual({
intentId: "intent-uuid",
operationId: "CREATE_ENTITY",
canonicalInputIdentity: "opaque-canonical-input",
idempotencyKey: "idempotency-uuid",
createdAtMonotonicMs: 12.5,
});
expect(Object.isFrozen(intent)).toBe(true);
expect(randomUUID).toHaveBeenCalledTimes(2);
});
it("rejects invalid or unbounded mutation intent values", () => {
const factory = createBrowserMutationIntentFactory({
randomUUID: () => "opaque-runtime-identifier",
monotonicNow: () => 1,
});
expect(() =>
factory.create({
operationId: " ",
canonicalInputIdentity: "valid-identity",
requiresIdempotencyKey: false,
}),
).toThrow(TypeError);
expect(() =>
factory.create({
operationId: "CREATE_ENTITY",
canonicalInputIdentity: "x".repeat(16_385),
requiresIdempotencyKey: false,
}),
).toThrow(TypeError);
expect(() =>
createBrowserMutationIntentFactory({
randomUUID: () => "opaque-runtime-identifier",
monotonicNow: () => -1,
}).create({
operationId: "CREATE_ENTITY",
canonicalInputIdentity: "valid-identity",
requiresIdempotencyKey: false,
}),
).toThrow(TypeError);
});
it("constructs the local demo seam and infrastructure adapters", async () => {
const adapters = await createRuntimeAdapters({
runtime,
release,
host: {},
});
expect(adapters.outputPorts.session.getState()).toBe("unauthenticated");
await expect(adapters.outputPorts.releaseInfo.getCurrent()).resolves.toMatchObject({
releaseId: "release-a",
});
expect(adapters.infrastructure.queryClient).toBeDefined();
expect(adapters.infrastructure.queryInvalidation).toBeDefined();
expect(adapters.infrastructure.mutationIntentFactory).toBeDefined();
expect(
adapters.infrastructure.crossContextInvalidationStatus(),
).toBe("DEGRADED_LOCAL_ONLY");
expect(adapters.outputPorts.diagnostics.record).toEqual(expect.any(Function));
expect(adapters.outputPorts.telemetry.emit).toEqual(expect.any(Function));
expect(adapters.outputPorts.telemetry.pendingCount()).toBe(0);
expect(adapters).not.toHaveProperty("http");
expect(adapters).not.toHaveProperty("storage");
adapters.infrastructure.dispose();
});
it("runtime infrastructure disposal disposes telemetry first", async () => {
const fetcher = vi.fn(async () => new Response(null, { status: 204 }));
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
TELEMETRY_ENABLED: true,
TELEMETRY_ENDPOINT: "https://telemetry.test/events",
},
} as Runtime,
release,
host: {},
fetcher: fetcher as unknown as typeof fetch,
});
adapters.outputPorts.telemetry.emit("api.request.failed", {
error_kind: "SERVER_FAILURE",
http_status_group: "5xx",
attempt_count_bucket: "1",
route_id: "TEST_ROUTE",
});
expect(adapters.outputPorts.telemetry.pendingCount()).toBe(1);
adapters.infrastructure.dispose();
expect(adapters.outputPorts.telemetry.pendingCount()).toBe(0);
await Promise.resolve();
await Promise.resolve();
expect(fetcher).not.toHaveBeenCalled();
});
it("sends telemetry stamped with the release identity (13-11)", async () => {
const bodies: { events: Record<string, unknown>[] }[] = [];
const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
if (String(_url) === "https://telemetry.test/events") {
bodies.push(JSON.parse(String(init?.body)));
}
return new Response(null, { status: 204 });
});
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
TELEMETRY_ENABLED: true,
TELEMETRY_ENDPOINT: "https://telemetry.test/events",
},
} as Runtime,
release,
host: {},
fetcher: fetcher as unknown as typeof fetch,
});
adapters.outputPorts.telemetry.emit("api.request.failed", {
error_kind: "SERVER_FAILURE",
http_status_group: "5xx",
attempt_count_bucket: "1",
route_id: "TEST_ROUTE",
});
await adapters.outputPorts.telemetry.flush();
expect(bodies[0]?.events[0]).toMatchObject({
eventName: "api.request.failed",
build_id: "build-a",
release_id: "release-a",
});
adapters.infrastructure.dispose();
});
it("replaces the QueryClient and coordinator for each session generation", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
const previousClient = adapters.infrastructure.queryClient;
const previousCoordinator = adapters.infrastructure.queryInvalidation;
const runtimeMutationIntentFactory =
adapters.infrastructure.mutationIntentFactory;
const clearPrevious = vi.spyOn(previousClient, "clear");
await adapters.outputPorts.session.beginSignIn();
await vi.waitFor(() =>
expect(adapters.infrastructure.queryClient).not.toBe(previousClient),
);
expect(adapters.infrastructure.queryInvalidation).not.toBe(
previousCoordinator,
);
expect(adapters.infrastructure.mutationIntentFactory).toBe(
runtimeMutationIntentFactory,
);
const clearCallsAfterReplacement = clearPrevious.mock.calls.length;
await previousCoordinator.resetLocal();
expect(clearPrevious).toHaveBeenCalledTimes(clearCallsAfterReplacement);
adapters.infrastructure.dispose();
});
it("does not fail boot when Web Storage capability getters throw", async () => {
const host: Record<string, unknown> = {};
Object.defineProperties(host, {
localStorage: {
get() {
throw new DOMException("denied", "SecurityError");
},
},
sessionStorage: {
get() {
throw new DOMException("denied", "SecurityError");
},
},
});
const adapters = await createRuntimeAdapters({
runtime,
release,
host,
});
expect(adapters.infrastructure.queryClient).toBeDefined();
expect(adapters.outputPorts.preferences.read("COLOR_SCHEME")).toEqual({
ok: true,
value: undefined,
});
adapters.infrastructure.dispose();
});
it("fails closed when an external auth owner was not installed", async () => {
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: { ...runtime.config, AUTH_MODE: "external" },
},
release,
host: {},
});
expect(adapters.outputPorts.session.getState()).toBe("integration-failed");
});
describe("installed external auth owner shape", () => {
const externalRuntime: Runtime = {
...runtime,
config: { ...runtime.config, AUTH_MODE: "external" },
};
const completeOwner = () => ({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
});
it("uses an owner that implements every method", async () => {
const adapters = await createRuntimeAdapters({
runtime: externalRuntime,
release,
host: { __CA_FRONTEND_AUTH_OWNER__: completeOwner() },
});
expect(adapters.outputPorts.session.getState()).toBe("authenticated");
expect(adapters.outputPorts.session.getSubject()).toBe("user-a");
adapters.infrastructure.dispose();
});
it.each(["readSubject", "readState"])(
"fails closed when the owner lacks %s",
async (method) => {
const owner: Record<string, unknown> = completeOwner();
delete owner[method];
const adapters = await createRuntimeAdapters({
runtime: externalRuntime,
release,
host: { __CA_FRONTEND_AUTH_OWNER__: owner },
});
expect(adapters.outputPorts.session.getState()).toBe(
"integration-failed",
);
adapters.infrastructure.dispose();
},
);
});
it("reports the static selection when no capability override disables it", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
const snapshot = adapters.outputPorts.runtimeCapabilities.getSnapshot();
expect(snapshot.map((status) => status.capabilityId)).toEqual([
"REALTIME",
"WEB_WORKER",
"SERVICE_WORKER",
"OFFLINE_COMMANDS",
]);
expect(snapshot.every((status) => status.override === "DEFAULT")).toBe(true);
});
it("carries a disabling override into the capability snapshot", async () => {
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
CAPABILITY_OVERRIDES: {
...runtime.config.CAPABILITY_OVERRIDES,
SERVICE_WORKER: "DISABLED",
},
FEATURE_OVERRIDES: {},
},
},
release,
host: {},
});
const serviceWorker = adapters.outputPorts.runtimeCapabilities
.getSnapshot()
.find((status) => status.capabilityId === "SERVICE_WORKER");
expect(serviceWorker?.override).toBe("DISABLED");
expect(serviceWorker?.active).toBe(0);
});
it("gives a feature switched off by FEATURE_OVERRIDES no application API (Q-6.9-5)", async () => {
const [disabledId, ...activeIds] = API_FEATURE_IDS;
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
FEATURE_OVERRIDES: { [disabledId!]: "DISABLED" },
},
},
release,
host: {},
});
const application = createApplication(
adapters.outputPorts,
{},
adapters.featureLoaders,
);
expect(adapters.outputPorts.productFeatures.isActive(disabledId!)).toBe(false);
// 15-01. A switched-off feature gets no loader, so loading installs nothing.
await application.features.load(disabledId!);
expect(application.features.has(disabledId!)).toBe(false);
expect(() =>
application.features.get(disabledId as ApplicationFeatureId),
).toThrow(/not installed/u);
for (const featureId of activeIds) {
await application.features.load(featureId);
expect(application.features.has(featureId)).toBe(true);
}
adapters.infrastructure.dispose();
});
it("still resolves every installed feature API when nothing is switched off", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
const application = createApplication(
adapters.outputPorts,
{},
adapters.featureLoaders,
);
for (const featureId of API_FEATURE_IDS) {
// 15-01. Not loaded until the router asks for the feature's routes.
expect(() =>
application.features.get(featureId as ApplicationFeatureId),
).toThrow(/not loaded yet/u);
await application.features.load(featureId);
expect(application.features.has(featureId)).toBe(true);
expect(
application.features.get(featureId as ApplicationFeatureId),
).toBeDefined();
}
adapters.infrastructure.dispose();
});
it("states contract identity as a digest for a V2 release manifest", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
const current = await adapters.outputPorts.releaseInfo.getCurrent();
expect(current.contractSetDigest).toBe(release.contractSet?.setDigest);
expect(current.apiContractVersion).toBeUndefined();
expect(current).not.toHaveProperty("contractSet");
});
it("states contract identity as the legacy scalar for a V1 release manifest", async () => {
const adapters = await createRuntimeAdapters({
runtime,
release: {
...release,
schemaVersion: 1,
contractSet: null,
legacyApiContractVersion: "1.4",
},
host: {},
});
const current = await adapters.outputPorts.releaseInfo.getCurrent();
expect(current.apiContractVersion).toBe("1.4");
expect(current.contractSetDigest).toBeUndefined();
expect(current).not.toHaveProperty("legacyApiContractVersion");
});
it("refetches the active release manifest with no-store semantics", async () => {
const activeRelease = {
...release,
buildId: "build-b",
releaseId: "release-b",
routeChunks: { "route-home": "assets/home-b.js" },
};
const fetcher = vi.fn(async () =>
new Response(JSON.stringify(activeRelease), {
headers: { "content-type": "application/json" },
}),
);
const adapters = await createRuntimeAdapters({
runtime,
release,
fetcher,
host: {},
});
await expect(adapters.outputPorts.releaseInfo.refresh()).resolves.toMatchObject({
buildId: "build-b",
releaseId: "release-b",
});
expect(fetcher).toHaveBeenCalledWith(
"/release-manifest.json",
expect.objectContaining({
method: "GET",
cache: "no-store",
credentials: "same-origin",
redirect: "error",
referrerPolicy: "no-referrer",
headers: { Accept: "application/json" },
}),
);
});
});
/**
* 1105/10-01. Runtime Config's two HTTP dials, on the test contracts. The
* reference feature's composition test drives MAX_RETRY_ATTEMPTS through
* `createRuntimeAdapters`, which needs an installed feature's HTTP. These need
* none, so they stay when a product removes the sample
* (`scripts/test-sample-removal.ts` keeps this file).
*/
describe("runtime contract HTTP executor", () => {
const answerReady = () => ({ kind: "READY" as const, headers: {} });
// The test list read is SAFE and declares a retry budget of 2.
it.each([
[0, 1],
[1, 2],
[2, 3],
])(
"honours MAX_RETRY_ATTEMPTS %i: a retryable read goes out %i time(s)",
async (maxRetryAttempts, sends) => {
const fetcher = vi.fn(async (_input: RequestInfo | URL) =>
Response.json(
{ type: "about:blank", title: "temporary", status: 503 },
{ status: 503 },
),
);
// No backoff wait: the jitter is the random draw times a ceiling.
const random = vi.spyOn(Math, "random").mockReturnValue(0);
try {
const executor = createRuntimeContractHttpExecutor(
{ ...runtime.config, MAX_RETRY_ATTEMPTS: maxRetryAttempts },
{ fetcher, attachCredentials: answerReady },
);
const outcome = await executor.execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 20 },
{ routeId: "TEST_ROUTE", scope: scopeSnapshot() },
);
expect(outcome.kind).not.toBe("SUCCESS");
expect(fetcher).toHaveBeenCalledTimes(sends);
} finally {
random.mockRestore();
}
},
);
// The test list read declares a 10s deadline; REQUEST_TIMEOUT_MS may only
// shorten it.
it("holds a contract's deadline to REQUEST_TIMEOUT_MS", async () => {
vi.useFakeTimers();
try {
const fetcher = vi.fn(
(_input: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
"abort",
() => reject(new DOMException("Aborted", "AbortError")),
{ once: true },
);
}),
);
const executor = createRuntimeContractHttpExecutor(
{ ...runtime.config, MAX_RETRY_ATTEMPTS: 0, REQUEST_TIMEOUT_MS: 5 },
{ fetcher, attachCredentials: answerReady },
);
let settled = false;
const result = executor
.execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 20 },
{ routeId: "TEST_ROUTE", scope: scopeSnapshot() },
)
.then((outcome) => {
settled = true;
return outcome;
});
await vi.advanceTimersByTimeAsync(5);
await Promise.resolve();
await Promise.resolve();
expect(settled).toBe(true);
await expect(result).resolves.toMatchObject({
kind: "TRANSPORT_FAILURE",
failure: { kind: "TIMEOUT" },
});
} finally {
vi.useRealTimers();
}
});
});