Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-forge/blob/main/server/tests/jsonpages.py # interplane-forge INTERPLANE Forge Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `interplane-forge / server / tests / jsonpages.py` 448 lines ยท 18908 bytes Raw Blame History 1 # ORACLE: host test harness (Python 3 standard library only), not product code. It walks every forged 2 # page under both bases asking for JSON, validates each document against the schema tables of 3 # docs/API.md, checks the documents against their HTML pages, byte-compares the HTML with a base build, 4 # and checks that refused repositories answer 404 with a forge/error/1 document. 5 # python3 server/tests/jsonpages.py NEW_PORT BASE_PORT API_MD DENIED_NAMES [MAXREPOS] 6 # BASE_PORT 0 skips the HTML byte compare. Exit 0 only when every check passed. 7 import html 8 import json 9 import re 10 import sys 11 import urllib.error 12 import urllib.parse 13 import urllib.request 14 15 NEW, BASEP, APIMD, DENIED = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], sys.argv[4].split(",") 16 MAXREPOS = int(sys.argv[5]) if len(sys.argv) > 5 else 1000 17 OWNER = "drakestapleton" 18 fails, passes = [], 0 19 seen_schemas = set() 20 21 22 def ok(msg): 23 global passes 24 passes += 1 25 26 27 def bad(msg): 28 fails.append(msg) 29 print("FAIL " + msg, flush=True) 30 31 32 class NoRedirect(urllib.request.HTTPRedirectHandler): 33 def redirect_request(self, *a, **k): 34 return None 35 36 37 OPENER = urllib.request.build_opener(NoRedirect) 38 39 40 def fetch(port, base, path, accept=None): 41 """GET (no leading /) on port with X-Forge-Base base; returns (status, headers, body bytes).""" 42 req = urllib.request.Request("http://127.0.0.1:%d/%s" % (port, path)) 43 req.add_header("X-Forge-Base", base) 44 req.add_header("X-Real-IP", "10.9.9.7") 45 if accept: 46 req.add_header("Accept", accept) 47 try: 48 r = OPENER.open(req, timeout=120) 49 return r.status, r.headers, r.read() 50 except urllib.error.HTTPError as e: 51 return e.code, e.headers, e.read() 52 53 54 # ---- schema tables from docs/API.md 55 TYPES = ("string", "integer", "boolean", "object", "array") 56 57 58 def parse_type(cell): 59 c = cell.strip().lower() 60 w = c.split()[0] if c else "" 61 if w not in TYPES: 62 return None 63 return (w, c.endswith("or null")) 64 65 66 def parse_api(path): 67 """{schema: {"": {key: type}, " items": {...}, " object": {...}}}""" 68 text = open(path, encoding="utf-8").read().split("\n") 69 out, cur, sub = {}, None, None 70 for ln in text: 71 m = re.match(r"^## `(forge/[a-z-]+/\d+)`", ln) 72 if m: 73 cur, sub = m.group(1), "" 74 out[cur] = {"": {}} 75 continue 76 if ln.startswith("## "): 77 cur = None 78 continue 79 if cur is None: 80 continue 81 m = re.match(r"^### `([a-z_.]+)` (items|object)\s*$", ln) 82 if m: 83 sub = m.group(1) + " " + m.group(2) 84 out[cur][sub] = {} 85 continue 86 if ln.startswith("### "): 87 sub = None 88 continue 89 if ln.startswith("A repo summary"): 90 sub = "summary" 91 out[cur][sub] = {} 92 continue 93 m = re.match(r"^\| `([a-z_0-9]+)` \| ([^|]+) \|", ln) 94 if m and sub is not None: 95 t = parse_type(m.group(2)) 96 if t is None: 97 bad("API.md %s %s: key %s has type '%s' outside the vocabulary" % (cur, sub, m.group(1), m.group(2).strip())) 98 continue 99 out[cur][sub][m.group(1)] = t 100 # forge/explore/1 and forge/repo/1 (written before this card): repo summaries are the explore items 101 # and the first keys of forge/repo/1 102 if "forge/explore/1" in out and "summary" in out["forge/explore/1"]: 103 summ = out["forge/explore/1"].pop("summary") 104 out["forge/explore/1"]["repos items"] = summ 105 if "forge/repo/1" in out: 106 out["forge/repo/1"][""] = dict(summ, **out["forge/repo/1"][""]) 107 out["forge/repo/1"]["last_commit object"] = {"sha": ("string", False), "time": ("string", False), "subject": ("string", False)} 108 out["forge/explore/1"]["repos.last_commit object"] = out["forge/repo/1"]["last_commit object"] 109 return out 110 111 112 SCHEMAS = parse_api(APIMD) 113 REPO_OBJ = {"owner": ("string", False), "name": ("string", False), "rid": ("string", False), "path": ("string", False), "json": ("string", False)} 114 115 116 def tcheck(where, key, val, t): 117 w, nul = t 118 if val is None: 119 if not nul: 120 bad("%s: %s is null, documented %s" % (where, key, w)) 121 return 122 py = {"string": str, "integer": int, "boolean": bool, "object": dict, "array": list}[w] 123 if w == "integer" and isinstance(val, bool): 124 bad("%s: %s is boolean, documented integer" % (where, key)) 125 elif not isinstance(val, py): 126 bad("%s: %s is %s, documented %s" % (where, key, type(val).__name__, w)) 127 128 129 def keycheck(where, obj, table): 130 if not isinstance(obj, dict): 131 bad("%s: not an object" % where) 132 return 133 for k in table: 134 if k not in obj: 135 bad("%s: documented key %s missing" % (where, k)) 136 for k in obj: 137 if k not in table: 138 bad("%s: key %s not documented" % (where, k)) 139 else: 140 tcheck(where, k, obj[k], table[k]) 141 142 143 def walk_sub(where, doc, dotted, kind, table): 144 """apply an items/object table at a dotted path (lists along the way are walked).""" 145 parts = dotted.split(".") 146 nodes = [doc] 147 for p in parts: 148 nxt = [] 149 for n in nodes: 150 if isinstance(n, list): 151 n_items = n 152 else: 153 n_items = [n] 154 for x in n_items: 155 if isinstance(x, dict) and x.get(p) is not None: 156 nxt.append(x[p]) 157 nodes = nxt 158 for n in nodes: 159 if kind == "items": 160 if not isinstance(n, list): 161 bad("%s: %s is not an array" % (where, dotted)) 162 continue 163 for i, x in enumerate(n): 164 if isinstance(x, dict): 165 keycheck("%s %s[%d]" % (where, dotted, i), x, table) 166 else: 167 keycheck("%s %s" % (where, dotted), n, table) 168 169 170 def validate(where, doc, base): 171 s = doc.get("schema") if isinstance(doc, dict) else None 172 if s not in SCHEMAS: 173 bad("%s: schema %r is not documented in docs/API.md" % (where, s)) 174 return False 175 seen_schemas.add(s) 176 sc = SCHEMAS[s] 177 if list(doc.keys())[0] != "schema": 178 bad("%s: first key is not schema" % where) 179 keycheck(where, doc, sc[""]) 180 if "base" in sc[""] and doc.get("base") != base: 181 bad("%s: base %r, want %r" % (where, doc.get("base"), base)) 182 if "repo" in doc and s not in ("forge/repo/1",): 183 keycheck(where + " repo", doc["repo"], REPO_OBJ) 184 for sub, table in sc.items(): 185 if sub == "": 186 continue 187 dotted, kind = sub.rsplit(" ", 1) 188 walk_sub(where, doc, dotted, kind, table) 189 # conventions: links start with the base, shas are 40 hex, times are ISO-8601 UTC 190 for k, v in leaves(doc): 191 if k in ("html", "raw", "blame", "history", "next", "prev", "patch", "diff_path", "tree", "zip", "tar_gz", "download") and isinstance(v, str): 192 if not v.startswith(base): 193 bad("%s: link %s=%r does not start with %s" % (where, k, v, base)) 194 if k == "sha" and isinstance(v, str) and not re.fullmatch(r"[0-9a-f]{40}", v): 195 bad("%s: sha %r is not 40 hex" % (where, v)) 196 if k in ("time", "since", "as_of") and isinstance(v, str) and not re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", v): 197 bad("%s: time %r is not ISO-8601 UTC" % (where, v)) 198 return True 199 200 201 def leaves(x, key=None): 202 if isinstance(x, dict): 203 for k, v in x.items(): 204 yield from leaves(v, k) 205 elif isinstance(x, list): 206 for v in x: 207 yield from leaves(v, key) 208 else: 209 yield key, x 210 211 212 ALT = re.compile(rb'') 213 214 215 def self_href(base, path): 216 return html.escape(base + path, quote=True).replace("'", "'") 217 218 219 # ---- one page: JSON, HTML, alternate link, facts, byte compare 220 pages = 0 221 222 223 def page(base, path, want=200, expect_schema=None): 224 """GET path as JSON and as HTML under base; returns the parsed JSON (or None).""" 225 global pages 226 pages += 1 227 where = "%s%s" % (base, path) 228 st, hd, body = fetch(NEW, base, path, "application/json") 229 if st != want: 230 bad("%s: JSON status %d, want %d" % (where, st, want)) 231 return None 232 if st in (301, 302, 303): 233 hst, hhd, _ = fetch(NEW, base, path) 234 if hst != st or hhd.get("Location") != hd.get("Location"): 235 bad("%s: JSON redirect %d %s differs from HTML %d %s" % (where, st, hd.get("Location"), hst, hhd.get("Location"))) 236 return None 237 ct = hd.get("Content-Type", "") 238 if ct != "application/json; charset=utf-8": 239 bad("%s: JSON content type %r" % (where, ct)) 240 return None 241 try: 242 doc = json.loads(body.decode("utf-8")) 243 except Exception as e: # noqa: BLE001 244 bad("%s: invalid JSON (%s): %r" % (where, e, body[:200])) 245 return None 246 if st >= 400: 247 if doc.get("schema") != "forge/error/1" or doc.get("status") != st: 248 bad("%s: error body %r" % (where, body[:200])) 249 else: 250 validate(where, doc, base) 251 hst, _, hbody = fetch(NEW, base, path) 252 if hst != st: 253 bad("%s: HTML status %d differs from JSON %d" % (where, hst, st)) 254 if ALT.search(hbody): 255 bad("%s: the HTML error page names a JSON alternate" % where) 256 if BASEP: 257 bst, _, bbody = fetch(BASEP, base, path) 258 if bst != hst or hbody != bbody: 259 bad("%s: HTML error page differs from the base build (status %d vs %d)" % (where, hst, bst)) 260 return doc 261 validate(where, doc, base) 262 if expect_schema and doc.get("schema") != expect_schema: 263 bad("%s: schema %s, want %s" % (where, doc.get("schema"), expect_schema)) 264 hst, hhd, hbody = fetch(NEW, base, path) 265 if hst != st: 266 bad("%s: HTML status %d differs from JSON %d" % (where, hst, st)) 267 return doc 268 if not hhd.get("Content-Type", "").startswith("text/html"): 269 return doc 270 alts = ALT.findall(hbody) 271 if not path.endswith(".json"): 272 want_alt = self_href(base, path).encode() 273 if path in ("", "explore"): 274 want_alt = (base + "explore.json").encode() 275 elif re.fullmatch(r"%s/[^/?]+" % OWNER, path) and doc.get("schema") == "forge/repo/1": 276 want_alt = (base + path + ".json").encode() 277 if alts != [want_alt]: 278 bad("%s: HTML alternate links %r, want [%r]" % (where, alts, want_alt)) 279 facts(where, doc, hbody.decode("utf-8", "replace")) 280 if BASEP: 281 bst, _, bbody = fetch(BASEP, base, path) 282 mine = self_href(base, path).encode() 283 stripped = hbody.replace(b'', b"", 1) if alts == [mine] else hbody 284 if bst != hst or stripped != bbody: 285 bad("%s: HTML differs from the base build (status %d vs %d, %d vs %d bytes)" % (where, hst, bst, len(stripped), len(bbody))) 286 return doc 287 288 289 def dicts(x): 290 if isinstance(x, dict): 291 yield x 292 for v in x.values(): 293 yield from dicts(v) 294 elif isinstance(x, list): 295 for v in x: 296 yield from dicts(v) 297 298 299 def esc(s): 300 return html.escape(s, quote=True).replace("'", "'") 301 302 303 def facts(where, doc, h): 304 """the document's facts are on the HTML page: the sha (7 hex) of every listed commit (an object 305 with a subject or an author), every name / title / subject (first 40 bytes), every html link""" 306 for d in dicts(doc): 307 sha = d.get("sha") 308 if isinstance(sha, str) and ("subject" in d or "author" in d) and sha[:7] not in h: 309 bad("%s: commit %s not on the HTML page" % (where, sha[:7])) 310 for k, v in leaves(doc): 311 if not isinstance(v, str) or not v: 312 continue 313 if k in ("title", "subject", "name") and html.escape(v[:40], quote=False) not in h and esc(v[:40]) not in h: 314 bad("%s: %s %r not on the HTML page" % (where, k, v[:40])) 315 elif k in ("html", "path") and v.startswith("/") and ('href="%s' % esc(v)) not in h: 316 bad("%s: link %r not on the HTML page" % (where, v)) 317 318 319 def rel(base, link): 320 return link[len(base):] if link.startswith(base) else None 321 322 323 def rawsame(base, path): 324 """a raw route answers the same bytes with or without the JSON Accept header""" 325 global pages 326 pages += 1 327 a = fetch(NEW, base, path, "application/json") 328 b = fetch(NEW, base, path) 329 if a[0] != 200 or b[0] != 200 or a[2] != b[2] or "json" in (a[1].get("Content-Type") or ""): 330 bad("%s%s: raw route changed by the JSON Accept header (%d/%d, %d/%d bytes)" % (base, path, a[0], b[0], len(a[2]), len(b[2]))) 331 332 333 def link(base, x, *keys): 334 """the first page link (relative to base) among keys of object x""" 335 for k in keys or ("html", "path"): 336 v = x.get(k) if isinstance(x, dict) else None 337 if isinstance(v, str) and rel(base, v): 338 return rel(base, v) 339 return None 340 341 342 # ---- the walk 343 def repo_pages(base, name): 344 r = "%s/%s" % (OWNER, name) 345 home = page(base, r, expect_schema="forge/repo/1") 346 if not home: 347 return 348 br = home.get("default_branch") 349 page(base, r + ".json", expect_schema="forge/repo/1") 350 tree = page(base, "%s/tree/%s" % (r, urllib.parse.quote(br)), expect_schema="forge/tree/1") 351 if tree: 352 ents = tree.get("entries") or [] 353 dirs = [e for e in ents if e.get("type") == "tree"][:1] 354 blobs = [e for e in ents if e.get("type") == "blob"] 355 for d in dirs: 356 if link(base, d, "html"): 357 page(base, link(base, d, "html"), expect_schema="forge/tree/1") 358 small = sorted(blobs, key=lambda e: e.get("size") or 0) 359 pick = small[:1] + [e for e in blobs if e.get("name", "").lower().endswith(".md")][:1] 360 for b in pick: 361 rawsame(base, "%s/raw/%s/%s" % (r, urllib.parse.quote(br), urllib.parse.quote(b.get("path", "")))) 362 if link(base, b, "html"): 363 bl = page(base, link(base, b, "html"), expect_schema="forge/blob/1") 364 if bl and link(base, bl.get("links"), "blame"): 365 page(base, link(base, bl["links"], "blame"), expect_schema="forge/blame/1") 366 if link(base, tree.get("readme"), "html"): 367 page(base, link(base, tree["readme"], "html"), expect_schema="forge/blob/1") 368 cm = page(base, r + "/commits", expect_schema="forge/commits/1") 369 if cm: 370 if cm.get("next") and rel(base, cm["next"]): 371 page(base, rel(base, cm["next"]), expect_schema="forge/commits/1") 372 cs = cm.get("commits") or [] 373 for c in cs[:2]: 374 if link(base, c): 375 page(base, link(base, c), expect_schema="forge/commit/1") 376 if len(cs) >= 2: 377 rawsame(base, "%s/commit/%s.patch" % (r, cs[0]["sha"])) 378 rawsame(base, "%s/commit/%s.diff" % (r, cs[0]["sha"])) 379 page(base, "%s/compare/%s...%s" % (r, cs[1]["sha"], cs[0]["sha"]), expect_schema="forge/compare/1") 380 page(base, r + "/commits/%s" % urllib.parse.quote(br), expect_schema="forge/commits/1") 381 page(base, r + "/compare", expect_schema="forge/compare/1") 382 page(base, r + "/branches", expect_schema="forge/branches/1") 383 tg = page(base, r + "/tags", expect_schema="forge/tags/1") 384 rl = page(base, r + "/releases", expect_schema="forge/releases/1") 385 if rl: 386 if link(base, rl, "next"): 387 page(base, link(base, rl, "next"), expect_schema="forge/releases/1") 388 for x in (rl.get("releases") or [])[:2]: 389 if link(base, x): 390 page(base, link(base, x), expect_schema="forge/release/1") 391 for st in ("", "?state=merged", "?state=archived", "?state=draft", "?state=all"): 392 pl = page(base, r + "/patches" + st, expect_schema="forge/patches/1") 393 if pl and st == "?state=all": 394 for x in (pl.get("patches") or [])[:3]: 395 if link(base, x): 396 page(base, link(base, x), expect_schema="forge/patch/1") 397 rawsame(base, link(base, x) + ".diff") 398 for st in ("", "?state=closed", "?state=all"): 399 il = page(base, r + "/issues" + st, expect_schema="forge/issues/1") 400 if il and st == "?state=all": 401 for x in (il.get("issues") or [])[:3]: 402 if link(base, x): 403 page(base, link(base, x), expect_schema="forge/issue/1") 404 page(base, r + "/search?q=the", expect_schema="forge/repo-search/1") 405 page(base, r + "/search", expect_schema="forge/repo-search/1") 406 page(base, r + "/stargazers", expect_schema="forge/stargazers/1") 407 page(base, r + "/watchers", expect_schema="forge/watchers/1") 408 # refusals of the same repo: a bad ref and a missing object 409 page(base, r + "/tree/-x", want=404) 410 page(base, r + "/commit/" + "0" * 40, want=404) 411 page(base, r + "/patches/ffffffffffffffffffffffffffffffffffffffff", want=404) 412 413 414 def main(): 415 for base in ("/", "/forge/"): 416 ex = page(base, "explore.json", expect_schema="forge/explore/1") 417 page(base, "explore", expect_schema="forge/explore/1") 418 page(base, "search?q=omega", expect_schema="forge/search/1") 419 page(base, "search", expect_schema="forge/search/1") 420 page(base, OWNER, expect_schema="forge/user/1") 421 page(base, OWNER + "?tab=stars", expect_schema="forge/user/1") 422 page(base, OWNER + "?tab=followers", expect_schema="forge/user/1") 423 page(base, OWNER + "?tab=following", expect_schema="forge/user/1") 424 page(base, OWNER + "/followers", expect_schema="forge/user/1") 425 page(base, OWNER + "/following", expect_schema="forge/user/1") 426 page(base, "stars", want=303) 427 page(base, "no-such-user-x", want=404) 428 names = [x["name"] for x in (ex or {}).get("repos", [])][:MAXREPOS] 429 if not names: 430 bad("%s: explore lists no repos" % base) 431 for n in names: 432 repo_pages(base, n) 433 # refused repositories: every page form answers 404 with forge/error/1 434 for d in DENIED: 435 for sfx in ("", ".json", "/tree/main", "/blob/main/README.md", "/commits", "/commit/" + "a" * 40, 436 "/compare", "/branches", "/tags", "/releases", "/patches", "/issues", "/search?q=a", 437 "/stargazers", "/blame/main/README.md"): 438 page(base, "%s/%s%s" % (OWNER, d, sfx), want=404) 439 # forge/stars/1 answers only with a session (signed out it is the 303 above); social/tests/run.sh 440 # signs in and checks it 441 for s in SCHEMAS: 442 if s not in seen_schemas and s not in ("forge/error/1", "forge/stars/1"): 443 bad("schema %s is documented but no walked page answered it" % s) 444 print("jsonpages: %d pages walked, %d schemas seen, %d failures" % (pages, len(seen_schemas), len(fails))) 445 sys.exit(1 if fails else 0) 446 447 448 main()