Files
clean-architecture-frontend…/tests/features/reference-feature/reference-production-vertical.test.tsx
T
DongHyeonka 64e98ee2fa fix(http): V2 검증 거절을 적용 안 됨으로 보고 고친 값을 다시 저장하게 한다 (백엔드 1101/02-01)
문제
V2 클라이언트(client.ts)는 필드 검증 거절(422, 짝 백엔드의 400
VALIDATION_FAILED + 필드 목록)에 effect를 붙이지 않는다. mutation
코디네이터(application-query.ts mutationFailureWithEffect)는 effect가 없으면
MAYBE_APPLIED로 보고 admission을 UNKNOWN으로 붙든다. 폼은 VALIDATION_
REJECTED를 필드 오류로 보여 주지만, 참조 폼 페이지는 코디네이터가 결과 불명을
들고 있으면 저장 버튼을 끈다(reference-resource-form-page.tsx
mutationBlocked). 사용자가 필드를 고쳐도 다시 저장할 수 없다. use-app-form
자체는 VALIDATION_REJECTED에서 unknownSubmissionRef를 비우므로 막지 않는다.
막는 것은 코디네이터 상태다.
V3 참조 기능은 재현되지 않는다. 생성 분류기가 400·422를 NOT_APPLIED로
본다(reference-feature-contract-contribution.ts classifyProblem).

고른 방법
V2에서 필드 검증 거절(fieldValidation: 422, 또는 400 VALIDATION_FAILED +
배열 details)에 effect NOT_APPLIED를 붙인다. 멱등성 거절(IDEMPOTENCY_
REFUSALS)과 같은 자리에서 붙이고, 진단 reason은 멱등성 거절에만 남긴다.

근거(백엔드 계약)
- docs/web/http-contract.md 4절과 web adapter README 예외 표가 VALIDATION_
  FAILED의 출처를 적는다: 요청 본문 바인딩(MethodArgumentNotValid
  Exception), 컨트롤러 파라미터 제약(HandlerMethodValidationException),
  Bean Validation(ConstraintViolationException), 페이지 파라미터, 읽을 수
  없는 본문. 모두 요청을 묶는 단계에서 컨트롤러·use case보다 먼저 거절한다.
- 4절에 "상태를 바꾸지 않는다"는 문장은 없다. 이 판정은 위 출처에서
  끌어낸 것이다.

버린 대안
- 코디네이터가 effect 없는 VALIDATION_REJECTED를 모두 NOT_APPLIED로 보기:
  거절을 판정하는 곳은 응답을 읽는 클라이언트다. 코디네이터의 "모르면
  MAYBE_APPLIED" 규칙은 그대로 둔다.
- 폼 페이지가 VALIDATION_REJECTED 뒤 결과 불명을 무시하기: 키가 붙은 채
  남아 같은 입력을 다시 저장하면 같은 키가 나간다.

위험·한계
- application 층에서 쓰기 뒤에 VALIDATION_FAILED를 던지는 백엔드 코드가
  있다면 이 판정은 틀린다. 짝 백엔드 IdempotencyExecutor는 실행 중 예외를
  EFFECT_UNKNOWN_ABANDONED로 기록한다. 이 경우 같은 키 재전송은 500
  IDEMPOTENCY_RECOVERY_REQUIRED를 받는다. NOT_APPLIED면 다음 저장이 새 키를
  쓰므로 그 경로를 타지 않는다.
- 필드 목록 없는 400 VALIDATION_FAILED({cause}, 본문 파싱 실패)와 그 밖의
  400·409는 effect 없이 둔다(결과 불명으로 붙듦). 이번 범위 밖이다.
- 422 IDEMPOTENT_REQUEST_MISMATCH는 원래 NOT_APPLIED였고 그대로다.

검증
- RED: tests/component/form-foundation.test.tsx "saves the corrected value
  after a $status field error" 2행(422, 400 VALIDATION_FAILED) 실패. 필드
  오류 뒤 저장 버튼이 disabled다.
- V3: tests/features/reference-feature/reference-production-vertical.test.tsx
  "saves the corrected value after a server 422 field error"는 수정 전에도
  통과한다(재현 안 됨, 동작 고정).
- GREEN: 위 행 통과. tests/integration/http-diagnostics.test.ts의 "unrelated
  422" 행은 effect가 없다고 기대하던 것을 NOT_APPLIED로 바꾸고, 409 행을
  더해 다른 거절은 effect가 없음을 고정했다. tests/integration/http-client.
  test.ts에 400 VALIDATION_FAILED effect 단언을 더했다.
  tests/unit·contract·runtime-schema·integration·component·features·platform
  3398 tests 통과, 1개 실패(tests/unit/second-api-feature-registries.test.ts,
  기준 3b7d73a에서도 같은 메시지로 실패). tsc app·test, 바꾼 파일 eslint
  통과.

Refs: clean-architecture-backend-template docs/web/http-contract.md 4절, src/adapter/inbound/web/README.md 예외 표
2026-11-03 02:16:49 +09:00

443 lines
16 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import {
afterAll,
afterEach,
beforeAll,
describe,
expect,
it,
vi,
} from "vitest";
import { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.ts";
import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.tsx";
import { createBootstrapHandlers } from "../../mocks/handlers/bootstrap.ts";
import { createReferenceResourceHandlers } from "./reference-resource-handlers.ts";
import { createStrictMockServer } from "../../mocks/server.ts";
const runtimeConfig = {
APP_ENV: "local",
API_BASE_URL: "https://api.test",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 0,
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
CONFIG_SCHEMA_VERSION: "1",
API_CONTRACT_VERSION: "1",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "local-build",
RELEASE_ID: "local-release",
};
const releaseManifest = {
schemaVersion: 1,
appVersion: "0.2.0",
buildId: "local-build",
commitSha: "local",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
releaseId: "local-release",
builtAt: "2026-07-26T00:00:00.000Z",
routeChunks: {
"route-home": "assets/home.js",
"route-examples-ui": "assets/ui.js",
"route-examples-states": "assets/states.js",
"route-examples-auth": "assets/auth.js",
"route-reference-resources": "assets/reference.js",
"route-reference-resource-detail": "assets/reference-detail.js",
"route-reference-resource-form": "assets/reference-form.js",
"route-reference-resource-status": "assets/reference-status.js",
"route-not-found": "assets/not-found.js",
},
};
const listRequests = vi.fn();
const createRequests = vi.fn();
const resources = [{ id: "reference-1", name: "Existing" }];
const mockApi = createStrictMockServer(
...createBootstrapHandlers(runtimeConfig, releaseManifest),
...createReferenceResourceHandlers({
resources,
onList: listRequests,
onCreate: createRequests,
}),
);
beforeAll(mockApi.listen);
afterEach(() => {
mockApi.reset();
listRequests.mockClear();
createRequests.mockClear();
resources.splice(1);
});
afterAll(mockApi.close);
const absoluteFetch: typeof fetch = (input, init) => {
if (input instanceof Request) return fetch(input, init);
const url = new URL(
input instanceof URL ? input.href : input,
"http://app.test",
);
return fetch(url, init);
};
describe("reference feature production vertical path", () => {
it("traverses bootstrap, router, application, HTTP schema/mapper and query cache", async () => {
const user = userEvent.setup();
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState(
{},
"",
"/examples/reference-resources?tags=open&tags=new&limit=5",
);
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
expect(await screen.findByText("Existing")).toBeVisible();
expect(listRequests).toHaveBeenCalledWith(
"?limit=5&tags=open&tags=new",
);
await user.click(screen.getByRole("button", { name: "새 항목 만들기" }));
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
" Created ",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByText("저장했습니다.")).toBeVisible();
await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" }));
expect(await screen.findByText("Created")).toBeVisible();
expect(createRequests).toHaveBeenCalledWith({ name: "Created" });
expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2);
});
it("resends a create whose 504 lost the response with the same Idempotency-Key", async () => {
const user = userEvent.setup();
const idempotencyKeys: (string | null)[] = [];
mockApi.server.use(
http.post("https://api.test/api/reference-resources", async ({ request }) => {
idempotencyKeys.push(request.headers.get("idempotency-key"));
// The first request reaches the server; only its response is lost.
if (idempotencyKeys.length === 1) {
return new HttpResponse(null, { status: 504 });
}
const body = (await request.json()) as { name: string };
return HttpResponse.json(
{
id: "reference-created",
name: body.name,
createdAt: "2026-07-26T00:00:00.000Z",
},
{ status: 201 },
);
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Lost response",
);
await user.click(screen.getByRole("button", { name: "저장" }));
await user.click(
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
expect(await screen.findByText("저장했습니다.")).toBeVisible();
expect(idempotencyKeys).toHaveLength(2);
expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u);
expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]);
});
// 0929/03-04. A write past its deadline has no server answer to echo an
// id, so the screen shows the id the request itself carried.
it("shows the sent x-correlation-id for a create past its deadline", async () => {
const user = userEvent.setup();
const sentIds: (string | null)[] = [];
mockApi.server.use(
http.get("http://app.test/config.json", () =>
HttpResponse.json({ ...runtimeConfig, REQUEST_TIMEOUT_MS: 200 }),
),
http.post("https://api.test/api/reference-resources", async ({ request }) => {
sentIds.push(request.headers.get("x-correlation-id"));
// The server is still working when the client deadline ends.
await new Promise<void>((resolve) => {
request.signal.addEventListener("abort", () => resolve(), { once: true });
});
return new HttpResponse(null, { status: 504 });
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Past the deadline",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(
await screen.findByText("변경 결과를 확인할 수 없습니다."),
).toBeVisible();
expect(sentIds).toHaveLength(1);
expect(sentIds[0]).toMatch(/^[A-Za-z0-9._:-]{1,128}$/u);
expect(screen.getByText(`지원 참조: ${sentIds[0]}`)).toBeVisible();
});
it("keeps the key when the resend meets the first attempt still in flight (0929/03-01)", async () => {
const user = userEvent.setup();
const idempotencyKeys: (string | null)[] = [];
const sentAt: number[] = [];
// A server that deduplicates by key: one receipt per created resource.
const receipts = new Map<string, Record<string, string>>();
let firstAttemptRunning = true;
mockApi.server.use(
http.post("https://api.test/api/reference-resources", async ({ request }) => {
const key = request.headers.get("idempotency-key") ?? "";
idempotencyKeys.push(key);
sentAt.push(performance.now());
const receipt = receipts.get(key);
if (receipt) {
if (firstAttemptRunning) {
// The paired backend answers a same-key request while the first
// attempt still runs with 409 IDEMPOTENT_IN_FLIGHT and
// Retry-After (2 there; 1 here to keep the test short).
firstAttemptRunning = false;
return HttpResponse.json(
{
type: "https://api.test/problems/idempotent_in_flight",
title: "IDEMPOTENT_IN_FLIGHT",
status: 409,
code: "IDEMPOTENT_IN_FLIGHT",
},
{
status: 409,
headers: {
"content-type": "application/problem+json",
"retry-after": "1",
},
},
);
}
return HttpResponse.json(receipt, { status: 201 });
}
const body = (await request.json()) as { name: string };
const resource = {
id: `reference-created-${receipts.size + 1}`,
name: body.name,
createdAt: "2026-07-26T00:00:00.000Z",
};
receipts.set(key, resource);
// The first attempt reaches the server; only its response is lost.
if (receipts.size === 1) return new HttpResponse(null, { status: 504 });
return HttpResponse.json(resource, { status: 201 });
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Slow write",
);
await user.click(screen.getByRole("button", { name: "저장" }));
await user.click(
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
await waitFor(() => expect(idempotencyKeys).toHaveLength(2));
// After the 409 the user takes the next step the screen offers.
const next = await waitFor(() => {
const resend = screen.queryByRole("button", {
name: "같은 요청으로 다시 보내기",
});
if (resend) return resend;
const save = screen.getByRole("button", { name: "저장" });
expect(save).toBeEnabled();
return save;
});
const shownAfterInFlight = {
unknown: screen.queryByText("변경 결과를 확인할 수 없습니다.") !== null,
conflict: screen.queryAllByText(/충돌/).length > 0,
};
await user.click(next);
await waitFor(() => expect(idempotencyKeys).toHaveLength(3), {
timeout: 3_000,
});
const [first] = idempotencyKeys;
expect(idempotencyKeys).toEqual([first, first, first]);
expect(receipts.size).toBe(1);
expect(shownAfterInFlight).toEqual({ unknown: true, conflict: false });
// 백엔드 1101/02-01. The click came right after the 409; the resend
// waited out its Retry-After instead of meeting the same 409 again.
expect((sentAt[2] ?? 0) - (sentAt[1] ?? 0)).toBeGreaterThanOrEqual(990);
expect(await screen.findByText("저장했습니다.")).toBeVisible();
});
it.each([
// The demo session treats a server 401 as signed out; the route guard
// then asks for sign-in and the form is gone.
[401, "세션이 필요합니다."],
[403, "이 작업을 수행할 권한이 없습니다."],
[429, "요청이 많습니다. 잠시 후 다시 시도해 주세요."],
])(
"treats a create rejected with %i as not applied, not unknown",
async (status, guidance) => {
const user = userEvent.setup();
mockApi.server.use(
http.post(
"https://api.test/api/reference-resources",
() => new HttpResponse(null, { status }),
),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Rejected",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByText(guidance)).toBeVisible();
expect(
screen.queryByText("변경 결과를 확인할 수 없습니다."),
).not.toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }),
).not.toBeInTheDocument();
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
},
);
it("shows a server 422 field error on its field (03-04)", async () => {
const user = userEvent.setup();
mockApi.server.use(
http.post("https://api.test/api/reference-resources", () =>
HttpResponse.json(
{
type: "https://api.test/problems/validation_rejected",
title: "VALIDATION_REJECTED",
status: 422,
code: "VALIDATION_REJECTED",
issues: [
{ path: "name", code: "too_big", message: "backend copy" },
{ path: "serverOnly", code: "REQUIRED" },
],
},
{ status: 422 },
),
),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
await user.type(name, "Too long for the server");
await user.click(screen.getByRole("button", { name: "저장" }));
const summary = await screen.findByRole("alert");
expect(summary).toHaveTextContent("새 항목 이름: 입력값이 너무 깁니다.");
expect(summary).toHaveTextContent("서버가 확인하지 못한 입력 항목이 있습니다.");
expect(name).toHaveAttribute("aria-invalid", "true");
expect(document.body).not.toHaveTextContent("backend copy");
});
// A validation refusal is not an unknown effect: the corrected value can
// be saved (the create classifier answers 422 NOT_APPLIED).
it("saves the corrected value after a server 422 field error", async () => {
const user = userEvent.setup();
let sent = 0;
mockApi.server.use(
http.post("https://api.test/api/reference-resources", async ({ request }) => {
sent += 1;
if (sent === 1) {
return HttpResponse.json(
{
type: "https://api.test/problems/validation_rejected",
title: "VALIDATION_REJECTED",
status: 422,
code: "VALIDATION_REJECTED",
issues: [{ path: "name", code: "too_big" }],
},
{ status: 422 },
);
}
const body = (await request.json()) as { name: string };
return HttpResponse.json(
{ id: "reference-created-1", name: body.name },
{ status: 201 },
);
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
await user.type(name, "Too long for the server");
await user.click(screen.getByRole("button", { name: "저장" }));
await waitFor(() => expect(name).toHaveAttribute("aria-invalid", "true"));
await user.clear(name);
await user.type(name, "Short");
expect(screen.getByRole("button", { name: "저장" })).toBeEnabled();
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByText("저장했습니다.")).toBeVisible();
expect(sent).toBe(2);
});
});