feat(assessment): add the review band of attempt signals and the disclosed collector

This commit is contained in:
shira committed 2026-10-08 23:04:57 +03:00
1 parent 68286af8b7
commit b3c6dc870b
124 files changed
+13522 -633

No files matched your search

+344 -1
View File
@@ -213,7 +213,7 @@ test("candidate can review, resume, and finish separate assessment modes", async
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 expect(page.getByText(/камера и запись экрана не используются/)).toBeVisible();
await page.getByLabel("Язык задания").selectOption("python");
await expect(page.getByLabel("Язык задания")).toHaveValue("python");
await expectNoHorizontalOverflow(page, 360);
@@ -226,6 +226,9 @@ test("candidate can review, resume, and finish separate assessment modes", async
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({
@@ -503,3 +506,343 @@ test("candidate can review, resume, and finish separate assessment modes", async
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<void> {
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<string> {
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<void> {
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<void> {
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<void> {
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<string, unknown>;
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<typeof Date>)),
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: 1 });
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);
});