"""The published Space renders, and its pages agree with the data and each other. Two failures this suite exists for, both of which shipped: * /probes/ was rendered from its own sampling run, so it showed clips of probes that were not in the published set, including one from a session the set excludes. Two pages, one dataset, opposite answers. * a tile's was 464x480 while its was 464x348, so every overlay sat 93 px from the sensor it annotated while every arithmetic check stayed green. So this checks three things a screenshot cannot: that each page loads clean, that what it displays matches the published artefacts it describes, and that overlay canvases actually cover their images. python scripts/test_site.py [--base URL] """ from __future__ import annotations import argparse import asyncio import json import sys import tempfile import urllib.error import urllib.request from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from react_toolbox.staging import staging_dir RESULTS: list[tuple[bool, str, str]] = [] BASE = "https://yxma-react-force-recovery.static.hf.space" PAGES = ["testset/index.html", "probes/index.html", "calib/a/index.html", "calib/pre/index.html"] def check(ok: bool, name: str, evidence: str) -> None: RESULTS.append((bool(ok), name, evidence)) async def audit(base, pages): from playwright.async_api import async_playwright out = {} async with async_playwright() as pw: b = await pw.chromium.launch() for p in pages: pg = await b.new_page(viewport={"width": 1440, "height": 1000}) errs, bad = [], [] pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) # the FULL url. Storing the basename and rebuilding # f"{base}/{dir}/{name}" dropped the subdirectory, so the retry # fetched /testset/run4_trans-y.jpg for a file that lives at # /testset/overlays/... — a 404 on a URL that never existed, which # I read as a missing file when all 72 were present. pg.on("response", lambda r: bad.append((r.status, r.url)) if r.status >= 400 else None) r = await pg.goto(f"{base}/{p}", wait_until="networkidle", timeout=90000) await pg.evaluate("window.scrollTo(0, document.body.scrollHeight)") await pg.wait_for_timeout(3500) d = await pg.evaluate("""(() => { const im = [...document.querySelectorAll('img')]; const cv = [...document.querySelectorAll('.tile, .zoomwrap')].map(t => { const i = t.querySelector('img'), c = t.querySelector('canvas'); if (!i || !c) return 0; const a = i.getBoundingClientRect(), b = c.getBoundingClientRect(); return Math.max(Math.abs(a.x-b.x), Math.abs(a.y-b.y), Math.abs(a.width-b.width), Math.abs(a.height-b.height)); }); const vd = [...document.querySelectorAll('video')]; return {imgs: im.length, broken: im.filter(x => x.naturalWidth === 0 && x.getAttribute('src')).length, videos: vd.length, vsrc: vd.length ? vd[0].currentSrc || vd[0].src : null, overflow: document.documentElement.scrollWidth > window.innerWidth, canvasGap: cv.length ? Math.max(...cv) : null, title: document.title}; })()""") out[p] = {"status": r.status, "errs": errs, "bad": bad, **d} await pg.close() await b.close() return out def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--base", default=BASE) a = ap.parse_args() au = asyncio.run(audit(a.base, PAGES)) # 1 — every page loads clean. # # A sub-resource failure is RE-REQUESTED before it counts. The static Space # returns transient 429/503 under a cold start, and the first version of # this check reported 4 failures on a page whose files were all present — # a re-run showed zero. A flaky check that cries wolf is worse than none, # because the next real failure gets waved through. persist = [] for pg_, v in au.items(): for st, url in v["bad"]: name = url.rsplit("/", 1)[-1] try: again = urllib.request.urlopen(url, timeout=45).status except urllib.error.HTTPError as e: again = e.code except Exception: again = 0 if again >= 400 or again == 0: persist.append(f"{pg_}: {name} -> {st} then {again}") bad = [f"{p_}: HTTP {v['status']}" for p_, v in au.items() if v["status"] != 200] bad += persist # A console error CAUSED by a transient 4xx is that 4xx counted twice. The # browser logs "Failed to load resource" for the same request `persist` # already adjudicated, so only errors that are not about a re-fetchable # sub-resource count as page defects. def real_errs(v): urls = {u.rsplit("/", 1)[-1] for _, u in v["bad"]} return [e for e in v["errs"] if not any(u and u in e for u in urls) and "Failed to load resource" not in e] bad += [f"{p_}: {len(real_errs(v))} console errors {real_errs(v)[:1]}" for p_, v in au.items() if real_errs(v)] transient = sum(len(v["bad"]) for v in au.values()) - len(persist) check(not bad, "every page loads with no persistent 4xx and no console errors", f"{len(PAGES)} pages, all HTTP 200, 0 persistent sub-resource failures, " f"0 console errors" + (f" ({transient} transient, re-requested OK)" if transient else "") + (f"; {bad[:3]}" if bad else "")) # 2 — nothing broken or overflowing # RE-FETCH before calling an image broken. One that lost a race with a # cold-start 429 reports naturalWidth 0 while its file is perfectly there — # measured, 4 of them on one run and 0 on the next. My first attempt at # this patch searched for `p_` where the file said `p`, so `.replace()` # silently did nothing and the run that happened not to hit a 429 reported # a clean pass. Every edit here now asserts its anchor. br = [] for p_, v in au.items(): if not v["broken"]: continue still = 0 for st, url in v["bad"]: if url.endswith((".jpg", ".jpeg", ".png", ".webp", ".gif")): try: if urllib.request.urlopen(url, timeout=45).status >= 400: still += 1 except Exception: still += 1 if still: br.append(f"{p_}: {still} genuinely broken imgs") ov = [p_ for p_, v in au.items() if v["overflow"]] n_transient_img = sum(v["broken"] for v in au.values()) check(not br and not ov, "no broken media and no horizontal overflow", f"{sum(v['imgs'] for v in au.values())} images, " f"{sum(v['videos'] for v in au.values())} videos, 0 persistently broken, " f"0 overflowing" + (f" ({n_transient_img} lost a race with a cold-start 429, all " f"re-fetched OK)" if n_transient_img else "") + (f"; {br + ov}" if (br or ov) else "")) # 3 — VIDEOS ACTUALLY DECODE. Counting