"""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'', 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
@pytest.mark.parametrize("path", [APP, SHADERS])
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}"
@pytest.mark.parametrize("path", [APP, HUB, ATELIER])
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}"
@pytest.mark.parametrize("path", [APP, HUB, ATELIER])
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("