| 1 | #!/usr/bin/env python3 |
| 2 | """tests/e2e.py - viewport checks for the plugin_memory graph browser. |
| 3 | |
| 4 | Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens |
| 5 | it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts: |
| 6 | |
| 7 | * no console error and no page error at any viewport |
| 8 | * scrollWidth <= innerWidth (no horizontal overflow) |
| 9 | * the entity list renders from a graph seeded through the plugin's own API |
| 10 | * the search box filters, the type chips filter, the inspector opens |
| 11 | * adding an observation and a relation round-trips into the JSONL store |
| 12 | * deleting cascades, and the list shrinks |
| 13 | * screenshots land in docs/ for the README |
| 14 | |
| 15 | Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays |
| 16 | dependency-free. |
| 17 | |
| 18 | python3 tests/e2e.py # run if Playwright is available |
| 19 | python3 tests/e2e.py --strict # exit 2 when Playwright is missing |
| 20 | """ |
| 21 | |
| 22 | import argparse |
| 23 | import http.server |
| 24 | import json |
| 25 | import os |
| 26 | import socketserver |
| 27 | import subprocess |
| 28 | import sys |
| 29 | import tempfile |
| 30 | import threading |
| 31 | from urllib.parse import urlparse |
| 32 | |
| 33 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 34 | BIN = os.path.join(ROOT, "plugin_memory") |
| 35 | DOCS = os.path.join(ROOT, "docs") |
| 36 | VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] |
| 37 | THEMES = ["dark", "light"] |
| 38 | |
| 39 | |
| 40 | def cgi_call(store, query, method="GET", payload=None): |
| 41 | """Run the binary once as a CGI process and return the parsed JSON body.""" |
| 42 | env = dict(os.environ) |
| 43 | env["MEMORY_FILE_PATH"] = store |
| 44 | env["MEMORY_CONNECTOR_DIR"] = os.path.dirname(store) |
| 45 | env["QUERY_STRING"] = query |
| 46 | env["REQUEST_METHOD"] = method |
| 47 | env.pop("BOT_PASSWORD", None) |
| 48 | data = json.dumps(payload).encode() if payload is not None else b"" |
| 49 | env["CONTENT_LENGTH"] = str(len(data)) |
| 50 | out = subprocess.run([BIN], input=data, capture_output=True, env=env, |
| 51 | timeout=60).stdout |
| 52 | return json.loads(out.split(b"\r\n\r\n", 1)[-1]) |
| 53 | |
| 54 | |
| 55 | class Handler(http.server.BaseHTTPRequestHandler): |
| 56 | store = "" |
| 57 | |
| 58 | def _run(self, method): |
| 59 | u = urlparse(self.path) |
| 60 | length = int(self.headers.get("Content-Length") or 0) |
| 61 | body = self.rfile.read(length) if length else b"" |
| 62 | env = dict(os.environ) |
| 63 | env["QUERY_STRING"] = u.query |
| 64 | env["REQUEST_METHOD"] = method |
| 65 | env["MEMORY_FILE_PATH"] = self.store |
| 66 | env["MEMORY_CONNECTOR_DIR"] = os.path.dirname(self.store) |
| 67 | env.pop("BOT_PASSWORD", None) |
| 68 | env["CONTENT_LENGTH"] = str(len(body)) |
| 69 | out = subprocess.run( |
| 70 | [BIN], input=body, capture_output=True, env=env, timeout=60 |
| 71 | ).stdout |
| 72 | sep = out.find(b"\r\n\r\n") |
| 73 | headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" |
| 74 | payload = out[sep + 4:] if sep >= 0 else out |
| 75 | status = 200 |
| 76 | ctype = "application/json; charset=utf-8" |
| 77 | for line in headers.splitlines(): |
| 78 | low = line.lower() |
| 79 | if low.startswith("content-type:"): |
| 80 | ctype = line.split(":", 1)[1].strip() |
| 81 | elif low.startswith("status:"): |
| 82 | try: |
| 83 | status = int(line.split(":", 1)[1].strip().split()[0]) |
| 84 | except (IndexError, ValueError): |
| 85 | status = 200 |
| 86 | self.send_response(status) |
| 87 | self.send_header("Content-Type", ctype) |
| 88 | self.send_header("Cache-Control", "no-store") |
| 89 | self.send_header("Content-Length", str(len(payload))) |
| 90 | self.end_headers() |
| 91 | self.wfile.write(payload) |
| 92 | |
| 93 | def do_GET(self): # noqa: N802 |
| 94 | self._run("GET") |
| 95 | |
| 96 | def do_POST(self): # noqa: N802 |
| 97 | self._run("POST") |
| 98 | |
| 99 | def log_message(self, *_a): |
| 100 | pass |
| 101 | |
| 102 | |
| 103 | def seed(store): |
| 104 | """A small connected graph, written through the plugin itself so the |
| 105 | JSONL on disk is exactly what a real session would leave behind.""" |
| 106 | for name, etype, obs in [ |
| 107 | ("Earl Grey", "tea", ["black tea", "bergamot", "ceramic pot at 95C"]), |
| 108 | ("Cup", "object", ["stoneware", "handed down from grandad"]), |
| 109 | ("Zebra", "animal", ["striped", "lives on the savanna"]), |
| 110 | ]: |
| 111 | cgi_call(store, "action=add_entity", "POST", |
| 112 | {"name": name, "entityType": etype, "observations": obs}) |
| 113 | cgi_call(store, "action=add_relation", "POST", |
| 114 | {"from": "Earl Grey", "to": "Cup", "relationType": "is served in"}) |
| 115 | cgi_call(store, "action=add_relation", "POST", |
| 116 | {"from": "Zebra", "to": "Earl Grey", "relationType": "shares a stripe with"}) |
| 117 | |
| 118 | |
| 119 | def main(): |
| 120 | ap = argparse.ArgumentParser() |
| 121 | ap.add_argument("--strict", action="store_true", |
| 122 | help="exit 2 when Playwright is not installed") |
| 123 | args = ap.parse_args() |
| 124 | |
| 125 | try: |
| 126 | from playwright.sync_api import sync_playwright |
| 127 | except Exception: |
| 128 | print("playwright not installed - skipping e2e (offline suite is unaffected)") |
| 129 | return 2 if args.strict else 0 |
| 130 | |
| 131 | if not os.path.exists(BIN): |
| 132 | print("plugin_memory not built - run make first") |
| 133 | return 1 |
| 134 | |
| 135 | work = tempfile.mkdtemp(prefix="memory-e2e-") |
| 136 | store = os.path.join(work, "memory.jsonl") |
| 137 | seed(store) |
| 138 | Handler.store = store |
| 139 | |
| 140 | httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler) |
| 141 | port = httpd.server_address[1] |
| 142 | threading.Thread(target=httpd.serve_forever, daemon=True).start() |
| 143 | base = "http://127.0.0.1:%d/" % port |
| 144 | |
| 145 | os.makedirs(DOCS, exist_ok=True) |
| 146 | failures = [] |
| 147 | checks = 0 |
| 148 | |
| 149 | def ok(cond, label): |
| 150 | nonlocal checks |
| 151 | checks += 1 |
| 152 | if not cond: |
| 153 | failures.append(label) |
| 154 | print(" FAIL %s" % label) |
| 155 | |
| 156 | try: |
| 157 | with sync_playwright() as pw: |
| 158 | browser = pw.chromium.launch() |
| 159 | for w, h in VIEWPORTS: |
| 160 | for theme in THEMES: |
| 161 | page = browser.new_page(viewport={"width": w, "height": h}, |
| 162 | color_scheme=theme) |
| 163 | errors = [] |
| 164 | page.on("console", lambda m: errors.append(m.text) |
| 165 | if m.type == "error" else None) |
| 166 | page.on("pageerror", lambda e: errors.append(str(e))) |
| 167 | # deleting an entity asks for confirmation; auto-accept so |
| 168 | # the delete assertion below reaches the server instead of |
| 169 | # hanging on a dialog Playwright dismisses silently. |
| 170 | page.on("dialog", lambda dialog: dialog.accept()) |
| 171 | |
| 172 | # each viewport/theme pair gets a fresh graph: the checks |
| 173 | # below mutate it (add observation, add relation, delete |
| 174 | # entity), so a shared store would leave the next pair with |
| 175 | # two entities and fail a count that is really correct. |
| 176 | for junk in os.listdir(work): |
| 177 | os.unlink(os.path.join(work, junk)) |
| 178 | seed(store) |
| 179 | |
| 180 | page.goto(base + "?theme=%s" % theme, wait_until="load") |
| 181 | page.wait_for_selector(".item", timeout=8000) |
| 182 | |
| 183 | # list rendered from the three seeded entities |
| 184 | ok(page.locator(".item").count() == 3, |
| 185 | "list has 3 entities @%dx%d %s" % (w, h, theme)) |
| 186 | ok("3 entities" in page.inner_text("#tally"), |
| 187 | "tally label @%dx%d %s" % (w, h, theme)) |
| 188 | |
| 189 | # type chips: all + the three distinct types |
| 190 | ok(page.locator("#chips .chip").count() == 4, |
| 191 | "four type chips @%dx%d %s" % (w, h, theme)) |
| 192 | |
| 193 | # no horizontal overflow |
| 194 | sw = page.evaluate("document.documentElement.scrollWidth") |
| 195 | iw = page.evaluate("window.innerWidth") |
| 196 | ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s" |
| 197 | % (sw, iw, w, h, theme)) |
| 198 | |
| 199 | # the page never reached out beyond the shim |
| 200 | ok(page.evaluate( |
| 201 | "performance.getEntriesByType('resource')" |
| 202 | ".filter(r=>!r.name.startsWith(location.origin)).length" |
| 203 | ) == 0, "zero external requests @%dx%d %s" % (w, h, theme)) |
| 204 | |
| 205 | # search filters the list down to one |
| 206 | page.fill("#q", "bergamot") |
| 207 | page.wait_for_function( |
| 208 | "document.querySelectorAll('.item').length===1", timeout=8000) |
| 209 | ok("Earl Grey" in page.inner_text("#list"), |
| 210 | "search by observation @%dx%d %s" % (w, h, theme)) |
| 211 | |
| 212 | # a type chip filters to its own type |
| 213 | page.fill("#q", "") |
| 214 | page.locator("#chips .chip", has_text="animal").first.click() |
| 215 | page.wait_for_function( |
| 216 | "document.querySelectorAll('.item').length===1", timeout=8000) |
| 217 | ok("Zebra" in page.inner_text("#list"), |
| 218 | "chip filter @%dx%d %s" % (w, h, theme)) |
| 219 | page.locator("#chips .chip", has_text="all").first.click() |
| 220 | page.wait_for_function( |
| 221 | "document.querySelectorAll('.item').length===3", timeout=8000) |
| 222 | |
| 223 | # open the inspector and read both relation directions |
| 224 | page.locator(".item", has_text="Earl Grey").first.click() |
| 225 | page.wait_for_selector("#detail .card", timeout=8000) |
| 226 | # card headers are uppercased by the stylesheet, so compare |
| 227 | # lower-cased rendered text rather than the source case. |
| 228 | detail = page.inner_text("#detail").lower() |
| 229 | ok("observations" in detail, |
| 230 | "inspector shows observations @%dx%d %s" % (w, h, theme)) |
| 231 | ok("relations out" in detail and "relations in" in detail, |
| 232 | "inspector shows both relation directions @%dx%d %s" |
| 233 | % (w, h, theme)) |
| 234 | ok(page.locator("#detail .obs li").count() == 3, |
| 235 | "three observation rows @%dx%d %s" % (w, h, theme)) |
| 236 | ok(page.locator("#detail .rel").count() == 2, |
| 237 | "two relation rows @%dx%d %s" % (w, h, theme)) |
| 238 | |
| 239 | # add an observation, it lands in the graph and on disk |
| 240 | page.fill("#newObs", "best poured at 4 minutes") |
| 241 | page.click("#addObs") |
| 242 | page.wait_for_function( |
| 243 | "document.querySelectorAll('#detail .obs li').length===4", |
| 244 | timeout=8000) |
| 245 | ok("best poured at 4 minutes" in |
| 246 | open(store, encoding="utf-8").read(), |
| 247 | "observation persisted to JSONL @%dx%d %s" % (w, h, theme)) |
| 248 | |
| 249 | # link to another entity through the select + type box |
| 250 | page.select_option("#relTo", "Zebra") |
| 251 | page.fill("#relType", "tastes like") |
| 252 | page.click("#addRel") |
| 253 | page.wait_for_function( |
| 254 | "document.querySelectorAll('#detail .rel').length===3", |
| 255 | timeout=8000) |
| 256 | ok("tastes like" in open(store, encoding="utf-8").read(), |
| 257 | "relation persisted to JSONL @%dx%d %s" % (w, h, theme)) |
| 258 | |
| 259 | # status line reports something on every interaction |
| 260 | ok(page.inner_text("#status").strip() != "", |
| 261 | "status line not blank @%dx%d %s" % (w, h, theme)) |
| 262 | |
| 263 | # delete the entity, the list shrinks to two |
| 264 | page.click("#detail [data-dele]") |
| 265 | page.wait_for_function( |
| 266 | "document.querySelectorAll('.item').length===2", timeout=8000) |
| 267 | rest = open(store, encoding="utf-8").read() |
| 268 | ok("Earl Grey" not in rest, |
| 269 | "delete removed the entity @%dx%d %s" % (w, h, theme)) |
| 270 | ok("Cup" in rest, |
| 271 | "delete kept the untouched entity @%dx%d %s" % (w, h, theme)) |
| 272 | |
| 273 | ok(not errors, "no console errors @%dx%d %s (%s)" |
| 274 | % (w, h, theme, "; ".join(errors[:3]))) |
| 275 | |
| 276 | # The README shots show a graph at full strength, so put a |
| 277 | # fresh one back after the destructive checks above. The |
| 278 | # narrow shot is the list (its own pane at 390 px), the wide |
| 279 | # shots are the inspector with observations and relations. |
| 280 | for junk in os.listdir(work): |
| 281 | os.unlink(os.path.join(work, junk)) |
| 282 | seed(store) |
| 283 | page.goto(base + "?theme=%s" % theme, wait_until="load") |
| 284 | page.wait_for_selector(".item", timeout=8000) |
| 285 | if w >= 1024: |
| 286 | page.locator(".item", has_text="Earl Grey").first.click() |
| 287 | page.wait_for_selector("#detail .obs li", timeout=8000) |
| 288 | page.screenshot(path=os.path.join( |
| 289 | DOCS, "ui-%d-%s.png" % (w, theme)), full_page=True) |
| 290 | |
| 291 | page.close() |
| 292 | browser.close() |
| 293 | finally: |
| 294 | httpd.shutdown() |
| 295 | |
| 296 | print("\ne2e: %d checks, %d failed" % (checks, len(failures))) |
| 297 | if failures: |
| 298 | for f in failures: |
| 299 | print(" - %s" % f) |
| 300 | return 1 if failures else 0 |
| 301 | |
| 302 | |
| 303 | if __name__ == "__main__": |
| 304 | sys.exit(main()) |