#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_files browser. Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts: * no console error and no page error at any viewport * scrollWidth <= innerWidth (no horizontal overflow) * the root list renders, a directory opens, a text file previews with line numbers, a markdown file renders, an image previews * the rendered page really has a stylesheet and a working script * screenshots land in docs/ for the README Skips cleanly (exit 0) when Playwright is missing, 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 shutil 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_files") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] PNG_1PX = ( b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01" b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01" b"\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82" ) class Handler(http.server.BaseHTTPRequestHandler): root_dir = "" def _run(self, method): u = urlparse(self.path) length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length) if length else b"" env = dict(os.environ) env["QUERY_STRING"] = u.query env["REQUEST_METHOD"] = method env["FILES_ALLOWED_ROOT"] = self.root_dir env.pop("BOT_PASSWORD", None) env["CONTENT_LENGTH"] = str(len(body)) out = subprocess.run( [BIN], input=body, 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 "" payload = out[sep + 4:] if sep >= 0 else out status = 200 ctype = "application/json; charset=utf-8" for line in headers.splitlines(): low = line.lower() if low.startswith("content-type:"): ctype = line.split(":", 1)[1].strip() elif low.startswith("status:"): try: status = int(line.split(":", 1)[1].strip().split()[0]) except (IndexError, ValueError): status = 200 self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) def do_GET(self): # noqa: N802 self._run("GET") def do_POST(self): # noqa: N802 self._run("POST") def log_message(self, *_a): pass def seed(root_dir): os.makedirs(os.path.join(root_dir, "src"), exist_ok=True) os.makedirs(os.path.join(root_dir, "docs"), exist_ok=True) with open(os.path.join(root_dir, "README.md"), "w", encoding="utf-8") as f: f.write( "# Local File Browser\n\n" "A read-only browser for **SCORPIOX BOT** nodes.\n\n" "- list directories inside the allowlisted roots\n" "- preview text with line numbers\n" "- view images and download files\n\n" "> Nothing on disk can be modified by this plugin.\n\n" "```\ncurl 'http://node:8150/plugin_files?action=roots'\n```\n" ) with open(os.path.join(root_dir, "src", "main.c"), "w", encoding="utf-8") as f: f.write("#include \n\nint main(void)\n{\n puts(\"hi\");\n return 0;\n}\n") with open(os.path.join(root_dir, "notes.txt"), "w", encoding="utf-8") as f: f.write("line one\nline two\nline three\n") with open(os.path.join(root_dir, "blob.bin"), "wb") as f: f.write(b"PK\x03\x04\x00\x00binary\x00data\x00") with open(os.path.join(root_dir, "docs", "pixel.png"), "wb") as f: f.write(PNG_1PX) with open(os.path.join(root_dir, ".hiddenrc"), "w", encoding="utf-8") as f: f.write("hidden\n") def main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true", help="exit 2 when Playwright is not installed") args = ap.parse_args() try: from playwright.sync_api import sync_playwright except Exception: print("playwright not installed - skipping e2e (offline suite is unaffected)") return 2 if args.strict else 0 if not os.path.exists(BIN): print("plugin_files not built - run make first") return 1 work = tempfile.mkdtemp(prefix="files-e2e-") root_dir = os.path.join(work, "root") os.makedirs(root_dir, exist_ok=True) seed(root_dir) Handler.root_dir = root_dir httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler) port = httpd.server_address[1] threading.Thread(target=httpd.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/" % port os.makedirs(DOCS, exist_ok=True) failures = [] checks = 0 def ok(cond, label): nonlocal checks checks += 1 if not cond: failures.append(label) print(" FAIL %s" % label) try: with sync_playwright() as pw: browser = pw.chromium.launch() for w, h in VIEWPORTS: for theme in THEMES: page = browser.new_page(viewport={"width": w, "height": h}, color_scheme=theme) 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=%s" % theme, wait_until="load") page.wait_for_selector(".root", timeout=8000) ok(page.locator(".root").count() >= 1, "roots rendered @%dx%d %s" % (w, h, theme)) # the seeded root is the last one, so pick it by its path page.evaluate( "ROOTPATH => Array.from(document.querySelectorAll('.root'))" ".filter(function(b){return b.textContent.indexOf(ROOTPATH)>=0;})[0]" ".click()", root_dir) page.wait_for_function( "document.querySelectorAll('.row').length >= 4", timeout=8000) page.wait_for_selector(".row", timeout=8000) ok(page.locator(".row").count() >= 4, "entries listed @%dx%d %s" % (w, h, theme)) ok(page.locator(".row.dir").count() >= 2, "directories first @%dx%d %s" % (w, h, theme)) ok(".hiddenrc" not in page.inner_text("#entries"), "hidden files hidden by default @%dx%d %s" % (w, h, theme)) sw = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s" % (sw, iw, w, h, theme)) # a real stylesheet, not plain text in the page ok(page.evaluate( "document.styleSheets.length>0 && " "Array.from(document.styleSheets)" ".reduce(function(n,s){return n+s.cssRules.length;},0)>80"), "stylesheet parsed @%dx%d %s" % (w, h, theme)) # open the markdown file -> rendered headings and bold page.evaluate( "Array.from(document.querySelectorAll('.row'))" ".filter(function(b){return b.textContent.indexOf('README.md')>=0;})[0]" ".click()") page.wait_for_selector(".md h1", timeout=8000) html = page.inner_html(".md") ok("

Local File Browser

" in html, "markdown h1 rendered @%dx%d %s" % (w, h, theme)) ok("SCORPIOX BOT" in html, "markdown bold rendered @%dx%d %s" % (w, h, theme)) ok("