feat(assessment): keep real attempts in fullscreen and protect the task text

This commit is contained in:
shira committed 2026-10-11 03:03:55 +03:00
1 parent 56dcf32f8c
commit efa41d5967
46 files changed
+1940 -72

No files matched your search

+166
View File
@@ -0,0 +1,166 @@
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;
};
export type MockedAttempt = {
/** Events of every signal batch the page sent, in order. */
signals: SignalEvent[];
/** Bodies of the answers the page sent. */
answers: unknown[];
/** Calls to the notice acknowledgement, to see what was stored. */
acknowledgements: unknown[];
};
type Options = {
content: MockItemContent;
/** The candidate already acknowledged the notice, so the start asks nothing. */
noticeAcknowledged?: boolean;
};
function isoSeconds(ms: number): string {
return `${new Date(ms).toISOString().slice(0, 19)}Z`;
}
function attemptBody(version: number, content: MockItemContent) {
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: taskPrompt, content },
practices: [],
};
}
/** Answers the API calls of the attempt page; every other API call gets a 404. */
export async function mockAttemptApi(page: Page, options: Options): Promise<MockedAttempt> {
const recorded: MockedAttempt = { signals: [], answers: [], acknowledgements: [] };
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: 2,
acknowledged,
acknowledged_at: acknowledged ? "2026-10-10T10:00:00Z" : null,
});
}
if (path === base && method === "GET") return reply(attemptBody(1, options.content));
if (path === `${base}/sessions`) return reply(attemptBody(2, options.content));
if (path === `${base}/answers`) {
recorded.answers.push(JSON.parse(request.postData() ?? "{}"));
return reply(attemptBody(3, options.content));
}
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<void> {
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<boolean> {
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<void> {
await page.goto(`/candidate/assessment/${attemptId}`);
await page.getByRole("button", { name: "Начать или продолжить" }).click();
}
+160
View File
@@ -0,0 +1,160 @@
import { expect, test } from "@playwright/test";
import {
attemptId,
isFullscreen,
mockAttemptApi,
numberContent,
setTabHidden,
startAttempt,
taskPrompt,
} from "./assessment-attempt-mock";
// Fullscreen and the cover of the task during a real attempt. The API is
// mocked: these specs check what the page does, not the server.
const coverHeading = "Задание скрыто";
const continueName = "Продолжить в полном экране";
const answerName = /^Числовой ответ/;
test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" });
test("leaving fullscreen hides the task and sends a signal, and returning restores it with the draft", async ({
page,
}) => {
const recorded = await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
// The click that resumed the work asked for fullscreen.
await expect.poll(() => isFullscreen(page)).toBe(true);
await page.getByRole("textbox", { name: answerName }).fill("73");
await page.evaluate(() => document.exitFullscreen());
await expect(page.getByRole("heading", { name: coverHeading })).toBeVisible();
// The task is replaced, not blurred: neither its text nor the answer controls are in the page.
expect(await page.locator("body").innerText()).not.toContain(taskPrompt);
expect(await page.content()).not.toContain(taskPrompt);
await expect(page.getByRole("textbox", { name: answerName })).toHaveCount(0);
await expect(page.getByRole("heading", { name: "Задание 1" })).toHaveCount(0);
// The timer is the server's and stays on screen.
await expect(page.getByRole("timer")).toBeVisible();
// The keyboard focus waits on the way back.
await expect(page.getByRole("button", { name: continueName })).toBeFocused();
// The collector sends the exit with the next batch (every 10 seconds).
await expect
.poll(() => recorded.signals.some((event) => event.kind === "fullscreen_exit"), {
timeout: 15_000,
})
.toBe(true);
await page.getByRole("button", { name: continueName }).click();
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect(page.getByRole("heading", { name: coverHeading })).toHaveCount(0);
await expect.poll(() => isFullscreen(page)).toBe(true);
await expect(page.getByText(taskPrompt)).toBeVisible();
await expect(page.getByRole("textbox", { name: answerName })).toHaveValue("73");
});
test("leaving the tab covers the task and returning in fullscreen shows it again", async ({
page,
}) => {
const recorded = await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect.poll(() => isFullscreen(page)).toBe(true);
await page.getByRole("textbox", { name: answerName }).fill("5");
await setTabHidden(page, true);
await expect(page.getByRole("heading", { name: coverHeading })).toBeVisible();
expect(await page.locator("body").innerText()).not.toContain(taskPrompt);
// Only the tab was left, so there is nothing to click: returning is enough.
await expect(page.getByRole("button", { name: continueName })).toHaveCount(0);
await page.waitForTimeout(300);
await setTabHidden(page, false);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect(page.getByText(taskPrompt)).toBeVisible();
await expect(page.getByRole("textbox", { name: answerName })).toHaveValue("5");
await expect
.poll(() => recorded.signals.some((event) => event.kind === "focus_loss"), { timeout: 15_000 })
.toBe(true);
});
test("a browser without fullscreen explains it and still takes the test with the cover on leave", async ({
page,
}) => {
// iPhone Safari has no element fullscreen.
await page.addInitScript(() => {
Object.defineProperty(document, "fullscreenEnabled", { configurable: true, get: () => false });
Object.defineProperty(Element.prototype, "requestFullscreen", {
configurable: true,
value: undefined,
});
});
const recorded = await mockAttemptApi(page, { content: numberContent });
await page.goto(`/candidate/assessment/${attemptId}`);
// The explanation is on screen before the work starts, and the start is not blocked.
await expect(page.getByText(/не поддерживает полноэкранный режим/)).toBeVisible();
await expect(page.getByText(/Тест можно пройти и без него/)).toBeVisible();
await page.getByRole("button", { name: "Начать или продолжить" }).click();
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
expect(await isFullscreen(page)).toBe(false);
await setTabHidden(page, true);
await expect(page.getByRole("heading", { name: coverHeading })).toBeVisible();
expect(await page.locator("body").innerText()).not.toContain(taskPrompt);
await setTabHidden(page, false);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
// The test can be finished from the keyboard in this mode too.
await page.getByRole("textbox", { name: answerName }).focus();
await page.keyboard.type("42");
await page.keyboard.press("Tab");
await expect(page.getByRole("button", { name: "Отправить ответ" })).toBeFocused();
await page.keyboard.press("Enter");
await expect.poll(() => recorded.answers.length).toBe(1);
});
test("a browser that refuses the fullscreen request continues without it", async ({ page }) => {
await page.addInitScript(() => {
Element.prototype.requestFullscreen = () =>
Promise.reject(new TypeError("Permissions check failed"));
});
await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect(page.getByText(/не включил полноэкранный режим/)).toBeVisible();
expect(await isFullscreen(page)).toBe(false);
// No cover is waiting for a fullscreen that cannot come.
await expect(page.getByRole("heading", { name: coverHeading })).toHaveCount(0);
});
test("closing the notice without confirming leaves fullscreen and starts nothing", async ({
page,
}) => {
const recorded = await mockAttemptApi(page, {
content: numberContent,
noticeAcknowledged: false,
});
await startAttempt(page);
const dialog = page.getByRole("dialog", { name: /какие сигналы собираются/ });
await expect(dialog).toBeVisible();
await expect(dialog.getByText("Полноэкранный режим", { exact: false }).first()).toBeVisible();
await expect.poll(() => isFullscreen(page)).toBe(true);
await page.getByRole("button", { name: "Закрыть без подтверждения" }).click();
await expect(dialog).toBeHidden();
await expect.poll(() => isFullscreen(page)).toBe(false);
await expect(page.getByRole("heading", { name: "Задание 1" })).toHaveCount(0);
expect(recorded.acknowledgements).toHaveLength(0);
// Confirming goes on to the test in fullscreen.
await page.getByRole("button", { name: "Начать или продолжить" }).click();
await page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }).click();
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect.poll(() => isFullscreen(page)).toBe(true);
expect(recorded.acknowledgements).toEqual([{ notice_version: 2 }]);
});
@@ -0,0 +1,198 @@
import { expect, test, type Page } from "@playwright/test";
import {
exampleInput,
mockAttemptApi,
numberContent,
practiceContent,
setTabHidden,
startAttempt,
taskPrompt,
} from "./assessment-attempt-mock";
// Copy, selection, context menu, drag, print, and paste rules during a real
// attempt. The API is mocked: these specs check what the page does.
const sentinel = "CLIPBOARD-SENTINEL";
const modifier = "ControlOrMeta";
const refusedNotice = "Вставка в поля ответа отключена";
test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" });
async function allowClipboard(page: Page): Promise<void> {
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
}
async function writeClipboard(page: Page, text: string): Promise<void> {
await page.evaluate((value) => navigator.clipboard.writeText(value), text);
}
async function readClipboard(page: Page): Promise<string> {
return page.evaluate(() => navigator.clipboard.readText());
}
/** Sends the queued signals now: hiding the tab flushes the batch. */
async function flushSignals(page: Page): Promise<void> {
await setTabHidden(page, true);
await page.waitForTimeout(300);
await setTabHidden(page, false);
await page.waitForTimeout(500);
}
test("the task text cannot be selected, copied, dragged, or printed, and stays readable by assistive tools", async ({
page,
}) => {
await allowClipboard(page);
await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
const prompt = page.getByText(taskPrompt);
await expect(prompt).toBeVisible();
// Selection: the text is not selectable, so a triple click and select-all take none of it.
expect(await prompt.evaluate((element) => getComputedStyle(element).userSelect)).toBe("none");
await prompt.click({ clickCount: 3 });
expect(await page.evaluate(() => window.getSelection()?.toString())).toBe("");
await page.mouse.click(5, 5);
await page.keyboard.press(`${modifier}+a`);
expect(await page.evaluate(() => window.getSelection()?.toString())).not.toContain("SECRET");
// Copy: neither the keyboard nor a script that selects the text gets it into the clipboard.
await writeClipboard(page, sentinel);
await page.keyboard.press(`${modifier}+c`);
expect(await readClipboard(page)).not.toContain("SECRET-PROMPT");
const refused = await page.evaluate(() => {
const element = document.querySelector("article p");
if (!element) return null;
const range = document.createRange();
range.selectNodeContents(element);
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
let prevented: boolean | null = null;
const listener = (event: Event) => {
prevented = event.defaultPrevented;
};
// A bubbling listener on the window runs after the page's own handlers.
window.addEventListener("copy", listener);
document.execCommand("copy");
window.removeEventListener("copy", listener);
return prevented;
});
expect(refused).toBe(true);
expect(await readClipboard(page)).not.toContain("SECRET-PROMPT");
// Context menu and drag are cancelled on the task; a field keeps its own menu.
const prevented = await page.evaluate(() => {
const element = document.querySelector("article p");
const field = document.querySelector("input[name=number-answer]");
const cancelled = (target: Element | null, event: Event) =>
target !== null && !target.dispatchEvent(event);
return {
taskMenu: cancelled(
element,
new MouseEvent("contextmenu", { bubbles: true, cancelable: true }),
),
taskDrag: cancelled(element, new DragEvent("dragstart", { bubbles: true, cancelable: true })),
fieldMenu: cancelled(
field,
new MouseEvent("contextmenu", { bubbles: true, cancelable: true }),
),
};
});
expect(prevented).toEqual({ taskMenu: true, taskDrag: true, fieldMenu: false });
// The field's own text can still be copied.
await page.getByRole("textbox", { name: /^Числовой ответ/ }).fill("4242");
await page.keyboard.press(`${modifier}+a`);
await page.keyboard.press(`${modifier}+c`);
expect(await readClipboard(page)).toBe("4242");
// The text stays in the page for a screen reader.
expect(await page.getByRole("article").ariaSnapshot()).toContain("SECRET-PROMPT");
// Printing leaves the task out.
await page.emulateMedia({ media: "print" });
await expect(page.getByRole("article")).toBeHidden();
expect(await page.locator("body").innerText()).not.toContain("SECRET-PROMPT");
await page.emulateMedia({ media: "screen" });
await expect(prompt).toBeVisible();
});
test("an answer field refuses paste, says so, records the attempt as a signal, and still takes typing", async ({
page,
}) => {
await allowClipboard(page);
const recorded = await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
const field = page.getByRole("textbox", { name: /^Числовой ответ/ });
await expect(field).toBeVisible();
await writeClipboard(page, "PASTED123");
await field.click();
await page.keyboard.press(`${modifier}+v`);
await expect(field).toHaveValue("");
await expect(page.getByText(refusedNotice)).toBeVisible();
await page.keyboard.type("77");
await expect(field).toHaveValue("77");
await expect(page.getByText(refusedNotice)).toHaveCount(0);
await flushSignals(page);
const pastes = recorded.signals.filter((event) => event.kind === "paste");
expect(pastes.map((event) => event.size_bytes)).toEqual(["PASTED123".length]);
expect(JSON.stringify(recorded.signals)).not.toContain("PASTED123");
});
test("the practice code editor accepts paste and records its size, and protects its examples", async ({
page,
}) => {
await allowClipboard(page);
const recorded = await mockAttemptApi(page, { content: practiceContent });
await startAttempt(page);
const editor = page.getByRole("textbox", { name: "Код решения" });
await expect(editor).toBeVisible();
const code = "print('PASTED-CODE')";
await writeClipboard(page, code);
await editor.click();
await page.keyboard.press(`${modifier}+v`);
await expect(editor).toHaveValue(code);
await expect(page.getByText(refusedNotice)).toHaveCount(0);
await page.keyboard.type(" # note");
await expect(editor).toHaveValue(`${code} # note`);
// Dropped text is refused even here, because a drop is not a recorded paste.
const dropCancelled = await editor.evaluate(
(element) => !element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true })),
);
expect(dropCancelled).toBe(true);
// The examples are task text: not selectable, not copyable.
const example = page.getByText(exampleInput);
expect(await example.evaluate((element) => getComputedStyle(element).userSelect)).toBe("none");
await flushSignals(page);
const pastes = recorded.signals.filter((event) => event.kind === "paste");
expect(pastes.map((event) => event.size_bytes)).toEqual([code.length]);
expect(JSON.stringify(recorded.signals)).not.toContain("PASTED-CODE");
});
test("an item is answered with the keyboard alone while the protection is on", async ({ page }) => {
const recorded = await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
const field = page.getByRole("textbox", { name: /^Числовой ответ/ });
await expect(field).toBeVisible();
for (let step = 0; step < 30; step += 1) {
if (await field.evaluate((element) => element === document.activeElement)) break;
await page.keyboard.press("Tab");
}
await expect(field).toBeFocused();
await page.keyboard.type("42");
await expect(field).toHaveValue("42");
await page.keyboard.press("Tab");
await expect(page.getByRole("button", { name: "Отправить ответ" })).toBeFocused();
await page.keyboard.press("Enter");
await expect.poll(() => recorded.answers.length).toBe(1);
expect(recorded.answers[0]).toMatchObject({ answer: { format: "number", number: 42 } });
});
+6 -1
View File
@@ -780,6 +780,11 @@ test("closing the notice does not start the attempt and a confirmation is rememb
"Смена вкладки или окна",
"Копирование, вставка и вырезание",
"Выход из полноэкранного режима",
"Полноэкранный режим",
"Скрытие задания",
"Защита текста задания",
"Вставка в поля ответа",
"Водяной знак на странице задания",
"Время ответа на каждое задание",
"Смена сетевого адреса во время попытки",
"Параллельные сессии",
@@ -801,7 +806,7 @@ test("closing the notice does not start the attempt and a confirmation is rememb
await page.getByRole("button", { name: "Закрыть без подтверждения" }).click();
await expect(dialog).toBeHidden();
expect(creates).toHaveLength(0);
expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 1 });
expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 2 });
await start.click();
await expect(dialog).toBeVisible();