262 lines
12 KiB
TypeScript
262 lines
12 KiB
TypeScript
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 } = 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");
|
||
});
|
||
});
|