/* UI-Test Auth-Gate (jsdom) gegen einen echten Server. * * Lauf: NODE_PATH=<...>/node_modules node tests/test_ui_auth.js */ const path = require("path"); const BASE = path.join(__dirname, ".."); const { JSDOM } = require("jsdom"); const { spawn } = require("child_process"); const fs = require("fs"); const http = require("http"); const STATE = "/tmp/tp_state_ui_auth"; const PORT = 8237; const BASE_URL = `http://127.0.0.1:${PORT}`; let pass = 0, fail = 0; function check(name, cond, detail = "") { if (cond) { pass++; console.log(" ok " + name); } else { fail++; console.log("FAIL " + name + " " + detail); } } const sleep = ms => new Promise(r => setTimeout(r, ms)); function api(method, p, body, token) { return new Promise((resolve, reject) => { const data = body ? JSON.stringify(body) : null; const req = http.request(BASE_URL + p, { method, headers: Object.assign(data ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data), } : {}, token ? { Authorization: "Bearer " + token } : {}), }, res => { let d = ""; res.on("data", c => d += c); res.on("end", () => resolve({ status: res.statusCode, body: JSON.parse(d || "{}") })); }); if (data) req.write(data); req.end(); req.on("error", reject); }); } async function loadApp(html, appJs, token) { const dom = new JSDOM(html, { runScripts: "dangerously", url: BASE_URL + "/" }); const { window } = dom; window.errors = []; window.addEventListener("error", e => window.errors.push(e.message || String(e))); window.fetch = (url, opts) => fetch(BASE_URL + url, opts); if (token) window.localStorage.setItem("tp_token", token); window.eval(appJs); return window; } async function main() { fs.rmSync(STATE, { recursive: true, force: true }); fs.mkdirSync(STATE, { recursive: true }); const server = spawn("python3", [path.join(BASE, "server.py")], { env: { ...process.env, TRAINING_STATE_DIR: STATE, PORT: String(PORT) }, cwd: BASE, stdio: "ignore", }); try { for (let i = 0; i < 60; i++) { try { await api("GET", "/api/meta"); break; } catch (_) { await sleep(200); } } const html = fs.readFileSync(path.join(BASE, "index.html"), "utf8") .replace(/