testirovanie-robot/test/units.test.ts
Peppa f06fd50865
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 9s
deploy / deploy (pull_request) Successful in 12s
TR-1: окно входа — страница входа, проверка логина и пароля, страница после входа
Каркас на Node.js + TypeScript, тексты на трёх языках, проверки и деплой.
OpenSpec change tr-1-login-window (в архиве).

Rebase на main с принятой TR-2: список пользователей (data/users.json, scrypt)
и блокировка 5 ошибок / 15 минут перенесены в src/users.ts и src/auth.ts,
единственная учётная запись из настроек и пробный вход убраны.

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

111 lines
5.4 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 { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { environmentFromHost, loadConfig } from "../src/config.ts";
import { LANGS, locales, pickLang } from "../src/i18n.ts";
import { createSessionToken, readSessionToken, SESSION_TTL_MS } from "../src/session.ts";
describe("session: отметка о входе", () => {
const secret = Buffer.from("k");
it("читается до истечения срока и не читается после", () => {
const token = createSessionToken("anna", secret, 1000);
expect(readSessionToken(token, secret, 1000 + SESSION_TTL_MS - 1)).toBe("anna");
expect(readSessionToken(token, secret, 1000 + SESSION_TTL_MS)).toBeNull();
});
it("не читается с другим ключом и в испорченном виде", () => {
const token = createSessionToken("anna", secret, 1000);
expect(readSessionToken(token, Buffer.from("other"), 1000)).toBeNull();
expect(readSessionToken(`${token}x`, secret, 1000)).toBeNull();
expect(readSessionToken(undefined, secret, 1000)).toBeNull();
expect(readSessionToken(".", secret, 1000)).toBeNull();
});
});
describe("config: настройки из окружения", () => {
it("значения по умолчанию", () => {
const config = loadConfig({});
expect(config.port).toBe(3000);
expect(config.usersFile.endsWith("data/users.json")).toBe(true);
expect(config.sentry).toEqual({ dsn: undefined, release: undefined, environment: "dev" });
});
it("порт, файл пользователей и ключ подписи берутся из окружения", () => {
const env = { PORT: "8080", USERS_FILE: "/tmp/u.json", SESSION_SECRET: "k" };
const config = loadConfig(env);
expect(config.port).toBe(8080);
expect(config.usersFile).toBe("/tmp/u.json");
expect(config.sessionSecret.equals(loadConfig(env).sessionSecret)).toBe(true);
// Без SESSION_SECRET ключ случайный на каждый запуск.
expect(loadConfig({}).sessionSecret.equals(loadConfig({}).sessionSecret)).toBe(false);
});
it("отметка о входе только по https в production", () => {
expect(loadConfig({ NODE_ENV: "production" }).cookieSecure).toBe(true);
expect(loadConfig({ NODE_ENV: "production", COOKIE_SECURE: "false" }).cookieSecure).toBe(false);
expect(loadConfig({}).cookieSecure).toBe(false);
});
it("окружение для отчётов об ошибках", () => {
expect(environmentFromHost("testirovanie-robot-prod.telecom.quest")).toBe("prod");
expect(environmentFromHost("testirovanie-robot-staging.telecom.quest")).toBe("staging");
expect(environmentFromHost("testirovanie-robot-pr1.telecom.quest")).toBe("dev");
expect(environmentFromHost(undefined)).toBe("dev");
const config = loadConfig({
SENTRY_DSN: "https://k@example.test/1",
SENTRY_ENVIRONMENT: "prod",
});
expect(config.sentry.environment).toBe("prod");
});
it("неверный порт — ошибка запуска", () => {
expect(() => loadConfig({ PORT: "abc" })).toThrow();
});
});
describe("i18n: тексты экранов", () => {
it("язык: выбор → cookie → браузер → русский", () => {
expect(pickLang("en", "kk", "ru")).toBe("en");
expect(pickLang("xx", "kk", "en")).toBe("kk");
expect(pickLang(undefined, undefined, "fr, en;q=0.8, kk;q=0.9")).toBe("kk");
expect(pickLang(undefined, undefined, "en;q=0, de")).toBe("ru");
expect(pickLang(undefined, undefined, undefined)).toBe("ru");
});
it("во всех языках один и тот же набор текстов и подстановок", () => {
const placeholders = (text: string) => (text.match(/\{\w+\}/g) ?? []).sort();
for (const { code } of LANGS) {
expect(Object.keys(locales[code]).sort(), code).toEqual(Object.keys(locales.ru).sort());
for (const [key, text] of Object.entries(locales[code])) {
expect(text.trim(), `${code}:${key}`).not.toBe("");
const reference = locales.ru[key as keyof typeof locales.ru];
expect(placeholders(text), `${code}:${key}`).toEqual(placeholders(reference));
}
}
});
it("в текстах нет слов из колонки «Нельзя» словаря docs/glossary.md", () => {
const glossary = readFileSync(new URL("../docs/glossary.md", import.meta.url), "utf8");
const forbidden = glossary
.split("\n")
.filter((line) => line.startsWith("|") && !line.startsWith("|---"))
.slice(1)
.flatMap((line) => (line.split("|")[3] ?? "").split(","))
.map((word) => word.trim().toLowerCase())
.filter(Boolean);
expect(forbidden.length).toBeGreaterThan(50);
const violations: string[] = [];
for (const { code } of LANGS) {
for (const [key, text] of Object.entries(locales[code])) {
for (const word of forbidden) {
const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Слово целиком: рядом нет других букв и цифр (кириллица, казахские буквы, латиница).
const pattern = new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "iu");
if (pattern.test(text)) violations.push(`${code}:${key} — «${word}»`);
}
}
}
expect(violations).toEqual([]);
});
});