import type { Page, Route } from "@playwright/test"; // A fake API for one real attempt, shared by the specs that check what the page // does while the candidate takes the test (fullscreen, the cover, copy and // paste rules). The browser talks to a mocked API, so the specs need no data and // no backend fixtures; they check the page, not the server. export const attemptId = "01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d"; export const itemId = "01928f7b-3333-7a2b-8c3d-4e5f6a7b8c01"; export const taskPrompt = "SECRET-PROMPT: which HTTP status code means that a resource was created?"; export const exampleInput = "SECRET-EXAMPLE-INPUT"; export type MockItemContent = | { format: "number"; unit: null } | { format: "practice"; languages: ["python"]; public_examples: { input: string; expected_output: string }[]; max_source_length: number; }; export const numberContent: MockItemContent = { format: "number", unit: null }; export const practiceContent: MockItemContent = { format: "practice", languages: ["python"], public_examples: [{ input: exampleInput, expected_output: "SECRET-EXAMPLE-OUTPUT" }], max_source_length: 5000, }; export type SignalEvent = { kind: string; size_bytes?: number; duration_ms?: number; [field: string]: unknown; }; /** * The work session of the attempt as the server holds it. Pages that mock the * same attempt share one object, so a second tab meets the hold of the first. */ export type LeaseState = { holder: string | null }; export type MockedAttempt = { /** Events of every signal batch the page sent, in order. */ signals: SignalEvent[]; /** The page identifier of every hold or renewal the page sent. */ holds: string[]; /** The page identifier of every release the page sent. */ releases: string[]; /** The page identifier of every session start the page sent (null: no header). */ starts: Array; /** Bodies of the answers the page sent. */ answers: unknown[]; /** Calls to the notice acknowledgement, to see what was stored. */ acknowledgements: unknown[]; }; export const watermarkCode = "7K3QD-9XM2T"; /** The notice text version the page knows; the mock server requires the same one. */ export const noticeVersion = 4; type Options = { content: MockItemContent; /** The candidate already acknowledged the notice, so the start asks nothing. */ noticeAcknowledged?: boolean; /** The task text the server sends, with its invisible mark when it has one. */ prompt?: string; /** The visible code of the attempt, or null for an attempt without one. */ watermark?: string | null; /** The work session shared by the pages of one attempt; one page has its own by default. */ lease?: LeaseState; /** How often the server asks the page to renew its hold. */ renewAfterSeconds?: number; }; function isoSeconds(ms: number): string { return `${new Date(ms).toISOString().slice(0, 19)}Z`; } function attemptBody(version: number, options: Options) { const { content, prompt = taskPrompt, watermark = watermarkCode } = options; return { id: attemptId, version, kind: "root", specialization: "backend", target_grade: "middle", task_language: "python", root_attempt_id: null, chain_deadline: null, mode: "adaptive", state: "in_progress", versions: { policy_version: 2, bank_version: "backend.2026-11.3", algorithm_version: "irt-1pl-eap.1", }, started_at: isoSeconds(Date.now() - 60_000), expires_at: isoSeconds(Date.now() + 3_600_000), sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 }, finished_at: null, progress: { answered_items: 0, max_items: 5 }, current_item: { id: itemId, sequence: 1, prompt, content }, practices: [], ...(watermark ? { watermark: { code: watermark } } : {}), }; } /** Answers the API calls of the attempt page; every other API call gets a 404. */ export async function mockAttemptApi(page: Page, options: Options): Promise { const recorded: MockedAttempt = { signals: [], holds: [], releases: [], starts: [], answers: [], acknowledgements: [], }; const lease = options.lease ?? { holder: null }; let acknowledged = options.noticeAcknowledged ?? true; await page.route("**/api/v1/**", async (route: Route) => { const request = route.request(); const path = new URL(request.url()).pathname; const method = request.method(); const reply = (body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", headers: { date: new Date().toUTCString() }, body: JSON.stringify(body), }); const base = `/api/v1/me/assessment-attempts/${attemptId}`; if (path === "/api/v1/identity/sessions/current") { return reply({ account: { id: "01928f7b-0000-7a2b-8c3d-4e5f6a7b8c01", email: "candidate@example.test", email_verified: true, scenario: "candidate", onboarding_step: "completed", created_at: "2026-10-01T10:00:00Z", }, csrf_token: "c".repeat(40), }); } if (path === "/api/v1/me/assessment-signal-notice") { if (method === "PUT") { acknowledged = true; recorded.acknowledgements.push(JSON.parse(request.postData() ?? "{}")); } return reply({ notice_version: noticeVersion, acknowledged, acknowledged_at: acknowledged ? "2026-10-10T10:00:00Z" : null, }); } const client = request.headers()["x-attempt-client"] ?? null; const heldByAnother = lease.holder !== null && lease.holder !== client; const busy = () => reply( { type: "urn:lincodex:problem:state_conflict", title: "Conflict", status: 409, code: "state_conflict", }, 409, ); if (path === `${base}/work-session`) { if (method === "DELETE") { recorded.releases.push(client ?? ""); if (lease.holder === client) lease.holder = null; return route.fulfill({ status: 204, headers: { "cache-control": "no-store" } }); } recorded.holds.push(client ?? ""); if (heldByAnother) return busy(); lease.holder = client; return reply({ held_until: isoSeconds(Date.now() + 120_000), renew_after_seconds: options.renewAfterSeconds ?? 15, }); } if (path === base && method === "GET") return reply(attemptBody(1, options)); if (path === `${base}/sessions`) { recorded.starts.push(client); if (heldByAnother) return busy(); return reply(attemptBody(2, options)); } if (path === `${base}/answers`) { if (heldByAnother) return busy(); recorded.answers.push(JSON.parse(request.postData() ?? "{}")); return reply(attemptBody(3, options)); } if (path === `${base}/signals`) { const body = JSON.parse(request.postData() ?? "{}") as { events: SignalEvent[] }; recorded.signals.push(...body.events); return reply({ status: "accepted", accepted_events: body.events.length, received_at: isoSeconds(Date.now()), }); } return reply({ type: "about:blank", title: "Not found", status: 404 }, 404); }); return recorded; } /** Hides or shows the tab the way a tab switch does, through visibilitychange. */ export async function setTabHidden(page: Page, hidden: boolean): Promise { await page.evaluate((nextHidden) => { Object.defineProperty(document, "visibilityState", { configurable: true, get: () => (nextHidden ? "hidden" : "visible"), }); document.hasFocus = () => true; document.dispatchEvent(new Event("visibilitychange")); }, hidden); } export async function isFullscreen(page: Page): Promise { return page.evaluate(() => document.fullscreenElement !== null); } /** Opens the attempt page and starts the work the way a candidate does, with a click. */ export async function startAttempt(page: Page): Promise { await page.goto(`/candidate/assessment/${attemptId}`); await page.getByRole("button", { name: "Начать или продолжить" }).click(); }