peppa/bench/lib/run-checks.mjs
Асель d108197f0f PEP-184: задачи 5–8, тест набора, archive change, память
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:09:17 +05:00

179 lines
6.9 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.

#!/usr/bin/env node
// Скрытые проверки эталонной задачи (PEP-184).
// node bench/lib/run-checks.mjs <taskDir> <workdir> [context.json]
// Копирует рабочую копию во временный каталог (проверки и продукт ничего не пишут в оригинал),
// поднимает продукт `node product/server.mjs` на свободном порту со своим DATA_DIR и без
// окружения платформы, выполняет случаи из <taskDir>/checks/check.mjs по порядку и печатает
// последней строкой JSON {ok, passed, total, cases, error?}. Код выхода 0 — засчитано, 1 — нет.
//
// check.mjs: `export default [{ name, run(t) }]` и необязательный `export async function setup(t)`
// → `{ env?, teardown? }` (например, мок внешнего сервиса). t = { app, ctx, workdir, assert, run }.
import { spawn } from "node:child_process";
import { cpSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import assert from "node:assert/strict";
import { freePort } from "./check-kit.mjs";
const CASE_TIMEOUT_MS = Number(process.env.BENCH_CASE_TIMEOUT_MS ?? 30_000);
const START_TIMEOUT_MS = Number(process.env.BENCH_START_TIMEOUT_MS ?? 15_000);
function cleanEnv(extra = {}) {
// Только самое нужное: продукт эталона не должен видеть ключи и настройки платформы.
return { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: process.env.HOME ?? tmpdir(), LANG: "ru_RU.UTF-8", ...extra };
}
async function response(r) {
const text = await r.text();
return {
status: r.status,
headers: r.headers,
text,
json() {
try {
return JSON.parse(text);
} catch {
return undefined;
}
},
};
}
class App {
constructor(dir, env) {
this.dir = dir;
this.env = env;
this.dataDir = join(dir, ".bench-data");
this.child = null;
this.log = "";
}
async start() {
const port = await freePort();
this.url = `http://127.0.0.1:${port}`;
this.log = "";
const child = spawn(process.execPath, ["product/server.mjs"], {
cwd: this.dir,
env: cleanEnv({ PORT: String(port), DATA_DIR: this.dataDir, ...this.env }),
stdio: ["ignore", "pipe", "pipe"],
});
this.child = child;
let exited = false;
child.on("exit", () => (exited = true));
const keep = (d) => (this.log = (this.log + d).slice(-4000));
child.stdout.on("data", keep);
child.stderr.on("data", keep);
const until = Date.now() + START_TIMEOUT_MS;
while (Date.now() < until && !exited) {
try {
if ((await fetch(`${this.url}/healthz`)).status === 200) return;
} catch {}
await new Promise((r) => setTimeout(r, 100));
}
await this.stop();
throw new Error(`продукт не запустился${this.log ? `: ${this.log.trim().split("\n").slice(-5).join(" | ")}` : ""}`);
}
async stop() {
const child = this.child;
this.child = null;
if (!child || child.exitCode !== null) return;
await new Promise((r) => {
child.once("exit", r);
child.kill("SIGTERM");
setTimeout(() => child.kill("SIGKILL"), 2000).unref();
});
}
async restart() {
await this.stop();
await this.start();
}
async get(path) {
return response(await fetch(this.url + path, { redirect: "manual" }));
}
async post(path, body, { form = false } = {}) {
const init = form
? { body: new URLSearchParams(body).toString(), headers: { "content-type": "application/x-www-form-urlencoded" } }
: { body: body === undefined ? undefined : JSON.stringify(body), headers: { "content-type": "application/json" } };
return response(await fetch(this.url + path, { method: "POST", redirect: "manual", ...init }));
}
}
/** Команда в копии рабочей папки (например, видимые тесты проекта). */
function runIn(dir) {
return (cmd, args, { timeoutMs = 120_000 } = {}) =>
new Promise((ok) => {
const env = cleanEnv();
const child = spawn(cmd === "node" ? process.execPath : cmd, args, { cwd: dir, env, stdio: ["ignore", "pipe", "pipe"] });
let out = "";
const keep = (d) => (out = (out + d).slice(-8000));
child.stdout.on("data", keep);
child.stderr.on("data", keep);
const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
child.on("close", (code) => {
clearTimeout(timer);
ok({ code, out });
});
});
}
function withTimeout(promise, ms) {
let timer;
return Promise.race([
promise,
new Promise((_, fail) => (timer = setTimeout(() => fail(new Error(`не уложилось в ${ms / 1000} с`)), ms))),
]).finally(() => clearTimeout(timer));
}
export async function runChecks(taskDir, workdir, ctx = {}) {
const mod = await import(pathToFileURL(join(resolve(taskDir), "checks", "check.mjs")).href);
const cases = mod.default ?? [];
const copy = mkdtempSync(join(tmpdir(), `bench-${basename(resolve(taskDir))}-`));
cpSync(workdir, copy, { recursive: true, filter: (src) => !/(^|\/)(\.git|node_modules|\.bench-data)$/.test(src) });
const context = { questions: [], needs: [], ...ctx };
const t = { ctx: context, workdir: copy, assert, run: runIn(copy), app: null };
const result = { ok: false, passed: 0, total: cases.length, cases: [] };
let teardown;
let app;
try {
const prepared = mod.setup ? await mod.setup(t) : {};
teardown = prepared?.teardown;
app = new App(copy, prepared?.env ?? {});
t.app = app;
await app.start();
for (const c of cases) {
try {
await withTimeout(Promise.resolve().then(() => c.run(t)), CASE_TIMEOUT_MS);
result.cases.push({ name: c.name, ok: true });
result.passed++;
} catch (e) {
result.cases.push({ name: c.name, ok: false, detail: String(e?.message ?? e).slice(0, 500) });
}
}
result.ok = result.total > 0 && result.passed === result.total;
} catch (e) {
result.error = String(e?.message ?? e).slice(0, 1000);
} finally {
await app?.stop().catch(() => {});
await Promise.resolve(teardown?.()).catch(() => {});
rmSync(copy, { recursive: true, force: true });
}
return result;
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const [taskDir, workdir, contextPath] = process.argv.slice(2);
if (!taskDir || !workdir) {
console.error("usage: run-checks.mjs <taskDir> <workdir> [context.json]");
process.exit(2);
}
const ctx = contextPath ? JSON.parse(readFileSync(contextPath, "utf8")) : {};
const result = await runChecks(taskDir, workdir, ctx);
process.stdout.write(`\n${JSON.stringify(result)}\n`);
process.exit(result.ok ? 0 : 1);
}