scorpiox-bot-plugin-notes
←e2e.pypython
264 lines · 10 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport checks for the plugin_notes editor.
3
4Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens
5it 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 note list renders, a note opens, the markdown renders
10 * the saved/unsaved pill flips and settles back to "saved"
11 * screenshots land in docs/ for the README
12
13Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
14dependency-free.
15
16 python3 tests/e2e.py # run if Playwright is available
17 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
18"""
19
20import argparse
21import http.server
22import json
23import os
24import shutil
25import socketserver
26import subprocess
27import sys
28import tempfile
29import threading
30from urllib.parse import urlparse
31
32ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
33BIN = os.path.join(ROOT, "plugin_notes")
34DOCS = os.path.join(ROOT, "docs")
35VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
36THEMES = ["dark", "light"]
37
38
39class Handler(http.server.BaseHTTPRequestHandler):
40 notes_dir = ""
41
42 def _run(self, method):
43 u = urlparse(self.path)
44 length = int(self.headers.get("Content-Length") or 0)
45 body = self.rfile.read(length) if length else b""
46 env = dict(os.environ)
47 env["QUERY_STRING"] = u.query
48 env["REQUEST_METHOD"] = method
49 env["NOTES_DIR"] = self.notes_dir
50 env.pop("BOT_PASSWORD", None)
51 env["CONTENT_LENGTH"] = str(len(body))
52 out = subprocess.run(
53 [BIN], input=body, capture_output=True, env=env, timeout=60
54 ).stdout
55 sep = out.find(b"\r\n\r\n")
56 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
57 payload = out[sep + 4:] if sep >= 0 else out
58 status = 200
59 ctype = "application/json; charset=utf-8"
60 for line in headers.splitlines():
61 low = line.lower()
62 if low.startswith("content-type:"):
63 ctype = line.split(":", 1)[1].strip()
64 elif low.startswith("status:"):
65 try:
66 status = int(line.split(":", 1)[1].strip().split()[0])
67 except (IndexError, ValueError):
68 status = 200
69 self.send_response(status)
70 self.send_header("Content-Type", ctype)
71 self.send_header("Cache-Control", "no-store")
72 self.send_header("Content-Length", str(len(payload)))
73 self.end_headers()
74 self.wfile.write(payload)
75
76 def do_GET(self): # noqa: N802
77 self._run("GET")
78
79 def do_POST(self): # noqa: N802
80 self._run("POST")
81
82 def log_message(self, *_a):
83 pass
84
85
86def seed(notes_dir):
87 """Two notes, written through the plugin itself so the format is real."""
88 def call(qs, payload=None):
89 env = dict(os.environ)
90 env["NOTES_DIR"] = notes_dir
91 env["QUERY_STRING"] = qs
92 env["REQUEST_METHOD"] = "POST" if payload is not None else "GET"
93 env.pop("BOT_PASSWORD", None)
94 data = json.dumps(payload).encode() if payload is not None else b""
95 env["CONTENT_LENGTH"] = str(len(data))
96 return json.loads(
97 subprocess.run([BIN], input=data, capture_output=True, env=env,
98 timeout=60).stdout.split(b"\r\n\r\n", 1)[-1]
99 )
100
101 call("action=save", {
102 "title": "Release checklist",
103 "pinned": 1,
104 "body": "# Release checklist\n\nShipping **SCORPIOX BOT** plugins:\n\n"
105 "- build all six targets\n- verify every SHA-256\n- mirror to plugingit\n\n"
106 "> Never trust the word *publish*.\n\n"
107 "```\nscorpiox-cli-botplugin publish .\n```\n",
108 })
109 call("action=save", {
110 "title": "Meeting notes",
111 "body": "## Tuesday\n\nDiscussed the markdown renderer, the autosave debounce "
112 "and the keyboard shortcuts (`Ctrl/Cmd+S`, `Ctrl/Cmd+K`).\n\n"
113 "1. Escape first\n2. Then render\n3. Then assert\n",
114 })
115
116
117def main():
118 ap = argparse.ArgumentParser()
119 ap.add_argument("--strict", action="store_true",
120 help="exit 2 when Playwright is not installed")
121 args = ap.parse_args()
122
123 try:
124 from playwright.sync_api import sync_playwright
125 except Exception:
126 print("playwright not installed - skipping e2e (offline suite is unaffected)")
127 return 2 if args.strict else 0
128
129 if not os.path.exists(BIN):
130 print("plugin_notes not built - run make first")
131 return 1
132
133 work = tempfile.mkdtemp(prefix="notes-e2e-")
134 notes_dir = os.path.join(work, "notes")
135 os.makedirs(notes_dir, exist_ok=True)
136 seed(notes_dir)
137 Handler.notes_dir = notes_dir
138
139 httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler)
140 port = httpd.server_address[1]
141 threading.Thread(target=httpd.serve_forever, daemon=True).start()
142 base = "http://127.0.0.1:%d/" % port
143
144 os.makedirs(DOCS, exist_ok=True)
145 failures = []
146 checks = 0
147
148 def ok(cond, label):
149 nonlocal checks
150 checks += 1
151 if not cond:
152 failures.append(label)
153 print(" FAIL %s" % label)
154
155 try:
156 with sync_playwright() as pw:
157 browser = pw.chromium.launch()
158 for w, h in VIEWPORTS:
159 for theme in THEMES:
160 page = browser.new_page(viewport={"width": w, "height": h},
161 color_scheme=theme)
162 errors = []
163 page.on("console", lambda m: errors.append(m.text)
164 if m.type == "error" else None)
165 page.on("pageerror", lambda e: errors.append(str(e)))
166
167 page.goto(base + "?theme=%s" % theme, wait_until="load")
168 page.wait_for_selector(".item", timeout=8000)
169
170 # list rendered with both seeded notes
171 ok(page.locator(".item").count() == 2,
172 "list has 2 items @%dx%d %s" % (w, h, theme))
173 ok(page.inner_text("#count").startswith("2 "),
174 "count label @%dx%d %s" % (w, h, theme))
175
176 # no horizontal overflow
177 sw = page.evaluate("document.documentElement.scrollWidth")
178 iw = page.evaluate("window.innerWidth")
179 ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s"
180 % (sw, iw, w, h, theme))
181
182 # open the pinned note
183 page.locator(".item").first.click()
184 page.wait_for_selector("#editorWrap:not(.hidden)", timeout=8000)
185 ok(page.input_value("#title") == "Release checklist",
186 "opened pinned note @%dx%d %s" % (w, h, theme))
187 page.wait_for_function(
188 "document.querySelector('#preview').innerHTML.length > 40",
189 timeout=8000)
190 html = page.inner_html("#preview")
191 ok("<h1>Release checklist</h1>" in html,
192 "markdown h1 rendered @%dx%d %s" % (w, h, theme))
193 ok("<strong>SCORPIOX BOT</strong>" in html,
194 "markdown bold rendered @%dx%d %s" % (w, h, theme))
195 ok("<script>" not in html,
196 "no raw script tag in preview @%dx%d %s" % (w, h, theme))
197
198 # autosave flips the pill and settles back to "saved"
199 original_body = page.input_value("#body")
200 page.fill("#body", original_body + "\n\n- added line\n")
201 page.wait_for_function(
202 "document.getElementById('state').textContent !== 'saved'",
203 timeout=4000)
204 page.wait_for_function(
205 "document.getElementById('state').textContent === 'saved'",
206 timeout=8000)
207 ok(True, "autosave settled @%dx%d %s" % (w, h, theme))
208
209 # put the note back so the next viewport (and the shot) sees
210 # the seeded content, not every appended test line
211 page.fill("#body", original_body)
212 page.wait_for_function(
213 "document.getElementById('state').textContent === 'saved'",
214 timeout=8000)
215
216 # overflow again with the editor open (editor is the tallest thing)
217 sw = page.evaluate("document.documentElement.scrollWidth")
218 iw = page.evaluate("window.innerWidth")
219 ok(sw <= iw + 1, "no h-overflow after open (%d<=%d) @%dx%d %s"
220 % (sw, iw, w, h, theme))
221
222 ok(not errors, "no console error @%dx%d %s (%s)"
223 % (w, h, theme, "; ".join(errors[:2])))
224
225 # reload so the shot shows the seeded note, not every line the
226 # autosave test appended, then reopen it and park at the top
227 page.goto(base + "?theme=%s" % theme, wait_until="load")
228 page.wait_for_selector(".item", timeout=8000)
229 page.locator(".item").first.click()
230 page.wait_for_selector("#editorWrap:not(.hidden)", timeout=8000)
231 page.wait_for_function(
232 "document.querySelector('#preview').innerHTML.length > 40",
233 timeout=8000)
234 page.evaluate("document.getElementById('body').scrollTop = 0")
235 page.evaluate("document.getElementById('preview').scrollTop = 0")
236 shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme))
237 page.screenshot(path=shot)
238 page.close()
239
240 # embed mode hides the theme toggle and the back link
241 page = browser.new_page(viewport={"width": 1024, "height": 768})
242 page.goto(base + "?embed=1&theme=dark", wait_until="load")
243 page.wait_for_selector(".item", timeout=8000)
244 ok(not page.is_visible("#btnTheme"), "embed hides the theme toggle")
245 ok(page.evaluate(
246 "document.documentElement.classList.contains('embedded')"),
247 "embed marks html.embedded")
248 page.close()
249 browser.close()
250 finally:
251 httpd.shutdown()
252 shutil.rmtree(work, ignore_errors=True)
253
254 print("\n%d checks, %d failure(s)" % (checks, len(failures)))
255 if failures:
256 for f in failures:
257 print(" - %s" % f)
258 return 1
259 print("RESULT: OK")
260 return 0
261
262
263if __name__ == "__main__":
264 sys.exit(main())