200 lines
8.7 KiB
TypeScript
200 lines
8.7 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||
import type { FastifyInstance } from "fastify";
|
||
import { buildApp } from "../src/app.ts";
|
||
import { LlmUnavailableError } from "../src/modules/audits/llm.ts";
|
||
import { mockLlm } from "../src/modules/audits/mock-llm.ts";
|
||
import { mockChannel } from "../src/modules/content/mock-channel.ts";
|
||
import { createTestDb } from "./helpers/db.ts";
|
||
|
||
const BASE = "https://clt.example";
|
||
const ADMIN = { "content-type": "application/json", authorization: "Bearer mock-admin-token" };
|
||
let clock = 0;
|
||
let app: FastifyInstance;
|
||
let db: Awaited<ReturnType<typeof createTestDb>>;
|
||
let channel: ReturnType<typeof mockChannel>;
|
||
|
||
async function setup(extra: Record<string, unknown> = {}) {
|
||
clock = Date.parse("2026-11-10T10:00:00Z");
|
||
db = await createTestDb();
|
||
channel = mockChannel();
|
||
app = await buildApp({
|
||
db,
|
||
accounts: { now: () => clock },
|
||
content: { baseUrl: BASE, adminToken: "mock-admin-token", sweepIntervalMs: 0, telegram: { client: channel, chatId: "@clt_channel" }, ...extra },
|
||
});
|
||
}
|
||
beforeEach(() => setup());
|
||
afterEach(async () => app.close());
|
||
|
||
const post = (o: Record<string, unknown> = {}) => ({
|
||
slug: "cold-tone",
|
||
title: "Разбор ошибки: холодный тон",
|
||
summary: "Почему клиент уходит после сухого ответа",
|
||
body: "Первый абзац.\n\nВторой абзац.",
|
||
topic: "mistakes",
|
||
ctaProduct: "express-audit",
|
||
...o,
|
||
});
|
||
const create = (o: Record<string, unknown> = {}) => app.inject({ method: "POST", url: "/api/admin/content/posts", headers: ADMIN, payload: post(o) });
|
||
const approve = (id: string) => app.inject({ method: "POST", url: `/api/admin/content/posts/${id}/approve`, headers: { authorization: ADMIN.authorization } });
|
||
async function publish(o: Record<string, unknown> = {}) {
|
||
const pid = (await create(o)).json().id as string;
|
||
await approve(pid);
|
||
clock += 1000;
|
||
await app.publishContent();
|
||
return pid;
|
||
}
|
||
|
||
describe("Requirement: Модерация и расписание публикаций", () => {
|
||
it("Scenario: Публикация одобренного поста по расписанию", async () => {
|
||
const id = (await create({ publishAt: "2026-11-10T09:00:00Z" })).json().id as string;
|
||
await approve(id);
|
||
expect(await app.publishContent()).toEqual({ published: 1, sent: 1 });
|
||
const status = (await db.query<{ status: string }>("SELECT status FROM content_posts WHERE id = $1", [id])).rows[0]?.status;
|
||
expect(status).toBe("published");
|
||
expect((await app.inject({ url: "/blog" })).body).toContain("Разбор ошибки: холодный тон");
|
||
});
|
||
|
||
it("Scenario: Неодобренный пост не публикуется", async () => {
|
||
await create({ publishAt: "2026-11-10T09:00:00Z" });
|
||
expect((await app.publishContent()).published).toBe(0);
|
||
expect((await app.inject({ url: "/blog" })).body).not.toContain("холодный тон");
|
||
});
|
||
|
||
it("Scenario: Админ-API без токена", async () => {
|
||
const res = await app.inject({ method: "POST", url: "/api/admin/content/posts", payload: post() });
|
||
expect(res.statusCode).toBe(401);
|
||
expect(res.json()).toEqual({ error: "unauthenticated" });
|
||
});
|
||
|
||
it("Scenario: Автоодобрение по решению PM", async () => {
|
||
await app.close();
|
||
await setup({ autoApprove: true });
|
||
expect((await create()).json().status).toBe("approved");
|
||
});
|
||
|
||
it("Scenario: Автоодобрение выключено по умолчанию", async () => {
|
||
expect((await create()).json().status).toBe("draft");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Ссылки только на собственные домены", () => {
|
||
it("Scenario: Чужая ссылка отклонена", async () => {
|
||
const res = await create({ body: "Смотрите https://evil.example/x" });
|
||
expect(res.statusCode).toBe(422);
|
||
expect(res.json()).toEqual({ error: "foreign_link" });
|
||
});
|
||
|
||
it("Scenario: Своя ссылка допустима", async () => {
|
||
expect((await create({ body: `Подробнее ${BASE}/legal/offer` })).statusCode).toBe(201);
|
||
});
|
||
|
||
it("Scenario: Неизвестный продукт", async () => {
|
||
const res = await create({ ctaProduct: "nope" });
|
||
expect(res.statusCode).toBe(422);
|
||
expect(res.json()).toEqual({ error: "unknown_product" });
|
||
});
|
||
|
||
it("Scenario: CTA с UTM", async () => {
|
||
await publish();
|
||
const html = (await app.inject({ url: "/blog/cold-tone" })).body;
|
||
expect(html).toContain(`${BASE}/?utm_source=blog&utm_medium=content&utm_campaign=cold-tone#express-audit`);
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Блог и SEO", () => {
|
||
it("Scenario: Sitemap", async () => {
|
||
await publish();
|
||
await create({ slug: "draft-one" });
|
||
const xml = (await app.inject({ url: "/sitemap.xml" })).body;
|
||
expect(xml).toContain(`${BASE}/blog/cold-tone`);
|
||
expect(xml).not.toContain("draft-one");
|
||
});
|
||
|
||
it("Scenario: Мета-теги", async () => {
|
||
await publish();
|
||
const html = (await app.inject({ url: "/blog/cold-tone" })).body;
|
||
expect(html).toContain('<meta name="description" content="Почему клиент уходит после сухого ответа">');
|
||
expect(html).toContain('property="og:title"');
|
||
expect(html).toContain(`<link rel="canonical" href="${BASE}/blog/cold-tone">`);
|
||
});
|
||
|
||
it("Scenario: Черновик недоступен", async () => {
|
||
await create();
|
||
expect((await app.inject({ url: "/blog/cold-tone" })).statusCode).toBe(404);
|
||
});
|
||
|
||
it("Scenario: Экранирование", async () => {
|
||
await publish({ title: "<script>x</script>" });
|
||
const html = (await app.inject({ url: "/blog" })).body;
|
||
expect(html).not.toContain("<script>x");
|
||
expect(html).toContain("<script>x");
|
||
});
|
||
|
||
it("Scenario: QR", async () => {
|
||
await publish();
|
||
const res = await app.inject({ url: "/blog/cold-tone/qr.svg" });
|
||
expect(res.headers["content-type"]).toContain("image/svg+xml");
|
||
expect(res.body).toContain("<svg");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Автопостинг в Telegram", () => {
|
||
it("Scenario: Пост ушёл в канал", async () => {
|
||
await publish();
|
||
expect(channel.sent).toHaveLength(1);
|
||
expect(channel.sent[0]?.chatId).toBe("@clt_channel");
|
||
expect(channel.sent[0]?.text).toContain("Разбор ошибки: холодный тон");
|
||
expect(channel.sent[0]?.text).toContain("utm_source=telegram");
|
||
});
|
||
|
||
it("Scenario: Сбой Telegram", async () => {
|
||
channel.failing = true;
|
||
const id = await publish();
|
||
const tg = async () => (await db.query<{ tg_status: string; status: string }>("SELECT tg_status, status FROM content_posts WHERE id = $1", [id])).rows[0];
|
||
expect(await tg()).toEqual({ tg_status: "pending", status: "published" });
|
||
await app.publishContent();
|
||
await app.publishContent();
|
||
expect((await tg())?.tg_status).toBe("failed");
|
||
expect(channel.sent).toHaveLength(0);
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Генерация черновика", () => {
|
||
const gen = (payload: Record<string, unknown>) => app.inject({ method: "POST", url: "/api/admin/content/generate", headers: ADMIN, payload });
|
||
|
||
it("Scenario: Черновик из материала", async () => {
|
||
await app.close();
|
||
const llm = mockLlm({ title: "Эмпатия в первой фразе", summary: "Коротко", body: "Текст поста" });
|
||
await setup({ llm });
|
||
const res = await gen({ material: "Конспект урока про эмпатию", topic: "mistakes", slug: "empathy-first" });
|
||
expect(res.statusCode).toBe(201);
|
||
expect(res.json().status).toBe("draft");
|
||
expect(llm.calls).toHaveLength(1);
|
||
});
|
||
|
||
it("Scenario: Сбой LLM", async () => {
|
||
await app.close();
|
||
await setup({ llm: mockLlm(new LlmUnavailableError()) });
|
||
const res = await gen({ material: "Конспект", topic: "case" });
|
||
expect(res.statusCode).toBe(503);
|
||
expect(res.json()).toEqual({ error: "llm_unavailable" });
|
||
expect((await db.query("SELECT 1 FROM content_posts")).rows).toHaveLength(0);
|
||
});
|
||
|
||
it("Scenario: ПДн в материале не уходят в LLM", async () => {
|
||
await app.close();
|
||
const llm = mockLlm({ title: "t", summary: "s", body: "b" });
|
||
await setup({ llm });
|
||
await gen({ material: "Клиент звонил с почты anna@example.com", topic: "case" });
|
||
expect(llm.calls.every((c) => !c.user.includes("anna@example.com"))).toBe(true);
|
||
});
|
||
|
||
it("Scenario: LLM вернула чужую ссылку", async () => {
|
||
await app.close();
|
||
await setup({ llm: mockLlm({ title: "t", summary: "s", body: "см. https://evil.example" }) });
|
||
const res = await gen({ material: "Конспект", topic: "case" });
|
||
expect(res.statusCode).toBe(502);
|
||
});
|
||
});
|