Spaces:
Running

File size: 7,705 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/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 <web-url>/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())