feat(candidate): add the candidate home, results and result history screens

This commit is contained in:
shira committed 2026-10-09 01:24:45 +03:00
1 parent 8277133712
commit 4761508f13
52 files changed
+5334 -81

No files matched your search

+217 -2
View File
@@ -1,4 +1,12 @@
import { expect, test, type Locator, type Page, type Request, type Route } from "@playwright/test";
import {
expect,
test,
type Locator,
type Page,
type Request,
type Response,
type Route,
} from "@playwright/test";
type InboxMessage = {
text?: string;
@@ -57,7 +65,7 @@ function verificationToken(message: InboxMessage): string {
return token;
}
async function registerVerifiedCandidate(page: Page): Promise<void> {
async function registerVerifiedCandidate(page: Page): Promise<string> {
const email = `assessment-${crypto.randomUUID()}@example.test`;
await page.goto("/register");
await expect(
@@ -98,6 +106,7 @@ async function registerVerifiedCandidate(page: Page): Promise<void> {
);
await page.getByRole("button", { name: "Войти" }).click();
expect((await loginResponse).status()).toBe(201);
return email;
}
async function grantC3(page: Page): Promise<void> {
@@ -846,3 +855,209 @@ test("a failed signal batch is retried with the same key while the answer is sav
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, and answers every item. */
async function runAttemptToResult(
page: Page,
start: { name: string; confirmNotice: boolean },
): 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: 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);
const finalizeResponse = page.waitForResponse((response) =>
isFinalizeResponse(response, attempt.id),
);
await page.getByRole("button", { name: "Завершить проверку" }).click();
expect((await finalizeResponse).status()).toBe(200);
await expect(page.getByRole("heading", { name: resultHeading })).toBeVisible();
return attempt.id;
}
async function signOut(page: Page): Promise<void> {
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<void> {
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 realResult = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
response.status() === 200 &&
/^\/api\/v1\/me\/assessment-attempts\/[^/]+\/result$/.test(new URL(response.url()).pathname),
);
const realId = await runAttemptToResult(page, {
name: "Начать полную проверку",
confirmNotice: true,
});
const stored = (await (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("Предварительный результат")).toBeVisible();
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 run is a demonstration: no category, and it offers the full test.
await page.goto("/candidate/assessment");
await expect(page.getByRole("button", { name: "Начать демонстрацию" })).toBeVisible();
const 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 sign-out the SPA keeps its in-memory state. The app has no sign-out
// control yet, so the session ends through the API; 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);
});