shortstats/tests/unitaires/test_modules_js.py
ploush 81ef12a9cd
Some checks failed
build / test (push) Failing after 2m48s
build / images (collector) (push) Has been skipped
build / images (web) (push) Has been skipped
upgrade 1.4.0
2026-11-29 20:43:50 +01:00

73 lines
3.3 KiB
Python

"""Scripts du site en modules ES : chaque import vise un fichier qui existe et qui exporte
les noms importés ; plus aucune variable globale entre nos scripts (seul le bundle Vega,
script classique, en expose une)."""
from __future__ import annotations
import posixpath
import re
from shortstats.web.templating import HERE
JS = HERE / "static" / "js"
IMPORT = re.compile(r'^import\s+(?:\{([^}]*)\}|\*\s+as\s+\w+)\s+from\s+"([^"]+)";', re.M | re.S)
def _exports(src: str) -> set[str]:
names = set(re.findall(r"^export\s+(?:async\s+)?(?:function|const|let|class)\s+([\w$]+)", src, re.M))
for block in re.findall(r"^export\s*\{([^}]*)\}", src, re.M | re.S):
names |= {n.strip().split(" as ")[-1] for n in block.split(",") if n.strip()}
return names
def test_every_import_resolves_and_is_exported():
modules = sorted(JS.rglob("*.js"))
assert len(modules) >= 12
checked = 0
for path in modules:
src = path.read_text()
for names, target in IMPORT.findall(src):
assert target.startswith("./") or target.startswith("../"), (path.name, target)
dest = (path.parent / target).resolve()
assert dest.is_file(), f"{path.relative_to(JS)} importe {target}, absent"
if names:
wanted = {n.strip().split(" as ")[0] for n in names.split(",") if n.strip()}
missing = wanted - _exports(dest.read_text())
assert not missing, f"{path.relative_to(JS)} importe {sorted(missing)} de {target}, non exportés"
checked += 1
assert checked > 20
def test_no_globals_between_our_scripts():
for path in JS.rglob("*.js"):
src = path.read_text()
assert not re.search(r"window\.Shortstats(?!Vega)\w*", src), path.name
assert '"use strict"' not in src, path.name # implicite dans un module
# chaque module est importé par un autre ou chargé par une page
pages = "".join(p.read_text() for p in (HERE / "templates").glob("*.html"))
imported = set()
for path in JS.rglob("*.js"):
for _names, target in IMPORT.findall(path.read_text()):
imported.add(posixpath.normpath(posixpath.join(path.parent.relative_to(HERE / "static").as_posix(), target)))
for path in JS.rglob("*.js"):
rel = path.relative_to(HERE / "static").as_posix()
assert rel in imported or f"asset('{rel}')" in pages, f"{rel} n'est utilisé nulle part"
def test_package_includes_every_static_file():
"""Le paquet (et donc l'image Docker) embarque chaque fichier servi par le site :
un nouveau dossier de scripts oublié dans pyproject.toml laisserait le site sans eux."""
import fnmatch
import tomllib
from ..outils import RACINE
patterns = tomllib.loads((RACINE / "pyproject.toml").read_text())["tool"]["setuptools"]["package-data"]["shortstats"]
package = RACINE / "src" / "shortstats"
for path in (HERE / "static").rglob("*"):
if path.is_file() and path.parent.name != "__pycache__" and not path.name.endswith(".LEGAL.txt"):
rel = path.relative_to(package).as_posix()
assert any(fnmatch.fnmatchcase(rel, p) and rel.count("/") == p.count("/") for p in patterns), rel
for path in (HERE / "templates").glob("*.html"):
rel = path.relative_to(package).as_posix()
assert any(fnmatch.fnmatchcase(rel, p) for p in patterns), rel