import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { http, HttpResponse } from "msw"; import { setupServer } from "msw/node"; import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; import { AssessmentAttempt } from "../../../shared/api/schemas"; import { submitPendingAnswerCommand, type PendingAnswerCommand } from "./answer-command"; const attemptId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01"; const server = setupServer(); beforeAll(() => server.listen()); afterEach(() => { vi.unstubAllGlobals(); server.resetHandlers(); }); afterAll(() => server.close()); const validAttempt: AssessmentAttempt = { id: attemptId, version: 2, kind: "root", specialization: "backend", target_grade: "junior", task_language: "python", root_attempt_id: null, chain_deadline: null, mode: "demo_basic", state: "in_progress", versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" }, started_at: "2026-10-08T10:00:00Z", expires_at: "2026-10-08T11:00:00Z", sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 }, finished_at: null, progress: { answered_items: 1, max_items: 2 }, current_item: { id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02", sequence: 2, prompt: "Сколько?", content: { format: "number", unit: null }, }, practices: [], }; describe("assessment answer response validation", () => { it.each([{}, { id: attemptId, version: 2 }])( "keeps the exact command retryable when a successful response is incomplete", async (body) => { const interceptedFetch = globalThis.fetch; vi.stubGlobal("fetch", (input: string, init?: RequestInit) => interceptedFetch(new URL(input, "http://localhost"), init), ); const requests: Array<{ body: string | null; key: string | null; csrf: string | null }> = []; server.use( http.post( `http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`, async ({ request }) => { requests.push({ body: await request.text(), key: request.headers.get("Idempotency-Key"), csrf: request.headers.get("X-CSRF-Token"), }); return HttpResponse.json(body, { status: 200 }); }, ), ); const command: PendingAnswerCommand = { key: "answer-command-key", body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}', itemId: "item-1", }; const outcome = await submitPendingAnswerCommand(command, attemptId, "csrf-token"); expect(outcome.kind).toBe("retry"); if (outcome.kind !== "retry") return; expect(outcome.command).toBe(command); expect(outcome.command).toEqual({ key: "answer-command-key", body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}', itemId: "item-1", }); expect(outcome.error).toMatchObject({ status: 200, code: invalidResponseCode, } satisfies Partial); expect(requests).toEqual([ { body: command.body, key: command.key, csrf: "csrf-token", }, ]); }, ); it("accepts a complete server attempt response", async () => { const interceptedFetch = globalThis.fetch; vi.stubGlobal("fetch", (input: string, init?: RequestInit) => interceptedFetch(new URL(input, "http://localhost"), init), ); server.use( http.post(`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`, () => HttpResponse.json(validAttempt, { status: 200 }), ), ); const outcome = await submitPendingAnswerCommand( { key: "answer-command-key", body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}', itemId: "item-1", }, attemptId, "csrf-token", ); expect(outcome).toEqual({ kind: "accepted", attempt: validAttempt }); }); it("replays the original key and body after a malformed success response", async () => { const interceptedFetch = globalThis.fetch; vi.stubGlobal("fetch", (input: string, init?: RequestInit) => interceptedFetch(new URL(input, "http://localhost"), init), ); const requests: Array<{ body: string; key: string | null }> = []; let responseCount = 0; server.use( http.post( `http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`, async ({ request }) => { requests.push({ body: await request.text(), key: request.headers.get("Idempotency-Key"), }); responseCount += 1; return HttpResponse.json(responseCount === 1 ? {} : validAttempt, { status: 200 }); }, ), ); const original: PendingAnswerCommand = { key: "same-answer-key", body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}', itemId: "item-1", }; const first = await submitPendingAnswerCommand(original, attemptId, "csrf-token"); expect(first.kind).toBe("retry"); if (first.kind !== "retry") return; const second = await submitPendingAnswerCommand(first.command, attemptId, "csrf-token"); expect(second).toEqual({ kind: "accepted", attempt: validAttempt }); expect(requests).toEqual([ { body: original.body, key: original.key }, { body: original.body, key: original.key }, ]); }); }); describe("assessment answer command page identifier", () => { it("sends the open page identifier so a second window is refused, and omits it when there is none", async () => { const interceptedFetch = globalThis.fetch; vi.stubGlobal("fetch", (input: string, init?: RequestInit) => interceptedFetch(new URL(input, "http://localhost"), init), ); const clients: Array = []; server.use( http.post( `http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`, ({ request }) => { clients.push(request.headers.get("X-Attempt-Client")); return HttpResponse.json(validAttempt, { status: 200 }); }, ), ); const command: PendingAnswerCommand = { key: "answer-command-key", body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}', itemId: "item-1", }; const withClient = await submitPendingAnswerCommand( command, attemptId, "csrf-token", "7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG", ); const withoutClient = await submitPendingAnswerCommand(command, attemptId, "csrf-token"); expect(withClient.kind).toBe("accepted"); expect(withoutClient.kind).toBe("accepted"); expect(clients).toEqual(["7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG", null]); }); });