brendmanager/test/channel-matrix.test.js

113 lines
7.1 KiB
JavaScript
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.

// BRM-146: матрица каналов, путь через согласование, пакет для ручной публикации, публичная отправка выключена.
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 { createPublisher } from "../src/publisher.js";
import { mockTelegram } from "../src/telegram.js";
import { CHANNELS, MATRIX, OFFICIAL, PUBLIC_SEND, publicGate, rightsConfirmed } from "../src/channels.js";
import { buildPack } from "../src/manual-pack.js";
import { TEXTS, LANGS } from "../src/i18n.js";
const tmp = () => path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm146-")), "plan.json");
async function withServer(fn) {
const tg = mockTelegram();
const srv = createApp({ file: tmp(), telegram: tg }).listen(0);
await new Promise((r) => srv.once("listening", r));
const base = `http://127.0.0.1:${srv.address().port}`;
try { await fn(base, tg); } finally { srv.close(); }
}
const strip = (h) => h.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ");
test("Сценарий: Открыта матрица — 12 строк, у LinkedIn и Instagram заполнены все колонки (в ответе сервера)", () => withServer(async (base) => {
const html = await (await fetch(base + "/channels.html")).text();
const box = html.split("<script>")[0];
assert.match(box, /<h2>Матрица каналов<\/h2>/);
assert.equal([...box.matchAll(/<tr id="m-(\w+)">/g)].length, 12);
for (const id of ["linkedin", "instagram"]) {
const row = box.match(new RegExp(`<tr id="m-${id}">.*?</tr>`, "s"))[0];
assert.equal([...row.matchAll(/<td>/g)].length, 6);
for (const cell of row.match(/<td>(.*?)<\/td>/gs)) assert.ok(strip(cell).trim().length > 3, `${id}: пустая ячейка`);
}
for (const k of ["can", "rights", "blocks", "fallback", "next"]) assert.ok(box.includes(TEXTS.ru["ui.ch.m.col." + k]));
}));
test("Сценарий: Права не проверены — у Instagram «не подтверждено», подтверждённых прав нет ни у одного канала", () => withServer(async (base) => {
const html = await (await fetch(base + "/channels.html")).text();
assert.match(html.match(/<tr id="m-instagram">.*?<\/tr>/s)[0], /<td>не подтверждено<\/td>/);
assert.ok(CHANNELS.every((c) => MATRIX[c.id] && !rightsConfirmed(c.id)));
}));
test("Сценарий: Путь для сайта — четыре шага, последний «вручную по пакету»", () => withServer(async (base) => {
const html = await (await fetch(base + "/channels.html")).text();
assert.deepEqual(OFFICIAL, ["site", "telegram"]);
const ol = html.match(/<ol id="path-site">(.*?)<\/ol>/s)[1];
const steps = [...ol.matchAll(/<li>(.*?)<\/li>/g)].map((m) => m[1]);
assert.equal(steps.length, 4);
assert.match(steps[1], /согласование/);
assert.match(steps[3], /вручную по пакету/);
}));
test("Сценарий: Путь для Telegram-канала — проверен в закрытом тестовом, в официальном права не даны", () => withServer(async (base) => {
const html = await (await fetch(base + "/channels.html")).text();
assert.match(html, /<ol id="path-telegram">/);
const note = html.match(/<p class="hint" id="pathnote-telegram">(.*?)<\/p>/)[1];
assert.match(note, /закрытом тестовом канале/);
assert.match(note, /добавить бота администратором/);
}));
for (const [channel, len, limit, cut] of [["threadsx", 400, 280, true], ["instagram", 400, 2200, false]]) {
test(`Сценарий: Текст подогнан под канал — ${channel}, ${len} знаков → не больше ${limit}, сокращено: ${cut}`, () => {
const p = buildPack(channel, { text: "а".repeat(len - 7) + " #бренд" });
assert.ok(p.length <= limit);
assert.equal(p.cut, cut);
assert.match(p.text, /#бренд$/);
});
}
test("Сценарий: Пакет — хэштеги в конце, у сайта нужен заголовок, ничего не публикуется", () => withServer(async (base, tg) => {
const p = buildPack("instagram", { text: "Привет #бренд мир" });
assert.equal(p.text, "Привет мир\n\n#бренд");
assert.equal(buildPack("site", { text: "Текст" }).needsTitle, true);
const r = await fetch(base + "/api/channels/pack", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ channel: "telegram", text: "Пост" }) });
assert.equal(r.status, 200);
assert.equal((await r.json()).text, "Пост");
assert.equal(tg.sent.length + tg.calls.length, 0);
}));
test("Сценарий: Пустой текст — 400 и «Добавьте текст материала»; неизвестный канал — 400", () => withServer(async (base) => {
const post = (b) => fetch(base + "/api/channels/pack", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(b) });
let r = await post({ channel: "linkedin", text: " " });
assert.equal(r.status, 400);
assert.match((await r.json()).error, /^Добавьте текст материала/);
r = await post({ channel: "myspace", text: "x" });
assert.equal(r.status, 400);
}));
test("Сценарий: Попытка публичной отправки — отказ public-off даже при утверждённой стратегии", async () => {
assert.equal(PUBLIC_SEND, false);
const tg = mockTelegram();
const test = { ...mockTelegram(), channel: "telegram-test" };
const p = createPublisher({ file: tmp(), channels: { telegram: tg, "telegram-test": test }, gate: (r) => publicGate(r) ?? null });
const e = await p.publish({ channel: "telegram", text: "Одобренный текст", approvedBy: "tatiana" });
assert.equal(e.result, "rejected");
assert.equal(e.reason, "public-off");
});
test("Сценарий: Тестовый канал работает — причины public-off нет", () => {
assert.equal(publicGate({ channel: "telegram-test" }), null);
for (const c of ["telegram", "linkedin"]) assert.equal(publicGate({ channel: c }), "public-off");
});
test("Сценарий: на странице сказано, что публичная отправка выключена; тексты на трёх языках", () => withServer(async (base) => {
const html = await (await fetch(base + "/channels.html")).text();
assert.match(html, /<p class="box" id="publicoff" role="status">Публичная отправка выключена/);
const keys = Object.keys(TEXTS.ru).filter((k) => k.startsWith("ui.ch.m.") || k.startsWith("ui.ch.path.") || k.startsWith("ui.ch.pack."));
assert.ok(keys.length > 50);
for (const l of LANGS) for (const k of keys) assert.ok(TEXTS[l][k], `${l} ${k}`);
const en = await (await fetch(base + "/channels.html?lang=en")).text();
assert.match(en, /Channel matrix/);
}));