// BENCH-HIDDEN — скрытые проверки задачи 6 (переделка без изменения поведения). import { copyFileSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { files } from "../../../lib/check-kit.mjs"; import * as original from "./original-report.mjs"; const MAX_FUNCTION_LINES = 40; function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32); } function sampleOrders(seed) { const r = rng(seed); const pick = (a) => a[Math.floor(r() * a.length)]; const n = Math.floor(r() * 25); return Array.from({ length: n }, (_, i) => ({ id: i + 1, date: `2026-${pick(["10", "11", "12"])}-${String(1 + Math.floor(r() * 28)).padStart(2, "0")}`, manager: pick(["Аса", "Бек", "Вика", "", undefined, "<Дана & Ко>"]), city: pick(["Алматы", "Астана", "Шымкент", " ", "", undefined]), status: pick(["paid", "paid", "paid", "cancelled", "refunded"]), promo: pick([undefined, undefined, "HALF", "MINUS500", "OTHER"]), items: Array.from({ length: 1 + Math.floor(r() * 3) }, () => ({ title: "x", qty: 1 + Math.floor(r() * 5), price: pick([99, 300, 1500, 12000, 333]) })), })); } function sampleOpts(seed) { const r = rng(seed * 7 + 3); const pick = (a) => a[Math.floor(r() * a.length)]; return { groupBy: pick(["day", "manager", "city"]), from: pick([undefined, "2026-11-01", "2026-10-15"]), to: pick([undefined, "2026-11-30", "2026-12-10"]) }; } /** Самая длинная функция в файле (строки от открывающей до закрывающей скобки тела). */ export function longestFunction(src) { const code = src .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")) .replace(/\/\/[^\n]*/g, "") .replace(/(["'`])(?:\\.|(?!\1)[^\\\n])*\1/g, (m) => m.replace(/[{}]/g, " ")); const lines = code.split("\n"); let best = 0; const stack = []; lines.forEach((line, i) => { for (let c = 0; c < line.length; c++) { if (line[c] === "{") { const before = (lines[i].slice(0, c) + " ").trimEnd(); const isFn = /(\bfunction\b[^{]*|=>\s*|\)\s*)$/.test(before) && !/\b(if|for|while|switch|catch)\s*\([^)]*\)\s*$/.test(before); stack.push({ line: i, isFn }); } else if (line[c] === "}") { const open = stack.pop(); if (open?.isFn) best = Math.max(best, i - open.line + 1); } } }); return best; } export default [ { name: "прежние тесты не ослаблены и зелёные", async run(t) { copyFileSync(new URL("./visible-report.test.mjs.txt", import.meta.url), join(t.workdir, "product", "test", "bench-visible-report.test.mjs")); const r = await t.run("node", ["--test", "product/test/"]); t.assert.equal(r.code, 0, `тесты упали:\n${r.out.slice(-1500)}`); }, }, { name: "отчёт совпадает с прежним на 300 наборах данных", async run(t) { const mod = await import(pathToFileURL(join(t.workdir, "product", "report.mjs")).href); for (let seed = 1; seed <= 300; seed++) { const orders = sampleOrders(seed); const opts = sampleOpts(seed); const want = original.buildReport(structuredClone(orders), opts); const got = mod.buildReport(structuredClone(orders), opts); t.assert.deepEqual(JSON.parse(JSON.stringify(got)), JSON.parse(JSON.stringify(want)), `набор ${seed} (${JSON.stringify(opts)})`); t.assert.equal(mod.renderReport(got, opts.groupBy), original.renderReport(want, opts.groupBy), `таблица, набор ${seed}`); } t.assert.throws(() => mod.buildReport([], { groupBy: "week" }), "неизвестная группировка больше не ошибка"); }, }, { name: "страница отчёта отвечает", async run(t) { const r = await t.app.get("/report?by=manager"); t.assert.equal(r.status, 200); t.assert.match(r.text, /Итого/); }, }, { name: `нет функций длиннее ${MAX_FUNCTION_LINES} строк`, async run(t) { const sources = files(t.workdir).filter((f) => f.startsWith("product/") && f.endsWith(".mjs") && !f.includes("/test/") && !f.startsWith("product/lib/")); for (const f of sources) { const n = longestFunction(readFileSync(join(t.workdir, f), "utf8")); t.assert.ok(n <= MAX_FUNCTION_LINES, `${f}: функция на ${n} строк`); } }, }, ];