#!/usr/bin/env python3 """CR-020 (wave 12): bulk user administration in the browser, at 1440px and 390px. python tests/bulk_users_ui_check.py Self-contained like the other probes: a throwaway SQLite database seeded by browser_check.seed(), its own uvicorn, headless Edge or Chrome over CDP. Your real wpsuite.db is never touched. Run it alone, not back to back with another probe (file-map.md: chained runs exhaust the browser's ports). The server rules are proven in tests/bulk_users_check.py without a browser. This file proves the page: selection, the toolbar, the CSV path and the typed delete, end to end against the real server, operable by keyboard, and holding together at 390px. It writes the after-screenshots CLAUDE.md asks for to docs/reference/baseline/wave-12/; the before-shots are the existing users-1440.png and after-wave9/users-390.png. Exit 0 all passed, 1 a failure, 2 could not run. """ import json import os import sys import tempfile import time import urllib.request sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import cdp # noqa: E402 from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402 ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SHOTS = os.path.join(ROOT, "docs", "reference", "baseline", "wave-12") READY = "!!document.querySelector('#users-table table')" def api(base, path, token): req = urllib.request.Request(base + path, headers={"Cookie": "wp_session=" + token}) with urllib.request.urlopen(req, timeout=10) as r: return json.loads(r.read().decode()) def user(base, token, username): return next((u for u in api(base, "/api/auth/users", token) if u["username"] == username), None) def press(page, key, code, vk): """A REAL key event (Input.dispatchKeyEvent), not a synthetic KeyboardEvent: only a real one triggers a checkbox's native Space toggle - the lesson launcher_check.py records.""" for t in ("keyDown", "keyUp"): page.ws.call("Input.dispatchKeyEvent", {"type": t, "key": key, "code": code, "windowsVirtualKeyCode": vk, "text": " " if t == "keyDown" else ""}) time.sleep(0.3) def answer(page, ok=True, typed=None): time.sleep(0.4) if typed is not None: page.eval("document.getElementById('wp-dlg-input').value=%s" % json.dumps(typed)) page.eval("document.getElementById('%s').click()" % ("wp-dlg-ok" if ok else "wp-dlg-cancel")) time.sleep(1.2) def tick(page, username): page.eval("(() => { const b=[...document.querySelectorAll('input.selbox')]" ".find(x => x.dataset.id==='user_%s'); if(b) b.click(); })()" % username) time.sleep(0.2) BAR_390 = """(function(){ var bar=document.getElementById('bulk-bar'); var out={sw:document.documentElement.scrollWidth,under:[],clipped:[],n:0}; bar.querySelectorAll('button, select').forEach(function(el){ var r=el.getBoundingClientRect(); if(!r.width||!r.height) return; out.n++; var id=el.tagName+' '+(el.textContent||el.id).trim().slice(0,20)+' '+Math.round(r.width)+'x'+Math.round(r.height); if(Math.min(r.width,r.height)<24) out.under.push(id); if(r.left<-2||r.right>392) out.clipped.push(id); }); return JSON.stringify(out); })()""" def main(): exe = cdp.find_browser() if not exe: print("no headless-capable browser found; set WP_BROWSER.") return 2 tmpdir = tempfile.mkdtemp(prefix="wpsuite-bulkui-") db_path = os.path.join(tmpdir, "check.db") server = browser = None try: tok = seed(db_path) port = cdp.free_port() base = "http://127.0.0.1:%d" % port server = start_server(port, db_path) if server is None: print("server would not start") return 2 browser = cdp.Browser(exe) page = browser.page() def visit(who, width, mobile=False): page.clear_cookies() page.set_cookie("wp_session", tok[who]) page.viewport(width, 900 if width > 500 else 844, mobile=mobile) page.goto(base + "/users.html", wait_for=READY) time.sleep(0.6) print("\n1. the admin at 1440px") visit("root", 1440) page.screenshot(os.path.join(SHOTS, "users-1440.png")) chk("a selection column with select-all", page.eval("!!document.getElementById('sel-all')")) chk("no bulk bar until a row is selected", page.eval("document.getElementById('bulk-bar').hidden")) page.eval("document.querySelector('input.selbox[data-id=\"user_pat\"]').focus()") press(page, " ", "Space", 32) chk("Space on a focused row checkbox selects it (keyboard operable)", page.eval("document.querySelector('input.selbox[data-id=\"user_pat\"]').checked")) chk("the bar appears, reachable by keyboard", page.eval("!document.getElementById('bulk-bar').hidden && document.querySelector('#bulk-bar button').tabIndex >= 0")) tick(page, "legacy") chk("the bar counts the selection", page.eval("document.getElementById('bulk-count').textContent") == "2 selected") page.screenshot(os.path.join(SHOTS, "users-1440-selected.png")) page.eval("document.getElementById('bulk-role').value='project_admin';" "document.querySelector('[onclick=\"bulkRole()\"]').click()") time.sleep(0.4) chk("the confirm names the count", "for 2 users" in (page.eval("document.getElementById('wp-dlg-msg').textContent") or "")) answer(page) chk("both accounts changed on the server", user(base, tok["root"], "pat")["role"] == "project_admin" and user(base, tok["root"], "legacy")["role"] == "project_admin") chk("the result is announced", "2 changed" in page.eval("document.getElementById('bulk-banner').textContent") and page.eval("document.getElementById('bulk-banner').getAttribute('role')") in ("status", "alert")) tick(page, "pat") page.eval("const f=document.getElementById('user-filter'); f.value='active'; f.dispatchEvent(new Event('change'))") time.sleep(0.3) chk("changing the filter clears the selection, and says so", page.eval("document.getElementById('bulk-bar').hidden") and "filter changed" in page.eval("document.getElementById('sel-banner').textContent")) print("\n2. the super user, a CSV with good and bad lines") visit("sue", 1440) page.eval("loadCsv(new File(['username\\npat\\nmix\\nbob\\nsue\\npat\\n'], 'list.csv', {type:'text/csv'}))") time.sleep(1.5) rep = page.eval("document.getElementById('csv-banner').textContent") or "" chk("only the account she may change is selected", page.eval("document.getElementById('bulk-count').textContent") == "1 selected", rep) chk("every bad line is reported by number and reason: another job, not found, herself, a duplicate", all(s in rep for s in ("Line 3 (mix)", "Line 4 (bob): User not found", "Line 5 (sue)", "Line 6 (pat): duplicate of line 2")), rep) page.eval("document.getElementById('bulk-project-role').value='project_admin';" "document.querySelector('[onclick=\"bulkProject(\\'add\\')\"]').click()") answer(page) roles = api(base, "/api/auth/users/user_pat/projects", tok["root"])["roles"] chk("add to project with a role landed on the server", roles.get("projA") == "project_admin", roles) print("\n3. bulk delete needs the typed word") visit("root", 1440) tick(page, "bob") page.eval("document.querySelector('[onclick=\"bulkDelete()\"]').click()") time.sleep(0.4) chk("the dialog lists the username", "bob" in page.eval("document.getElementById('wp-dlg-msg').textContent")) page.eval("document.getElementById('wp-dlg-input').value='delete'; document.getElementById('wp-dlg-ok').click()") time.sleep(0.4) chk("a wrong word sends nothing", user(base, tok["root"], "bob") is not None and page.eval("document.getElementById('wp-dlg-overlay').classList.contains('open')")) answer(page, typed="DELETE") chk("DELETE deletes, and the report says so", user(base, tok["root"], "bob") is None and "1 changed" in page.eval("document.getElementById('bulk-banner').textContent")) print("\n4. the gloved-hands width: 390px") visit("root", 390, mobile=True) page.screenshot(os.path.join(SHOTS, "users-390.png")) tick(page, "pat") m = json.loads(page.eval(BAR_390)) page.screenshot(os.path.join(SHOTS, "users-390-selected.png")) chk("390px with the bar open: no sideways scrolling", m["sw"] <= 392, m["sw"]) chk("390px: no bar control clipped past the screen", not m["clipped"], m["clipped"]) chk("390px: every bar control meets the 24px floor", m["n"] > 0 and not m["under"], m["under"]) errs = [e for e in page.js_errors() if "beforeunload" not in e] chk("no JavaScript errors in the whole run", not errs, errs[:3]) finally: if browser is not None: try: browser.close() except Exception: pass if server is not None: server.terminate() print("\n" + "-" * 54) print("%d/%d checks passed." % (len(_PASS), len(_PASS) + len(_FAIL))) for f in _FAIL: print(" - " + f) return 1 if _FAIL else 0 if __name__ == "__main__": sys.exit(main())