brendmanager/test/market.test.js
2026-11-16 23:29:42 +05:00

145 lines
9.4 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 { createMarketStore, coverage, REASONS } from "../src/market.js";
import { TEXTS, LANGS } from "../src/i18n.js";
import { REPORT_RECORDS } from "../src/market-seed.js";
import { createApp } from "../src/server.js";
const tmp = () => path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm27-")), "market.json");
test("Сценарий: данные отчёта целиком, числа совпадают с отчётом", () => {
const s = createMarketStore(tmp());
const r = s.importReport(REPORT_RECORDS);
assert.deepEqual(r.rejected, []);
assert.equal(s.list("competitor").length, 13); // 8 Казахстан, 1 Центральная Азия, 4 международных
assert.equal(s.list("hypothesis").length, 9); // A–E и 4 ниши
assert.ok(s.list("trend").length >= 1);
});
test("Сценарий: у каждой записи источник, дата, уверенность; у конкурента профиль; у гипотезы статус", () => {
const s = createMarketStore(tmp()); s.importReport(REPORT_RECORDS);
for (const x of s.list()) { assert.ok(x.source && x.collectedAt && ["высокая", "средняя", "низкая"].includes(x.confidence)); }
for (const x of s.list("competitor")) assert.match(x.profileUrl, /^https?:\/\//);
assert.equal(s.get("niche-1").score, 75);
assert.ok(s.list("hypothesis").every((h) => ["подтверждена", "отклонена", "не проверена"].includes(h.status)));
assert.equal(s.get("niche-1").expertiseCategory, "практик-консультант");
});
test("Сценарий: повторный перенос не создаёт дублей", () => {
const f = tmp(); const s = createMarketStore(f);
s.importReport(REPORT_RECORDS);
const r = s.importReport(REPORT_RECORDS);
assert.equal(r.created, 0);
assert.equal(createMarketStore(f).list().length, REPORT_RECORDS.length);
});
test("Сценарий: конкурент без профиля и запись без источника отклоняются", () => {
const s = createMarketStore(tmp());
const ok = { key: "x", kind: "competitor", title: "X", source: "s", collectedAt: "2026-11-15", confidence: "низкая", group: "kz", country: "Казахстан" };
assert.match(s.upsert(ok).err, /профиль/);
assert.match(s.upsert({ ...ok, profileUrl: "https://x.kz", source: "" }).err, /Источник/);
assert.match(s.upsert({ ...ok, profileUrl: "https://x.kz", confidence: "99" }).err, /Уверенность/);
assert.match(s.upsert({ ...ok, kind: "hypothesis", status: "не проверена", score: 120 }).err, /Оценка/);
assert.equal(s.list().length, 0);
});
test("Сценарий: Конкурент без региона отклоняется", () => {
const s = createMarketStore(tmp());
const b = { key: "x", kind: "competitor", title: "X", source: "s", collectedAt: "2026-11-15", confidence: "низкая", profileUrl: "https://x.kz" };
assert.match(s.upsert(b).err, /регион/);
assert.match(s.upsert({ ...b, group: "mars", country: "Марс" }).err, /регион/);
assert.match(s.upsert({ ...b, group: "kz" }).err, /страна/);
assert.ok(s.upsert({ ...b, group: "kz", country: "Казахстан" }).record);
});
test("Сценарий: Проверено меньше обещанного — 13 из 80: 8 из 30, 1 из 30, 4 из 20", () => {
const s = createMarketStore(tmp()); s.importReport(REPORT_RECORDS);
assert.deepEqual(coverage(s.list()), [
{ group: "kz", target: 30, found: 8 }, { group: "ca", target: 30, found: 1 }, { group: "intl", target: 20, found: 4 },
]);
assert.equal(TEXTS.ru["ui.mk.total"].startsWith("Проверено {found} из {target}"), true);
for (const l of LANGS) for (const g of ["kz", "ca", "intl"]) assert.ok(TEXTS[l]["ui.mk.gap." + g].length > 40, `${l}: объяснение ${g}`);
});
test("Сценарий: Регион собран полностью — 20 из 20, объяснение нехватки не показывается", () => {
const s = createMarketStore(tmp());
for (let n = 1; n <= 20; n++) s.upsert({ key: "i" + n, kind: "competitor", title: "X" + n, source: "s", collectedAt: "2026-11-15", confidence: "низкая", profileUrl: `https://x${n}.example.org`, group: "intl", country: "Германия" });
assert.deepEqual(coverage(s.list())[2], { group: "intl", target: 20, found: 20 });
assert.match(fs.readFileSync("public/market.html", "utf8"), /c\.found<c\.target\?`<p class="hint">/);
});
test("Сценарий: Отдельные блоки — CX Lab в Центральной Азии, Renascence в международных, страна указана", () => {
const s = createMarketStore(tmp()); s.importReport(REPORT_RECORDS);
const by = (title) => s.list("competitor").find((c) => c.title.startsWith(title));
assert.deepEqual([by("CX Lab").group, by("CX Lab").country], ["ca", "Узбекистан (Ташкент)"]);
assert.deepEqual([by("Renascence").group, by("Renascence").country], ["intl", "ОАЭ (Дубай)"]);
assert.ok(s.list("competitor").every((c) => c.country));
for (const l of LANGS) for (const g of ["kz", "ca", "intl"]) assert.ok(TEXTS[l]["ui.mk.group." + g]);
});
test("Сценарий: Ссылка подписана адресом сайта — без слова «профиль», без адресов-образцов, без повторов", () => {
const urls = REPORT_RECORDS.filter((r) => r.kind === "competitor").map((r) => r.profileUrl);
assert.equal(new Set(urls).size, urls.length);
for (const u of urls) {
const x = new URL(u);
assert.equal(x.protocol, "https:");
assert.doesNotMatch(x.hostname, /example\.|localhost|test\.|^[\d.]+$/, u);
}
const page = fs.readFileSync("public/market.html", "utf8");
assert.match(page, /target="_blank" rel="noopener noreferrer"/);
for (const l of LANGS) for (const [k, v] of Object.entries(TEXTS[l])) if (k.startsWith("ui.mk.")) assert.doesNotMatch(v, /профиль|profile/i, `${l}: ${k}`);
});
test("Сценарий: Технических слов в записях нет", () => {
for (const r of REPORT_RECORDS) for (const f of ["title", "summary", "source", "country"])
assert.doesNotMatch(r[f] ?? "", /п\.\s?\d|BRM-|\.md\b|\bТЗ\b|\bLLM\b|\bCRM\b|\bCX\b(?! Lab)|\bML\b/, `${r.key}.${f}: ${r[f]}`);
for (const l of LANGS) for (const [k, v] of Object.entries(TEXTS[l])) if (k.startsWith("ui.mk.")) assert.doesNotMatch(v, /п\.\s?\d|BRM-|\.md\b/, `${l}: ${k}`);
});
test("Сценарий: Дата и уверенность — код уверенности в ответе, пояснение трёх уровней на странице", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm34-"));
const srv = createApp({ file: path.join(dir, "plan.json") }).listen(0);
await new Promise((r) => srv.once("listening", r));
try {
const b = await (await fetch(`http://127.0.0.1:${srv.address().port}/api/market`)).json();
assert.equal(b.coverage.reduce((a, c) => a + c.found, 0), 13);
assert.equal(b.coverage.reduce((a, c) => a + c.target, 0), 80);
assert.ok(b.items.every((i) => ["high", "mid", "low"].includes(i.confidenceCode)));
assert.equal(b.items.find((i) => i.key === "niche-1").checkCode, "open");
} finally { srv.close(); }
const page = fs.readFileSync("public/market.html", "utf8");
for (const k of ["high", "mid", "low"]) assert.ok(page.includes(`data-t="ui.mk.confHelp.${k}"`));
assert.match(page, /toLocaleDateString\(LANG,\{day:"numeric",month:"long",year:"numeric"\}\)/);
assert.equal(new Date("2026-11-15T00:00:00").toLocaleDateString("ru", { day: "numeric", month: "long", year: "numeric" }), "15 ноября 2026 г.");
});
test("Сценарий: чтение по API с фильтром по типу", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm27-"));
const srv = createApp({ file: path.join(dir, "plan.json") }).listen(0);
await new Promise((r) => srv.once("listening", r));
const base = `http://127.0.0.1:${srv.address().port}`;
try {
const j = async (u) => { const r = await fetch(base + u); return [r.status, await r.json()]; };
let [c, b] = await j("/api/market?type=competitor");
assert.equal(c, 200); assert.equal(b.items.length, 13);
[c, b] = await j("/api/market/niche-1"); assert.equal(b.score, 75);
[c] = await j("/api/market?type=bad"); assert.equal(c, 400);
[c] = await j("/api/market/nope"); assert.equal(c, 404);
} finally { srv.close(); }
});
test("Сценарий: Сводка по регионам и причина уверенности у каждой записи (BRM-40)", () => {
const s = createMarketStore(tmp()); s.importReport(REPORT_RECORDS);
for (const l of LANGS) {
assert.ok(TEXTS[l]["ui.mk.summary"].includes("{kz}") && TEXTS[l]["ui.mk.summary"].includes("{intlT}"), l);
for (const c of REASONS) assert.ok(TEXTS[l]["ui.mk.why." + c], `${l}: ${c}`);
}
assert.equal(TEXTS.ru["ui.mk.summary"], "Казахстан {kz} из {kzT}, Центральная Азия {ca} из {caT}, международные {intl} из {intlT}.");
assert.ok(s.list().every((r) => REASONS.includes(r.confidenceReason)));
assert.equal(s.get("competitor-kz-2").confidenceReason, "nodate");
assert.match(fs.readFileSync("public/market.html", "utf8"), /id="summary"/);
});