Download tests/test_app.py from Evidra/web-agent: direct link, hf CLI and curl.
- Browser
- Download file 22.8 kB
-
https://huggingface.co/spaces/Evidra/web-agent/resolve/main/tests/test_app.py
- Command line
-
hf download hf://spaces/Evidra/web-agent/tests/test_app.py
-
curl -L -o test_app.py https://huggingface.co/spaces/Evidra/web-agent/resolve/main/tests/test_app.py
22.8 kB
| #!/usr/bin/env python3 | |
| """End-to-end test for the web-agent app. | |
| Boots the real server on a scratch port, then verifies over HTTP: | |
| 1. /api/evaluation matches the system's recorded run files exactly | |
| (results/run_on.json / results/run_off.json, read independently | |
| here from the system directory). | |
| 2. /api/tasks lists all 36 tasks, including | |
| adversarial_rename_under_overlay. | |
| 3. A live SSE run of adversarial_rename_under_overlay (recovery on) | |
| passes with exactly 2 recoveries and 5 attempts — the recorded | |
| behaviour — with streamed screenshots and step events. | |
| 4. A live SSE run of the control task `login` passes with | |
| 0 recoveries. | |
| 5. The UI and a fixture page are served. | |
| 6. Public-page rails over HTTP: private-IP / localhost / non-http(s) | |
| URLs are refused before any browsing. | |
| 7. The three stored traces play back with the results-panel figures | |
| of their recorded runs, verified over SSE and again in a headless | |
| browser (panel totals + trace strip). | |
| 8. The public-page loop end-to-end, in-process, against local | |
| test pages (guard resolution layer stubbed in the test only): | |
| type and click intents pass for real; a password field is | |
| refused; a cross-domain navigation is a reported hard stop; a | |
| field hidden behind a same-purpose toggle (Wikipedia's header | |
| search structure) is revealed and typed into; the grounding | |
| order (label > aria-label > placeholder > name) picks the | |
| right field; a toggle-hidden password field is refused before | |
| anything is clicked. | |
| Run with the web-agent system's venv Python (provides Playwright): | |
| ~/workspace/browser-agent-lab/.venv/bin/python tests/test_app.py | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import subprocess | |
| import sys | |
| import time | |
| import urllib.error | |
| import urllib.parse | |
| import urllib.request | |
| from pathlib import Path | |
| APP_DIR = Path(__file__).resolve().parent.parent | |
| LAB_DIR = APP_DIR.parent / "browser-agent-lab" | |
| PORT = int(os.environ.get("TEST_PORT", "8931")) | |
| BASE = f"http://127.0.0.1:{PORT}" | |
| def get_json(path): | |
| with urllib.request.urlopen(BASE + path, timeout=30) as r: | |
| return json.loads(r.read()) | |
| def get_text(path): | |
| with urllib.request.urlopen(BASE + path, timeout=30) as r: | |
| return r.status, r.read().decode("utf-8", "replace") | |
| def sse_run(task, recovery="on"): | |
| """Read the SSE stream line by line; stop at the terminal event.""" | |
| return sse_get(f"/api/run?task={task}&recovery={recovery}") | |
| def sse_get(path): | |
| events = [] | |
| with urllib.request.urlopen(BASE + path, timeout=240) as r: | |
| for raw in r: | |
| line = raw.decode("utf-8", "replace").strip() | |
| if line.startswith("data: "): | |
| ev = json.loads(line[6:]) | |
| events.append(ev) | |
| if ev["type"] in ("verdict", "error"): | |
| break | |
| return events | |
| def get_status(path): | |
| try: | |
| with urllib.request.urlopen(BASE + path, timeout=30) as r: | |
| return r.status | |
| except urllib.error.HTTPError as e: | |
| return e.code | |
| def check(label, cond, detail=""): | |
| print(("PASS " if cond else "FAIL ") + label + (f" — {detail}" if detail else "")) | |
| if not cond: | |
| raise SystemExit(f"test failed: {label}") | |
| PUBLIC_PAGE = """<!doctype html><html><body> | |
| <h1>Public test page</h1> | |
| <form id="search-form" onsubmit="event.preventDefault(); | |
| fetch('/record?searched=' + encodeURIComponent(document.getElementById('q').value)); | |
| document.getElementById('done').textContent = | |
| 'Searched: ' + document.getElementById('q').value;"> | |
| <label for="q">Site search</label><input id="q" name="q" type="text"> | |
| <button type="submit">Submit</button></form> | |
| <p id="done"></p> | |
| <button id="learn" onclick="fetch('/record?clicked=1')">Learn more</button> | |
| <a id="leave" href="http://example.org/elsewhere">Leave site</a> | |
| <form id="login-form"><label for="pw">Password</label> | |
| <input id="pw" name="pw" type="password"><button type="submit">Sign in</button></form> | |
| </body></html>""" | |
| # Wikipedia's header structure, reduced to the load-bearing parts: | |
| # the search input has NO <label> (it is named by placeholder and | |
| # aria-label, name="search") and its container is display:none until | |
| # the same-widget search toggle is used — exactly what the app's | |
| # 1100px viewport gets from the real site (its stylesheet collapses | |
| # the search box below 1120px). | |
| WIKI_LIKE_PAGE = """<!doctype html><html><body> | |
| <header><div id="p-search"> | |
| <a href="#" class="search-toggle" onclick="event.preventDefault(); | |
| document.getElementById('typeahead').style.display = 'block';">Search</a> | |
| <div id="typeahead" style="display:none"> | |
| <form id="searchform" onsubmit="event.preventDefault(); | |
| fetch('/record?searched=' + encodeURIComponent(document.getElementById('searchInput').value));"> | |
| <div><input id="searchInput" type="search" name="search" | |
| placeholder="Search Wikipedia" aria-label="Search Wikipedia"></div> | |
| <button class="end-button">Search</button> | |
| </form></div> | |
| </div></header> | |
| </body></html>""" | |
| # Grounding order: a name-tier field and a placeholder-tier field, | |
| # both visible; the placeholder tier must win. | |
| ORDER_PAGE = """<!doctype html><html><body> | |
| <form id="fa" onsubmit="event.preventDefault(); | |
| fetch('/record?form=A:' + encodeURIComponent(document.getElementById('qa').value));"> | |
| <input id="qa" name="Search Wikipedia" type="text"> | |
| <button type="submit">Search A</button></form> | |
| <form id="fb" onsubmit="event.preventDefault(); | |
| fetch('/record?form=B:' + encodeURIComponent(document.getElementById('qb').value));"> | |
| <input id="qb" name="qb" type="text" placeholder="Search Wikipedia"> | |
| <button type="submit">Search B</button></form> | |
| </body></html>""" | |
| # Grounding order: an aria-tier field and a label-tier field, both | |
| # visible; the label tier must win. | |
| ORDER2_PAGE = """<!doctype html><html><body> | |
| <form id="fc" onsubmit="event.preventDefault(); | |
| fetch('/record?form=C:' + encodeURIComponent(document.getElementById('qc').value));"> | |
| <input id="qc" name="qc" type="text" aria-label="Site search"> | |
| <button type="submit">Send C</button></form> | |
| <form id="fd" onsubmit="event.preventDefault(); | |
| fetch('/record?form=D:' + encodeURIComponent(document.getElementById('qd').value));"> | |
| <label for="qd">Site search</label><input id="qd" name="qd" type="text"> | |
| <button type="submit">Send D</button></form> | |
| </body></html>""" | |
| # A password field hidden behind a toggle: the refusal must land | |
| # before anything is clicked (the run never starts). | |
| HIDDEN_PASSWORD_PAGE = """<!doctype html><html><body> | |
| <div id="login-box"> | |
| <a href="#" onclick="event.preventDefault(); | |
| document.getElementById('login-form').style.display = 'block';">Sign in</a> | |
| <form id="login-form" style="display:none"> | |
| <label for="pw2">Password</label> | |
| <input id="pw2" name="pw2" type="password"> | |
| <button type="submit">Sign in</button></form> | |
| </div> | |
| </body></html>""" | |
| PUBLIC_PAGES = {"/page": PUBLIC_PAGE, "/wiki-like": WIKI_LIKE_PAGE, | |
| "/order": ORDER_PAGE, "/order2": ORDER2_PAGE, | |
| "/hidden-password": HIDDEN_PASSWORD_PAGE} | |
| def public_loop_checks(): | |
| """Public-page mode end-to-end, in-process. The page is served on | |
| this machine; the guard's DNS-resolution layer is stubbed to | |
| return a public address for it (tests only — the app itself | |
| always uses the system resolver). Everything else is the real | |
| code path: validation, step construction, the StreamingAgent | |
| loop, the route/domain guard and the field guard.""" | |
| import threading | |
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | |
| sys.path.insert(0, str(APP_DIR)) | |
| import runner | |
| hits = [] | |
| class Handler(BaseHTTPRequestHandler): | |
| def log_message(self, *args): | |
| pass | |
| def do_GET(self): | |
| if self.path.startswith("/record"): | |
| hits.append(self.path) | |
| body = b"ok" | |
| else: | |
| body = PUBLIC_PAGES.get(self.path, PUBLIC_PAGE).encode() | |
| self.send_response(200) | |
| self.send_header("Content-Type", "text/html") | |
| self.send_header("Content-Length", str(len(body))) | |
| self.end_headers() | |
| self.wfile.write(body) | |
| server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) | |
| port = server.server_address[1] | |
| threading.Thread(target=server.serve_forever, daemon=True).start() | |
| url = f"http://127.0.0.1:{port}/page" | |
| stub_resolver = lambda host: ["93.184.216.34"] # noqa: E731 | |
| def run(**kw): | |
| events = [] | |
| runner.execute_public_run(emit=events.append, | |
| resolver=stub_resolver, **kw) | |
| return next(e for e in events if e["type"] == "verdict") | |
| try: | |
| v = run(url=url, intent="type", label="Site search", | |
| text="hello world", recovery=True) | |
| check("public loop: type intent passes end-to-end", | |
| v["success"] is True and v["steps_completed"] == 2 | |
| and v["attempts"] == 2, str(v)) | |
| check("public loop: the typed text really reached the page", | |
| any(h.startswith("/record?searched=hello") for h in hits), | |
| str(hits)) | |
| v = run(url=url, intent="click", label="Learn more", text="", | |
| recovery=True) | |
| check("public loop: click intent passes end-to-end", | |
| v["success"] is True and v["steps_completed"] == 1, str(v)) | |
| check("public loop: the click really reached the page", | |
| "/record?clicked=1" in hits, str(hits)) | |
| v = run(url=url, intent="type", label="Password", text="nope", | |
| recovery=True) | |
| check("rail: password field refused, nothing typed", | |
| v["success"] is False and "password field" in v["error"] | |
| and v["attempts"] == 0, str(v)) | |
| # Grounding: a field hidden behind a same-purpose toggle is | |
| # revealed and used (Wikipedia's header search at this app's | |
| # viewport); the field is named by placeholder/aria-label. | |
| hits.clear() | |
| v = run(url=url.replace("/page", "/wiki-like"), intent="type", | |
| label="Search Wikipedia", text="ClinVar", recovery=True) | |
| check("grounding: toggle-hidden field is revealed and typed into", | |
| v["success"] is True and v["steps_completed"] == 2 | |
| and v["attempts"] == 2, str(v)) | |
| check("grounding: the typed text really reached the hidden field", | |
| any(h.startswith("/record?searched=ClinVar") for h in hits), | |
| str(hits)) | |
| # Grounding order: placeholder tier beats name tier. | |
| hits.clear() | |
| v = run(url=url.replace("/page", "/order"), intent="type", | |
| label="Search Wikipedia", text="xyz", recovery=True) | |
| check("grounding order: placeholder match beats name match", | |
| v["success"] is True | |
| and any(h.startswith("/record?form=B:xyz") for h in hits) | |
| and not any(h.startswith("/record?form=A") for h in hits), | |
| str(v) + " " + str(hits)) | |
| # Grounding order: label tier beats aria tier. | |
| hits.clear() | |
| v = run(url=url.replace("/page", "/order2"), intent="type", | |
| label="Site search", text="xyz", recovery=True) | |
| check("grounding order: label match beats aria-label match", | |
| v["success"] is True | |
| and any(h.startswith("/record?form=D:xyz") for h in hits) | |
| and not any(h.startswith("/record?form=C") for h in hits), | |
| str(v) + " " + str(hits)) | |
| # Rail: a hidden password field is refused before any click. | |
| v = run(url=url.replace("/page", "/hidden-password"), | |
| intent="type", label="Password", text="nope", | |
| recovery=True) | |
| check("rail: hidden password field refused, run never starts", | |
| v["success"] is False and "password field" in v["error"] | |
| and v["attempts"] == 0, str(v)) | |
| v = run(url=url, intent="click", label="Leave site", text="", | |
| recovery=True) | |
| check("rail: cross-domain navigation is a reported hard stop", | |
| v["success"] is False and "different domain" in v["error"], | |
| str(v)) | |
| events = [] | |
| runner.execute_public_run(url="http://192.168.1.10/admin", | |
| intent="click", label="x", text="", | |
| recovery=True, emit=events.append) | |
| check("rail: private-IP URL refused before any browsing", | |
| events and events[0]["type"] == "error" | |
| and "non-public" in events[0]["message"], str(events)) | |
| finally: | |
| server.shutdown() | |
| def main(): | |
| env = dict(os.environ, PORT=str(PORT)) | |
| proc = subprocess.Popen( | |
| [sys.executable, str(APP_DIR / "app.py")], | |
| env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) | |
| try: | |
| # wait for the server | |
| deadline = time.time() + 30 | |
| while True: | |
| try: | |
| status, _ = get_text("/") | |
| if status == 200: | |
| break | |
| except Exception: | |
| if time.time() > deadline: | |
| raise | |
| time.sleep(0.25) | |
| check("server boots and serves the UI", True) | |
| # 1. evaluation matches the recorded run files, recomputed here | |
| on = json.loads((LAB_DIR / "results/run_on.json").read_text()) | |
| off = json.loads((LAB_DIR / "results/run_off.json").read_text()) | |
| ev = get_json("/api/evaluation") | |
| check("evaluation available", ev["available"] is True) | |
| check("summary on", ev["summary"]["on"]["overall"] == | |
| {"passed": on["passed"], "total": on["total"]}, | |
| f'{ev["summary"]["on"]["overall"]} vs file {on["passed"]}/{on["total"]}') | |
| check("summary off", ev["summary"]["off"]["overall"] == | |
| {"passed": off["passed"], "total": off["total"]}, | |
| f'{ev["summary"]["off"]["overall"]} vs file {off["passed"]}/{off["total"]}') | |
| adv_on = sum(r["success"] for r in on["tasks"] if r["adversarial"]) | |
| adv_off = sum(r["success"] for r in off["tasks"] if r["adversarial"]) | |
| n_adv = sum(1 for r in on["tasks"] if r["adversarial"]) | |
| check("adversarial split", | |
| ev["summary"]["on"]["adversarial"] == {"passed": adv_on, "total": n_adv} | |
| and ev["summary"]["off"]["adversarial"] == {"passed": adv_off, "total": n_adv}, | |
| f"on {adv_on}/{n_adv}, off {adv_off}/{n_adv}") | |
| check("per-task rows", len(ev["tasks"]) == on["total"] == 36) | |
| key = next(t for t in ev["tasks"] | |
| if t["task"] == "adversarial_rename_under_overlay") | |
| key_file = next(r for r in on["tasks"] | |
| if r["task"] == "adversarial_rename_under_overlay") | |
| check("key task recorded row matches file", | |
| key["on"]["success"] == key_file["success"] | |
| and key["on"]["recoveries"] == key_file["recoveries"] == 2 | |
| and key["on"]["attempts"] == key_file["attempts"] == 5) | |
| # 2. task catalogue | |
| cat = get_json("/api/tasks")["tasks"] | |
| check("catalogue lists 36 tasks", len(cat) == 36) | |
| check("catalogue includes key task", | |
| any(t["name"] == "adversarial_rename_under_overlay" for t in cat)) | |
| # 5 (early). fixture page served | |
| status, body = get_text("/fixtures/adversarial_rename_overlay.html") | |
| check("fixture page served", status == 200 and "<html" in body.lower()) | |
| # 3. live run: the hardest task | |
| events = sse_run("adversarial_rename_under_overlay", "on") | |
| types = [e["type"] for e in events] | |
| verdict = next(e for e in events if e["type"] == "verdict") | |
| print(" live key-task events:", types) | |
| print(" live key-task verdict:", verdict) | |
| check("live key task passed", verdict["success"] is True) | |
| check("live key task recoveries == 2", verdict["recoveries"] == 2, | |
| f"got {verdict['recoveries']}") | |
| check("live key task attempts == 5", verdict["attempts"] == 5, | |
| f"got {verdict['attempts']}") | |
| check("streamed screenshots", types.count("screenshot") >= 3, | |
| f"{types.count('screenshot')} screenshots") | |
| check("streamed step_ok x3", types.count("step_ok") == 3) | |
| check("streamed a recovery", "recovery" in types or "dismiss_overlay" in types) | |
| # 4. live run: a control task | |
| events = sse_run("login", "on") | |
| verdict = next(e for e in events if e["type"] == "verdict") | |
| print(" live login verdict:", verdict) | |
| check("live login passed", verdict["success"] is True) | |
| check("live login recoveries == 0", verdict["recoveries"] == 0) | |
| # 6. public-page rails, over HTTP: refused before any browsing | |
| chk = get_json("/api/run-public-check?url=" | |
| + urllib.parse.quote("http://127.0.0.1:8000/admin", safe="")) | |
| check("rail: private-IP URL refused by check endpoint", | |
| chk["ok"] is False and "non-public" in chk["error"], chk["error"]) | |
| chk = get_json("/api/run-public-check?url=" | |
| + urllib.parse.quote("http://localhost:8000/", safe="")) | |
| check("rail: localhost URL refused by check endpoint", | |
| chk["ok"] is False and "localhost" in chk["error"], chk["error"]) | |
| status = get_status("/api/run-public?intent=click&label=x&url=" | |
| + urllib.parse.quote("http://10.0.0.5/internal", safe="")) | |
| check("rail: private-IP run refused with 400 (no stream, no browsing)", | |
| status == 400, f"status {status}") | |
| status = get_status("/api/run-public?intent=click&label=x&url=" | |
| + urllib.parse.quote("file:///etc/hostname", safe="")) | |
| check("rail: non-http(s) URL refused with 400", status == 400, | |
| f"status {status}") | |
| # 7. recorded traces: catalogue + playback figures | |
| expected_traces = { | |
| "adversarial_rename_under_overlay": | |
| {"steps": 3, "attempts": 5, "recoveries": 2}, | |
| "crm_record_update": | |
| {"steps": 6, "attempts": 6, "recoveries": 0}, | |
| "portal_edit_and_verify": | |
| {"steps": 6, "attempts": 6, "recoveries": 0}, | |
| } | |
| cat_traces = get_json("/api/traces")["traces"] | |
| check("trace catalogue lists 3 traces", len(cat_traces) == 3, | |
| f"got {len(cat_traces)}") | |
| trace_event_counts = {} | |
| for name, want in expected_traces.items(): | |
| row = next((t for t in cat_traces if t["name"] == name), None) | |
| check(f"trace catalogue row: {name}", row is not None) | |
| check(f"trace catalogue figures: {name}", | |
| row["steps_completed"] == want["steps"] | |
| and row["attempts"] == want["attempts"] | |
| and row["recoveries"] == want["recoveries"], | |
| f"{row['steps_completed']}/{row['attempts']}/{row['recoveries']}") | |
| evs = sse_get(f"/api/trace?name={name}") | |
| trace_event_counts[name] = len(evs) | |
| types = [e["type"] for e in evs] | |
| verdict = next(e for e in evs if e["type"] == "verdict") | |
| check(f"trace playback verdict: {name}", | |
| verdict["success"] is True | |
| and verdict["steps_completed"] == want["steps"] | |
| and verdict["attempts"] == want["attempts"] | |
| and verdict["recoveries"] == want["recoveries"], | |
| f"{verdict['steps_completed']} steps / {verdict['attempts']} " | |
| f"attempts / {verdict['recoveries']} recoveries") | |
| check(f"trace playback panel counts: {name}", | |
| types.count("observe") == want["attempts"] | |
| and types.count("recovery") == want["recoveries"] | |
| and types.count("step_ok") == want["steps"], | |
| f"observe {types.count('observe')}, recovery " | |
| f"{types.count('recovery')}, step_ok {types.count('step_ok')}") | |
| check(f"trace playback frames: {name}", | |
| types.count("screenshot") >= want["steps"] + 1, | |
| f"{types.count('screenshot')} screenshots") | |
| # 8. headless UI check: playing a stored trace renders the | |
| # correct results-panel totals and a full trace strip | |
| from playwright.sync_api import sync_playwright | |
| with sync_playwright() as pw: | |
| browser = pw.chromium.launch(headless=True) | |
| page = browser.new_page() | |
| page.goto(BASE + "/") | |
| page.wait_for_selector(".trace-item", timeout=30000) | |
| check("UI: public-page form present", | |
| page.locator("#pub-url").count() == 1 | |
| and page.locator("#pub-intent").count() == 1) | |
| for name, want in expected_traces.items(): | |
| want_meta = (f"{want['steps']}/{want['steps']} steps · " | |
| f"{want['attempts']} attempts · " | |
| f"{want['recoveries']} recoveries") | |
| page.click(f'.trace-item[data-trace="{name}"]') | |
| page.click("#run-btn") | |
| page.wait_for_function( | |
| """(a) => { const m = document.querySelector('.v-meta'); | |
| const s = document.querySelectorAll( | |
| '#trace-strip .tr-item'); | |
| return m && m.textContent.includes(a.want) | |
| && s.length === a.count; }""", | |
| arg={"want": want_meta, | |
| "count": trace_event_counts[name]}, | |
| timeout=60000) | |
| meta = page.locator(".v-meta").inner_text() | |
| check(f"UI trace panel totals: {name}", want_meta in meta, | |
| f"panel shows: {meta}") | |
| strip = page.locator("#trace-strip .tr-item").count() | |
| check(f"UI trace strip items: {name}", | |
| strip == trace_event_counts[name], | |
| f"{strip} strip items vs {trace_event_counts[name]} events") | |
| browser.close() | |
| # 9. public-page loop, in-process (the network guard's | |
| # resolution layer is stubbed here ONLY, so a page served on | |
| # this machine can stand in for a public page; every other | |
| # rail — domain guard, field guard, budgets, route guard — | |
| # runs for real) | |
| public_loop_checks() | |
| print("\nALL CHECKS PASSED") | |
| finally: | |
| proc.terminate() | |
| try: | |
| proc.wait(timeout=10) | |
| except Exception: | |
| proc.kill() | |
| if __name__ == "__main__": | |
| main() | |