peppa/packages/testkit/test/i18n.test.ts
2026-11-16 13:30:26 +05:00

151 lines
8.8 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.

// PEP-98: interface language — dictionary lookups, translating rendered text, the user's
// language, the coverage check, and the bot speaking the reader's language.
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { after, before, describe, test } from "node:test";
import { core, db, teardown, waitFor } from "./helpers.ts";
import { MockTelegram } from "../src/mock-telegram.ts";
import type { Bot } from "@peppa/bot";
import { wording } from "@peppa/shared/wording";
import { dictionary, localeFromAcceptLanguage, localizeText, normalizeLocale, productName, t, tn, translator } from "@peppa/shared/i18n";
const { createBot } = await import("@peppa/bot");
const { TelegramApi } = await import("@peppa/bot/telegram");
const run = promisify(execFile);
const root = new URL("../../..", import.meta.url).pathname;
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const tg = await new MockTelegram().start();
const ANNA = { id: 701, chatId: 701, username: "anna" };
let bot: Bot;
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
before(async () => {
anna = await core.upsertUserFromGitea(db, { id: 8701, login: "mock-i18n-anna" }, { access_token: "x" });
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 400 });
await bot.start();
});
after(async () => {
await bot.stop();
await tg.stop();
await teardown();
});
describe("язык интерфейса", () => {
test("Scenario: Переключение на английский — словарь и название", () => {
assert.equal(t("en", "Проекты"), "Projects");
assert.equal(t("ru", "Проекты"), "Проекты");
assert.equal(translator("en")("Настройки"), "Settings");
assert.equal(productName("en"), "Peppa FACTORY");
// KZ — the Kazakh dictionary (PEP-99).
assert.equal(t("kk", "Проекты"), "Жобалар");
assert.equal(t("en", "Ключа нет в словаре {x}", { x: 1 }), "Ключа нет в словаре 1");
});
test("Scenario: Слова режимов «Продакт» и «Инженер» по-английски", () => {
const product = wording("product", "en");
const engineer = wording("engineer", "en");
assert.equal(t("en", "Создать {task}", { task: product.task("acc") }), "Create task");
assert.equal(t("en", "Создать {task}", { task: engineer.task("acc") }), "Create story");
assert.equal(product.task("acc"), "task");
assert.equal(product.Task("pl"), "Tasks");
assert.equal(engineer.task("accPl"), "stories");
assert.equal(engineer.runner("pl"), "runners");
assert.equal(product.tasks(1), "1 task");
// Russian stays as PEP-123 wrote it.
assert.equal(wording("product").task("acc"), "задачу");
assert.equal(wording("product", "kk").task("acc"), "тапсырма"); // PEP-99: Kazakh, nominative
// Texts built with PRODUCT_WORDS are translated back word by word.
assert.equal(localizeText("en", "задачи"), "tasks");
});
test("Scenario: Неизвестный язык и язык браузера", () => {
assert.equal(normalizeLocale("de"), "ru");
assert.equal(normalizeLocale("en"), "en");
assert.equal(localeFromAcceptLanguage("en-US,en;q=0.9"), "en");
assert.equal(localeFromAcceptLanguage("de-DE,ru;q=0.5,en;q=0.4"), "ru");
assert.equal(localeFromAcceptLanguage("de-DE"), null);
});
test("Scenario: Перевод собранного уведомления", () => {
const en = dictionary("en");
// Added before the first localizeText call: templates are compiled once per locale.
en["Тестовая стори {key} в статусе {status}"] = "Test story {key} is {status}"; // captured values are translated too
assert.equal(localizeText("en", t("ru", "Ошибка: {message}", { message: "boom" })), "Error: boom");
// Templates are matched inside lines, between HTML tags and with decorations around.
assert.equal(localizeText("en", "<b>Проекты</b>\n✅ Принять"), "<b>Projects</b>\n✅ Accept");
assert.equal(localizeText("en", "Тестовая стори PEP-7 в статусе в работе"), "Test story PEP-7 is in progress");
assert.equal(localizeText("en", "Совсем неизвестная строка"), "Совсем неизвестная строка");
// Free text of a person or an agent is not cut by a template anchored only in the middle.
assert.equal(localizeText("en", "Какой формат из двух?"), "Какой формат из двух?");
assert.equal(localizeText("ru", "Проекты"), "Проекты");
assert.equal(tn("en", 1, "{n} вопросов ждут тебя", "{n} вопросов ждут тебя", "{n} вопросов ждут тебя"), "1 questions waiting for you");
assert.equal(tn("ru", 3, "{n} файл", "{n} файла", "{n} файлов"), "3 файла");
});
test("Scenario: Язык пользователя хранится в настройках", async () => {
assert.equal(await core.getUserLocaleSetting(db, anna.id), null);
assert.equal(await core.getUserLocale(db, anna.id), "ru");
await core.setUserLocale(db, anna.id, "en");
assert.equal(await core.getUserLocale(db, anna.id), "en");
await assert.rejects(core.setUserLocale(db, anna.id, "de" as never), /Неизвестный язык/);
await core.setUserLocale(db, anna.id, null);
assert.equal(await core.getUserLocaleSetting(db, anna.id), null);
});
test("Scenario: Бот отвечает на языке получателя", async () => {
tg.userSends(ANNA, `/start ${await core.createPairingCode(db, tg.token, anna.id)}`);
await waitFor("paired", async () => (await core.getUser(db, anna.id))!.telegramChatId === ANNA.chatId);
const before = tg.botMessages(ANNA.chatId).length;
// No language chosen → Russian, as before.
tg.userSends(ANNA, "/start 000000");
await waitFor("russian reply", async () => tg.botMessages(ANNA.chatId).length > before);
const ru = tg.botMessages(ANNA.chatId).at(-1)!.text;
assert.match(ru, /[А-Яа-я]/);
await core.setUserLocale(db, anna.id, "en");
core.forgetChatLocales();
const n = tg.botMessages(ANNA.chatId).length;
tg.userSends(ANNA, "/start 000000");
await waitFor("english reply", async () => tg.botMessages(ANNA.chatId).length > n);
const en = tg.botMessages(ANNA.chatId).at(-1)!.text;
assert.equal(en, localizeText("en", ru));
assert.doesNotMatch(en, /[А-Яа-я]/, `untranslated: ${en}`);
});
test("Scenario: Свободный текст не переводится — бот не трогает уже переведённое сообщение (PEP-138)", async () => {
// Anna reads English (previous test). A role's message is queued in her language with the
// model's own Russian words inside: the bot sends it as it is and strips the private mark.
const text = "💬 <b>Демо</b> · Analyst:\nСделано три задачи из пяти.\n\nReply: http://peppa.test/chats/DEMO";
await core.enqueueTelegram(db, { dedupeKey: "pep138:localized", method: "sendMessage", params: { chat_id: ANNA.chatId, text, parse_mode: "HTML", [core.LOCALIZED_PARAM]: true } });
await waitFor("sent", async () => tg.botMessages(ANNA.chatId).some((m) => m.text.includes("Analyst")));
assert.equal(tg.botMessages(ANNA.chatId).at(-1)!.text, text);
assert.equal(core.LOCALIZED_PARAM in tg.calls.at(-1)!.params, false, "the mark does not reach Telegram");
});
const check = (args: string[]) =>
run("node", ["scripts/i18n-check.ts", ...args], { cwd: root }).then(
(x) => ({ code: 0, out: x.stdout }),
(e: { code: number; stdout: string }) => ({ code: e.code, out: e.stdout }),
);
test("Scenario: Ключ без перевода — проверка i18n-check", async () => {
const dir = mkdtempSync(join(tmpdir(), "mock-i18n-"));
const file = join(dir, "mock-page.tsx");
writeFileSync(file, 'const t = (s: string) => s;\nexport const a = t("Новая кнопка без перевода");\nexport const b = <p>Голый текст</p>;\n');
const bad = await check(["--file", file]);
assert.equal(bad.code, 1);
assert.match(bad.out, /нет перевода: .*«Новая кнопка без перевода»/);
assert.match(bad.out, /не через словарь: .*«Голый текст»/);
});
test("Scenario: Все тексты веба и бота — через словарь", async () => {
const r = await check([]);
assert.equal(r.code, 0, r.out.split("\n").slice(-30).join("\n"));
});
});