#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_notes editor. 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 note list renders, a note opens, the markdown renders * the saved/unsaved pill flips and settles back to "saved" * 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 json 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_notes") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] class Handler(http.server.BaseHTTPRequestHandler): notes_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["NOTES_DIR"] = self.notes_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(notes_dir): """Two notes, written through the plugin itself so the format is real.""" def call(qs, payload=None): env = dict(os.environ) env["NOTES_DIR"] = notes_dir env["QUERY_STRING"] = qs env["REQUEST_METHOD"] = "POST" if payload is not None else "GET" env.pop("BOT_PASSWORD", None) data = json.dumps(payload).encode() if payload is not None else b"" env["CONTENT_LENGTH"] = str(len(data)) return json.loads( subprocess.run([BIN], input=data, capture_output=True, env=env, timeout=60).stdout.split(b"\r\n\r\n", 1)[-1] ) call("action=save", { "title": "Release checklist", "pinned": 1, "body": "# Release checklist\n\nShipping **SCORPIOX BOT** plugins:\n\n" "- build all six targets\n- verify every SHA-256\n- mirror to plugingit\n\n" "> Never trust the word *publish*.\n\n" "```\nscorpiox-cli-botplugin publish .\n```\n", }) call("action=save", { "title": "Meeting notes", "body": "## Tuesday\n\nDiscussed the markdown renderer, the autosave debounce " "and the keyboard shortcuts (`Ctrl/Cmd+S`, `Ctrl/Cmd+K`).\n\n" "1. Escape first\n2. Then render\n3. Then assert\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_notes not built - run make first") return 1 work = tempfile.mkdtemp(prefix="notes-e2e-") notes_dir = os.path.join(work, "notes") os.makedirs(notes_dir, exist_ok=True) seed(notes_dir) Handler.notes_dir = notes_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(".item", timeout=8000) # list rendered with both seeded notes ok(page.locator(".item").count() == 2, "list has 2 items @%dx%d %s" % (w, h, theme)) ok(page.inner_text("#count").startswith("2 "), "count label @%dx%d %s" % (w, h, theme)) # no horizontal overflow 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)) # open the pinned note page.locator(".item").first.click() page.wait_for_selector("#editorWrap:not(.hidden)", timeout=8000) ok(page.input_value("#title") == "Release checklist", "opened pinned note @%dx%d %s" % (w, h, theme)) page.wait_for_function( "document.querySelector('#preview').innerHTML.length > 40", timeout=8000) html = page.inner_html("#preview") ok("