brendmanager/test/publisher.test.js
Peppa 997a862f74
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 0с
ci / checks (pull_request) Successful in 3s
deploy / deploy (pull_request) Successful in 2s
BRM-14: публикация в Telegram по режиму B: лимит, журнал, остановка
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 14:53:17 +05:00

93 lines
4.6 KiB
JavaScript
Raw 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 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 { createPublisher } from "../src/publisher.js";
import { mockTelegram, createTelegram } from "../src/telegram.js";
import { createApp } from "../src/publish-server.js";
const tmp = () => path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm14-")), "s.json");
const setup = (opts) => { const tg = mockTelegram(opts); let t = 1e12; const p = createPublisher({ file: tmp(), channels: { telegram: tg }, now: () => t }); return { tg, p, tick: (ms) => (t += ms) }; };
const ok = { channel: "telegram", text: "Привет", approvedBy: "tatiana" };
test("Сценарий: разрешённая публикация уходит и попадает в журнал", async () => {
const { tg, p } = setup();
const e = await p.publish(ok);
assert.equal(e.result, "published");
assert.equal(tg.sent.length, 1);
assert.deepEqual(Object.keys(p.log()[0]).sort(), ["channel", "reason", "result", "text", "time"]);
});
test("Сценарий: неодобренный текст отклоняется по правилу", async () => {
const { tg, p } = setup();
const e = await p.publish({ ...ok, approvedBy: undefined });
assert.deepEqual([e.result, e.reason], ["rejected", "rule:approval"]);
assert.equal(tg.sent.length, 0);
});
test("Сценарий: превышение лимита и сброс по истечении периода", async () => {
const { tg, p, tick } = setup();
await p.publish(ok);
assert.equal((await p.publish(ok)).reason, "limit");
tick(25 * 3600 * 1000);
assert.equal((await p.publish(ok)).result, "published");
assert.equal(tg.sent.length, 2);
});
test("Сценарий: остановка и явное возобновление", async () => {
const { tg, p } = setup();
p.stop();
assert.equal((await p.publish(ok)).reason, "stopped");
assert.equal(tg.sent.length, 0);
p.resume();
assert.equal((await p.publish(ok)).result, "published");
});
test("Сценарий: ошибка платформы без токена в журнале, без повтора", async () => {
const { p } = setup({ fail: "Unauthorized MOCK_TOKEN" });
const e = await p.publish(ok);
assert.equal(e.result, "error");
assert.ok(!JSON.stringify(p.log()).includes("MOCK_TOKEN"));
assert.equal(p.log().length, 1);
});
test("Сценарий: текст с токеном отклоняется, пустой и слишком длинный тоже", async () => {
const { p } = setup();
assert.equal((await p.publish({ ...ok, text: "x MOCK_TOKEN" })).reason, "rule:secret-in-text");
assert.ok(!JSON.stringify(p.log()).includes("MOCK_TOKEN"));
assert.equal((await p.publish({ ...ok, text: " " })).reason, "rule:text-empty");
assert.equal((await p.publish({ ...ok, text: "a".repeat(4097) })).reason, "rule:text-too-long");
});
test("Сценарий: без доступов подключение не выполнено", async () => {
const tg = createTelegram({ token: "", chatId: "" });
const p = createPublisher({ file: tmp(), channels: { telegram: tg } });
assert.equal(p.status().channels.telegram.connected, false);
assert.equal((await p.publish(ok)).result, "error");
});
test("Telegram-клиент: контракт Bot API", async () => {
let call;
const f = async (u, o) => { call = [u, JSON.parse(o.body)]; return { json: async () => ({ ok: true, result: { message_id: 7 } }) }; };
const tg = createTelegram({ token: "T", chatId: "C", fetchImpl: f });
assert.equal((await tg.send("hi")).message_id, 7);
assert.deepEqual(call, ["https://api.telegram.org/botT/sendMessage", { chat_id: "C", text: "hi" }]);
const bad = createTelegram({ token: "T", chatId: "C", fetchImpl: async () => ({ json: async () => ({ ok: false, description: "chat not found" }) }) });
await assert.rejects(bad.send("x"), /chat not found/);
});
test("HTTP: публикация, стоп, журнал", async () => {
const srv = createApp({ file: tmp(), channels: { telegram: mockTelegram() } }).listen(0);
await new Promise((r) => srv.once("listening", r));
const b = `http://127.0.0.1:${srv.address().port}`;
const post = async (u, d) => (await fetch(b + u, { method: "POST", body: JSON.stringify(d ?? {}) })).json();
try {
assert.equal((await post("/api/publish", ok)).result, "published");
await post("/api/publish/stop");
assert.equal((await post("/api/publish", ok)).reason, "stopped");
const log = await (await fetch(b + "/api/publish/log")).json();
assert.equal(log.length, 2);
} finally { srv.close(); }
});