Spaces:
Running
Running
Download tests/test_frontend.py from RDS777/TARGET_SPACE: direct link, hf CLI and curl.
- Browser
- Download file 17 kB
-
https://huggingface.co/spaces/RDS777/TARGET_SPACE/resolve/main/tests/test_frontend.py
- Command line
-
hf download hf://spaces/RDS777/TARGET_SPACE/tests/test_frontend.py
-
curl -L -o test_frontend.py https://huggingface.co/spaces/RDS777/TARGET_SPACE/resolve/main/tests/test_frontend.py
17 kB
| """Frontend VORTEX / SYMBIOZA 3D : sans build, sans ressource externe, références locales résolues, texte jamais en HTML.""" | |
| import json | |
| import re | |
| from pathlib import Path | |
| import pytest | |
| from fastapi import FastAPI | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.testclient import TestClient | |
| ROOT = Path(__file__).resolve().parents[1] | |
| WEB = ROOT / "web" / "symbioza" | |
| VENDOR = WEB / "static" / "vendor" / "three" | |
| PAGE = WEB / "index.html" | |
| CSS = WEB / "static" / "css" / "hud.css" | |
| HUB_CSS = WEB / "static" / "css" / "hub.css" | |
| APP = WEB / "static" / "js" / "app.js" | |
| HUB = WEB / "static" / "js" / "hub.js" | |
| SHADERS = WEB / "static" / "js" / "shaders.js" | |
| FLAT = WEB / "static" / "js" / "flat.js" | |
| ATELIER = WEB / "static" / "js" / "atelier.js" | |
| ATELIER_CSS = WEB / "static" / "css" / "atelier.css" | |
| OWN_FILES = (PAGE, CSS, HUB_CSS, ATELIER_CSS, APP, HUB, SHADERS, FLAT, ATELIER) | |
| SERVER_ROUTES = {"/gradio/"} # seules adresses du serveur que la page a le droit de citer en lien | |
| IMPORT_RE = re.compile(r"""(?:import\s+(?:[\w*{}\s,]+\s+from\s+)?|export\s+[\w*{}\s,]+\s+from\s+)['"]([^'"]+)['"]""") | |
| def resolve_module(spec: str, base: Path) -> Path: | |
| """Chemin local d'un spécifieur ES : relatif, ``three`` ou ``three/addons/…`` (importmap).""" | |
| if spec.startswith("."): | |
| return (base.parent / spec).resolve() | |
| if spec == "three": | |
| return (VENDOR / "build" / "three.module.js").resolve() | |
| if spec.startswith("three/addons/"): | |
| return (VENDOR / "addons" / spec[len("three/addons/"):]).resolve() | |
| raise AssertionError(f"spécifieur non résolu : {spec}") | |
| def test_frontend_files_exist(): | |
| for path in (*OWN_FILES, VENDOR / "VERSION.txt", VENDOR / "LICENSE.txt"): | |
| assert path.is_file(), f"absent : {path}" | |
| def test_own_frontend_has_no_external_resource(): | |
| for path in OWN_FILES: | |
| text = path.read_text(encoding="utf-8") | |
| text = text.replace("http://www.w3.org/2000/svg", "") # espace de noms XML : un identifiant, jamais une requête | |
| assert not re.search(r"https?://", text), f"URL externe dans {path.name}" | |
| assert "//cdn" not in text and "@import url(" not in text, path.name | |
| def test_page_references_are_local_and_exist(): | |
| text = PAGE.read_text(encoding="utf-8") | |
| refs = re.findall(r'(?:href|src)="([^"]+)"', text) | |
| assert refs, "aucune référence locale trouvée" | |
| for ref in refs: | |
| assert not ref.startswith(("http:", "https:", "//")), ref | |
| if ref.startswith("/"): # lien vers le serveur lui-même, pas vers un fichier du dossier | |
| assert ref in SERVER_ROUTES, ref | |
| continue | |
| assert (WEB / ref.lstrip("./")).is_file(), f"fichier référencé absent : {ref}" | |
| def test_importmap_targets_exist_and_cover_three(): | |
| text = PAGE.read_text(encoding="utf-8") | |
| match = re.search(r'<script type="importmap">(.*?)</script>', text, re.DOTALL) | |
| assert match, "importmap absente" | |
| mapping = json.loads(match.group(1))["imports"] | |
| assert set(mapping) == {"three", "three/addons/"} | |
| for target in mapping.values(): | |
| assert (WEB / target).exists(), target | |
| def test_module_imports_resolve(path): | |
| text = path.read_text(encoding="utf-8") | |
| specs = IMPORT_RE.findall(text) | |
| assert specs, f"aucun import dans {path.name}" | |
| for spec in specs: | |
| target = resolve_module(spec, path) | |
| assert target.is_file(), f"{path.name} importe {spec} : introuvable ({target})" | |
| def test_vendored_three_relative_imports_resolve(): | |
| files = [p for p in VENDOR.rglob("*.js")] | |
| assert files, "three.js vendorisé absent" | |
| for path in files: | |
| for spec in IMPORT_RE.findall(path.read_text(encoding="utf-8")): | |
| if spec.startswith("."): | |
| assert (path.parent / spec).resolve().is_file(), f"{path.relative_to(WEB)} : {spec}" | |
| def test_scripts_only_write_text_never_markup(path): | |
| text = path.read_text(encoding="utf-8") | |
| for forbidden in ("innerHTML", "outerHTML", "insertAdjacentHTML", "document.write", "eval(", "new Function"): | |
| assert forbidden not in text, f"{forbidden} dans {path.name}" | |
| def test_every_element_the_script_touches_exists_in_the_page(path): | |
| script = path.read_text(encoding="utf-8") | |
| page = PAGE.read_text(encoding="utf-8") | |
| ids = set(re.findall(r'\sid="([^"]+)"', page)) | |
| used = set(re.findall(r"\$\('([^']+)'\)", script)) | |
| used |= set(re.findall(r"setText\('([^']+)'", script)) | |
| used |= set(re.findall(r"setPressed\('([^']+)'", script)) | |
| assert used, "aucun élément référencé : regex à revoir" | |
| assert used <= ids, f"ids absents du HTML : {sorted(used - ids)}" | |
| def test_mode_buttons_match_the_modes_of_the_script(): | |
| script = APP.read_text(encoding="utf-8") | |
| page = PAGE.read_text(encoding="utf-8") | |
| modes = set(re.search(r"const MODES = \[([^\]]+)\]", script).group(1).replace("'", "").replace(" ", "").split(",")) | |
| buttons = set(re.findall(r'data-mode="([^"]+)"', page)) | |
| assert modes == buttons == {"surface", "wire", "normals", "bbox", "fluid"} | |
| def test_shader_exports_match_the_script_usage(): | |
| shaders = SHADERS.read_text(encoding="utf-8") | |
| script = APP.read_text(encoding="utf-8") | |
| exported = set(re.findall(r"^export (?:function|const) (\w+)", shaders, re.MULTILINE)) | |
| used = set(re.findall(r"SH\.(\w+)", script)) | |
| assert used <= exported, sorted(used - exported) | |
| def test_static_mount_serves_the_page_and_the_module_with_js_mime(): | |
| app = FastAPI() | |
| app.mount("/symbioza", StaticFiles(directory=WEB, html=True), name="symbioza") | |
| client = TestClient(app) | |
| home = client.get("/symbioza/", headers={"x-admin-key": "secret"}) | |
| assert home.status_code == 200 and "VORTEX" in home.text | |
| js = client.get("/symbioza/static/js/app.js", headers={"x-admin-key": "secret"}) | |
| assert js.status_code == 200 and "javascript" in js.headers["content-type"] | |
| assert client.get("/symbioza/static/js/inconnu.js", headers={"x-admin-key": "secret"}).status_code == 404 | |
| def test_the_phone_inspector_is_placed_from_measured_panels_not_a_fixed_offset(): | |
| """Régression v4.3.3 : un `top` fixe faisait recouvrir les jauges par l'inspecteur dès que l'essaim a grandi.""" | |
| css = CSS.read_text(encoding="utf-8") | |
| script = APP.read_text(encoding="utf-8") | |
| phone = css[css.index("@media (max-width: 760px)"):] | |
| block = re.search(r"\.inspector\s*\{([^}]*)\}", phone).group(1) | |
| assert "--gauges-bottom" in block and "--modes-top" in block | |
| assert not re.search(r"top:\s*\d+px", block), "décalage fixe : il recouvrira un panneau dès que le contenu change" | |
| for var in ("--gauges-bottom", "--modes-top"): | |
| assert f"setProperty('{var}'" in script, var | |
| assert "ResizeObserver" in script and "'resize', measureLayout" in script # remesuré quand le contenu change | |
| def test_one_panel_without_tabs_the_mission_first_and_the_tools_folded(): | |
| """v4.7 : plus d'onglets. La mission en tête ; les quatre outils de l'ancienne interface, repliés dessous.""" | |
| page = PAGE.read_text(encoding="utf-8") | |
| script = HUB.read_text(encoding="utf-8") | |
| assert 'role="tab"' not in page and "TABS" not in script | |
| sections = re.search(r"const SECTIONS = \[([^\]]+)\]", script).group(1).replace("'", "").replace(" ", "").split(",") | |
| assert sections == ["pilotage", "donnees", "verifier", "agents"] | |
| ids = set(re.findall(r'\sid="([^"]+)"', page)) | |
| for name in sections: | |
| assert {f"sec-{name}", f"pane-{name}"} <= ids, name | |
| assert page.index('id="tools"') < page.index(f'id="sec-{name}"') # dans « Outils avancés » | |
| assert page.index('id="mission"') < page.index('id="tools"') # la mission d'abord | |
| for element in ("ms-text", "ms-start", "ms-stop", "ms-approve", "ms-resume", "ms-tasks", "ms-feed", "ms-line", | |
| "admin-key", "btn-gauges"): | |
| assert element in ids and f"'{element}'" in script, element | |
| sizes = re.search(r"const SIZES = \[([^\]]+)\]", script).group(1).replace("'", "").replace(" ", "").split(",") | |
| assert sizes == ["bar", "compact", "full"] | |
| for size in sizes: | |
| assert f'data-size="{size}"' in page | |
| css = HUB_CSS.read_text(encoding="utf-8") | |
| assert '.hub[data-size="bar"] .hub-body' in css and 'body[data-gauges="off"] .gauges' in css | |
| assert "'/mission/start'" in script and "'/mission'" in script | |
| def test_the_arena_leaves_room_only_for_an_open_panel(): | |
| """v4.7 : réduit à sa barre (ou jauges éteintes), le panneau ne décale plus la vue.""" | |
| script = APP.read_text(encoding="utf-8") | |
| assert "dataset.size !== 'bar'" in script and "function shown(" in script | |
| assert "ro.observe($('hub'))" in script | |
| def test_the_page_is_one_page_with_the_arena_and_the_console(): | |
| page = PAGE.read_text(encoding="utf-8") | |
| assert 'id="scene"' in page and 'id="hub"' in page # la 3D et la console dans le même document | |
| assert page.count("<script type=\"module\"") == 2 # app.js (arène) puis hub.js (console) | |
| assert "UNIQUE" in page.split("<title>")[1].split("</title>")[0] | |
| def test_palette_is_black_violet_yellow_and_the_old_red_green_is_gone(): | |
| css = (CSS.read_text(encoding="utf-8") + HUB_CSS.read_text(encoding="utf-8")).lower() | |
| for token in ("--violet:", "--yellow:", "--bg:"): | |
| assert token in css, token | |
| for old in ("#ff0033", "255, 0, 51", "#00ff88", "0, 255, 136", "--red", "--matrix"): | |
| assert old not in css, old | |
| scene = (APP.read_text(encoding="utf-8") + SHADERS.read_text(encoding="utf-8")).lower() | |
| for old in ("#ff0033", "0xff0033", "0x00ff88", "#00ff88"): | |
| assert old not in scene, old | |
| def test_the_arena_follows_the_world_the_console_builds(): | |
| """v4.4 : la console annonce la fin d'une expérience, l'arène relit le monde ; elle ne demande pas plus que l'API ne sert.""" | |
| from mouh.geometry.api import MAX_LIST | |
| app, hub = APP.read_text(encoding="utf-8"), HUB.read_text(encoding="utf-8") | |
| assert "'unique:world'" in app and "'unique:world'" in hub | |
| max_items = int(re.search(r"const MAX_ITEMS = (\d+);", app).group(1)) | |
| assert 12 <= max_items <= MAX_LIST | |
| assert "meta.place" in app or "entry.meta" in app, "l'arène doit placer les objets là où le serveur les a bâtis" | |
| def test_the_world_panel_and_its_button_exist_and_are_wired(): | |
| page, hub = PAGE.read_text(encoding="utf-8"), HUB.read_text(encoding="utf-8") | |
| for element in ("w-summary", "w-run", "w-msg"): | |
| assert f'id="{element}"' in page and f"'{element}'" in hub | |
| assert "'/jobs/world'" in hub and "world: 'batch'" in hub | |
| def test_without_webgl2_the_world_falls_back_to_a_flat_view(): | |
| """v4.5.1 : un navigateur sans WebGL 2 voit le monde en 2D au lieu d'un encart d'erreur seul.""" | |
| app, flat = APP.read_text(encoding="utf-8"), FLAT.read_text(encoding="utf-8") | |
| assert "import { createFlat } from './flat.js';" in app and "createFlat($('scene')" in app | |
| assert "export function createFlat" in flat and "innerHTML" not in flat and "getContext('2d')" in flat | |
| def test_cache_policy_revalidates_the_page_and_spares_the_api(): | |
| from mouh.webui import cache_policy | |
| assert cache_policy("/") == "no-cache" and cache_policy("/static/js/app.js") == "no-cache" | |
| assert cache_policy("/symbioza/static/css/hud.css") == "no-cache" | |
| assert cache_policy("/static/vendor/three/build/three.module.js").startswith("public, max-age=") | |
| assert cache_policy("/api/ui/meta") is None and cache_policy("/gradio/") is None | |
| def test_the_flat_view_is_frugal_on_old_machines(): | |
| """v4.5.3 : tracés groupés, budget de segments par image, aucune image tracée quand rien ne bouge.""" | |
| flat = FLAT.read_text(encoding="utf-8") | |
| assert "new Path2D()" in flat and "EDGE_BUDGET" in flat and "FRAME_MS" in flat | |
| assert "(!dirty && !animated())" in flat | |
| def test_the_learning_block_and_the_mission_queue_are_wired(): | |
| """v4.8 : examen figé, apprentissage automatique et file d'attente dans le panneau, sans nouvel onglet.""" | |
| page, script = PAGE.read_text(encoding="utf-8"), HUB.read_text(encoding="utf-8") | |
| ids = set(re.findall(r'\sid="([^"]+)"', page)) | |
| for element in ("learn", "lr-base", "lr-service", "lr-cand", "lr-auto", "lr-toggle", "lr-measure", "lr-seuil", | |
| "lr-max", "lr-save", "lr-history", "ms-queue", "ms-queue-box", "ms-next", "ms-clear", "rl-exam"): | |
| assert element in ids and f"'{element}'" in script, element | |
| assert page.index('id="mission"') < page.index('id="learn"') < page.index('id="tools"') | |
| for route in ("'/learn'", "'/learn/config'", "'/learn/measure'", "'/mission/next'", "'/mission/queue/clear'"): | |
| assert route in script, route | |
| assert "exam: $('rl-exam').checked" in script | |
| assert "role=\"tab\"" not in page | |
| def test_the_atelier_is_a_flat_2d_view_wired_into_the_page(): | |
| """v4.9 : l'objet en chantier seul au centre, dessiné en 2D (aucun WebGL), lu sur /api/lab, arène masquée.""" | |
| page, app = PAGE.read_text(encoding="utf-8"), APP.read_text(encoding="utf-8") | |
| script, css = ATELIER.read_text(encoding="utf-8"), ATELIER_CSS.read_text(encoding="utf-8") | |
| ids = set(re.findall(r'\sid="([^"]+)"', page)) | |
| for element in ("atelier", "at-canvas", "at-side", "at-state", "at-fold", "at-close", "at-rotate", "at-reset", | |
| "at-follow", "at-pick", "at-metrics", "at-fails", "at-parts", "at-checks", "at-history", "btn-atelier", "at-dot"): | |
| assert element in ids, element | |
| assert '<section id="atelier" class="atelier"' in page and "hidden>" in page.split('id="atelier"')[1].split(">")[0] + ">" | |
| assert page.index('id="scene"') < page.index('id="atelier"') < page.index('class="scanlines"') # sous les panneaux | |
| assert page.index('id="btn-atelier"') < page.index('id="btn-gauges"') | |
| assert 'href="./static/css/atelier.css"' in page | |
| # dessin 2D seulement, lecture seule de l'API du laboratoire | |
| code = "\n".join(line for line in script.splitlines() if not line.lstrip().startswith("//")) | |
| assert "getContext('2d')" in code and "webgl" not in code.lower() and "three" not in code.lower() | |
| assert "const LAB = '/api/lab';" in script and "'/atelier'" in script and "`/atelier/${" in script | |
| assert "export function createAtelier" in script | |
| # app.js : un seul espace libre partagé, l'arène 3D et la vue en plan se taisent quand l'atelier est ouvert | |
| assert "import { createAtelier } from './atelier.js';" in app and "createAtelier({ area: freeArea" in app | |
| assert app.count("body.dataset.atelier === 'on'") >= 3 | |
| assert "area: freeArea" in app and "suspended" in FLAT.read_text(encoding="utf-8") | |
| # l'atelier masque le reste de l'arène et fonctionne sans la 3D | |
| assert 'body[data-atelier="on"] #scene { visibility: hidden; }' in css | |
| assert ".atelier { display: contents; }" in css and ".atelier[hidden] { display: none; }" in css | |
| for hidden in (".modes", ".inspector", ".console", ".gauges"): | |
| assert f'body[data-atelier="on"] {hidden}' in css, hidden | |
| def test_the_atelier_polls_gently_and_draws_nothing_when_nothing_moves(): | |
| script = ATELIER.read_text(encoding="utf-8") | |
| assert "OPEN_MS" in script and "IDLE_MS" in script and "document.hidden" in script | |
| assert "const wait = dirty || rotating ? FRAME_MS : pulsing ? PULSE_MS : Infinity;" in script | |
| assert "prefers-reduced-motion" in script and "MAX_FILL" in script | |
| assert "unique.atelier.follow" in script and "try {" in script # le stockage local est facultatif | |
| def test_two_scores_with_overlapping_intervals_are_not_shown_as_a_difference(): | |
| """v4.9.1 : « 58/84 contre 59/84 » est dit non significatif au lieu d'être lu comme un recul.""" | |
| script = HUB.read_text(encoding="utf-8") | |
| assert "function versusBase(ex)" in script and "écart avec la base non significatif" in script | |
| assert "a.ci95[0] > b.ci95[1] || b.ci95[0] > a.ci95[1]" in script and script.count("versusBase(ex)") >= 3 | |
| def test_the_atelier_shows_the_nomenclature_and_links_the_csv_served_by_the_space(): | |
| """v4.10 : tableau des pièces (désignation, matière, quantité, masse), total, et fichier CSV servi par /api/lab.""" | |
| page, script = PAGE.read_text(encoding="utf-8"), ATELIER.read_text(encoding="utf-8") | |
| ids = set(re.findall(r'\sid="([^"]+)"', page)) | |
| for element in ("at-bom-box", "at-bom", "at-bom-total", "at-bom-mat", "at-bom-notes", "at-bom-csv"): | |
| assert element in ids and f"$('{element}')" in script, element | |
| assert page.index('id="at-parts-box"') < page.index('id="at-bom-box"') < page.index('id="at-checks"') | |
| assert "function fillBom(bom)" in script and "fillBom(report.bom)" in script | |
| assert "/bom.csv`" in script and "link.setAttribute('href', LAB + path)" in script | |
| assert "createObjectURL" not in script, "le fichier vient du Space, pas d'un calcul dans le navigateur" | |