#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_services board. Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, points it at the systemd fixtures so the table is always populated, and opens it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes. It asserts there is no horizontal overflow, no console error, that the summary chips and the table rendered, and that a row opens the detail drawer. Screenshots land in docs/ for the README. Skips cleanly (exit 0) when Playwright is not installed, so the offline suite stays dependency-free. 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 socketserver import subprocess import sys import tempfile import threading from urllib.parse import urlparse ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_services") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] UNITS = """[{"unit":"nginx.service","load":"loaded","active":"active","sub":"running","description":"A high performance web server and a reverse proxy server"}, {"unit":"ssh.service","load":"loaded","active":"active","sub":"running","description":"OpenBSD Secure Shell server"}, {"unit":"cron.service","load":"loaded","active":"inactive","sub":"dead","description":"Regular background program processing daemon"}, {"unit":"docker.service","load":"loaded","active":"active","sub":"running","description":"Docker Application Container Engine"}, {"unit":"broken.service","load":"loaded","active":"failed","sub":"failed","description":"A service that failed on purpose"}, {"unit":"postgresql.service","load":"loaded","active":"inactive","sub":"dead","description":"PostgreSQL RDBMS"}] """ SHOW = """Id=nginx.service MainPID=4242 MemoryCurrent=10485760 UnitFileState=enabled ActiveEnterTimestamp=Wed 2026-11-12 04:00:00 UTC Id=ssh.service MainPID=912 MemoryCurrent=7340032 UnitFileState=static ActiveEnterTimestamp=Wed 2026-11-12 03:00:00 UTC Id=docker.service MainPID=1180 MemoryCurrent=205520896 UnitFileState=enabled ActiveEnterTimestamp=Wed 2026-11-12 02:12:00 UTC """ class Handler(http.server.BaseHTTPRequestHandler): fixture_dir = "" def do_GET(self): # noqa: N802 u = urlparse(self.path) env = dict(os.environ) env["QUERY_STRING"] = u.query env["REQUEST_METHOD"] = "GET" env.pop("BOT_PASSWORD", None) env["SERVICES_MOCK_SYSTEMCTL"] = os.path.join(self.fixture_dir, "units.json") env["SERVICES_MOCK_SYSTEMCTL_SHOW"] = os.path.join(self.fixture_dir, "show.txt") out = subprocess.run([BIN], capture_output=True, env=env, timeout=30).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") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *_a): pass def main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true") args = ap.parse_args() if not os.path.exists(BIN): print("plugin_services is not built; run make first", file=sys.stderr) return 1 try: from playwright.sync_api import sync_playwright except Exception: msg = "playwright not installed - skipping viewport e2e" if args.strict: print(msg, file=sys.stderr) return 2 print(msg) return 0 fixture_dir = tempfile.mkdtemp(prefix="services-e2e-") with open(os.path.join(fixture_dir, "units.json"), "w", encoding="utf-8") as f: f.write(UNITS) with open(os.path.join(fixture_dir, "show.txt"), "w", encoding="utf-8") as f: f.write(SHOW) Handler.fixture_dir = fixture_dir os.makedirs(DOCS, exist_ok=True) with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv: port = srv.server_address[1] threading.Thread(target=srv.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/plugin_services" % port failures = [] with sync_playwright() as p: browser = p.chromium.launch() for (w, h) in VIEWPORTS: for theme in THEMES: url = "%s?theme=%s" % (base, theme) page = browser.new_page(viewport={"width": w, "height": h}) 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(url, wait_until="load") page.wait_for_timeout(1200) sw = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") if sw > iw + 1: failures.append("%dx%d %s horizontal overflow %d > %d" % (w, h, theme, sw, iw)) applied = page.evaluate( "document.documentElement.getAttribute('data-theme')") if applied != theme: failures.append("%dx%d %s ?theme= did not apply (%r)" % (w, h, theme, applied)) total = page.evaluate( "document.getElementById('vAll').textContent") if not total.strip().isdigit(): failures.append("%dx%d %s All chip did not render (%r)" % (w, h, theme, total)) rows = page.evaluate( "document.querySelectorAll('#rows tr.row').length") if rows < 1: failures.append("%dx%d %s service table is empty" % (w, h, theme)) img = page.query_selector("#rows") and page.query_selector("svg") if img is None: failures.append("%dx%d %s no inline SVG icon rendered" % (w, h, theme)) if theme == "dark": page.click("#rows tr.row") page.wait_for_timeout(350) opened = page.evaluate( "document.getElementById('drawer').classList.contains('open')") if not opened: failures.append("%dx%d drawer did not open" % (w, h)) name = page.evaluate( "document.getElementById('dName').textContent") if not name or name == "—": failures.append("%dx%d drawer has no unit name" % (w, h)) page.screenshot(path=os.path.join( DOCS, "ui-%d-%s.png" % (w, theme)), full_page=False) page.click("#dClose") else: page.screenshot(path=os.path.join( DOCS, "ui-%d-%s.png" % (w, theme)), full_page=False) if errors: failures.append("%dx%d %s console errors: %s" % (w, h, theme, errors[:3])) page.close() browser.close() if failures: print("FAIL") for f in failures: print(" " + f) return 1 print("ok - %d viewports x %d themes clean (no overflow, no console error, " "chips + table + drawer rendered)" % (len(VIEWPORTS), len(THEMES))) return 0 if __name__ == "__main__": sys.exit(main())