File size: 9,205 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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())