84 lines
4.7 KiB
JavaScript
84 lines
4.7 KiB
JavaScript
import test from "node:test";
|
||
import assert from "node:assert/strict";
|
||
import fs from "node:fs";
|
||
import os from "node:os";
|
||
import path from "node:path";
|
||
import { createApp } from "../src/server.js";
|
||
import { mockTelegram } from "../src/telegram.js";
|
||
import { buildSummary } from "../src/metrics.js";
|
||
|
||
async function withServer(telegram, fn, dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm16-"))) {
|
||
const srv = createApp({ file: path.join(dir, "plan.json"), telegram }).listen(0);
|
||
await new Promise((r) => srv.once("listening", r));
|
||
const base = `http://127.0.0.1:${srv.address().port}`;
|
||
const call = async (m, u, b) => {
|
||
const r = await fetch(base + u, { method: m, headers: { "content-type": "application/json" }, body: b && JSON.stringify(b) });
|
||
return [r.status, await r.json()];
|
||
};
|
||
try { await fn(call); } finally { srv.close(); }
|
||
}
|
||
const HEADS = ["Сделано", "Результат", "Возможность", "Риск", "Нужно решение", "Следующий шаг"];
|
||
|
||
test("Сценарий: сохранение значения и видно после перезапуска", async () => {
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm16-"));
|
||
await withServer(mockTelegram(), async (call) => {
|
||
assert.equal((await call("POST", "/api/metrics", { name: "Подписчики Telegram", value: "120", date: "2026-11-15" }))[0], 200);
|
||
}, dir);
|
||
await withServer(mockTelegram(), async (call) => {
|
||
const [, d] = await call("GET", "/api/metrics");
|
||
assert.equal(d.metrics[0].entries[0].value, 120);
|
||
}, dir);
|
||
});
|
||
|
||
test("Сценарий: шестой показатель и неверные данные отклоняются", () => withServer(mockTelegram(), async (call) => {
|
||
for (let i = 1; i <= 5; i++) assert.equal((await call("POST", "/api/metrics", { name: "M" + i, value: i, date: "2026-11-15" }))[0], 200);
|
||
assert.equal((await call("POST", "/api/metrics", { name: "M6", value: 1, date: "2026-11-15" }))[0], 400);
|
||
assert.equal((await call("POST", "/api/metrics", { name: "M1", value: "abc", date: "2026-11-15" }))[0], 400);
|
||
assert.equal((await call("POST", "/api/metrics", { name: "M1", value: 2, date: "2026-13-01" }))[0], 400);
|
||
}));
|
||
|
||
test("Сценарий: недельная сводка с изменением, шесть разделов по порядку", () => {
|
||
const metrics = [{ name: "Подписчики", entries: [{ date: "2026-11-08", value: 100 }, { date: "2026-11-15", value: 120 }] }];
|
||
const t = buildSummary({ metrics, period: "week", asOf: "2026-11-15", sections: { done: "Пост" } });
|
||
assert.match(t.split("\n")[0], /неделя: 2026-11-08 → 2026-11-15/);
|
||
assert.match(t, /Подписчики: 120 — было 100 \(2026-11-08\), \+20/);
|
||
const pos = HEADS.map((h) => t.indexOf(h + ":"));
|
||
assert.deepEqual([...pos].sort((a, b) => a - b), pos);
|
||
assert.ok(pos.every((p) => p >= 0));
|
||
});
|
||
|
||
test("Сценарий: одна запись и пустые разделы", () => {
|
||
const t = buildSummary({ metrics: [{ name: "Обращения", entries: [{ date: "2026-11-15", value: 3 }] }], period: "day", asOf: "2026-11-15" });
|
||
assert.match(t, /первое значение/);
|
||
assert.equal(t.match(/Нет данных/g).length, 5);
|
||
});
|
||
|
||
test("Сценарий: показатель без записей — «нет данных»", () => {
|
||
const t = buildSummary({ metrics: [{ name: "Охват", entries: [] }], period: "day", asOf: "2026-11-15" });
|
||
assert.match(t, /Охват: нет данных/);
|
||
});
|
||
|
||
test("Сценарий: отправка одним сообщением", () => withServer(mockTelegram(), async () => {}).then(async () => {
|
||
const tg = mockTelegram();
|
||
await withServer(tg, async (call) => {
|
||
const [c, d] = await call("POST", "/api/summary/send", { period: "day", date: "2026-11-15" });
|
||
assert.equal(c, 200);
|
||
assert.equal(tg.sent.length, 1);
|
||
assert.equal(tg.sent[0].text, d.text);
|
||
});
|
||
}));
|
||
|
||
test("Сценарий: Telegram недоступен или не подключён — текст не теряется", async () => {
|
||
await withServer(mockTelegram({ fail: "boom" }), async (call) => {
|
||
const [c, d] = await call("POST", "/api/summary/send", { period: "week", date: "2026-11-15" });
|
||
assert.equal(c, 502); assert.match(d.error, /Не удалось отправить/); assert.match(d.text, /Сводка по бренду/);
|
||
});
|
||
await withServer({ connected: () => false, send: async () => {} }, async (call) => {
|
||
const [c, d] = await call("POST", "/api/summary/send", { period: "day" });
|
||
assert.equal(c, 502); assert.ok(d.text);
|
||
});
|
||
await withServer(mockTelegram(), async (call) => {
|
||
assert.equal((await call("POST", "/api/summary/preview", { period: "year" }))[0], 400);
|
||
});
|
||
});
|