Download deploy/smoke_run.py from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 9.21 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/deploy/smoke_run.py
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/deploy/smoke_run.py
-
curl -L -o smoke_run.py https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/deploy/smoke_run.py
9.21 kB
| #!/usr/bin/env python3 | |
| """Rehearse the demo against a running instance: sign in, check the practice pod, run one quick simulation with a | |
| planted defect, approve the scenarios, confirm the defect, and check the result, the report and the Excel script. | |
| python deploy/smoke_run.py https://patch-coworker-demo.onrender.com demo <password> | |
| python deploy/smoke_run.py http://127.0.0.1:8800 admin <password> --full # all Procure-to-Pay scenarios | |
| Standard library only. Exit code 0 = every step worked. It creates one test run on the instance.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| CASES = ["P2P-APR-001", "P2P-APR-002", "P2P-INV-001", "P2P-REQ-001", "P2P-PO-001"] | |
| DEFECT = "P2P-APR-001" | |
| class Api: | |
| def __init__(self, base: str): | |
| self.base, self.token = base.rstrip("/"), None | |
| def call(self, method: str, path: str, body=None, raw: bool = False, timeout: int = 90): | |
| req = urllib.request.Request(self.base + path, method=method, data=json.dumps(body).encode() if body is not None else None) | |
| req.add_header("Content-Type", "application/json") | |
| if self.token: | |
| req.add_header("Authorization", f"Bearer {self.token}") | |
| try: | |
| with urllib.request.urlopen(req, timeout=timeout) as r: | |
| data = r.read() | |
| return (data, r.headers.get("Content-Type", "")) if raw else (json.loads(data) if data else None) | |
| except urllib.error.HTTPError as e: | |
| raise SystemExit(f"FAILED {method} {path} -> HTTP {e.code}: {e.read().decode(errors='replace')[:300]}") from e | |
| def step(name: str, detail: str = "") -> None: | |
| print(f" ok {name}{' ' + detail if detail else ''}", flush=True) | |
| def wait_for(api: Api, run_id: str, wanted: tuple[str, ...], timeout_s: int) -> dict: | |
| end, last = time.time() + timeout_s, None | |
| while time.time() < end: | |
| r = api.call("GET", f"/api/runs/{run_id}") | |
| if r["status"] != last: | |
| last = r["status"] | |
| print(f" ... {last}{' at ' + r['current_node'] if r.get('current_node') else ''}", flush=True) | |
| if r["status"] in wanted: | |
| return r | |
| if r["status"] in ("failed", "killed", "cancelled", "interrupted"): | |
| raise SystemExit(f"FAILED the test run stopped: {r['status']} {r.get('error') or ''}") | |
| time.sleep(3) | |
| raise SystemExit(f"FAILED still {last} after {timeout_s}s (wanted {wanted})") | |
| def browser_run(api: Api, a, pod_id: int, t0: float) -> int: | |
| """A full run in a real browser: approve, watch for live frames while it tests, accept whatever it decides.""" | |
| body = {"modules": ["P2P"], "playwright_mode": "live", "pod_id": pod_id} | |
| if not a.full: | |
| body["case_ids"] = CASES | |
| run_id = api.call("POST", "/api/runs", body)["run_id"] | |
| step("a full browser run started", run_id) | |
| wait_for(api, run_id, ("waiting_approval",), a.timeout) | |
| pending = [x["id"] for x in api.call("GET", f"/api/runs/{run_id}/gate")["pending"]] | |
| api.call("POST", f"/api/runs/{run_id}/gates/approve_cases", {"approved": pending, "rejected": [], "comments": {}}) | |
| step("scenarios approved", f"{len(pending)} scenarios") | |
| end, frames, caption, last = time.time() + a.timeout * 3, 0, None, None | |
| while time.time() < end: | |
| r = api.call("GET", f"/api/runs/{run_id}") | |
| if r["status"] != last: | |
| last = r["status"] | |
| print(f" ... {last}{' at ' + r['current_node'] if r.get('current_node') else ''}", flush=True) | |
| if r["status"] == "waiting_review": | |
| fails = [x for x in api.call("GET", f"/api/runs/{run_id}/failures") if x["pending"]] | |
| print(f" ... {len(fails)} failure(s) to decide: marking them not a defect for the rehearsal", flush=True) | |
| api.call("POST", f"/api/runs/{run_id}/gates/human_review", | |
| {"review": {x["case_id"]: ({"owner": "demo"} if x.get("ask") == "owner" else {"confirmed": "not_defect"}) for x in fails}}) | |
| elif r["status"] == "completed": | |
| break | |
| elif r["status"] in ("failed", "killed", "cancelled", "interrupted"): | |
| raise SystemExit(f"FAILED the test run stopped: {r['status']} {r.get('error') or ''}") | |
| live = api.call("GET", f"/api/runs/{run_id}/live") | |
| if live.get("active") and live.get("frame_ts"): | |
| frames += 1 | |
| caption = live.get("action") or caption | |
| time.sleep(2) | |
| else: | |
| raise SystemExit("FAILED the browser run did not finish in time") | |
| assert frames > 0, "the live view never had a frame while the browser was running" | |
| step("the live view showed the test browser", f"{frames} checks with a live picture; last caption: {caption}") | |
| r = api.call("GET", f"/api/runs/{run_id}") | |
| decision = r.get("decision") or next(iter((r.get("decisions") or {}).values()), None) | |
| step("the result is in", f"decision {decision}; counts {json.dumps(r.get('counts') or {})}") | |
| print(f"Browser rehearsal passed in {time.time() - t0:.0f}s. Open {api.base}/runs/{run_id}") | |
| return 0 | |
| def main() -> int: | |
| p = argparse.ArgumentParser(description=__doc__.split("\n")[0]) | |
| p.add_argument("base_url") | |
| p.add_argument("username") | |
| p.add_argument("password") | |
| p.add_argument("--full", action="store_true", help="run every Procure-to-Pay scenario instead of five") | |
| p.add_argument("--browser", action="store_true", help="a full run in a real browser (no planted defect); checks the live view") | |
| p.add_argument("--timeout", type=int, default=600, help="seconds to wait for each stage") | |
| a = p.parse_args() | |
| api = Api(a.base_url) | |
| t0 = time.time() | |
| print(f"Demo rehearsal against {api.base}") | |
| ready = api.call("GET", "/api/ready", timeout=180) # a sleeping free instance can take a minute to wake | |
| assert ready["ready"], ready | |
| step("the application is ready", f"{ready.get('product_name')} - orchestrator {ready['orchestrator']}") | |
| api.token = api.call("POST", "/api/auth/token", {"username": a.username, "password": a.password})["access_token"] | |
| step("sign-in works", a.username) | |
| pod = next(x for x in api.call("GET", "/api/pods") if x["is_default"]) | |
| assert pod["runnable"], pod | |
| test = api.call("POST", f"/api/pods/{pod['id']}/test") | |
| assert test["ok"], test | |
| step("the practice pod answers", test["detail"]) | |
| body = {"modules": ["P2P"], "playwright_mode": "stub", "stub_knobs": {"STUB_DEFECT": DEFECT}, "pod_id": pod["id"]} | |
| if not a.full: | |
| body["case_ids"] = CASES | |
| if a.browser: | |
| return browser_run(api, a, pod["id"], t0) | |
| run_id = api.call("POST", "/api/runs", body)["run_id"] | |
| step("a test run started", run_id) | |
| wait_for(api, run_id, ("waiting_approval",), a.timeout) | |
| pending = [x["id"] for x in api.call("GET", f"/api/runs/{run_id}/gate")["pending"]] | |
| assert pending, "no scenarios were offered for approval" | |
| data, ctype = api.call("GET", f"/api/runs/{run_id}/test-script.xlsx", raw=True) | |
| assert "spreadsheetml" in ctype and len(data) > 5000, (ctype, len(data)) | |
| step("scenarios are waiting for approval", f"{len(pending)} scenarios - Excel test script {len(data) // 1024} KB") | |
| api.call("POST", f"/api/runs/{run_id}/gates/approve_cases", {"approved": pending, "rejected": [], "comments": {}}) | |
| wait_for(api, run_id, ("waiting_review",), a.timeout) | |
| fails = api.call("GET", f"/api/runs/{run_id}/failures") | |
| f = next(x for x in fails if x["case_id"] == DEFECT) | |
| assert f["pending"] and f["expected"] and f["actual"], f | |
| step("the planted failure needs a decision", f"expected '{f['expected']}', got '{f['actual']}' - {f['suggestion']}") | |
| review = {x["case_id"]: ({"owner": "demo"} if x.get("ask") == "owner" else {"confirmed": "real_defect" if x["case_id"] == DEFECT else "not_defect"}) | |
| for x in fails if x["pending"]} | |
| api.call("POST", f"/api/runs/{run_id}/gates/human_review", {"review": review}) | |
| r = wait_for(api, run_id, ("completed",), a.timeout) | |
| decision = r.get("decision") or next(iter((r.get("decisions") or {}).values()), None) | |
| assert decision == "NO-GO", f"expected NO-GO because of the confirmed defect, got {decision}" | |
| step("the result is in", f"decision {decision} (Not ready), as expected with one confirmed defect") | |
| rep = api.call("GET", f"/api/runs/{run_id}/report") | |
| files = (rep.get("files") or {}).get("P2P") or {} | |
| assert files.get("html"), rep.get("files") | |
| step("the report exists", "HTML" + (" and PDF" if files.get("pdf") else " (no PDF: not enough memory for the PDF step on this instance)")) | |
| tickets = api.call("GET", f"/api/tickets?run_id={run_id}")["items"] | |
| assert any(t["case_id"] == DEFECT for t in tickets), tickets | |
| step("a ticket was raised for the defect", tickets[0]["ticket_id"]) | |
| print(f"Rehearsal passed in {time.time() - t0:.0f}s. Open {api.base}/runs/{run_id}") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |