175 lines
8.8 KiB
JavaScript
175 lines
8.8 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 { createPublisher } from "../src/publisher.js";
|
||
import { mockLinkedIn, createLinkedIn } from "../src/linkedin.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("telegram", "pm");
|
||
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, 3); // публикация, остановка, отказ
|
||
} finally { srv.close(); }
|
||
});
|
||
|
||
const li = { channel: "linkedin", text: "Пост", approvedBy: "tatiana" };
|
||
const setup2 = (o) => { const l = mockLinkedIn(o), tg = mockTelegram(); let t = 1e12; const p = createPublisher({ file: tmp(), channels: { telegram: tg, linkedin: l }, now: () => t }); return { l, tg, p, tick: (ms) => (t += ms) }; };
|
||
|
||
test("LinkedIn Сценарий: разрешённая публикация — ссылка в журнале", async () => {
|
||
const { l, p } = setup2();
|
||
const e = await p.publish(li);
|
||
assert.equal(e.result, "published");
|
||
assert.match(p.log()[0].url, /^https:\/\/www\.linkedin\.com\/feed\/update\//);
|
||
assert.equal(l.sent.length, 1);
|
||
});
|
||
|
||
test("LinkedIn Сценарий: неодобренное отклоняется с причиной", async () => {
|
||
const { l, p } = setup2();
|
||
assert.equal((await p.publish({ ...li, approvedBy: "x" })).reason, "rule:approval");
|
||
assert.equal(l.sent.length, 0);
|
||
});
|
||
|
||
test("LinkedIn Сценарий: лимит 1 в сутки и 5 в неделю", async () => {
|
||
const { l, p, tick } = setup2();
|
||
await p.publish(li);
|
||
assert.equal((await p.publish(li)).reason, "limit");
|
||
for (let i = 0; i < 4; i++) { tick(25 * 3600 * 1000); assert.equal((await p.publish(li)).result, "published"); }
|
||
tick(25 * 3600 * 1000);
|
||
assert.equal((await p.publish(li)).reason, "limit"); // 6-я за неделю
|
||
assert.equal(l.sent.length, 5);
|
||
});
|
||
|
||
test("LinkedIn Сценарий: остановка отдельно от Telegram, запись кто/когда", async () => {
|
||
const { l, tg, p } = setup2();
|
||
p.stop("linkedin", "tatiana");
|
||
assert.equal((await p.publish(li)).reason, "stopped");
|
||
assert.equal((await p.publish({ ...ok })).result, "published");
|
||
const s = p.log().find((e) => e.result === "stopped");
|
||
assert.equal(s.actor, "tatiana");
|
||
assert.ok(s.time);
|
||
assert.deepEqual([l.sent.length, tg.sent.length], [0, 1]);
|
||
p.resume("linkedin", "tatiana");
|
||
assert.equal((await p.publish(li)).result, "published");
|
||
});
|
||
|
||
test("LinkedIn Сценарий: пока приложение не одобрено — не публикуем, статус виден", async () => {
|
||
const { l, p } = setup2({ status: "waiting" });
|
||
assert.equal((await p.publish(li)).reason, "waiting-approval");
|
||
assert.equal(l.sent.length, 0);
|
||
assert.equal(p.status().channels.linkedin.approval, "waiting");
|
||
});
|
||
|
||
test("LinkedIn-клиент: контракт UGC Posts, без токена в журнале", async () => {
|
||
let call;
|
||
const f = async (u, o) => { call = [u, o]; return { ok: true, json: async () => ({ id: "urn:li:share:9" }) }; };
|
||
const c = createLinkedIn({ token: "TOK", author: "urn:li:person:1", status: "received", fetchImpl: f });
|
||
const r = await c.send("hi");
|
||
assert.equal(call[0], "https://api.linkedin.com/v2/ugcPosts");
|
||
assert.equal(JSON.parse(call[1].body).specificContent["com.linkedin.ugc.ShareContent"].shareCommentary.text, "hi");
|
||
assert.match(r.url, /urn:li:share:9/);
|
||
const bad = createLinkedIn({ token: "TOK", author: "a", fetchImpl: async () => ({ ok: false, status: 401, json: async () => ({ message: "bad TOK" }) }) });
|
||
await assert.rejects(bad.send("x"), /bad/);
|
||
assert.equal(createLinkedIn({ token: "", author: "" }).approval(), "waiting");
|
||
});
|
||
|
||
test("Сценарий: лимит сообщает время, когда можно снова", async () => {
|
||
const { p } = setup();
|
||
const first = await p.publish(ok);
|
||
const e = await p.publish(ok);
|
||
assert.equal(e.reason, "limit");
|
||
assert.equal(e.retryAt, new Date(Date.parse(first.time) + 24 * 3600 * 1000).toISOString());
|
||
});
|
||
|
||
test("Сценарий: запланированный пост во время остановки не выходит сам, а ждёт подтверждения", async () => {
|
||
const { tg, p } = setup();
|
||
p.stop(undefined, "tatiana");
|
||
const e = await p.publish({ ...ok, scheduled: true });
|
||
assert.equal(e.reason, "stopped");
|
||
assert.equal(p.queue().length, 1);
|
||
p.resume(undefined, "tatiana");
|
||
assert.equal(tg.sent.length, 0);
|
||
assert.equal((await p.confirm(p.queue()[0].id, "tatiana")).result, "published");
|
||
assert.equal(p.queue().length, 0);
|
||
assert.equal(tg.sent.length, 1);
|
||
});
|