freetravel/test/notifier.test.ts
Peppa 39d6884f34
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 3с
peppa/test test: success за 1с
peppa/build build: success за 1с
ci / checks (pull_request) Successful in 24s
deploy / deploy (pull_request) Successful in 14s
FRTVL-35: итог подтверждения привязки Телеграма с понятной причиной
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 03:36:06 +05:00

369 lines
18 KiB
TypeScript
Raw Permalink 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 { describe, expect, it } from "vitest";
import { emptyCatalog, type Internship } from "../src/domain/internship.js";
import { Notifier } from "../src/notify/notifier.js";
import { formatMessages, MAX_MESSAGE_LENGTH } from "../src/notify/message.js";
import { type NotificationSettings, type SettingsStore, emptySettings } from "../src/notify/settingsStore.js";
import { BotApiTelegramClient, MockTelegramClient } from "../src/notify/telegram.js";
import type { SearchProvider } from "../src/search/provider.js";
import { SearchService } from "../src/search/searchService.js";
import { MemoryStore, raw } from "./helpers.js";
class MemorySettings implements SettingsStore {
constructor(public value: NotificationSettings = emptySettings()) {}
async load() {
return structuredClone(this.value);
}
async save(value: NotificationSettings) {
this.value = structuredClone(value);
}
}
const NOW = new Date("2026-11-14T12:00:00.000Z");
function setup(
candidates: unknown[] | Error,
opts: { settings?: Partial<NotificationSettings>; catalog?: MemoryStore; clock?: () => Date } = {},
) {
const provider: SearchProvider = {
name: "test",
async search() {
if (candidates instanceof Error) throw candidates;
return candidates;
},
};
const catalog = opts.catalog ?? new MemoryStore();
const settings = new MemorySettings({ ...emptySettings(), chatId: 555, enabled: true, ...opts.settings });
const telegram = new MockTelegramClient();
const clock = opts.clock ?? (() => NOW);
const search = new SearchService({ store: catalog, provider, now: clock });
const notifier = new Notifier({ settings, catalog, search, telegram, now: clock });
return { notifier, settings, catalog, telegram, search };
}
const A = raw({ title: "Старая A", sourceUrl: "https://example.org/a" });
const B = raw({
title: "Новая B",
sourceUrl: "https://example.org/b",
adjacent: true,
confidence: "low",
deadline: "2027-02-01",
country: "Турция",
language: "not_required",
languageDetails: "",
coveredExpenses: "Жильё, питание",
});
describe("Requirement: Уведомление только о новых", () => {
it("Scenario: Новые стажировки — одно сообщение с B, без показанной A", async () => {
const { notifier, telegram, settings, catalog } = setup([A, B]);
await catalog.save({
...emptyCatalog(),
internships: [
{ ...raw(A), id: "example.org/a", sourceUrl: A.sourceUrl!, firstSeenAt: "x", checkedAt: "x", addedInRun: "r0", shownAt: "x" } as Internship,
],
});
await notifier.runScheduled();
expect(telegram.sent).toHaveLength(1);
const text = telegram.sent[0]!.text;
expect(telegram.sent[0]!.chatId).toBe(555);
expect(text).toContain("Новая B (смежная)");
expect(text).toContain("Страна: Турция");
expect(text).toContain("Язык: не требуется");
expect(text).toContain("Оплачивается: Жильё, питание");
expect(text).toContain("Срок подачи: 2027-02-01");
expect(text).toContain("Уверенность: низкая");
expect(text).toContain("https://example.org/b");
expect(text).not.toContain("Старая A");
expect(settings.value.lastRun).toMatchObject({ status: "sent", sent: 1 });
});
it("Scenario: Ничего нового — сообщения нет, итог «новых не найдено», повтор не шлёт", async () => {
const { notifier, telegram, settings } = setup([B]);
await notifier.runScheduled();
expect(telegram.sent).toHaveLength(1);
await notifier.runScheduled();
expect(telegram.sent).toHaveLength(1);
expect(settings.value.lastRun).toMatchObject({ status: "nothing_new", sent: 0 });
});
it("Scenario: Найдено ручным поиском — не приходит", async () => {
const { notifier, telegram, search } = setup([B]);
await search.start("manual");
await notifier.runScheduled();
expect(telegram.sent).toHaveLength(0);
});
it("Scenario: Срок подачи прошёл → не приходит и не показана; Срок продлён → приходит как новая", async () => {
let deadline = "2020-01-01";
const provider: SearchProvider = { name: "t", async search() { return [{ ...B, deadline }]; } };
const catalog = new MemoryStore();
const settings = new MemorySettings({ ...emptySettings(), chatId: 1, enabled: true });
const telegram = new MockTelegramClient();
const search = new SearchService({ store: catalog, provider, now: () => NOW });
const notifier = new Notifier({ settings, catalog, search, telegram, now: () => NOW });
await notifier.runScheduled();
expect(telegram.sent).toHaveLength(0);
expect(catalog.catalog.internships[0]!.shownAt).toBeNull();
deadline = "2099-01-01";
await notifier.runScheduled();
expect(telegram.sent).toHaveLength(1);
expect(telegram.sent[0]!.text).toContain("Срок подачи: 2099-01-01");
});
it("Scenario: Срок не указан", async () => {
const { notifier, telegram } = setup([{ ...B, deadline: null }]);
await notifier.runScheduled();
expect(telegram.sent[0]!.text).toContain("Срок подачи: срок не указан");
});
it("длинный список делится на несколько сообщений в пределах лимита", () => {
const items = Array.from({ length: 60 }, (_, i) => ({
...raw({ title: `Стажировка ${i}`, rationale: "x" }),
id: String(i),
sourceUrl: `https://example.org/${i}`,
firstSeenAt: "x",
checkedAt: "x",
addedInRun: "r",
shownAt: null,
})) as Internship[];
const parts = formatMessages(items);
expect(parts.length).toBeGreaterThan(1);
expect(parts.every((p) => p.length <= MAX_MESSAGE_LENGTH)).toBe(true);
expect(parts.join("\n")).toContain("Стажировка 59");
});
});
describe("Requirement: Сбои", () => {
it("Scenario: Источник недоступен — ничего не отправлено, итог «ошибка»", async () => {
const { notifier, telegram, settings } = setup(new Error("Сервис поиска недоступен"));
await notifier.runScheduled();
expect(telegram.sent).toHaveLength(0);
expect(settings.value.lastRun).toMatchObject({ status: "error", error: "Поиск: Сервис поиска недоступен" });
});
it("Scenario: Ошибка отправки — итог «ошибка», карточка придёт в следующий раз", async () => {
const { notifier, telegram, settings, catalog } = setup([B]);
telegram.failSend = true;
await notifier.runScheduled();
expect(settings.value.lastRun?.status).toBe("error");
expect(catalog.catalog.internships[0]!.shownAt).toBeNull();
telegram.failSend = false;
await notifier.runScheduled();
expect(telegram.sent).toHaveLength(1);
});
});
describe("Requirement: Ежесуточный запуск", () => {
const hoursAgo = (h: number) => new Date(NOW.getTime() - h * 3600_000).toISOString();
it("Scenario: Запуск по расписанию — прошло 25 часов", async () => {
const { notifier, telegram } = setup([B], { settings: { lastRun: { at: hoursAgo(25), status: "nothing_new", sent: 0 } } });
expect(await notifier.tick()).toBe(true);
expect(telegram.sent).toHaveLength(1);
});
it("Scenario: Запуск был недавно / после перезапуска сервиса — поиск не стартует", async () => {
const { notifier, telegram } = setup([B], { settings: { lastRun: { at: hoursAgo(3), status: "sent", sent: 1 } } });
expect(await notifier.tick()).toBe(false);
expect(telegram.sent).toHaveLength(0);
});
it("выключено или не привязано — не запускается", async () => {
expect(await setup([B], { settings: { enabled: false } }).notifier.tick()).toBe(false);
expect(await setup([B], { settings: { chatId: null } }).notifier.tick()).toBe(false);
});
it("идущий ручной поиск — тик пропускается", async () => {
const { notifier, search } = setup([B]);
const running = search.start("manual");
expect(await notifier.runScheduled()).toBe(false);
await running;
});
});
describe("Requirement: Привязка Телеграма и включение регулярного поиска", () => {
it("Scenario: Привязка через бота", async () => {
const { notifier, settings, telegram } = setup([], { settings: { chatId: null, enabled: false } });
const url = await notifier.startLink();
const code = url.split("start=")[1]!;
expect(url).toContain("https://t.me/mock_freetravel_bot?start=");
telegram.receive(555, `/start ${code}`);
expect(await notifier.pollLink()).toBe(true);
expect(settings.value.chatId).toBe(555);
expect(settings.value.linkCode).toBeNull();
expect((await notifier.view()).linked).toBe(true);
expect(telegram.sent).toEqual([{ chatId: 555, text: expect.stringContaining("привязан") }]);
});
it("Scenario: Неверный код или код устарел — привязки нет", async () => {
let now = NOW;
const { notifier, settings, telegram } = setup([], {
settings: { chatId: null, enabled: false },
clock: () => now,
});
const code = (await notifier.startLink()).split("start=")[1]!;
telegram.receive(7, "/start wrong");
expect(await notifier.pollLink()).toBe(false);
telegram.receive(8, `/start ${code}`);
now = new Date(NOW.getTime() + 16 * 60_000);
expect(await notifier.pollLink()).toBe(false);
expect(settings.value.chatId).toBeNull();
});
it("Scenario: Подтверждение привязки — привязано, тестовое сообщение, отвязка", async () => {
const { notifier, settings, telegram } = setup([], { settings: { chatId: null, enabled: false } });
const code = (await notifier.startLink()).split("start=")[1]!;
telegram.receive(555, `/start ${code}`);
expect(await notifier.checkLink()).toBe("linked");
expect(telegram.sent).toHaveLength(1);
expect((await notifier.view()).linked).toBe(true);
await notifier.unlink();
expect((await notifier.view()).linked).toBe(false);
expect(settings.value.chatId).toBeNull();
});
it("Scenario: Подтверждение без кода от бота / с неверным кодом / с устаревшим кодом", async () => {
let now = NOW;
const { notifier, telegram } = setup([], { settings: { chatId: null, enabled: false }, clock: () => now });
expect(await notifier.checkLink()).toBe("expired");
await notifier.startLink();
expect(await notifier.checkLink()).toBe("not_received");
telegram.receive(7, "/start wrong");
expect(await notifier.checkLink()).toBe("wrong_code");
now = new Date(NOW.getTime() + 16 * 60_000);
expect(await notifier.checkLink()).toBe("expired");
});
it("Scenario: Включение без привязки", async () => {
const { notifier, settings } = setup([], { settings: { chatId: null, enabled: false } });
await expect(notifier.setEnabled(true)).rejects.toThrow("Сначала привяжите Телеграм");
expect(settings.value.enabled).toBe(false);
});
it("отвязка выключает регулярный поиск", async () => {
const { notifier, settings } = setup([]);
await notifier.unlink();
expect(settings.value).toMatchObject({ chatId: null, enabled: false });
});
});
describe("BotApiTelegramClient", () => {
it("sendMessage шлёт запрос в Bot API, ошибка API не содержит токен", async () => {
const calls: Array<{ url: string; body: unknown }> = [];
const ok = new BotApiTelegramClient("TOKEN123", "bot", (async (url: string, init: RequestInit) => {
calls.push({ url, body: JSON.parse(init.body as string) });
return new Response(JSON.stringify({ ok: true, result: true }));
}) as typeof fetch);
await ok.sendMessage(5, "привет");
expect(calls[0]!.url).toBe("https://api.telegram.org/botTOKEN123/sendMessage");
expect(calls[0]!.body).toMatchObject({ chat_id: 5, text: "привет" });
const bad = new BotApiTelegramClient("TOKEN123", "bot", (async () => {
throw new Error("connect https://api.telegram.org/botTOKEN123/sendMessage");
}) as typeof fetch);
await expect(bad.sendMessage(5, "x")).rejects.toThrow(/^Telegram недоступен \(sendMessage\)$/);
});
it("getUpdates разбирает сообщения", async () => {
const client = new BotApiTelegramClient("T", "bot", (async () =>
new Response(
JSON.stringify({ ok: true, result: [{ update_id: 9, message: { chat: { id: 3 }, text: "/start abc" } }, { update_id: 10 }] }),
)) as typeof fetch);
expect(await client.getUpdates(0)).toEqual([{ updateId: 9, chatId: 3, text: "/start abc" }]);
});
});
describe("BotApiTelegramClient", () => {
it("Scenario: Ключ бота не попадает в текст ошибки", async () => {
const { BotApiTelegramClient } = await import("../src/notify/telegram.js");
const client = new BotApiTelegramClient("SECRET:token", "real_bot", async () => {
throw new Error("fetch failed https://api.telegram.org/botSECRET:token/sendMessage");
});
const error = await client.sendMessage(1, "hi").catch((e: Error) => e);
expect((error as Error).message).not.toContain("SECRET");
});
});
describe("Requirement: Привязка с настоящим ботом (FRTVL-13)", () => {
const meFetch = (async () =>
new Response(JSON.stringify({ ok: true, result: { username: "nternships_bot" } }))) as typeof fetch;
it("Scenario: имя бота берётся у Телеграма, даже если в настройках лежит ключ", async () => {
const client = new BotApiTelegramClient("1:SECRET", "1:SECRET", meFetch);
expect(client.botUsername).toBe("");
expect(await client.resolveUsername()).toBe(true);
expect(client.botUsername).toBe("nternships_bot");
});
it("Scenario: ключ не подошёл — имени нет, привязка отказывает понятным текстом", async () => {
const client = new BotApiTelegramClient("bad", "", (async () =>
new Response(JSON.stringify({ ok: false, description: "Unauthorized" }), { status: 401 })) as typeof fetch);
expect(await client.resolveUsername()).toBe(false);
const settings = new MemorySettings();
const catalog = new MemoryStore();
const search = new SearchService({ store: catalog, provider: { name: "t", async search() { return []; } } });
const notifier = new Notifier({ settings, catalog, search, telegram: client });
await expect(notifier.startLink()).rejects.toThrow(/Бот не настроен/);
});
it("Scenario: ссылка ведёт на настоящего бота", async () => {
const client = new BotApiTelegramClient("1:S", "", meFetch);
await client.resolveUsername();
const settings = new MemorySettings();
const catalog = new MemoryStore();
const search = new SearchService({ store: catalog, provider: { name: "t", async search() { return []; } } });
const notifier = new Notifier({ settings, catalog, search, telegram: client });
expect(await notifier.startLink()).toMatch(/^https:\/\/t\.me\/nternships_bot\?start=/);
});
});
describe("Requirement: Привязка-пример не переносится на настоящего бота (FRTVL-16)", () => {
function withBot(value: Partial<NotificationSettings>) {
const settings = new MemorySettings({ ...emptySettings(), ...value });
const catalog = new MemoryStore();
const provider: SearchProvider = { name: "test", search: async () => [] };
const search = new SearchService({ store: catalog, provider, now: () => NOW });
const telegram = new BotApiTelegramClient("1:x", "nternships_bot", (async () => new Response("{}")) as typeof fetch);
return { settings, notifier: new Notifier({ settings, catalog, search, telegram, now: () => NOW }) };
}
it("Scenario: Включили настоящего бота после примера", async () => {
const { notifier, settings } = withBot({ chatId: 1, linkedVia: "mock", enabled: true });
expect(await notifier.dropMockLink()).toBe(true);
const view = await notifier.view();
expect(view.linked).toBe(false);
expect(view.enabled).toBe(false);
expect(settings.value.linkedVia).toBeUndefined();
});
it("старые данные без отметки: chatId 1 — пример, сбрасывается", async () => {
const { notifier } = withBot({ chatId: 1, enabled: true });
expect(await notifier.dropMockLink()).toBe(true);
expect((await notifier.view()).linked).toBe(false);
});
it("Scenario: Настоящая привязка сохраняется", async () => {
const { notifier } = withBot({ chatId: 777, linkedVia: "telegram", enabled: true });
expect(await notifier.dropMockLink()).toBe(false);
const view = await notifier.view();
expect(view.linked).toBe(true);
expect(view.enabled).toBe(true);
});
it("на примере привязка-пример не сбрасывается и помечается как пример", async () => {
const { notifier, settings } = setup([], { settings: { chatId: null, enabled: false } });
await notifier.startLink();
await notifier.mockConfirmLink();
expect(settings.value.linkedVia).toBe("mock");
expect(await notifier.dropMockLink()).toBe(false);
});
it("причина неработающего бота попадает в настройки", async () => {
const settings = new MemorySettings();
const catalog = new MemoryStore();
const search = new SearchService({ store: catalog, provider: { name: "t", search: async () => [] } });
const notifier = new Notifier({ settings, catalog, search, telegram: new MockTelegramClient(), telegramProblem: "no_token" });
expect((await notifier.view()).telegramProblem).toBe("no_token");
});
});