#!/usr/bin/env python3 """tests/e2e.py - viewport and live-behaviour checks for the plugin_logs UI. Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, opens it with Playwright at 1440 / 1024 / 390 CSS pixels in BOTH themes, and asserts there is no horizontal overflow, no console error, that the source picker is populated from action=sources, that a tail renders rows, that a search renders highlighted hits, and that the live/save/theme controls respond. Skips cleanly (exit 0) when Playwright is not installed, so `make test` stays offline-only. python3 tests/e2e.py # run if Playwright is available python3 tests/e2e.py --strict # exit 2 when Playwright is missing """ import argparse import http.server import os import shutil import subprocess import sys import tempfile import threading from urllib.parse import urlparse, parse_qs ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_logs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] SHOTS = os.path.join(ROOT, "docs") FAILS = [] PASSES = [] def ok(desc): PASSES.append(desc) print(" ok %s" % desc) def bad(desc, extra=""): FAILS.append(desc) print(" FAIL %s%s" % (desc, (" -- " + str(extra)) if extra else "")) def check(desc, cond, extra=""): ok(desc) if cond else bad(desc, extra) def prepare_fixtures(): """A journal fixture plus a fixture log tree, exported for the child.""" tmp = tempfile.mkdtemp(prefix="logs_e2e_") jfix = os.path.join(tmp, "journal.jsonl") with open(jfix, "w") as f: rows = [ ("1762923001000000", "3", "nginx.service", "upstream timed out while reading response header from upstream"), ("1762923002000000", "4", "systemd", "Some unit is deprecated"), ("1762923003000000", "6", "kernel", "eth0 link up, 1000 Mbps"), ("1762923004000000", "6", "sshd.service", "Accepted publickey for root from a trusted key"), ("1762923005000000", "2", "postgresql.service", "PANIC: could not locate a valid checkpoint record"), ] for ts, pri, unit, msg in rows: f.write('{"__REALTIME_TIMESTAMP":"%s","PRIORITY":"%s",' '"__CURSOR":"x","_SYSTEMD_UNIT":"%s","MESSAGE":"%s"}\n' % (ts, pri, unit, msg)) root = os.path.join(tmp, "fixtures") os.makedirs(os.path.join(root, "svc")) with open(os.path.join(root, "svc", "app.log"), "w") as f: for i in range(60): sev = "error" if i % 7 == 0 else ("warn" if i % 5 == 0 else "info") f.write("Nov 12 06:%02d:%02d host app[%d]: %s: request %d handled\n" % (i // 60 % 60, i % 60, 100 + i, sev, i)) env = dict(os.environ) env["SX_LOGS_JOURNAL_FIXTURE"] = jfix env["SX_LOGS_EXTRA_ROOT"] = root return tmp, env class Handler(http.server.BaseHTTPRequestHandler): env = {} def do_GET(self): # noqa: N802 u = urlparse(self.path) qs = u.query # The UI appends ?pwd= for real nodes; this shim has no password set, # so just pass the query through. env = dict(self.env) env["QUERY_STRING"] = qs env["REQUEST_METHOD"] = "GET" env.pop("BOT_PASSWORD", None) if parse_qs(qs).get("theme"): pass out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout sep = out.find(b"\r\n\r\n") headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" body = out[sep + 4:] if sep >= 0 else out ctype = "text/html; charset=utf-8" for line in headers.splitlines(): if line.lower().startswith("content-type:"): ctype = line.split(":", 1)[1].strip() self.send_response(200) self.send_header("Content-Type", ctype) self.send_header("Cache-Control", "no-store") # no Content-Length from the plugin; the shim sets its own framing self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *_a): pass def serve(env): Handler.env = env httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) t = threading.Thread(target=httpd.serve_forever, daemon=True) t.start() return httpd, httpd.server_address[1] def main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true") args = ap.parse_args() try: from playwright.sync_api import sync_playwright except Exception: print(" skip e2e (playwright not installed)") return 2 if args.strict else 0 if not os.path.exists(BIN): print(" FAIL plugin binary missing; run `make` first") return 1 tmp, env = prepare_fixtures() httpd, port = serve(env) base = "http://127.0.0.1:%d/" % port print("== e2e: %s ==" % base) os.makedirs(SHOTS, exist_ok=True) try: with sync_playwright() as p: browser = p.chromium.launch() for w, h in VIEWPORTS: for theme in ("dark", "light"): page = browser.new_page(viewport={"width": w, "height": h}, device_scale_factor=1) errors = [] page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) page.on("pageerror", lambda e: errors.append(str(e))) page.goto(base + "?theme=" + theme, wait_until="load") page.wait_for_timeout(900) tag = "%dx%d %s" % (w, h, theme) check("%s: no console errors" % tag, not errors, errors[:3]) # theme actually applied attr = page.evaluate( "document.documentElement.getAttribute('data-theme')") check("%s: theme applied" % tag, attr == theme, attr) # horizontal overflow over = page.evaluate( "() => Math.max(document.documentElement.scrollWidth," " document.body.scrollWidth) - window.innerWidth") check("%s: no horizontal overflow" % tag, over <= 1, over) # source picker populated from action=sources n = page.evaluate("document.querySelectorAll('#srcSel option').length") check("%s: source picker populated" % tag, n >= 2, n) # tail rendered rows rows = page.evaluate("document.querySelectorAll('#log .ln').length") check("%s: tail rendered entries" % tag, rows >= 5, rows) # severity colouring present at least once sev = page.evaluate( "document.querySelectorAll('#log .ln.err, #log .ln.warn').length") check("%s: severity classes applied" % tag, sev >= 1, sev) # no stray grid overflow inside the log clip = page.evaluate( "() => { var l=document.getElementById('log');" " return l.scrollWidth - l.clientWidth; }") check("%s: log body fits its own width" % tag, clip <= 2, clip) shot = os.path.join(SHOTS, "ui-%dx%d-%s.png" % (w, h, theme)) page.screenshot(path=shot, full_page=False) size = os.path.getsize(shot) check("%s: screenshot < 900 KB" % tag, size < 900 * 1024, size) page.close() # one deep behavioural run at the primary viewport page = browser.new_page(viewport={"width": 1440, "height": 900}) page.goto(base + "?theme=dark", wait_until="load") page.wait_for_timeout(800) # switch to the fixture app.log, which carries "error" lines page.evaluate( "() => { var sel = document.getElementById('srcSel');" " for (var i = 0; i < sel.options.length; i++) {" " if (sel.options[i].value.indexOf('app.log') >= 0) {" " sel.value = sel.options[i].value;" " sel.dispatchEvent(new Event('change')); return; } } }") page.wait_for_timeout(800) # search renders highlighted hits page.fill("#q", "error") page.click("#btnSearch") page.wait_for_timeout(900) marks = page.evaluate("document.querySelectorAll('#log mark').length") check("search renders highlighted hits", marks >= 1, marks) fcount = page.inner_text("#fCount") check("search reports hits and scanned count", "hits" in fcount and "scanned" in fcount, fcount) # wrap toggle widens the layout class page.click("#btnWrap") page.wait_for_timeout(150) wrap = page.evaluate("document.getElementById('log').classList.contains('wrap')") check("wrap toggle applies", wrap is True, wrap) page.click("#btnWrap") # clearing the query returns to tail page.fill("#q", "") page.click("#btnSearch") page.wait_for_timeout(700) rows = page.evaluate("document.querySelectorAll('#log .ln').length") check("empty query returns to tail", rows >= 5, rows) # follow toggle pauses the poller page.click("#btnFollow") page.wait_for_timeout(200) st = page.inner_text("#pState") check("follow toggle pauses", "paused" in st.lower(), st) page.click("#btnFollow") # line-count segment changes the request page.click("#segLines button[data-n='500']") page.wait_for_timeout(700) on = page.evaluate( "document.querySelector('#segLines button.on').getAttribute('data-n')") check("line-count segment switches", on == "500", on) # theme button flips the document before = page.evaluate("document.documentElement.getAttribute('data-theme')") page.click("#btnTheme") page.wait_for_timeout(200) after = page.evaluate("document.documentElement.getAttribute('data-theme')") check("theme button flips appearance", before != after, (before, after)) # embed mode hides the back-link only page.goto(base + "?embed=1&theme=dark", wait_until="load") page.wait_for_timeout(600) body = page.inner_text("body") check("embed=1 hides the back-link", "Back to Bot" not in body) rows = page.evaluate("document.querySelectorAll('#log .ln').length") check("embed=1 still renders entries", rows >= 5, rows) page.close() browser.close() finally: httpd.shutdown() shutil.rmtree(tmp, ignore_errors=True) print("\n== summary ==") print(" passed: %d" % len(PASSES)) print(" failed: %d" % len(FAILS)) if FAILS: print(" RESULT: FAILED") return 1 print(" RESULT: ALL PASSED") return 0 if __name__ == "__main__": sys.exit(main())