Files
stack/tests/dev/test_dossier_page_build.py

210 lines
7.8 KiB
Python

"""dev/scripts/dossier_page/build.py: the lex app shell (lex S1 Task 5).
The page carries no data: build.py inlines the fhirworx design system (R85)
and stamps the module version on the entry script. It imports stdlib only.
"""
from __future__ import annotations
import ast
import importlib.util
import os
import re
import subprocess
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
BUILD = ROOT / "dev/scripts/dossier_page/build.py"
TEMPLATE = ROOT / "dev/scripts/dossier_page/template.html"
ASSETS = ROOT / "infra/gitea/custom/public/assets/dossier"
_spec = importlib.util.spec_from_file_location("_lex_page_build", BUILD)
build = importlib.util.module_from_spec(_spec)
sys.modules["_lex_page_build"] = build
_spec.loader.exec_module(build)
def _run(out: Path, **env: str) -> subprocess.CompletedProcess[str]:
e = {k: v for k, v in os.environ.items() if k != "DOMAIN"} | env
return subprocess.run(
[sys.executable, "-I", str(BUILD), "--out", str(out)],
capture_output=True,
text=True,
timeout=60,
check=False,
env=e,
cwd=out.parent,
)
def test_build_writes_shell(tmp_path: Path) -> None:
out = tmp_path / "index.html"
r = _run(out)
assert r.returncode == 0, r.stderr
page = out.read_text(encoding="utf-8")
assert "/*__" not in page and "<!--__" not in page
m = re.search(r'src="/assets/dossier/app\.js\?v=([0-9a-f]{12})"', page)
assert m, "entry module with its version"
assert '<script id="data"' not in page
assert "--fhirworx" in page or "--primary" in page
assert m.group(1) == build.module_version(ASSETS)
size = out.stat().st_size
assert r.stdout.strip() == f"wrote {out} ({size:,} bytes) v={m.group(1)}"
assert not list(tmp_path.glob(".*.tmp")), "written atomically"
def test_shell_structure(tmp_path: Path) -> None:
out = tmp_path / "index.html"
assert _run(out).returncode == 0
page = out.read_text(encoding="utf-8")
for el in (
'id="rail"',
'id="q"',
'id="toc"',
'id="main"',
'id="mast"',
'id="tabs"',
'id="view"',
'id="drawer"',
'id="status"',
'id="theme-btn"',
'id="tip"',
):
assert el in page, el
assert 'class="shell"' in page and 'class="masthead"' in page
# the theme bootstrap stays inline; the app is the one module script
assert 'localStorage.getItem("lex-theme")' in page
scripts = re.findall(r"<script\b([^>]*)>", page)
assert len(scripts) == 2, scripts
assert sum('type="module"' in s for s in scripts) == 1
assert not re.search(r'<script[^>]+src="(?!/assets/dossier/app\.js\?v=)', page)
assert "JSON.parse(document.getElementById" not in page
# the fhirworx logo symbol and the three favicons are inlined
assert '<symbol id="fw-logo"' in page
icons = re.findall(
r'<link rel="(?:icon|apple-touch-icon)"[^>]*href="data:image/', page
)
assert len(icons) == 3
assert ':root[data-theme="dark"] {' in page
def test_domain_fills(tmp_path: Path) -> None:
out = tmp_path / "index.html"
assert _run(out, DOMAIN="example.test").returncode == 0
page = out.read_text(encoding="utf-8")
assert "lex.example.test" in page
assert 'href="https://git.example.test/"' in page
assert 'href="https://dashboard.example.test/"' in page
assert "fhirworx.io" not in page
def test_build_imports_only_stdlib() -> None:
tree = ast.parse(BUILD.read_text(encoding="utf-8"))
mods = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
mods |= {a.name.split(".")[0] for a in node.names}
elif isinstance(node, ast.ImportFrom):
mods.add((node.module or "").split(".")[0])
assert mods, "no imports found"
assert mods <= set(sys.stdlib_module_names) | {"__future__"}, mods
def test_module_version(tmp_path: Path) -> None:
(tmp_path / "a.js").write_bytes(b"export const a = 1;\n")
(tmp_path / "b.js").write_bytes(b"export const b = 2;\n")
(tmp_path / "index.html").write_text("<p>page</p>")
v = build.module_version(tmp_path)
assert re.fullmatch(r"[0-9a-f]{12}", v)
(tmp_path / "index.html").write_text("<p>other</p>")
assert build.module_version(tmp_path) == v, "only *.js counts"
(tmp_path / "b.js").write_bytes(b"export const b = 3;\n")
v2 = build.module_version(tmp_path)
assert v2 != v
(tmp_path / "b.js").rename(tmp_path / "c.js")
assert build.module_version(tmp_path) != v2, "names count"
with pytest.raises(SystemExit, match="no \\*.js"):
build.module_version(tmp_path / "empty")
def test_fill_asserts_the_count() -> None:
assert build._fill("a X b", "X", "y") == "a y b"
assert build._fill("X X", "X", "y", count=2) == "y y"
with pytest.raises(SystemExit, match="expected 1 'X', found 2"):
build._fill("X X", "X", "y")
def test_default_out_is_the_served_page() -> None:
assert build.parse_args([]).out == ASSETS / "index.html"
def test_template_css_uses_tokens_only() -> None:
tpl = TEMPLATE.read_text(encoding="utf-8")
styles = re.findall(r"<style>(.*?)</style>", tpl, re.S)
assert len(styles) == 1, "one lex stylesheet besides the two inlined ones"
css = re.sub(r"/\*.*?\*/", "", styles[0], flags=re.S)
assert not re.search(r"#[0-9A-Fa-f]{3,8}\b", css), "a literal colour"
assert not re.search(r"\b(rgb|hsl)a?\(", css), "a literal colour"
for sel in (".err", ".acc", "[data-ref]", "[data-fact]"):
assert sel in css, sel
assert "cdn" not in tpl.lower()
def test_main_in_process(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
) -> None:
monkeypatch.setenv("DOMAIN", "example.test")
out = tmp_path / "sub" / "index.html"
assert build.main(["--out", str(out)]) == 0
v = build.module_version(ASSETS)
assert capsys.readouterr().out.strip() == (
f"wrote {out} ({out.stat().st_size:,} bytes) v={v}"
)
assert f'app.js?v={v}"' in out.read_text(encoding="utf-8")
def test_design_system_guards(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
css = tmp_path / "fw.css"
css.write_text(":root {\n --background: #fff;\n}\n/* </style> */\n")
monkeypatch.setattr(build, "FHIRWORX_CSS", css)
with pytest.raises(SystemExit, match="would end the inline"):
build.build_page("example.test", "0" * 12)
with pytest.raises(SystemExit, match="no :root block"):
build._root_vars(_write(tmp_path / "x.css", "a{}"))
with pytest.raises(SystemExit, match="cannot resolve --b"):
build._resolve({"--a": "var(--b)"}, "--a", css)
with pytest.raises(SystemExit, match="cannot resolve"):
build._resolve({"--a": "var(--a)"}, "--a", css) # a cycle
with pytest.raises(SystemExit, match="token --foreground is gone"):
build._dark_palette()
light = _write(
tmp_path / "light.css",
":root {\n" + "".join(f" --{t}: #000000;\n" for t in build.DARK_ROLES) + "}\n",
)
dark = _write(
tmp_path / "dark.css",
":root {\n"
+ "".join(f" {s}: #111111;\n" for s in set(build.DARK_ROLES.values()))
+ "}\n",
)
monkeypatch.setattr(build, "FHIRWORX_CSS", light)
monkeypatch.setattr(build, "GITEA_DARK", dark)
assert "--background: #111111; /* --fw-background */" in build._dark_palette()
_write(dark, dark.read_text().replace("--fw-card: #111111", "--fw-card: red"))
with pytest.raises(SystemExit, match="expected a hex colour"):
build._dark_palette()
icons = tmp_path / "icons"
icons.mkdir()
_write(icons / "logo.svg", "<svg><g/></svg>")
monkeypatch.setattr(build, "ICONS", icons)
with pytest.raises(SystemExit, match="expected one <svg viewBox"):
build._logo_symbol()
def _write(path: Path, text: str) -> Path:
path.write_text(text, encoding="utf-8")
return path