freetravel/test/server.test.ts
Peppa 278b7e48b9
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 2с
peppa/test test: success за 2с
peppa/build build: success за 2с
ci / checks (pull_request) Successful in 24s
deploy / deploy (pull_request) Successful in 14s
FRTVL-36: подтверждение до начала привязки объясняет, что сделать сначала
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 04:12:10 +05:00

147 lines
7.2 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 { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { emptyCatalog } from "../src/domain/internship.js";
import { mockSearchProvider } from "../src/search/mockSearchProvider.js";
import { SearchService } from "../src/search/searchService.js";
import { buildServer } from "../src/server.js";
import { JsonCatalogStore } from "../src/store/catalogStore.js";
import { MemoryStore } from "./helpers.js";
async function setup(searchToken?: string, delayMs = 0) {
const store = new MemoryStore();
const search = new SearchService({ store, provider: mockSearchProvider({ delayMs }) });
const app = await buildServer({ store, search, searchToken, providerName: "mock" });
return { app, store, search };
}
describe("HTTP API", () => {
it("GET /healthz → 200", async () => {
const { app } = await setup();
const response = await app.inject({ method: "GET", url: "/healthz" });
expect(response.statusCode).toBe(200);
});
it("GET / отдаёт страницу", async () => {
const { app } = await setup();
const response = await app.inject({ method: "GET", url: "/" });
expect(response.statusCode).toBe(200);
expect(response.body).toContain("Найти новые");
});
it("Scenario: Запуск без токена → 401, поиск не начинается", async () => {
const { app, search } = await setup("s3cret");
const response = await app.inject({ method: "POST", url: "/api/search" });
expect(response.statusCode).toBe(401);
expect(response.json()).toEqual({ error: "Неверный код доступа" });
expect(search.running).toBe(false);
});
it("Scenario: Запуск с верным токеном → 202", async () => {
const { app, search } = await setup("s3cret", 20);
const response = await app.inject({
method: "POST",
url: "/api/search",
headers: { authorization: "Bearer s3cret" },
});
expect(response.statusCode).toBe(202);
expect(search.running).toBe(true);
const status = await app.inject({ method: "GET", url: "/api/search/status" });
expect(status.json()).toMatchObject({ state: "running", provider: "mock", tokenRequired: true });
});
it("повторный запуск во время поиска → 409 «Поиск уже идёт»", async () => {
const { app } = await setup(undefined, 50);
await app.inject({ method: "POST", url: "/api/search" });
const second = await app.inject({ method: "POST", url: "/api/search" });
expect(second.statusCode).toBe(409);
expect(second.json()).toEqual({ error: "Поиск уже идёт" });
});
it("после поиска GET /api/internships отдаёт новые карточки и отчёт", async () => {
const { app, search } = await setup();
await app.inject({ method: "POST", url: "/api/search" });
while (search.running) await new Promise((resolve) => setTimeout(resolve, 5));
const body = (await app.inject({ method: "GET", url: "/api/internships" })).json();
expect(body.internships).toHaveLength(3);
expect(body.internships.every((card: { isNew: boolean }) => card.isNew)).toBe(true);
expect(body.lastRun).toMatchObject({ status: "ok", found: 3, added: 3 });
});
});
describe("JsonCatalogStore", () => {
let dir = "";
afterEach(async () => {
if (dir) await rm(dir, { recursive: true, force: true });
});
it("возвращает пустой каталог без файла и читает записанное", async () => {
dir = await mkdtemp(path.join(tmpdir(), "frtvl-"));
const store = new JsonCatalogStore(path.join(dir, "nested"));
expect(await store.load()).toEqual(emptyCatalog());
const catalog = { ...emptyCatalog(), lastSuccessfulRunId: "run-1" };
await store.save(catalog);
expect(await store.load()).toEqual(catalog);
});
});
describe("Настройки уведомлений (API)", () => {
async function withNotifier(token?: string) {
const { MockTelegramClient } = await import("../src/notify/telegram.js");
const { Notifier } = await import("../src/notify/notifier.js");
const { emptySettings } = await import("../src/notify/settingsStore.js");
const store = new MemoryStore();
const search = new SearchService({ store, provider: mockSearchProvider() });
let value = emptySettings();
const settings = {
load: async () => structuredClone(value),
save: async (v: typeof value) => {
value = structuredClone(v);
},
};
const notifier = new Notifier({ settings, catalog: store, search, telegram: new MockTelegramClient() });
const app = await buildServer({ store, search, notifier, searchToken: token });
return { app };
}
const auth = { authorization: "Bearer s3cret" };
it("Scenario: Включение без привязки → 409, затем привязка и включение", async () => {
const { app } = await withNotifier("s3cret");
const rejected = await app.inject({ method: "PUT", url: "/api/settings", headers: auth, payload: { enabled: true } });
expect(rejected.statusCode).toBe(409);
expect(rejected.json()).toEqual({ error: "Сначала привяжите Телеграм" });
const link = await app.inject({ method: "POST", url: "/api/settings/telegram/link", headers: auth });
expect(link.json().url).toContain("t.me/");
await app.inject({ method: "POST", url: "/api/settings/telegram/mock-confirm", headers: auth });
const ok = await app.inject({ method: "PUT", url: "/api/settings", headers: auth, payload: { enabled: true } });
expect(ok.json()).toMatchObject({ enabled: true, linked: true });
});
it("Scenario: Подтверждение привязки без кода от бота — понятный итог", async () => {
const { app } = await withNotifier("s3cret");
const notStarted = await app.inject({ method: "POST", url: "/api/settings/telegram/confirm", headers: auth });
expect(notStarted.json()).toMatchObject({ result: "not_started", settings: { linked: false } });
await app.inject({ method: "POST", url: "/api/settings/telegram/link", headers: auth });
const waiting = await app.inject({ method: "POST", url: "/api/settings/telegram/confirm", headers: auth });
expect(waiting.json().result).toBe("not_received");
const noAuth = await app.inject({ method: "POST", url: "/api/settings/telegram/confirm" });
expect(noAuth.statusCode).toBe(401);
});
it("изменение настроек без токена → 401, чтение открыто", async () => {
const { app } = await withNotifier("s3cret");
const write = await app.inject({ method: "PUT", url: "/api/settings", payload: { enabled: false } });
expect(write.statusCode).toBe(401);
const read = await app.inject({ method: "GET", url: "/api/settings" });
expect(read.json()).toMatchObject({ enabled: false, linked: false, lastRun: null });
});
it("неверное тело → 400", async () => {
const { app } = await withNotifier();
const bad = await app.inject({ method: "PUT", url: "/api/settings", payload: { enabled: "yes" } });
expect(bad.statusCode).toBe(400);
});
});