Files

120 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""Acceptance script for the CRM the agent builds (offline test driver, not shipped).
crm_acceptance.py WORKSPACE
Starts `python3 server.py` in WORKSPACE on a free port with a fresh database, drives the REST API of prompt-crm.txt and runs
the app's own tests. Exit status 0 when every check passed.
"""
import json
import os
import socket
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
ws = os.path.abspath(sys.argv[1])
results = []
def check(name, ok, detail=""):
results.append(bool(ok))
print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" :: {str(detail)[:300]}"), flush=True)
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
port = free_port()
db = os.path.join(tempfile.mkdtemp(prefix="crm-acc-"), "crm.db")
env = dict(os.environ, PORT=str(port), CRM_DB=db)
server = subprocess.Popen([sys.executable, "server.py"], cwd=ws, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
base = f"http://127.0.0.1:{port}"
def call(method, path, body=None):
data = None if body is None else json.dumps(body).encode()
req = urllib.request.Request(base + path, data=data, method=method, headers={"content-type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=10) as r:
raw = r.read()
try:
return r.status, (json.loads(raw) if raw else None)
except ValueError:
return r.status, raw
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw) if raw else None
except ValueError:
return e.code, raw
try:
for _ in range(100):
try:
socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
break
except OSError:
time.sleep(0.1)
st, _ = call("GET", "/")
check("GET / serves the front-end", st == 200, st)
st, co = call("POST", "/api/companies", {"name": "Acme Corp", "website": "https://acme.test", "industry": "tools"})
check("create company 201 with id", st == 201 and isinstance(co, dict) and isinstance(co.get("id"), int), (st, co))
cid = co["id"] if isinstance(co, dict) and "id" in co else 0
st, ct = call("POST", "/api/contacts", {"name": "Wile E. Coyote", "email": "wile@acme.test", "company_id": cid})
check("create contact 201", st == 201 and isinstance(ct, dict) and ct.get("company_id") == cid, (st, ct))
ctid = ct.get("id") if isinstance(ct, dict) else None
st, d = call("POST", "/api/deals", {"title": "Anvil order", "amount": 1500.5, "company_id": cid, "contact_id": ctid})
check("create deal 201 default stage lead", st == 201 and isinstance(d, dict) and d.get("stage") == "lead", (st, d))
did = d.get("id") if isinstance(d, dict) else 0
st, lst = call("GET", "/api/companies?q=acme")
check("search companies (case-insensitive)", st == 200 and isinstance(lst, list) and any(c.get("id") == cid for c in lst), (st, lst))
st, lst = call("GET", "/api/contacts?q=WILE@")
check("search contacts by email", st == 200 and isinstance(lst, list) and len(lst) == 1, (st, lst))
st, d2 = call("PUT", f"/api/deals/{did}", {"title": "Anvil order", "amount": 2000, "stage": "proposal", "company_id": cid, "contact_id": ctid})
check("update deal stage", st == 200 and isinstance(d2, dict) and d2.get("stage") == "proposal" and d2.get("amount") == 2000, (st, d2))
st, _ = call("PUT", f"/api/deals/{did}", {"title": "Anvil order", "amount": 2000, "stage": "bogus"})
check("invalid stage is 400", st == 400, st)
st, lst = call("GET", "/api/deals?stage=proposal&q=anvil")
check("deals filter by stage and q", st == 200 and isinstance(lst, list) and len(lst) == 1, (st, lst))
st, lst = call("GET", "/api/deals?stage=won")
check("deals filter by stage (empty)", st == 200 and lst == [], (st, lst))
st, n = call("POST", f"/api/deals/{did}/notes", {"body": "Called, wants a quote"})
check("add note 201", st == 201 and isinstance(n, dict) and n.get("body") == "Called, wants a quote", (st, n))
st, ns = call("GET", f"/api/deals/{did}/notes")
check("list notes", st == 200 and isinstance(ns, list) and len(ns) == 1, (st, ns))
st, p = call("GET", "/api/pipeline")
check("pipeline summary per stage", st == 200 and isinstance(p, dict) and set(p) == {"lead", "qualified", "proposal", "won", "lost"}
and p["proposal"]["count"] == 1 and p["proposal"]["amount"] == 2000, (st, p))
st, _ = call("POST", "/api/companies", {"website": "x"})
check("missing name is 400", st == 400, st)
st, _ = call("GET", "/api/deals/99999")
check("unknown id is 404", st == 404, st)
st, _ = call("DELETE", f"/api/companies/{cid}")
check("delete company 204", st == 204, st)
st, d3 = call("GET", f"/api/deals/{did}")
check("deleting the company keeps the deal and clears the reference", st == 200 and isinstance(d3, dict) and d3.get("company_id") in (None, 0), (st, d3))
st, _ = call("DELETE", f"/api/deals/{did}")
check("delete deal 204", st == 204, st)
st, _ = call("GET", f"/api/deals/{did}")
check("deleted deal is 404", st == 404, st)
finally:
server.terminate()
try:
server.wait(10)
except subprocess.TimeoutExpired:
server.kill()
t = subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", "tests"], cwd=ws, capture_output=True, text=True, timeout=300)
check("the app's own tests pass (unittest discover -s tests)", t.returncode == 0, t.stderr[-300:])
check("README.md exists", os.path.exists(os.path.join(ws, "README.md")))
print(f"SUMMARY {sum(results)}/{len(results)}")
sys.exit(0 if all(results) else 1)