import { expect, test, type Locator, type Page, type Request, type Response, type Route, } from "@playwright/test"; type InboxMessage = { text?: string; html?: string; }; type InboxResponse = { messages: InboxMessage[]; }; type AttemptSnapshot = { id: string; kind: "root" | "demo_express"; current_item: { id: string; prompt: string } | null; progress: { answered_items: number; max_items: number }; }; const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1"; const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; const password = "correct horse battery staple 2026"; // Pause after each saved answer of a full attempt. Back to back, the loop sends // about fifty requests a second (each answer and the attempt read that follows // it) from the one client address of the stand, which spends the per-address // API budget of the app Nginx in about a second. A candidate reads each item // before answering, so this pace is what a person produces. const answerPauseMs = 250; test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" }); function baseUrl(): string { const value = process.env.E2E_BASE_URL; if (!value) throw new Error("The local end-to-end base URL is not configured."); return value; } async function readInbox(email: string): Promise { const inboxUrl = process.env.E2E_MAILBOX_URL; const token = process.env.E2E_MAILBOX_TOKEN; if (!inboxUrl || !token) throw new Error("The local registration mailbox fixture is not configured."); const url = new URL(inboxUrl); url.searchParams.set("to", email); const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); if (!response.ok) throw new Error("Could not read the local registration mailbox."); return ((await response.json()) as InboxResponse).messages; } async function waitForVerificationMessage(email: string): Promise { const deadline = Date.now() + 20_000; while (Date.now() < deadline) { const message = (await readInbox(email)).at(-1); if (message) return message; await new Promise((resolve) => setTimeout(resolve, 250)); } throw new Error("The local registration mailbox did not receive the verification message."); } function verificationToken(message: InboxMessage): string { const content = `${message.text ?? ""}\n${message.html ?? ""}`; const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1]; if (!token) throw new Error("The local registration message had no verification link."); return token; } async function registerVerifiedCandidate(page: Page): Promise { const email = `assessment-${crypto.randomUUID()}@example.test`; await page.goto("/register"); await expect( page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }), ).toBeVisible(); await expect(page.getByText(/C4/)).toHaveCount(0); await page.getByLabel("Электронная почта").fill(email); await page.getByLabel("Пароль", { exact: true }).fill(password); await page.getByRole("radio", { name: /Кандидат/ }).check(); await page.getByRole("checkbox", { name: /принимаю его/ }).check(); await page.getByRole("button", { name: "Создать аккаунт" }).click(); await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); const message = await waitForVerificationMessage(email); const verificationUrl = new URL("/verify-email", baseUrl()); verificationUrl.hash = `token=${verificationToken(message)}`; await page.goto(verificationUrl.toString()); await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible(); await expect.poll(() => page.evaluate(() => window.location.hash)).toBe(""); await page.getByLabel("Пароль, выбранный при регистрации").fill(password); const confirmResponse = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/identity/email-verifications", ); await page.getByRole("button", { name: "Подтвердить почту" }).click(); expect((await confirmResponse).status()).toBe(200); await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); await page.goto("/candidate/questionnaire"); await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); await page.getByLabel("Электронная почта").fill(email); await page.getByLabel("Пароль", { exact: true }).fill(password); const loginResponse = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/identity/sessions", ); await page.getByRole("button", { name: "Войти" }).click(); expect((await loginResponse).status()).toBe(201); return email; } async function grantC3(page: Page): Promise { await page.goto("/candidate/privacy"); await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click(); await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check(); const response = page.waitForResponse( (item) => item.request().method() === "PUT" && new URL(item.url()).pathname === "/api/v1/me/consents/c3", ); await page.getByRole("button", { name: "Дать согласие C3" }).click(); expect((await response).status()).toBe(200); } async function saveAssessmentQuestionnaire(page: Page): Promise { await page.goto("/candidate/questionnaire"); await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); // The questionnaire is a form in steps; "Далее" moves the focus to the next heading. await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused(); await page.getByLabel("Моя оценка уровня").selectOption("junior"); await page.getByRole("checkbox", { name: "Go", exact: true }).check(); await page.getByRole("checkbox", { name: "Python", exact: true }).check(); await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused(); await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check(); await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused(); const response = page.waitForResponse( (item) => item.request().method() === "PUT" && new URL(item.url()).pathname === "/api/v1/me/questionnaire", ); await page.getByRole("button", { name: "Сохранить анкету" }).click(); expect((await response).status()).toBe(200); } async function focusWithKeyboard(page: Page, target: Locator): Promise { // The control appears only after the previous answer is saved and the attempt // is read again. On a loaded stand that takes longer than the default 5 s // expectation, so wait for it explicitly before walking the tab order. await expect(target).toBeVisible({ timeout: 20_000 }); await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); for (let attempt = 0; attempt < 80; attempt += 1) { await page.keyboard.press("Tab"); if (await target.evaluate((element) => element === document.activeElement)) { const visible = await target.evaluate((element) => { if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false; const style = getComputedStyle(element); return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0; }); expect(visible).toBe(true); return; } } throw new Error("Keyboard navigation did not reach the assessment action."); } async function expectNoHorizontalOverflow(page: Page, width: number): Promise { await page.setViewportSize({ width, height: 900 }); const overflow = await page.evaluate( () => document.documentElement.scrollWidth > window.innerWidth, ); expect(overflow, `no horizontal overflow at ${width}px`).toBe(false); } async function navigateInApp(page: Page, path: string): Promise { await page.evaluate((target) => { window.history.pushState(window.history.state, "", target); window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state })); }, path); } function attemptPath( response: { url(): string; request(): { method(): string } }, method: string, ): boolean { return ( response.request().method() === method && /^\/api\/v1\/me\/assessment-attempts\/[^/]+$/.test(new URL(response.url()).pathname) ); } async function answerRequiredNumericItems( page: Page, attemptId: string, itemCount: number, ): Promise { let submitted = 0; for (let sequence = 1; sequence <= itemCount; sequence += 1) { await expect(page.getByRole("heading", { name: `Задание ${sequence}` })).toBeVisible(); const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ }); await focusWithKeyboard(page, answerField); await page.keyboard.type("1"); const submitButton = page.getByRole("button", { name: "Отправить ответ" }); await focusWithKeyboard(page, submitButton); // A response wait expires after the action timeout counted from its // registration, so it is registered only right before the key press. const answerResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attemptId}/answers`, ); await page.keyboard.press("Enter"); expect((await answerResponsePromise).status()).toBe(200); submitted += 1; await page.waitForTimeout(answerPauseMs); } return submitted; } test("candidate can review, resume, and finish separate assessment modes", async ({ page }) => { test.skip( !questionnaireFixtureEnabled || !mailFixtureEnabled, "Requires the isolated reviewed assessment-bank and mail fixtures.", ); test.setTimeout(120_000); await registerVerifiedCandidate(page); await grantC3(page); await saveAssessmentQuestionnaire(page); await page.goto("/candidate/assessment"); await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); await expect(page.getByText(/Метод:/)).toBeVisible(); await expect(page.getByText("Лимит времени", { exact: true })).toBeVisible(); await expect(page.getByText(/камера и запись экрана не используются/)).toBeVisible(); await page.getByLabel("Язык задания").selectOption("python"); await expect(page.getByLabel("Язык задания")).toHaveValue("python"); await expectNoHorizontalOverflow(page, 360); await expectNoHorizontalOverflow(page, 1280); await expectNoHorizontalOverflow(page, 360); const createRealResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", ); await page.getByRole("button", { name: "Начать полную проверку" }).click(); await expect(page.getByRole("dialog", { name: /какие сигналы собираются/ })).toBeVisible(); await expectNoHorizontalOverflow(page, 360); await page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }).click(); const createRealResponse = await createRealResponsePromise; expect(createRealResponse.status()).toBe(201); expect(createRealResponse.request().postDataJSON()).toMatchObject({ kind: "root", specialization: "backend", target_grade: "junior", task_language: "python", }); const realAttempt = (await createRealResponse.json()) as AttemptSnapshot; expect(realAttempt.kind).toBe("root"); await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${realAttempt.id}$`)); const startRealResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${realAttempt.id}/sessions`, ); const firstResume = page.getByRole("button", { name: "Начать или продолжить" }); await focusWithKeyboard(page, firstResume); await page.keyboard.press("Enter"); const firstResumeResponse = await startRealResponsePromise; expect(firstResumeResponse.status()).toBe(200); const firstRealSnapshot = (await firstResumeResponse.json()) as AttemptSnapshot; expect(firstRealSnapshot.current_item?.id).toBeTruthy(); await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"; await expectNoHorizontalOverflow(page, 360); await page.screenshot({ path: `${artifactsDirectory}/assessment-attempt-360.png`, animations: "disabled", }); await expectNoHorizontalOverflow(page, 1280); await page.screenshot({ path: `${artifactsDirectory}/assessment-attempt-1280.png`, animations: "disabled", }); await expectNoHorizontalOverflow(page, 360); const reloadResponsePromise = page.waitForResponse((response) => attemptPath(response, "GET")); await page.reload(); const reloadedRealResponse = await reloadResponsePromise; expect(reloadedRealResponse.status()).toBe(200); const reloadedRealSnapshot = (await reloadedRealResponse.json()) as AttemptSnapshot; expect(reloadedRealSnapshot.current_item?.id).toBe(firstRealSnapshot.current_item?.id); const resumeAgainPromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${realAttempt.id}/sessions`, ); await page.getByRole("button", { name: "Начать или продолжить" }).click(); const resumeAgainResponse = await resumeAgainPromise; expect(resumeAgainResponse.status()).toBe(200); const resumedRealSnapshot = (await resumeAgainResponse.json()) as AttemptSnapshot; expect(resumedRealSnapshot.current_item?.id).toBe(firstRealSnapshot.current_item?.id); await expectNoHorizontalOverflow(page, 360); expect(resumedRealSnapshot.progress.max_items).toBeGreaterThan(0); expect(resumedRealSnapshot.progress.answered_items).toBe(0); expect( await answerRequiredNumericItems(page, realAttempt.id, resumedRealSnapshot.progress.max_items), ).toBe(resumedRealSnapshot.progress.max_items); await expect(page.getByRole("button", { name: "Завершить проверку" })).toBeVisible(); await expect(page.getByRole("heading", { name: "Результат с сервера" })).toHaveCount(0); const finalizeRootButton = page.getByRole("button", { name: "Завершить проверку" }); await focusWithKeyboard(page, finalizeRootButton); const finalizeRealResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${realAttempt.id}/finalize`, ); const resultResponsePromise = page.waitForResponse( (response) => response.request().method() === "GET" && response.status() === 200 && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${realAttempt.id}/result`, ); await page.keyboard.press("Enter"); expect((await finalizeRealResponsePromise).status()).toBe(200); const resultResponse = await resultResponsePromise; expect(resultResponse.status()).toBe(200); expect(await resultResponse.json()).toMatchObject({ attempt_id: realAttempt.id, kind: "root", task_language: "python", }); await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible(); await page.goto("/candidate/assessment"); await expect(page.getByRole("button", { name: "Пройти экспресс-тест" })).toBeVisible(); const createExpressResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", ); await page.getByRole("button", { name: "Пройти экспресс-тест" }).click(); const createExpressResponse = await createExpressResponsePromise; expect(createExpressResponse.status()).toBe(201); const expressAttempt = (await createExpressResponse.json()) as AttemptSnapshot; expect(expressAttempt.kind).toBe("demo_express"); await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${expressAttempt.id}$`)); const startExpressResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`, ); await page.getByRole("button", { name: "Начать или продолжить" }).click(); const startExpressResponse = await startExpressResponsePromise; expect(startExpressResponse.status()).toBe(200); const firstExpressSnapshot = (await startExpressResponse.json()) as AttemptSnapshot; expect(firstExpressSnapshot.current_item?.id).toBeTruthy(); // An unfinished express run is resumed: after a full reload of the // assessment page, a new start answers 409, and the page replays the start // with the key stored in this tab, which returns the stored 201 of the run. await page.goto("/candidate/assessment"); await expect(page.getByRole("button", { name: "Пройти экспресс-тест" })).toBeVisible(); const expressStarts: { status: number; key: string | null }[] = []; const recordExpressStart = (response: Response) => { if ( response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/me/assessment-attempts" ) { expressStarts.push({ status: response.status(), key: response.request().headers()["idempotency-key"] ?? null, }); } }; page.on("response", recordExpressStart); await page.getByRole("button", { name: "Пройти экспресс-тест" }).click(); await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${expressAttempt.id}$`)); await expect(page.getByText("Незавершенный экспресс-тест продолжен")).toBeVisible(); page.off("response", recordExpressStart); expect(expressStarts.map((start) => start.status)).toEqual([409, 201]); expect(expressStarts[0]?.key).not.toBe(expressStarts[1]?.key); await navigateInApp(page, `/candidate/assessment/${realAttempt.id}`); await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible(); await expect(page.getByRole("button", { name: "Начать или продолжить" })).toHaveCount(0); await expect(page.getByRole("heading", { name: "Экспресс-тест" })).toHaveCount(0); await navigateInApp(page, `/candidate/assessment/${expressAttempt.id}`); await expect(page.getByRole("button", { name: "Начать или продолжить" })).toBeVisible(); const resumedExpressResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`, ); await page.getByRole("button", { name: "Начать или продолжить" }).click(); const resumedExpressResponse = await resumedExpressResponsePromise; expect(resumedExpressResponse.status()).toBe(200); const resumedExpressSnapshot = (await resumedExpressResponse.json()) as AttemptSnapshot; expect(resumedExpressSnapshot.current_item?.id).toBe(firstExpressSnapshot.current_item?.id); await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); const answerCommands: { key: string | undefined; body: string | null }[] = []; const captureAnswerCommand = (request: Request) => { if ( request.method() !== "POST" || new URL(request.url()).pathname !== `/api/v1/me/assessment-attempts/${expressAttempt.id}/answers` ) { return; } answerCommands.push({ key: request.headers()["idempotency-key"], body: request.postData(), }); }; page.on("request", captureAnswerCommand); await expectNoHorizontalOverflow(page, 360); const numberAnswer = page.getByRole("textbox", { name: /^Числовой ответ/ }); await focusWithKeyboard(page, numberAnswer); await numberAnswer.fill("1"); const firstSubmitButton = page.getByRole("button", { name: "Отправить ответ" }); await focusWithKeyboard(page, firstSubmitButton); await page.context().setOffline(true); await page.keyboard.press("Enter"); await expect(page.getByRole("alert")).toContainText("Не удалось связаться с сервером"); await expect.poll(() => answerCommands.length).toBe(1); const offlineCommand = answerCommands[0]; expect(offlineCommand?.key).toBeTruthy(); await expect( page.getByRole("button", { name: "Повторить отправку того же ответа" }), ).toBeVisible(); await page.context().setOffline(false); let forwardedResponses = 0; await page.route("**/api/v1/me/assessment-attempts/*/answers", async (route: Route) => { const response = await route.fetch(); forwardedResponses += 1; if (forwardedResponses === 1) { await route.fulfill({ response, body: "{}" }); return; } await route.fulfill({ response }); }); const firstAnswerResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`, ); await page.getByRole("button", { name: "Повторить отправку того же ответа" }).click(); expect((await firstAnswerResponsePromise).status()).toBe(200); await expect(page.getByRole("alert")).toBeVisible(); const retryResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`, ); const savedAfterAnswerPromise = page.waitForResponse( (response) => response.request().method() === "GET" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}`, ); await page.getByRole("button", { name: "Повторить отправку того же ответа" }).click(); expect((await retryResponsePromise).status()).toBe(200); const savedAfterAnswer = await savedAfterAnswerPromise; expect(savedAfterAnswer.status()).toBe(200); const savedAfterAnswerSnapshot = (await savedAfterAnswer.json()) as AttemptSnapshot; expect(savedAfterAnswerSnapshot.current_item?.id).not.toBe(firstExpressSnapshot.current_item?.id); expect(savedAfterAnswerSnapshot.progress.answered_items).toBe(1); expect(answerCommands).toHaveLength(3); expect(answerCommands[0]?.key).toBeTruthy(); expect(answerCommands[1]?.key).toBe(answerCommands[0]?.key); expect(answerCommands[1]?.body).toBe(answerCommands[0]?.body); expect(answerCommands[2]?.key).toBe(answerCommands[0]?.key); expect(answerCommands[2]?.body).toBe(answerCommands[0]?.body); await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible(); await page.unroute("**/api/v1/me/assessment-attempts/*/answers"); const expressReloadResponsePromise = page.waitForResponse( (response) => response.request().method() === "GET" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}`, ); await page.reload(); const expressReloadResponse = await expressReloadResponsePromise; expect(expressReloadResponse.status()).toBe(200); const reloadedExpressSnapshot = (await expressReloadResponse.json()) as AttemptSnapshot; expect(reloadedExpressSnapshot.current_item?.id).not.toBe(firstExpressSnapshot.current_item?.id); expect(reloadedExpressSnapshot.progress.answered_items).toBe(1); const resumeSavedProgressPromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`, ); await page.getByRole("button", { name: "Начать или продолжить" }).click(); const resumeSavedProgressResponse = await resumeSavedProgressPromise; expect(resumeSavedProgressResponse.status()).toBe(200); const resumedExpressProgress = (await resumeSavedProgressResponse.json()) as AttemptSnapshot; expect(resumedExpressProgress.current_item?.id).toBe(reloadedExpressSnapshot.current_item?.id); expect(resumedExpressProgress.progress.answered_items).toBe(1); await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible(); for (const sequence of [2, 3]) { const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ }); await focusWithKeyboard(page, answerField); await page.keyboard.type("1"); const submitButton = page.getByRole("button", { name: "Отправить ответ" }); await focusWithKeyboard(page, submitButton); const answerResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`, ); await page.keyboard.press("Enter"); expect((await answerResponsePromise).status()).toBe(200); if (sequence < 3) await expect(page.getByRole("heading", { name: `Задание ${sequence + 1}` })).toBeVisible(); } const finalizeButton = page.getByRole("button", { name: "Завершить проверку" }); await focusWithKeyboard(page, finalizeButton); const finalizeResponsePromise = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}/finalize`, ); await page.keyboard.press("Enter"); expect((await finalizeResponsePromise).status()).toBe(200); await expect(page.getByText("Экспресс-тест не присваивает грейд.")).toBeVisible(); await expect(page.getByText(/Подтвержденный уровень/)).toHaveCount(0); page.off("request", captureAnswerCommand); }); const noticePath = "/api/v1/me/assessment-signal-notice"; const confirmNoticeName = "Подтверждаю ознакомление и начинаю"; function isSignalsRequest(request: Request): boolean { return ( request.method() === "POST" && /^\/api\/v1\/me\/assessment-attempts\/[^/]+\/signals$/.test(new URL(request.url()).pathname) ); } async function prepareCandidateOnAssessmentScreen(page: Page): Promise { await registerVerifiedCandidate(page); await grantC3(page); await saveAssessmentQuestionnaire(page); await page.goto("/candidate/assessment"); await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); await page.getByLabel("Язык задания").selectOption("python"); } async function readNotice(page: Page): Promise<{ acknowledged: boolean; notice_version: number }> { return page.evaluate(async (path) => { const response = await fetch(path, { credentials: "same-origin" }); return (await response.json()) as { acknowledged: boolean; notice_version: number }; }, noticePath); } /** Confirms the notice, creates the real attempt, and opens its first item. */ async function openFirstRealItem(page: Page): Promise { const createResponse = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", ); await page.getByRole("button", { name: "Начать полную проверку" }).click(); await page.getByRole("button", { name: confirmNoticeName }).click(); const attempt = (await (await createResponse).json()) as AttemptSnapshot; await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`)); await page.getByRole("button", { name: "Начать или продолжить" }).click(); await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); return attempt.id; } /** Dispatches a paste event that carries recognizable clipboard text. */ async function simulatePaste(page: Page, text: string): Promise { await page.evaluate((pasted) => { const target = document.querySelector("input, textarea") ?? document.body; const data = new DataTransfer(); data.setData("text/plain", pasted); target.dispatchEvent( new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }), ); }, text); } /** Hides or shows the tab the way a tab switch does, through visibilitychange. */ 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); } /** Paste, then leave the tab for a moment. Hiding the tab sends the queued paste. */ async function simulatePasteAndTabSwitch(page: Page, pastedText: string): Promise { await simulatePaste(page, pastedText); await setTabHidden(page, true); await page.waitForTimeout(300); await setTabHidden(page, false); } function utf8Length(text: string): number { return new TextEncoder().encode(text).length; } type SignalEventBody = Record; function signalEvents(bodies: string[]): SignalEventBody[] { return bodies.flatMap((body) => (JSON.parse(body) as { events: SignalEventBody[] }).events); } test("signal requests carry counters and sizes, never the clipboard text", async ({ page }) => { test.skip( !questionnaireFixtureEnabled || !mailFixtureEnabled, "Requires the isolated reviewed assessment-bank and mail fixtures.", ); test.setTimeout(120_000); const asciiText = "PASTED-SECRET-TEXT-12345"; const cyrillicText = "Пароль-тест-секрет"; const bodies: string[] = []; const keys: (string | undefined)[] = []; const requestTexts: string[] = []; const receipts: unknown[] = []; page.on("request", (request) => { // Every URL, query string, and body of a non-GET request is searched for the text. requestTexts.push(decodeURIComponent(request.url()), request.postData() ?? ""); if (!isSignalsRequest(request)) return; bodies.push(request.postData() ?? ""); keys.push(request.headers()["idempotency-key"]); }); page.on("response", async (response) => { if (isSignalsRequest(response.request()) && response.status() === 200) { receipts.push(await response.json()); } }); await prepareCandidateOnAssessmentScreen(page); const attemptId = await openFirstRealItem(page); await simulatePaste(page, asciiText); await simulatePaste(page, cyrillicText); // Hiding the tab sends the pastes; the absence is sent when the tab is hidden again. await setTabHidden(page, true); await page.waitForTimeout(300); await setTabHidden(page, false); await setTabHidden(page, true); await expect .poll(() => signalEvents(bodies).some((event) => event.kind === "focus_loss"), { timeout: 15_000, }) .toBe(true); await setTabHidden(page, false); await expect.poll(() => receipts.length, { timeout: 10_000 }).toBeGreaterThan(1); const events = signalEvents(bodies); const pastes = events.filter((event) => event.kind === "paste"); expect(pastes.map((event) => event.size_bytes)).toEqual([ utf8Length(asciiText), utf8Length(cyrillicText), ]); // The size is bytes, not characters: the Cyrillic text is longer in UTF-8. expect(utf8Length(cyrillicText)).toBeGreaterThan(cyrillicText.length); const focusLoss = events.find((event) => event.kind === "focus_loss"); expect(Number(focusLoss?.duration_ms)).toBeGreaterThan(0); const allowed = new Set(["kind", "item_instance_id", "occurred_at", "size_bytes", "duration_ms"]); for (const event of events) { for (const field of Object.keys(event)) expect(allowed.has(field)).toBe(true); } for (const text of [asciiText, cyrillicText, encodeURIComponent(cyrillicText)]) { for (const seen of [...bodies, ...requestTexts]) expect(seen).not.toContain(text); } expect(keys.every((key) => Boolean(key))).toBe(true); expect(new Set(keys).size).toBe(keys.length); expect(receipts[0]).toMatchObject({ status: "accepted" }); expect(attemptId).toBeTruthy(); // Collection shows nothing: no alert and no status text appeared for the candidate. await expect(page.getByRole("alert")).toHaveCount(0); }); test("a device clock far from the server clock does not drop the signals", async ({ page }) => { test.skip( !questionnaireFixtureEnabled || !mailFixtureEnabled, "Requires the isolated reviewed assessment-bank and mail fixtures.", ); test.setTimeout(120_000); // The page believes it is two hours later than the server says. const skewMs = 2 * 60 * 60 * 1000; await page.addInitScript((skew) => { const RealDate = Date; window.Date = new Proxy(RealDate, { construct: (target, args: unknown[]) => args.length === 0 ? new target(RealDate.now() + skew) : new target(...(args as ConstructorParameters)), get: (target, property, receiver) => property === "now" ? () => RealDate.now() + skew : Reflect.get(target, property, receiver), apply: () => new RealDate(RealDate.now() + skew).toString(), }); }, skewMs); const bodies: string[] = []; const statuses: number[] = []; page.on("request", (request) => { if (isSignalsRequest(request)) bodies.push(request.postData() ?? ""); }); page.on("response", (response) => { if (isSignalsRequest(response.request())) statuses.push(response.status()); }); await prepareCandidateOnAssessmentScreen(page); await openFirstRealItem(page); expect(await page.evaluate(() => Date.now())).toBeGreaterThan(Date.now() + skewMs - 60_000); await simulatePaste(page, "clock skew paste"); await setTabHidden(page, true); await expect.poll(() => statuses.length, { timeout: 15_000 }).toBeGreaterThan(0); expect(statuses).toEqual([200]); const [event] = signalEvents(bodies); const occurredAt = Date.parse(String(event?.occurred_at)); // The timestamp was moved back to server time, within the five minutes the server accepts. expect(Math.abs(occurredAt - Date.now())).toBeLessThan(2 * 60 * 1000); }); test("closing the notice does not start the attempt and a confirmation is remembered", async ({ page, }) => { test.skip( !questionnaireFixtureEnabled || !mailFixtureEnabled, "Requires the isolated reviewed assessment-bank and mail fixtures.", ); test.setTimeout(120_000); const creates: string[] = []; page.on("request", (request) => { if ( request.method() === "POST" && new URL(request.url()).pathname === "/api/v1/me/assessment-attempts" ) { creates.push(request.url()); } }); await prepareCandidateOnAssessmentScreen(page); const start = page.getByRole("button", { name: "Начать полную проверку" }); const dialog = page.getByRole("dialog", { name: /какие сигналы собираются/ }); await start.click(); await expect(dialog).toBeVisible(); for (const text of [ "Смена вкладки или окна", "Копирование, вставка и вырезание", "Выход из полноэкранного режима", "Полноэкранный режим", "Скрытие задания", "Защита текста задания", "Вставка в поля ответа", "Водяной знак на странице задания", "Время ответа на каждое задание", "Смена сетевого адреса во время попытки", "Параллельные сессии", "Изображение: камера и запись экрана не используются", "Звук: микрофон не используется", "Содержимое буфера обмена и вводимый текст", "только пока действует согласие C3", "Адреса и токены сессий не хранятся", ]) { await expect(dialog.getByText(text)).toBeVisible(); } await expect(page.getByRole("heading", { name: /Перед началом/ })).toBeFocused(); await page.keyboard.press("Escape"); await expect(dialog).toBeHidden(); await expect(start).toBeFocused(); await start.click(); await expect(dialog).toBeVisible(); await page.getByRole("button", { name: "Закрыть без подтверждения" }).click(); await expect(dialog).toBeHidden(); expect(creates).toHaveLength(0); expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 2 }); await start.click(); await expect(dialog).toBeVisible(); const confirm = dialog.getByRole("button", { name: confirmNoticeName }); await focusWithKeyboard(page, confirm); const putResponse = page.waitForResponse( (response) => response.request().method() === "PUT" && new URL(response.url()).pathname === noticePath, ); const createResponse = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", ); await page.keyboard.press("Enter"); expect((await putResponse).status()).toBe(200); expect(((await (await putResponse).json()) as { acknowledged: boolean }).acknowledged).toBe(true); const attempt = (await (await createResponse).json()) as AttemptSnapshot; expect(creates).toHaveLength(1); await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`)); // The confirmation lives on the server: a reload goes straight to the work. await page.reload(); expect(await readNotice(page)).toMatchObject({ acknowledged: true }); const sessionResponse = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}/sessions`, ); await page.getByRole("button", { name: "Начать или продолжить" }).click(); expect((await sessionResponse).status()).toBe(200); await expect(page.getByRole("dialog")).toHaveCount(0); await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); }); test("a failed signal batch is retried with the same key while the answer is saved", async ({ page, }) => { test.skip( !questionnaireFixtureEnabled || !mailFixtureEnabled, "Requires the isolated reviewed assessment-bank and mail fixtures.", ); test.setTimeout(120_000); const signalRequests: { key: string | undefined; body: string }[] = []; const failedSignalUrls: string[] = []; page.on("request", (request) => { if (isSignalsRequest(request)) { signalRequests.push({ key: request.headers()["idempotency-key"], body: request.postData() ?? "", }); } }); page.on("requestfailed", (request) => { if (isSignalsRequest(request)) failedSignalUrls.push(request.url()); }); await prepareCandidateOnAssessmentScreen(page); const attemptId = await openFirstRealItem(page); // The network is down exactly while the batch is sent. await page.context().setOffline(true); await simulatePasteAndTabSwitch(page, "text that must never be sent"); await expect.poll(() => failedSignalUrls.length, { timeout: 10_000 }).toBe(1); await page.context().setOffline(false); // The answer does not wait for, or depend on, the signal batch. const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ }); await focusWithKeyboard(page, answerField); await page.keyboard.type("1"); const answerResponse = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attemptId}/answers`, ); await page.getByRole("button", { name: "Отправить ответ" }).click(); expect((await answerResponse).status()).toBe(200); await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible(); await expect(page.getByRole("alert")).toHaveCount(0); // The failed batch is sent again with the same key and body, and only once more. await expect .poll(() => signalRequests.filter((item) => item.key === signalRequests[0]?.key).length, { timeout: 20_000, }) .toBe(2); const [first, second] = signalRequests; expect(first?.key).toBeTruthy(); expect(second?.key).toBe(first?.key); expect(second?.body).toBe(first?.body); expect(first?.body).not.toContain("must never be sent"); await page.waitForTimeout(3_000); expect(signalRequests.filter((item) => item.key === first?.key)).toHaveLength(2); }); const resultHeading = "Результат с сервера"; const expressBanner = "Экспресс-тест не присваивает грейд."; function isFinalizeResponse(response: Response, attemptId: string): boolean { return ( response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attemptId}/finalize` ); } /** * Creates an attempt from the assessment page, resumes it, answers every item, * and finalizes it. Returns the attempt ID and the stored result the page read. */ async function runAttemptToResult( page: Page, start: { name: string; confirmNotice: boolean }, ): Promise<{ id: string; result: Response }> { const createResponse = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", ); await page.getByRole("button", { name: start.name }).click(); if (start.confirmNotice) await page.getByRole("button", { name: confirmNoticeName }).click(); const attempt = (await (await createResponse).json()) as AttemptSnapshot; await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`)); const resumeResponse = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}/sessions`, ); await page.getByRole("button", { name: "Начать или продолжить" }).click(); const resumed = (await (await resumeResponse).json()) as AttemptSnapshot; await answerRequiredNumericItems(page, attempt.id, resumed.progress.max_items); // The result is read only after the finalize command succeeds, so both waits // start right before that click. A wait registered before the whole run // would expire after the action timeout while items are still answered. const finalizeResponse = page.waitForResponse((response) => isFinalizeResponse(response, attempt.id), ); const resultResponse = page.waitForResponse( (response) => response.request().method() === "GET" && response.status() === 200 && new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}/result`, ); await page.getByRole("button", { name: "Завершить проверку" }).click(); expect((await finalizeResponse).status()).toBe(200); const result = await resultResponse; await expect(page.getByRole("heading", { name: resultHeading })).toBeVisible(); return { id: attempt.id, result }; } async function signOut(page: Page): Promise { const status = await page.evaluate(async () => { const current = await fetch("/api/v1/identity/sessions/current", { credentials: "same-origin", }); const session = (await current.json()) as { csrf_token: string }; const response = await fetch("/api/v1/identity/sessions/current", { method: "DELETE", credentials: "same-origin", headers: { "X-CSRF-Token": session.csrf_token }, }); return response.status; }); expect(status).toBe(204); } async function signIn(page: Page, email: string): Promise { await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); await page.getByLabel("Электронная почта").fill(email); await page.getByLabel("Пароль", { exact: true }).fill(password); const loginResponse = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/identity/sessions", ); await page.getByRole("button", { name: "Войти" }).click(); expect((await loginResponse).status()).toBe(201); } // Browser coverage here is the shape of the flow (a real result, the express // run, ownership, and sign-out). The stand cannot produce a failed attempt // after a successful one or an adaptive estimate, so those values, the retry // dates, and the missing-field cases are covered by the unit fixtures. test("results keep the express run apart and stay private to the signed-in candidate", async ({ page, browser, }) => { test.skip( !questionnaireFixtureEnabled || !mailFixtureEnabled, "Requires the isolated reviewed assessment-bank and mail fixtures.", ); test.setTimeout(240_000); const email = await registerVerifiedCandidate(page); await grantC3(page); await saveAssessmentQuestionnaire(page); await page.goto("/candidate/assessment"); await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); await page.getByLabel("Язык задания").selectOption("python"); // The full result: method, date, category state, and the provisional status. const { id: realId, result: realResult } = await runAttemptToResult(page, { name: "Начать полную проверку", confirmNotice: true, }); const stored = (await realResult.json()) as { mode: "demo_basic" | "adaptive" }; // Only a short phrase is a live message; the record is ordinary content and // the focus moved to its heading. await expect(page.getByRole("heading", { name: resultHeading })).toBeFocused(); await expect(page.getByRole("status").filter({ hasText: "Результат получен" })).toHaveCount(1); await expect(page.getByRole("status").getByRole("article")).toHaveCount(0); const inline = page.getByRole("article"); await expect(inline.getByText("Метод и ограничения")).toBeVisible(); await expect(inline.getByText("Категория после этого результата", { exact: true })).toBeVisible(); await expect(inline.getByText("Дата решения", { exact: true })).toBeVisible(); await expect(inline.getByText(/Предварительный|Демо|калибр/)).toHaveCount(0); if (stored.mode === "demo_basic") { await expect(inline.getByText(/Перцентиль, оценка способности, интервал/)).toBeVisible(); await expect(inline.getByText("Стандартная ошибка (SE)")).toHaveCount(0); } await expect(page.getByRole("link", { name: "Открыть на странице результатов" })).toHaveAttribute( "href", `/candidate/results/${realId}`, ); await expectNoHorizontalOverflow(page, 360); await expectNoHorizontalOverflow(page, 1280); // The express test assigns no category, and it offers the full test. await page.goto("/candidate/assessment"); await expect(page.getByRole("button", { name: "Пройти экспресс-тест" })).toBeVisible(); const { id: expressId } = await runAttemptToResult(page, { name: "Пройти экспресс-тест", confirmNotice: false, }); await expect(page.getByText(expressBanner)).toBeVisible(); await expect(page.getByText("не присваивается", { exact: true })).toBeVisible(); await expect(page.getByText(/Подтвержденный уровень/)).toHaveCount(0); await page.getByRole("link", { name: "Перейти к полной проверке" }).click(); await expect(page).toHaveURL(/\/candidate\/assessment$/); await expect(page.getByRole("heading", { name: "Проверка знаний", level: 1 })).toBeVisible(); // History: only the real result; the express run does not replace or join it. await page.goto("/candidate/results"); await expect(page.getByRole("heading", { name: "Результаты проверок", level: 1 })).toBeVisible(); const history = page.getByRole("list", { name: "История результатов" }); await expect(history.getByRole("listitem")).toHaveCount(1); await expect(history.getByRole("link")).toHaveAttribute("href", `/candidate/results/${realId}`); await expect(page.locator(`a[href$="${expressId}"]`)).toHaveCount(0); await expect(page.getByText(/Экспресс-тест сюда не попадает/)).toBeVisible(); await expectNoHorizontalOverflow(page, 360); await page.screenshot({ path: `${process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"}/assessment-history-360.png`, animations: "disabled", }); await expectNoHorizontalOverflow(page, 1280); // The stored real result opens by its URL and is not a demonstration. await history.getByRole("link").click(); await expect(page).toHaveURL(new RegExp(`/candidate/results/${realId}$`)); await expect(page.getByRole("heading", { name: "Результат проверки", level: 1 })).toBeVisible(); await expect(page.getByText("Основная проверка", { exact: true })).toBeVisible(); await expect(page.getByText(expressBanner)).toHaveCount(0); // The express result opens by its own URL, still without a category. await page.goto(`/candidate/results/${expressId}`); await expect(page.getByText(expressBanner)).toBeVisible(); await expect(page.getByRole("link", { name: "Перейти к полной проверке" })).toBeVisible(); // Another candidate cannot read the history or the result by a direct URL. const otherContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); try { const other = await otherContext.newPage(); await registerVerifiedCandidate(other); await other.goto("/candidate/results"); await expect(other.getByText("Результатов пока нет")).toBeVisible(); await expect(other.locator(`a[href$="${realId}"]`)).toHaveCount(0); await other.goto(`/candidate/results/${realId}`); await expect(other.getByText("Результат недоступен")).toBeVisible(); await expect(other.getByText("Метод и ограничения")).toHaveCount(0); } finally { await otherContext.close(); } // After the session ends elsewhere the SPA keeps its in-memory state. The // session ends through the API here, not through the account menu, which // reloads the page; moving inside the app must then show no stored data, and // a fresh load must ask for sign-in. await navigateInApp(page, "/candidate/results"); await expect(history.getByRole("listitem")).toHaveCount(1); await signOut(page); expect((await page.request.get("/api/v1/me/assessment-results")).status()).toBe(401); await navigateInApp(page, `/candidate/results/${realId}`); await expect(page.getByText(/недоступ/).first()).toBeVisible(); await expect(page.getByText("Метод и ограничения")).toHaveCount(0); await navigateInApp(page, "/candidate/results"); await expect(page.getByText(/недоступ/).first()).toBeVisible(); await expect(history.getByRole("listitem")).toHaveCount(0); await page.goto(`/candidate/results/${realId}`); await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); await expect(page.getByText("Метод и ограничения")).toHaveCount(0); // Signing in again restores the permitted screen. await signIn(page, email); await navigateInApp(page, "/candidate/results"); await expect(history.getByRole("listitem")).toHaveCount(1); });