#!/usr/bin/env python3 """Post-deploy smoke test for a running WorkPilot API (stdlib only, no install needed). python deploy/scripts/smoke.py --base-url https://api-staging.example.com \ [--email demo@workpilot.dev --password ...] [--web-url https://staging.example.com] Steps (each prints one line; the exit code is the number of failed steps): 1. ``GET /healthz`` and ``GET /readyz`` (database reachable). 2. ``POST /auth/signup`` with a throwaway workspace, then ``POST /auth/login`` with it (``--no-signup`` skips this, e.g. in production). 3. Chat as the demo user (``--email``/``--password`` or ``WP_SMOKE_EMAIL``/``WP_SMOKE_PASSWORD``; without them, as the throwaway user): ``POST /chat`` with ``--message`` (default "cancel order ORD-1001", the demo pack's mock store, which always needs an approval). 4. Approval round-trip: the run is ``waiting_approval``; the matching inbox item is approved (``POST /approvals/{id}/decision``) and the resumed run ends ``completed``. 5. Optional: ``GET /login`` answers 200. It changes data (one cancelled demo order, one throwaway workspace): run it against staging or the demo tenant, which is reset nightly (``python -m core.cli seed-demo --reset``). """ from __future__ import annotations import argparse import json import os import sys import time import urllib.error import urllib.request import uuid from typing import Any class SmokeError(Exception): pass class Client: def __init__(self, base_url: str, timeout: float) -> None: if not base_url.startswith(("http://", "https://")): raise SmokeError(f"base URL must be http(s): {base_url}") self.base = base_url.rstrip("/") self.timeout = timeout def call( self, method: str, path: str, body: dict[str, Any] | None = None, token: str | None = None, expect: tuple[int, ...] = (200,), ) -> Any: data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(self.base + path, data=data, method=method) # noqa: S310 req.add_header("Accept", "application/json") if data is not None: req.add_header("Content-Type", "application/json") if token: req.add_header("Authorization", f"Bearer {token}") try: with urllib.request.urlopen(req, timeout=self.timeout) as resp: # noqa: S310 status, raw = resp.status, resp.read() except urllib.error.HTTPError as exc: status, raw = exc.code, exc.read() except (urllib.error.URLError, TimeoutError, ConnectionError) as exc: raise SmokeError(f"{method} {path}: {exc}") from exc if status not in expect: raise SmokeError(f"{method} {path}: HTTP {status}: {raw[:300]!r}") try: return json.loads(raw) if raw else None except ValueError: return raw.decode(errors="replace") def run(args: argparse.Namespace) -> int: c = Client(args.base_url, args.timeout) failures = 0 state: dict[str, Any] = {} def step(name: str, fn: Any) -> Any: nonlocal failures t0 = time.monotonic() try: out = fn() except (SmokeError, AssertionError, KeyError, TypeError) as exc: failures += 1 print(f"FAIL {name}: {exc}", flush=True) return None print(f"ok {name} ({(time.monotonic() - t0) * 1000:.0f} ms)", flush=True) return out if out is not None else True def health() -> None: assert c.call("GET", "/healthz") == {"status": "ok"} assert c.call("GET", "/readyz") == {"status": "ready"} def signup_login() -> None: email = f"smoke-{uuid.uuid4().hex[:10]}@example.com" password = f"smoke-{uuid.uuid4().hex}" c.call( "POST", "/auth/signup", {"business_name": "Smoke Test", "email": email, "password": password}, expect=(201,), ) tokens = c.call("POST", "/auth/login", {"email": email, "password": password}) assert tokens["access_token"], "no access token" state["token"] = tokens["access_token"] def demo_login() -> None: tokens = c.call("POST", "/auth/login", {"email": args.email, "password": args.password}) state["token"] = tokens["access_token"] def chat() -> None: run_out = c.call("POST", "/chat", {"message": args.message}, token=state["token"]) state["run"] = run_out if args.expect_approval: assert run_out["status"] == "waiting_approval", f"run is {run_out['status']}: {run_out}" else: assert run_out["status"] in ("completed", "waiting_approval"), run_out def approve() -> None: run_id = state["run"]["run_id"] inbox = c.call("GET", "/approvals", token=state["token"]) mine = [a for a in inbox if str(a.get("run_id")) == str(run_id)] assert mine, f"no pending approval for run {run_id}" res = c.call( "POST", f"/approvals/{mine[0]['id']}/decision", {"decision": "approve", "note": "smoke test"}, token=state["token"], ) assert res["run"] and res["run"]["status"] == "completed", f"resumed run: {res['run']}" got = c.call("GET", f"/runs/{run_id}", token=state["token"]) assert got["status"] == "completed", got def web() -> None: try: with urllib.request.urlopen( # noqa: S310 args.web_url.rstrip("/") + "/login", timeout=args.timeout ) as resp: assert resp.status == 200, resp.status except urllib.error.URLError as exc: raise SmokeError(f"web /login: {exc}") from exc if not step("health and readiness", health): return failures # nothing else can work if not args.no_signup: step("signup and login (throwaway workspace)", signup_login) if args.email and args.password: step(f"login as {args.email}", demo_login) if "token" not in state: print("FAIL chat: no login (pass --email/--password or allow signup)") return failures + 1 if step(f"chat run: {args.message!r}", chat) and args.expect_approval: step("approval round-trip resumes the run to completion", approve) if args.web_url: step("web /login", web) print("smoke: " + ("PASSED" if failures == 0 else f"{failures} step(s) FAILED")) return failures def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) p.add_argument("--base-url", default=os.environ.get("WP_SMOKE_BASE_URL"), required=False) p.add_argument("--web-url", default=os.environ.get("WP_SMOKE_WEB_URL")) p.add_argument("--email", default=os.environ.get("WP_SMOKE_EMAIL")) p.add_argument("--password", default=os.environ.get("WP_SMOKE_PASSWORD")) p.add_argument("--message", default="cancel order ORD-1001") p.add_argument("--no-signup", action="store_true") p.add_argument( "--no-approval", dest="expect_approval", action="store_false", help="accept a run that completes without an approval", ) p.add_argument("--timeout", type=float, default=90.0) args = p.parse_args(argv) if not args.base_url: p.error("--base-url (or WP_SMOKE_BASE_URL) is required") return run(args) if __name__ == "__main__": sys.exit(main())