Files
leleka/scripts/e2e/codex/tasks/nestng-crm/accept.py
T

528 lines
26 KiB
Python

#!/usr/bin/env python3
"""Acceptance for the NestJS + Angular CRM task (no network, no browser; Node.js on PATH).
accept.py WORKSPACE exit 0 = every check passed
Everything runs on a COPY of the workspace in a temp directory (the workspace itself is only read). node_modules are not copied: they are linked
(symlink, on Windows a junction) from WORKSPACE/<dir>/node_modules, or, when the workspace has none (the self-test builds it from the seed alone), from
$NESTNG_NM_ROOT/<dir>/node_modules. Node and npm come from PATH; $NESTNG_NODE_BIN (a directory) is put in front of it. Expected run time 30-120 s.
Groups: structure (read only) / backend build + black-box REST checks over HTTP / the agent's own tests / frontend build / static checks of the frontend.
"""
import glob
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
WS = os.path.abspath(sys.argv[1])
NM_ROOT = os.environ.get("NESTNG_NM_ROOT", "")
STAGES = ["lead", "qualified", "proposal", "won", "lost"]
MIN_TESTS = 15
results = []
def check(name, ok, detail=""):
results.append(bool(ok))
print(("PASS " if ok else "FAIL ") + name + ("" if ok else " :: " + str(detail).replace("\n", " | ")[:300]), flush=True)
def guarded(name, fn):
"""Run fn() -> (ok, detail); an exception is a failed check, not a crash."""
try:
ok, detail = fn()
except Exception as e: # noqa: BLE001
ok, detail = False, "%s: %s" % (type(e).__name__, e)
check(name, ok, detail)
def read(path):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return f.read()
except OSError:
return ""
# ---------------------------------------------------------------- environment
ENV = dict(os.environ)
if os.environ.get("NESTNG_NODE_BIN"):
ENV["PATH"] = os.environ["NESTNG_NODE_BIN"] + os.pathsep + ENV.get("PATH", "")
ENV.update({"CI": "1", "NG_CLI_ANALYTICS": "false", "NG_DISABLE_VERSION_CHECK": "1", "NO_COLOR": "1", "FORCE_COLOR": "0",
"npm_config_update_notifier": "false", "npm_config_fund": "false", "npm_config_audit": "false"})
NPM = shutil.which("npm", path=ENV["PATH"])
NODE = shutil.which("node", path=ENV["PATH"])
def run(cmd, cwd, timeout, env=None):
p = subprocess.run(cmd, cwd=cwd, env=env or ENV, capture_output=True, text=True, timeout=timeout, errors="replace")
return p.returncode, (p.stdout or "") + (p.stderr or "")
def link_dir(target, link):
try:
os.symlink(target, link, target_is_directory=True)
except (OSError, NotImplementedError):
if os.name != "nt":
raise
subprocess.run(["cmd", "/c", "mklink", "/J", link, target], check=True, capture_output=True)
def unlink_dir(link):
"""Remove a link made by link_dir without touching what it points at."""
try:
os.unlink(link)
except OSError:
try:
os.rmdir(link)
except OSError:
pass
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def is_int(v):
return isinstance(v, int) and not isinstance(v, bool)
# ---------------------------------------------------------------- 1. structure
guarded("structure: backend/package.json with build, test and test:e2e scripts", lambda: (
all(k in json.loads(read(os.path.join(WS, "backend", "package.json")) or "{}").get("scripts", {}) for k in ("build", "test", "test:e2e")), "scripts missing"))
guarded("structure: frontend/package.json with a build script", lambda: (
"build" in json.loads(read(os.path.join(WS, "frontend", "package.json")) or "{}").get("scripts", {}), "build script missing"))
guarded("structure: backend/src/main.ts exists", lambda: (os.path.isfile(os.path.join(WS, "backend", "src", "main.ts")), "missing"))
guarded("structure: backend has at least one test file", lambda: (
len(glob.glob(os.path.join(WS, "backend", "src", "**", "*.spec.ts"), recursive=True) + glob.glob(os.path.join(WS, "backend", "test", "**", "*.ts"), recursive=True)) > 0, "no *.spec.ts / test/*.ts"))
guarded("structure: frontend/proxy.conf.json maps /api to port 3000 on the loopback", lambda: (
re.search(r"(127\.0\.0\.1|localhost):3000", json.dumps(json.loads(read(os.path.join(WS, "frontend", "proxy.conf.json")) or "{}").get("/api", {}))) is not None, "no /api proxy target"))
guarded("structure: README.md exists and is not empty", lambda: (len(read(os.path.join(WS, "README.md")).strip()) > 20, "missing or empty"))
guarded("structure: node and npm are available", lambda: (NPM is not None and NODE is not None, "node=%s npm=%s" % (NODE, NPM)))
# ---------------------------------------------------------------- temp copy of the workspace
tmp = tempfile.mkdtemp(prefix="nestng-ws-")
copy = os.path.join(tmp, "ws")
links = []
nm_ok = {}
try:
shutil.copytree(WS, copy, ignore=shutil.ignore_patterns("node_modules", "dist", ".angular", "coverage", "out-tsc", "*.tsbuildinfo", ".git"))
for d in ("backend", "frontend"):
src = os.path.join(WS, d, "node_modules")
if not os.path.isdir(src) and NM_ROOT:
src = os.path.join(NM_ROOT, d, "node_modules")
nm_ok[d] = os.path.isdir(src) and os.path.isdir(os.path.join(copy, d))
if nm_ok[d]:
link = os.path.join(copy, d, "node_modules")
link_dir(os.path.realpath(src), link)
links.append(link)
BE, FE = os.path.join(copy, "backend"), os.path.join(copy, "frontend")
# ------------------------------------------------------------ 2. backend build and start
built = {"ok": False}
def backend_build():
if not (NPM and nm_ok.get("backend")):
return False, "no npm or no backend node_modules"
rc, out = run([NPM, "run", "build"], BE, 240)
built["ok"] = rc == 0 and os.path.isfile(os.path.join(BE, "dist", "main.js"))
return built["ok"], "rc=%s dist/main.js=%s %s" % (rc, os.path.isfile(os.path.join(BE, "dist", "main.js")), out[-200:])
guarded("backend: npm run build succeeds and produces dist/main.js", backend_build)
port = free_port()
server = None
server_log = os.path.join(tmp, "server.log")
if built["ok"]:
env = dict(ENV)
env["PORT"] = str(port)
logf = open(server_log, "w")
server = subprocess.Popen([NODE, os.path.join("dist", "main.js")], cwd=BE, env=env, stdout=logf, stderr=subprocess.STDOUT)
up = False
for _ in range(120):
if server.poll() is not None:
break
try:
socket.create_connection(("127.0.0.1", port), timeout=0.3).close()
up = True
break
except OSError:
time.sleep(0.25)
else:
up = False
guarded("backend: node dist/main.js listens on 127.0.0.1:$PORT", lambda: (up, "not listening; log: " + read(server_log)[-200:]))
BASE = "http://127.0.0.1:%d" % 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", "Accept": "application/json"})
try:
with urllib.request.urlopen(req, timeout=15) as r:
raw, status = r.read(), r.status
except urllib.error.HTTPError as e:
raw, status = e.read(), e.code
try:
js = json.loads(raw.decode("utf-8")) if raw else None
except ValueError:
js = None
return status, js
TAG = "zq%d" % (int(time.time()) % 100000)
def rest(name, fn):
if not up:
check(name, False, "the server is not running")
else:
guarded(name, fn)
def mk_company(name=None, **extra):
s, j = call("POST", "/api/companies", dict({"name": name or TAG + "-co"}, **extra))
assert s == 201 and is_int(j.get("id")), "create company: %s %s" % (s, j)
return j
def mk_contact(name=None, **extra):
s, j = call("POST", "/api/contacts", dict({"name": name or TAG + "-ct"}, **extra))
assert s == 201 and is_int(j.get("id")), "create contact: %s %s" % (s, j)
return j
def mk_deal(title=None, **extra):
s, j = call("POST", "/api/deals", dict({"title": title or TAG + "-dl"}, **extra))
assert s == 201 and is_int(j.get("id")), "create deal: %s %s" % (s, j)
return j
# ---- companies
def t_company_create():
s, j = call("POST", "/api/companies", {"name": TAG + " Acme", "website": "https://acme.test", "industry": "Tools"})
ok = s == 201 and is_int(j.get("id")) and j.get("name") == TAG + " Acme" and j.get("website") == "https://acme.test" and j.get("industry") == "Tools"
return ok, "%s %s" % (s, j)
def t_company_name_required():
a = call("POST", "/api/companies", {"website": "x"})[0]
b = call("POST", "/api/companies", {"name": ""})[0]
c = call("POST", "/api/companies", {"name": 12})[0]
return (a, b, c) == (400, 400, 400), "statuses %s %s %s" % (a, b, c)
def t_company_get_list():
c = mk_company()
s, j = call("GET", "/api/companies/%d" % c["id"])
s2, lst = call("GET", "/api/companies")
ok = s == 200 and j.get("id") == c["id"] and s2 == 200 and isinstance(lst, list) and any(x.get("id") == c["id"] for x in lst)
return ok, "%s %s %s" % (s, s2, type(lst))
def t_company_404():
a = call("GET", "/api/companies/987654")[0]
b = call("PUT", "/api/companies/987654", {"name": "x"})[0]
c = call("DELETE", "/api/companies/987654")[0]
return (a, b, c) == (404, 404, 404), "statuses %s %s %s" % (a, b, c)
def t_company_update():
c = mk_company(industry="Old")
s, j = call("PUT", "/api/companies/%d" % c["id"], {"name": c["name"] + "-x", "industry": "New"})
s2, g = call("GET", "/api/companies/%d" % c["id"])
ok = s == 200 and j.get("industry") == "New" and g.get("name") == c["name"] + "-x" and g.get("industry") == "New"
return ok, "%s %s %s" % (s, j, g)
def t_company_update_invalid():
c = mk_company()
s = call("PUT", "/api/companies/%d" % c["id"], {"name": ""})[0]
return s == 400, "status %s" % s
def t_company_search():
mk_company(TAG + " Searchable Widgets")
mk_company(TAG + " Other")
s, j = call("GET", "/api/companies?q=" + TAG.upper() + "%20SEARCHABLE")
ok = s == 200 and len(j) == 1 and j[0]["name"].endswith("Searchable Widgets")
return ok, "%s %s" % (s, j)
def t_company_delete():
c = mk_company()
a = call("DELETE", "/api/companies/%d" % c["id"])[0]
b = call("GET", "/api/companies/%d" % c["id"])[0]
return (a, b) == (204, 404), "statuses %s %s" % (a, b)
# ---- contacts
def t_contact_create():
c = mk_company()
s, j = call("POST", "/api/contacts", {"name": TAG + " Ann", "email": "ann@acme.test", "phone": "123", "companyId": c["id"]})
ok = s == 201 and is_int(j.get("id")) and j.get("email") == "ann@acme.test" and j.get("phone") == "123" and j.get("companyId") == c["id"]
return ok, "%s %s" % (s, j)
def t_contact_name_required():
a = call("POST", "/api/contacts", {"email": "a@b.co"})[0]
b = call("POST", "/api/contacts", {"name": ""})[0]
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
def t_contact_bad_email():
s = call("POST", "/api/contacts", {"name": "Bob", "email": "not-an-email"})[0]
return s == 400, "status %s" % s
def t_contact_unknown_company():
s = call("POST", "/api/contacts", {"name": "Bob", "companyId": 987654})[0]
return s == 400, "status %s" % s
def t_contact_search():
mk_contact(TAG + " Searchable Ann", email="ann.%s@one.test" % TAG)
mk_contact(TAG + " Bob", email="bob.%s@two.test" % TAG)
s, byname = call("GET", "/api/contacts?q=" + TAG.upper() + "%20searchable")
s2, byemail = call("GET", "/api/contacts?q=BOB." + TAG.upper() + "@TWO")
ok = s == 200 and len(byname) == 1 and s2 == 200 and len(byemail) == 1 and byemail[0]["name"].endswith("Bob")
return ok, "%s %s | %s %s" % (s, byname, s2, byemail)
def t_contact_update_clear_company():
co = mk_company()
ct = mk_contact(companyId=co["id"])
s, j = call("PUT", "/api/contacts/%d" % ct["id"], {"phone": "999", "companyId": None})
g = call("GET", "/api/contacts/%d" % ct["id"])[1]
ok = s == 200 and j.get("phone") == "999" and j.get("companyId") is None and g.get("companyId") is None and g.get("phone") == "999"
return ok, "%s %s %s" % (s, j, g)
def t_contact_404_delete():
ct = mk_contact()
a = call("GET", "/api/contacts/987654")[0]
b = call("DELETE", "/api/contacts/%d" % ct["id"])[0]
c = call("GET", "/api/contacts/%d" % ct["id"])[0]
return (a, b, c) == (404, 204, 404), "statuses %s %s %s" % (a, b, c)
# ---- deals
def t_deal_defaults():
s, j = call("POST", "/api/deals", {"title": TAG + " Renewal"})
ok = s == 201 and is_int(j.get("id")) and j.get("amount") == 0 and j.get("stage") == "lead" and j.get("companyId") is None and j.get("contactId") is None
return ok, "%s %s" % (s, j)
def t_deal_full():
co, ct = mk_company(), mk_contact()
s, j = call("POST", "/api/deals", {"title": TAG + " Full", "amount": 1234.5, "stage": "proposal", "companyId": co["id"], "contactId": ct["id"]})
ok = s == 201 and j.get("amount") == 1234.5 and j.get("stage") == "proposal" and j.get("companyId") == co["id"] and j.get("contactId") == ct["id"]
return ok, "%s %s" % (s, j)
def t_deal_title_required():
a = call("POST", "/api/deals", {"amount": 5})[0]
b = call("POST", "/api/deals", {"title": ""})[0]
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
def t_deal_amount_not_number():
a = call("POST", "/api/deals", {"title": "x", "amount": "lots"})[0]
b = call("POST", "/api/deals", {"title": "x", "amount": -5})[0]
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
def t_deal_invalid_stage():
s = call("POST", "/api/deals", {"title": "x", "stage": "maybe"})[0]
return s == 400, "status %s" % s
def t_deal_unknown_refs():
a = call("POST", "/api/deals", {"title": "x", "companyId": 987654})[0]
b = call("POST", "/api/deals", {"title": "x", "contactId": 987654})[0]
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
def t_deal_move_stage():
d = mk_deal(amount=10)
s, j = call("PUT", "/api/deals/%d" % d["id"], {"stage": "qualified"})
g = call("GET", "/api/deals/%d" % d["id"])[1]
ok = s == 200 and j.get("stage") == "qualified" and g.get("stage") == "qualified" and g.get("title") == d["title"] and g.get("amount") == 10
return ok, "%s %s %s" % (s, j, g)
def t_deal_put_invalid_stage():
d = mk_deal()
s = call("PUT", "/api/deals/%d" % d["id"], {"stage": "nope"})[0]
g = call("GET", "/api/deals/%d" % d["id"])[1]
return s == 400 and g.get("stage") == "lead", "status %s stage %s" % (s, g.get("stage"))
def t_deal_404():
a = call("GET", "/api/deals/987654")[0]
b = call("PUT", "/api/deals/987654", {"stage": "won"})[0]
c = call("DELETE", "/api/deals/987654")[0]
return (a, b, c) == (404, 404, 404), "statuses %s %s %s" % (a, b, c)
def t_deal_stage_filter():
mk_deal(TAG + " f1", stage="won")
mk_deal(TAG + " f2", stage="lost")
s, j = call("GET", "/api/deals?stage=won")
ok = s == 200 and len(j) >= 1 and all(d["stage"] == "won" for d in j) and any(d["title"] == TAG + " f1" for d in j) and not any(d["title"] == TAG + " f2" for d in j)
return ok, "%s n=%s" % (s, None if j is None else len(j))
def t_deal_stage_bogus():
s = call("GET", "/api/deals?stage=bogus")[0]
return s == 400, "status %s" % s
def t_deal_q_and_stage():
mk_deal(TAG + " Alpha one", stage="won")
mk_deal(TAG + " Alpha two", stage="lost")
mk_deal(TAG + " Beta", stage="won")
s, j = call("GET", "/api/deals?stage=won&q=" + TAG.upper() + "%20alpha")
s2, k = call("GET", "/api/deals?q=" + TAG.upper() + "%20ALPHA")
ok = s == 200 and [d["title"] for d in j] == [TAG + " Alpha one"] and s2 == 200 and len(k) == 2
return ok, "%s %s | %s %s" % (s, j, s2, k)
def t_deal_delete():
d = mk_deal()
a = call("DELETE", "/api/deals/%d" % d["id"])[0]
b = call("GET", "/api/deals/%d" % d["id"])[0]
c = call("DELETE", "/api/deals/%d" % d["id"])[0]
return (a, b, c) == (204, 404, 404), "statuses %s %s %s" % (a, b, c)
# ---- pipeline and references
def t_pipeline_shape():
s, j = call("GET", "/api/pipeline")
ok = s == 200 and isinstance(j, dict) and all(st in j and is_int(j[st].get("count")) and isinstance(j[st].get("amount"), (int, float)) for st in STAGES)
return ok, "%s %s" % (s, j)
def t_pipeline_totals():
before = call("GET", "/api/pipeline")[1]
mk_deal(stage="proposal", amount=7.5)
mk_deal(stage="proposal", amount=2.25)
after = call("GET", "/api/pipeline")[1]
ok = (after["proposal"]["count"] == before["proposal"]["count"] + 2 and abs(after["proposal"]["amount"] - before["proposal"]["amount"] - 9.75) < 1e-6
and after["won"] == before["won"])
return ok, "%s -> %s" % (before["proposal"], after["proposal"])
def t_pipeline_matches_list():
pipe = call("GET", "/api/pipeline")[1]
deals = call("GET", "/api/deals")[1]
for st in STAGES:
mine = [d for d in deals if d["stage"] == st]
if pipe[st]["count"] != len(mine) or abs(pipe[st]["amount"] - sum(d["amount"] for d in mine)) > 1e-6:
return False, "stage %s: %s vs %d deals" % (st, pipe[st], len(mine))
return True, ""
def t_delete_company_clears_refs():
co = mk_company()
ct = mk_contact(companyId=co["id"])
d = mk_deal(companyId=co["id"], contactId=ct["id"])
s = call("DELETE", "/api/companies/%d" % co["id"])[0]
c2 = call("GET", "/api/contacts/%d" % ct["id"])
d2 = call("GET", "/api/deals/%d" % d["id"])
ok = s == 204 and c2[0] == 200 and c2[1].get("companyId") is None and d2[0] == 200 and d2[1].get("companyId") is None and d2[1].get("contactId") == ct["id"]
return ok, "%s %s %s" % (s, c2, d2)
def t_delete_contact_clears_refs():
ct = mk_contact()
d = mk_deal(contactId=ct["id"])
s = call("DELETE", "/api/contacts/%d" % ct["id"])[0]
d2 = call("GET", "/api/deals/%d" % d["id"])
return s == 204 and d2[0] == 200 and d2[1].get("contactId") is None, "%s %s" % (s, d2)
def t_ids_unique_integers():
ids = [mk_company()["id"] for _ in range(3)]
return len(set(ids)) == 3 and all(is_int(i) for i in ids), "ids %s" % ids
for nm, fn in [
("rest: POST /api/companies creates (201, integer id, fields)", t_company_create),
("rest: company name is required (400)", t_company_name_required),
("rest: GET company by id and in the list", t_company_get_list),
("rest: unknown company id gives 404 on GET, PUT and DELETE", t_company_404),
("rest: PUT /api/companies/:id updates and persists", t_company_update),
("rest: PUT company with an empty name is 400", t_company_update_invalid),
("rest: ?q= searches companies case-insensitively", t_company_search),
("rest: DELETE company is 204, then 404", t_company_delete),
("rest: POST /api/contacts creates with a company", t_contact_create),
("rest: contact name is required (400)", t_contact_name_required),
("rest: contact email must look like an email (400)", t_contact_bad_email),
("rest: contact with an unknown companyId is 400", t_contact_unknown_company),
("rest: ?q= searches contacts by name and by email", t_contact_search),
("rest: PUT contact updates and companyId null clears it", t_contact_update_clear_company),
("rest: contact 404 on unknown id, DELETE 204", t_contact_404_delete),
("rest: POST /api/deals defaults (amount 0, stage lead, null refs)", t_deal_defaults),
("rest: POST deal with all fields", t_deal_full),
("rest: deal title is required (400)", t_deal_title_required),
("rest: deal amount must be a number >= 0 (400)", t_deal_amount_not_number),
("rest: deal with an invalid stage is 400", t_deal_invalid_stage),
("rest: deal with unknown companyId or contactId is 400", t_deal_unknown_refs),
("rest: PUT deal moves it to another stage", t_deal_move_stage),
("rest: PUT deal with an invalid stage is 400 and changes nothing", t_deal_put_invalid_stage),
("rest: deal 404 on unknown id for GET, PUT and DELETE", t_deal_404),
("rest: GET /api/deals?stage= filters", t_deal_stage_filter),
("rest: GET /api/deals?stage=bogus is 400", t_deal_stage_bogus),
("rest: ?stage= and ?q= combine; q is case-insensitive", t_deal_q_and_stage),
("rest: DELETE deal is 204, then 404", t_deal_delete),
("rest: GET /api/pipeline has count and amount for all five stages", t_pipeline_shape),
("rest: pipeline totals follow new deals", t_pipeline_totals),
("rest: pipeline agrees with the deals list", t_pipeline_matches_list),
("rest: deleting a company clears references, keeps deals", t_delete_company_clears_refs),
("rest: deleting a contact clears the deal reference", t_delete_contact_clears_refs),
("rest: ids are unique integers", t_ids_unique_integers),
]:
rest(nm, fn)
if server is not None:
server.terminate()
try:
server.wait(10)
except subprocess.TimeoutExpired:
server.kill()
# ------------------------------------------------------------ 3. the agent's own backend tests
def count_tests(out):
m = re.search(r"Tests:\s+(?:(\d+) failed,\s*)?(?:(\d+) skipped,\s*)?(?:(\d+) todo,\s*)?(?:(\d+) passed,\s*)?(\d+) total", out)
if not m:
return 0, 0
return int(m.group(4) or 0), int(m.group(1) or 0)
own = {"passed": 0}
def own_tests(script):
def f():
if not (NPM and nm_ok.get("backend")):
return False, "no npm or no backend node_modules"
rc, out = run([NPM, "run", script], BE, 240)
passed, failed = count_tests(out)
own["passed"] += passed if rc == 0 else 0
return rc == 0 and failed == 0 and passed >= 1, "rc=%s passed=%s failed=%s %s" % (rc, passed, failed, out[-250:])
return f
guarded("backend tests: npm test passes (>= 1 test)", own_tests("test"))
guarded("backend tests: npm run test:e2e passes (>= 1 test)", own_tests("test:e2e"))
check("backend tests: at least %d test cases pass in total" % MIN_TESTS, own["passed"] >= MIN_TESTS, "total passed %d" % own["passed"])
# ------------------------------------------------------------ 4. frontend build
def frontend_build():
if not (NPM and nm_ok.get("frontend")):
return False, "no npm or no frontend node_modules"
rc, out = run([NPM, "run", "build"], FE, 280)
idx = glob.glob(os.path.join(FE, "dist", "**", "index.html"), recursive=True)
return rc == 0 and len(idx) > 0, "rc=%s index.html=%d %s" % (rc, len(idx), out[-300:])
guarded("frontend: npm run build (production) succeeds and writes index.html", frontend_build)
finally:
for lk in links:
unlink_dir(lk)
shutil.rmtree(tmp, ignore_errors=True)
# ---------------------------------------------------------------- 5. static checks of the frontend sources (read only, on the workspace)
SRC = os.path.join(WS, "frontend", "src")
files = [p for p in glob.glob(os.path.join(SRC, "**", "*"), recursive=True) if os.path.isfile(p) and p.endswith((".ts", ".html")) and not p.endswith(".spec.ts")]
texts = {p: read(p) for p in files}
alltext = "\n".join(texts.values())
ts_text = "\n".join(t for p, t in texts.items() if p.endswith(".ts"))
guarded("frontend src: Router config with companies, contacts and deals routes", lambda: (
re.search(r"\bRoutes\b", ts_text) is not None and all(re.search(r"""path\s*:\s*['"]%s['"]""" % r, ts_text) for r in ("companies", "contacts", "deals")), "routes not found"))
guarded("frontend src: router outlet and provideRouter are used", lambda: (
re.search(r"router-outlet|RouterOutlet", alltext) is not None and re.search(r"provideRouter|RouterModule", ts_text) is not None, "missing"))
guarded("frontend src: HttpClient is provided and injected", lambda: (
re.search(r"provideHttpClient|HttpClientModule", ts_text) is not None and re.search(r"inject\(\s*HttpClient\s*\)|:\s*HttpClient\b", ts_text) is not None, "missing"))
guarded("frontend src: calls /api/companies, /api/contacts and /api/deals", lambda: (
all(re.search(r"/api/" + r, ts_text) or (re.search(r"/api/\$\{", ts_text) and r in ts_text) for r in ("companies", "contacts", "deals")), "no calls to the API"))
guarded("frontend src: create, update and delete requests are made", lambda: (
all(re.search(pat, ts_text) for pat in (r"\.post\s*[<(]", r"\.(put|patch)\s*[<(]", r"\.delete\s*[<(]")), "post/put/delete missing"))
guarded("frontend src: a board with one column per stage (all five stages and a loop over stages)", lambda: (
all(st in alltext for st in STAGES) and any(re.search(r"@for|\*ngFor|\.map\(|\.forEach\(", t) and re.search(r"stage", t, re.I) for t in texts.values()), "the five stages and a loop over stages are not both in the frontend sources"))
guarded("frontend src: a search input", lambda: (
re.search(r"<input[^>]*search", alltext, re.I) is not None, "no <input ... search ...>"))
guarded("frontend src: forms use FormsModule or ReactiveFormsModule", lambda: (
re.search(r"FormsModule|ReactiveFormsModule|FormBuilder|FormControl", ts_text) is not None, "no forms module"))
guarded("frontend src: components for companies, contacts and deals exist", lambda: (
re.search(r"@Component", ts_text) is not None and all(re.search(r"class\s+\w*" + r, ts_text, re.I) for r in ("Compan", "Contact", "Deal")), "components missing"))
print("SUMMARY %d/%d" % (sum(results), len(results)))
sys.exit(0 if all(results) else 1)