157 lines
6.8 KiB
JavaScript
157 lines
6.8 KiB
JavaScript
import { test, before } from "node:test";
|
||
import assert from "node:assert/strict";
|
||
import { once } from "node:events";
|
||
import { join } from "node:path";
|
||
import ExcelJS from "exceljs";
|
||
import { HyperFormula } from "hyperformula";
|
||
import { createApp } from "../src/server.js";
|
||
import { testConfig, tmp } from "./helpers.js";
|
||
import { TEMPLATES, filterTemplates } from "../src/templates/catalog.js";
|
||
import { CHAPTERS } from "../src/templates/chapters.js";
|
||
import { buildTemplateFiles, templateXlsx, SHEETS } from "../src/templates/files.js";
|
||
|
||
let productDir;
|
||
before(async () => {
|
||
productDir = await tmp();
|
||
await buildTemplateFiles(join(productDir, "templates"));
|
||
});
|
||
|
||
async function withServer(fn) {
|
||
const server = createApp(testConfig({ productDir })).listen(0);
|
||
await once(server, "listening");
|
||
try {
|
||
await fn(`http://127.0.0.1:${server.address().port}`);
|
||
} finally {
|
||
server.close();
|
||
}
|
||
}
|
||
const cards = (html) => (html.match(/<article class="card"/g) ?? []).length;
|
||
|
||
// Пересчитывает лист формулами HyperFormula и возвращает значение ячейки.
|
||
function recalc(ws, addr) {
|
||
const data = [];
|
||
ws.eachRow({ includeEmpty: true }, (row, r) => {
|
||
data[r - 1] = [];
|
||
row.eachCell({ includeEmpty: true }, (c, ci) => {
|
||
const v = c.value;
|
||
data[r - 1][ci - 1] = v && typeof v === "object" && "formula" in v ? `=${v.formula}` : (v ?? null);
|
||
});
|
||
});
|
||
const hf = HyperFormula.buildFromArray(data.map((r) => r ?? []), { licenseKey: "gpl-v3" });
|
||
const { row, col } = hf.simpleCellAddressFromString(addr, 0);
|
||
return hf.getCellValue({ sheet: 0, row, col });
|
||
}
|
||
|
||
test("Каталог покрывает все 14 глав, у каждого шаблона задача, формат, инструкция и пример", () => {
|
||
assert.equal(CHAPTERS.length, 14);
|
||
for (const c of CHAPTERS) assert.ok(TEMPLATES.some((t) => t.chapter === c.n), `глава ${c.n}`);
|
||
for (const t of TEMPLATES) {
|
||
assert.ok(t.task && t.instruction.length >= 3, t.id);
|
||
assert.ok(["xlsx", "docx"].includes(t.format), t.id);
|
||
assert.ok(t.kind === "table" ? t.example.length >= 3 : t.fields.some((f) => f.example ?? f.value), t.id);
|
||
}
|
||
});
|
||
|
||
test("Сценарий: Посетитель открывает каталог", async () => {
|
||
await withServer(async (base) => {
|
||
const html = await (await fetch(`${base}/templates`)).text();
|
||
assert.equal(cards(html), 14);
|
||
assert.equal((html.match(/Задача:/g) ?? []).length, 14);
|
||
assert.equal((html.match(/>Скачать \((Excel|Word)\)</g) ?? []).length, 14);
|
||
assert.equal((html.match(/<summary>Как заполнять</g) ?? []).length, 14);
|
||
assert.match(html, /Глава 11\. [^<]+· <span class="fmt">Excel<\/span><\/p>\n<h2>Калькулятор себестоимости обращения/);
|
||
});
|
||
});
|
||
|
||
test("Сценарий: Финмодель сопоставлена с главой", async () => {
|
||
await withServer(async (base) => {
|
||
const html = await (await fetch(`${base}/templates?chapter=11`)).text();
|
||
assert.match(html, /<a href="\/">Универсальная финансовая модель<\/a>/);
|
||
});
|
||
});
|
||
|
||
for (const [query, count] of [
|
||
["chapter=3", 1],
|
||
["format=docx", 6],
|
||
["format=xlsx", 8],
|
||
["chapter=6&format=xlsx", 0],
|
||
["chapter=99", 14],
|
||
]) {
|
||
test(`Сценарий: Фильтр каталога — ${query} → ${count}`, async () => {
|
||
await withServer(async (base) => assert.equal(cards(await (await fetch(`${base}/templates?${query}`)).text()), count));
|
||
});
|
||
}
|
||
|
||
test("Сценарий: Пустая выборка", async () => {
|
||
await withServer(async (base) => {
|
||
const html = await (await fetch(`${base}/templates?chapter=6&format=xlsx`)).text();
|
||
assert.match(html, /По этим условиям шаблонов нет/);
|
||
assert.match(html, /<a href="\/templates">Показать все<\/a>/);
|
||
});
|
||
});
|
||
|
||
test("Фильтр: выбранные значения отмечены в форме", () => {
|
||
const r = filterTemplates({ chapter: "8", format: "xlsx" });
|
||
assert.deepEqual([r.chapter, r.format, r.items.map((t) => t.id)], [8, "xlsx", ["quality-audit"]]);
|
||
});
|
||
|
||
test("Сценарий: Скачивание шаблона", async () => {
|
||
await withServer(async (base) => {
|
||
const res = await fetch(`${base}/templates/cost-per-contact.xlsx`);
|
||
assert.equal(res.status, 200);
|
||
assert.match(res.headers.get("content-type"), /spreadsheetml/);
|
||
const wb = new ExcelJS.Workbook();
|
||
await wb.xlsx.load(Buffer.from(await res.arrayBuffer()));
|
||
assert.deepEqual(wb.worksheets.map((w) => w.name), [SHEETS.guide, SHEETS.example, SHEETS.blank]);
|
||
const ex = wb.getWorksheet(SHEETS.example);
|
||
let addr;
|
||
ex.eachRow((row, r) => row.getCell(1).value === "Себестоимость одного обращения" && (addr = `B${r}`));
|
||
assert.match(ex.getCell(addr).value.formula, /\//);
|
||
const value = recalc(ex, addr);
|
||
assert.ok(Math.abs(value - 4760000 / 12000) < 0.01, String(value));
|
||
assert.ok(Math.abs(ex.getCell(addr).value.result - value) < 0.01);
|
||
});
|
||
});
|
||
|
||
test("Word-шаблон скачивается с правильным типом", async () => {
|
||
await withServer(async (base) => {
|
||
const res = await fetch(`${base}/templates/pilot-passport.docx`);
|
||
assert.equal(res.status, 200);
|
||
assert.match(res.headers.get("content-type"), /wordprocessingml/);
|
||
assert.equal(Buffer.from(await res.arrayBuffer()).subarray(0, 2).toString(), "PK");
|
||
});
|
||
});
|
||
|
||
test("Сценарий: Неизвестный файл", async () => {
|
||
await withServer(async (base) => {
|
||
for (const p of ["/templates/..%2Fpackage.json", "/templates/unknown.xlsx", "/templates/pilot-passport.xlsx"]) {
|
||
assert.equal((await fetch(`${base}${p}`)).status, 404, p);
|
||
}
|
||
});
|
||
});
|
||
|
||
test("Формулы примеров совпадают с заранее посчитанными значениями", async () => {
|
||
for (const t of TEMPLATES.filter((x) => x.format === "xlsx")) {
|
||
const wb = await templateXlsx(t);
|
||
const ws = wb.getWorksheet(SHEETS.example);
|
||
ws.eachRow((row, r) =>
|
||
row.eachCell((c, ci) => {
|
||
const v = c.value;
|
||
if (v && typeof v === "object" && "formula" in v) {
|
||
const addr = `${String.fromCharCode(64 + ci)}${r}`;
|
||
const got = recalc(ws, addr);
|
||
assert.ok(Math.abs(got - (v.result ?? 0)) < 0.01, `${t.id} ${addr}: ${got} ≠ ${v.result}`); // exceljs не хранит результат 0
|
||
}
|
||
}),
|
||
);
|
||
assert.ok(wb.getWorksheet(SHEETS.blank), t.id);
|
||
}
|
||
});
|
||
|
||
test("Лендинг ведёт в каталог", async () => {
|
||
await withServer(async (base) => {
|
||
assert.match(await (await fetch(`${base}/`)).text(), /href="\/templates"/);
|
||
assert.doesNotMatch(await (await fetch(`${base}/en`)).text(), /href="\/templates"/);
|
||
});
|
||
});
|