make-app/test/live_test.py
2026-11-28 15:28:01 +02:00

145 lines
5.8 KiB
Python

#!/usr/bin/env python3
"""Checks the Make app files without Make: JSON is valid, references exist, and the
requests of the action modules work against the API with a Sandbox key.
TEST_API_URL=https://api.example.test TEST_API_KEY=sandbox_... python3 test/live_test.py
Only a small part of IML is understood here (the expressions these modules use).
"""
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
UNDEF = object()
def load(path):
with open(os.path.join(ROOT, path), encoding="utf-8") as f:
return json.load(f)
def expr(e, params):
e = e.strip()
if re.fullmatch(r"[A-Z_]+", e):
return "{{" + e + "}}" # brand marker, replaced by the generator
m = re.fullmatch(r"parameters\.(\w+)", e)
if m:
v = params.get(m.group(1))
return UNDEF if v is None else v
if e == "uuid":
return str(uuid.uuid4())
if e == "undefined":
return UNDEF
if re.fullmatch(r"'[^']*'", e):
return e[1:-1]
m = re.fullmatch(r"ifempty\((.+?);\s*(.+)\)", e)
if m:
v = expr(m.group(1), params)
return expr(m.group(2), params) if v in (UNDEF, "", [], {}) else v
m = re.fullmatch(r"(encodeURL|lower|trim)\((.+)\)", e)
if m:
v = str(expr(m.group(2), params))
return {"encodeURL": urllib.parse.quote, "lower": str.lower, "trim": str.strip}[m.group(1)](v)
m = re.fullmatch(r"if\(length\(parameters\.(\w+)\) > 0; toCollection\(parameters\.\w+; 'name'; 'value'\); undefined\)", e)
if m:
items = params.get(m.group(1)) or []
return {i["name"]: i.get("value", "") for i in items} if items else UNDEF
raise ValueError("expression not covered by this test: " + e)
def render(value, params):
if isinstance(value, dict):
out = {}
for k, v in value.items():
r = render(v, params)
if r is not UNDEF:
out[k] = r
return out
if isinstance(value, list):
return [render(v, params) for v in value]
if isinstance(value, str):
whole = re.fullmatch(r"\{\{(.+)\}\}", value)
if whole and "{{" not in whole.group(1):
return expr(whole.group(1), params)
return re.sub(r"\{\{(.+?)\}\}", lambda m: str(expr(m.group(1), params)), value)
return value
def call(base, key, comm, params):
c = render({k: v for k, v in comm.items() if k not in ("response", "log", "pagination")}, params)
url = base + c["url"]
if c.get("qs"):
url += "?" + urllib.parse.urlencode(c["qs"])
data = json.dumps(c["body"]).encode() if "body" in c else None
headers = {"Authorization": "Bearer " + key, "Accept": "application/json", "User-Agent": "make-app-test"}
headers.update({k: v for k, v in c.get("headers", {}).items() if "{{" not in v})
if data:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, method=c.get("method", "GET"), headers=headers)
try:
with urllib.request.urlopen(req, timeout=60) as r:
return r.status, json.loads(r.read() or b"{}")
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read() or b"{}")
def main():
app = load("makecomapp.json")
mods = app["components"]["module"]
results = []
def check(name, ok, info=""):
results.append(("ok" if ok else "FAIL", name + ("" if ok else ": " + info)))
for name, m in mods.items():
for f in m["codeFiles"].values():
load(f)
check("all files load as JSON", True)
base = os.environ.get("TEST_API_URL", "").rstrip("/")
key = os.environ.get("TEST_API_KEY", "")
if not (base and key):
results.append(("skip", "live checks (set TEST_API_URL and TEST_API_KEY)"))
else:
conn = load(app["components"]["connection"]["apikey"]["codeFiles"]["communication"])
s, b = call(base, key, dict(conn, url=conn["url"].replace("https://api.interweb.ao", "")), {"apiKey": key})
check("connection test", s == 200 and b["data"]["mode"] == "sandbox", str(s))
cases = {
"sendSms": {"number": "923123456", "text": "Make app test."},
"sendEmail": {"from": os.environ.get("TEST_EMAIL_FROM", "noreply@example.com"), "to": ["joao.fernandes@example.com"],
"subject": "Make app test", "text": "Hello {{name}}", "variables": [{"name": "name", "value": "João"}]},
"addEmailContact": {"email": "make-test@example.com", "name": "João Fernandes"},
"createDnsRecord": {"domain": os.environ.get("TEST_DNS_DOMAIN", "example.co.ao"), "type": "TXT", "name": "make-test", "value": "make-app-test"},
"whoisLookup": {"domain": " Example.co.ao ", "language": "en"},
"checkAvailability": {"domain": "example.co.ao"},
}
for name, params in cases.items():
comm = load(mods[name]["codeFiles"]["communication"])
s, b = call(base, key, comm, params)
check("live: " + name, 200 <= s < 300 and "data" in b, "%s %s" % (s, json.dumps(b)[:200]))
for rpc, r in app["components"]["rpc"].items():
comm = load(r["codeFiles"]["communication"])
comm = json.loads(json.dumps(comm).replace("{{pagination.page}}", "1"))
s, b = call(base, key, comm, {})
check("live rpc: " + rpc, s == 200 and isinstance(b.get("data"), list), str(s))
for wh, w in app["components"]["webhook"].items():
first = load(w["codeFiles"]["attach"])[0]
s, b = call(base, key, first, {})
check("live webhook read: " + wh, s == 200 and "url" in b.get("data", {}), str(s))
for r in results:
print(r[0].ljust(5), r[1])
sys.exit(1 if any(r[0] == "FAIL" for r in results) else 0)
if __name__ == "__main__":
main()