testirovanie-robot/test/login.test.ts
Peppa 00ce7ff313
All checks were successful
peppa/lint lint: success за 0с
peppa/typecheck typecheck: success за 0с
peppa/test test: success за 1с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 7s
deploy / deploy (pull_request) Successful in 8s
TR-1: окно входа — страница входа, проверка логина и пароля, страница после входа
Каркас на Node.js + TypeScript, тексты на трёх языках, проверки и деплой.
OpenSpec change tr-1-login-window (в архиве).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 11:12:19 +05:00

259 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { afterEach, describe, expect, it } from "vitest";
import { mockAccount } from "../src/auth.ts";
import { createSessionToken } from "../src/session.ts";
import { cookieFrom, startApp, type TestApp } from "./helpers.ts";
const INVALID = "Неверный логин или пароль. Проверьте их и попробуйте ещё раз.";
const EMPTY = "Вы не заполнили логин или пароль. Заполните оба поля и нажмите «Войти».";
let app: TestApp;
afterEach(() => app?.close());
/** Значение поля «Логин» на странице. */
const loginFieldValue = (html: string) => /<input id="login"[^>]* value="([^"]*)"/.exec(html)?.[1];
describe("Requirement: Страница входа", () => {
it("Scenario: Страница входа открывается", async () => {
app = await startApp();
const response = await app.get("/login");
const html = await response.text();
expect(response.status).toBe(200);
expect(html).toContain("<h1>Вход</h1>");
expect(html).toContain("Введите логин и пароль. После входа откроется главная страница.");
expect(html).toContain('<label for="login">Логин</label>');
expect(html).toContain('<label for="password">Пароль</label>');
expect(html).toMatch(/<input id="password"[^>]* type="password"/);
expect(html).toContain('<button type="submit">Войти</button>');
});
it("Scenario: Вход нажатием Enter", async () => {
app = await startApp();
const html = await (await app.get("/login")).text();
// Оба поля и кнопка отправки лежат в одной форме: Enter в любом поле отправляет её.
const form =
/<form method="post" action="\/login"[^>]*>([\s\S]*?)<\/form>/.exec(html)?.[1] ?? "";
expect(form).toContain('name="login"');
expect(form).toContain('name="password"');
expect(form).toContain('<button type="submit">');
});
});
describe("Requirement: Вход по логину и паролю", () => {
it("Scenario: Успешный вход", async () => {
app = await startApp();
const response = await app.post("/login", { login: "anna", password: "s3cret-pass" });
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/");
const cookie = cookieFrom(response, "session") ?? "";
const home = await app.get("/", { cookie });
expect(await home.text()).toContain("Вы вошли как anna");
});
it("Scenario: Логин набран в другом регистре", async () => {
app = await startApp();
const response = await app.post("/login", { login: " Anna ", password: "s3cret-pass" });
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/");
});
it.each([
["anna", "wrong"],
["boris", "s3cret-pass"],
["anna", "S3CRET-PASS"],
])("Scenario Outline: Неверный логин или пароль (%s / %s)", async (login, password) => {
app = await startApp();
const response = await app.post("/login", { login, password });
const html = await response.text();
expect(response.status).toBe(401);
expect(html).toContain(INVALID);
expect(loginFieldValue(html)).toBe(login);
expect(html).not.toMatch(/<input id="password"[^>]* value=/);
expect(html).not.toContain(password);
expect(cookieFrom(response, "session")).toBeUndefined();
});
it.each([
["", "s3cret-pass"],
["anna", ""],
["", ""],
])("Scenario Outline: Поле не заполнено («%s» / «%s»)", async (login, password) => {
app = await startApp();
const response = await app.post("/login", { login, password });
const html = await response.text();
expect(response.status).toBe(400);
expect(html).toContain(EMPTY);
expect(cookieFrom(response, "session")).toBeUndefined();
});
it("форму можно отправить пустой: сообщение показывает страница, а не браузер", async () => {
app = await startApp();
const html = await (await app.get("/login")).text();
expect(html).toContain("novalidate");
expect(html).not.toMatch(/<input[^>]* required/);
});
it("введённый логин показывается без исполнения разметки", async () => {
app = await startApp();
const response = await app.post("/login", { login: '"><script>x</script>', password: "p" });
const html = await response.text();
expect(html).not.toContain("<script>");
expect(html).toContain("&lt;script&gt;");
});
});
describe("Requirement: Страница после входа", () => {
it("Scenario: Страница после входа", async () => {
app = await startApp();
const cookie = await app.signIn("anna", "s3cret-pass");
const response = await app.get("/", { cookie });
const html = await response.text();
expect(response.status).toBe(200);
expect(html).toContain("Вы вошли как anna");
expect(html).toContain("Вход выполнен.");
});
it("Scenario: Страница после входа без входа", async () => {
app = await startApp();
const response = await app.get("/");
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/login");
});
it("Scenario: Подделанная отметка о входе", async () => {
app = await startApp();
const forged = createSessionToken("admin", Buffer.from("not-the-secret"), Date.UTC(2026, 0, 1));
const cookie = await app.signIn("anna", "s3cret-pass");
const swapped = `session=${forged.split(".")[0]}.${cookie.split(".")[1]}`;
for (const value of [`session=${forged}`, swapped, "session=garbage", "session=a.b"]) {
const response = await app.get("/", { cookie: value });
expect(response.headers.get("location"), value).toBe("/login");
}
});
it("отметка о входе недоступна скриптам и живёт, пока открыт браузер", async () => {
app = await startApp({ cookieSecure: true });
const response = await app.post("/login", { login: "anna", password: "s3cret-pass" });
const cookie = response.headers.getSetCookie().find((c) => c.startsWith("session=")) ?? "";
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).toContain("Secure");
expect(cookie).not.toMatch(/Max-Age|Expires/i);
});
});
describe("Requirement: Пробный вход, пока логин и пароль не заданы", () => {
it("Scenario: Пробный вход работает", async () => {
app = await startApp({ account: mockAccount, mockAuth: true });
const page = await app.get("/login");
expect(await page.text()).toContain("Пробный вход: логин demo, пароль demo.");
const response = await app.post("/login", { login: "demo", password: "demo" });
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/");
});
it("Scenario: Пробный вход отключён", async () => {
app = await startApp();
const response = await app.post("/login", { login: "demo", password: "demo" });
const html = await response.text();
expect(response.status).toBe(401);
expect(html).toContain(INVALID);
expect(html).not.toContain("Пробный вход");
const page = await (await app.get("/login")).text();
expect(page).not.toContain("Пробный вход");
// Логин и пароль владельца в тексте страницы не появляются.
expect(page).not.toContain("anna");
expect(page).not.toContain("s3cret-pass");
});
});
describe("Requirement: Язык экранов", () => {
it.each([
["ru", "Русский", "Войти"],
["kk", "Қазақша", "Кіру"],
["en", "English", "Sign in"],
])("Scenario Outline: Язык выбран в переключателе (%s)", async (code, name, button) => {
app = await startApp();
const start = await app.get("/login", { "accept-language": "de" });
expect(await start.text()).toContain(`<a href="/login?lang=${code}" lang="${code}"`);
const chosen = await app.get(`/login?lang=${code}`);
const html = await chosen.text();
expect(html).toContain(`<button type="submit">${button}</button>`);
expect(html).toContain(`aria-current="true">${name}</a>`);
const cookie = cookieFrom(chosen, "lang");
expect(cookie).toBe(`lang=${code}`);
const again = await app.get("/login", { cookie: cookie ?? "", "accept-language": "de" });
expect(await again.text()).toContain(`<button type="submit">${button}</button>`);
});
it("Scenario: Язык браузера не поддерживается", async () => {
app = await startApp();
const response = await app.get("/login", { "accept-language": "de-DE,de;q=0.9" });
expect(await response.text()).toContain('<button type="submit">Войти</button>');
expect(response.headers.get("content-language")).toBe("ru");
});
it("без выбора в переключателе берётся язык браузера", async () => {
app = await startApp();
const response = await app.get("/login", {
"accept-language": "de;q=0.9,kk-KZ;q=0.8,en;q=0.5",
});
expect(await response.text()).toContain('<button type="submit">Кіру</button>');
});
it("ошибка входа показана на выбранном языке", async () => {
app = await startApp();
const response = await app.post(
"/login",
{ login: "anna", password: "wrong" },
{ cookie: "lang=en" },
);
expect(await response.text()).toContain("Wrong login or password.");
});
});
describe("Requirement: Проверка работоспособности", () => {
it("Scenario: Сервис работает", async () => {
app = await startApp();
const response = await app.get("/healthz");
expect(response.status).toBe(200);
});
it("Scenario: Неизвестный адрес", async () => {
app = await startApp();
const response = await app.get("/no-such-page");
expect(response.status).toBe(404);
expect(await response.text()).toContain("Такой страницы нет. Вернитесь на главную.");
});
it("сбой показывает две фразы без подробностей и сообщает об ошибке", async () => {
const errors: unknown[] = [];
app = await startApp({
onError: (error) => errors.push(error),
now: () => {
throw new Error("boom-secret-detail");
},
});
const response = await app.get("/");
const html = await response.text();
expect(response.status).toBe(500);
expect(html).toContain("Что-то пошло не так. Обновите страницу и попробуйте ещё раз.");
expect(html).not.toContain("boom-secret-detail");
expect(errors).toHaveLength(1);
});
it("слишком большая форма отклоняется", async () => {
app = await startApp();
const response = await app.post("/login", { login: "anna", password: "x".repeat(20_000) });
expect(response.status).toBe(413);
});
it("страницы запрещают встраивание и посторонние скрипты", async () => {
app = await startApp();
const response = await app.get("/login");
expect(response.headers.get("content-security-policy")).toContain("default-src 'none'");
expect(response.headers.get("cache-control")).toBe("no-store");
const css = await app.get("/static/style.css");
expect(css.headers.get("content-type")).toContain("text/css");
});
});