"""Smoke + regression tests for composing-html. Run with: python -m pytest composing-html/tests -q or python composing-html/tests/test_smoke.py (no pytest needed) Covers every template builder with a representative spec, then asserts each output: - starts with `` - parses cleanly with html.parser - contains the expected content marker - does NOT contain raw `" def test_table_does_not_emit_raw_script(): out = table(["x"], [[INJECT]]) assert " after", "variables": [{"name": "x", "default": ""}], }) # Inside the inlined JS string literal, ` must not appear except as the closing tag # of the actual ") assert closing_tags == 1, ( f"expected exactly one (the real closer); found {closing_tags}" ) def test_flag_editor_escapes_id_in_attrs(): out = _build("editor.flag_editor", { "title": "f", "flags": [{"id": 'a"b', "label": "L", "default": True, "requires": ['x"y']}], }) # The injected " must be HTML-escaped inside both the data-id and # data-requires attributes; the surrounding attribute uses double quotes. assert 'data-id="a"b"' in out assert """ in out # JSON " inside data-requires is escaped def test_flag_editor_handles_missing_id(): out = _build("editor.flag_editor", { "title": "f", "flags": [{"label": "no-id", "default": False}], }) assert "" in out # no KeyError def test_module_map_does_not_mutate_spec(): spec = {"nodes": [{"id": "a", "label": "A"}, {"id": "b", "label": "B"}], "edges": [{"from": "a", "to": "b"}]} snap = json.dumps(spec, sort_keys=True) _build("review.module_map", spec) assert json.dumps(spec, sort_keys=True) == snap, ( "module_map mutated the caller's spec — nodes still hold injected x/y" ) def test_module_map_warns_on_unknown_edge(capsys): spec = {"nodes": [{"id": "a", "label": "A"}], "edges": [{"from": "a", "to": "missing"}]} _build("review.module_map", spec) err = capsys.readouterr().err assert "unknown id" in err or "missing" in err def test_slide_deck_raises_on_unknown_kind(): try: _build("deck.slide_deck", {"slides": [{"kind": "contant", "title": "x"}]}) except ValueError as e: assert "unknown slide kind" in str(e) else: raise AssertionError("expected ValueError") def test_css_color_rejects_injection(): assert css_color("#D97757") == "#D97757" assert css_color("var(--clay)") == "var(--clay)" assert css_color("rgb(217,119,87)") == "rgb(217,119,87)" assert css_color("red;background-image:url(http://x)") != "red;background-image:url(http://x)" assert css_color("javascript:alert(1)") != "javascript:alert(1)" assert css_color("transparent") == "transparent" def test_describe_emits_valid_json(): """Regression for #8 — the printed skeleton must round-trip via json.loads.""" import contextlib import io import re import build as _build_mod class _Args: pass for name in REGISTRY: a = _Args(); a.template = name buf = io.StringIO() with contextlib.redirect_stdout(buf): _build_mod.cmd_describe(a) out = buf.getvalue() m = re.search(r"```json\n(.*?)\n```", out, re.DOTALL) assert m, f"{name}: no JSON block in describe output" json.loads(m.group(1)) # raises if invalid # --------------------------------------------------------------------------- # # --set CLI override behavior # # --------------------------------------------------------------------------- # def test_apply_set_inline_value(): from build import _apply_set spec = {} rc = _apply_set(spec, ["title=Hello", "subtitle=World"]) assert rc == 0 assert spec == {"title": "Hello", "subtitle": "World"} def test_apply_set_preserves_equals_in_value(): """KEY=VALUE uses str.partition('='), so '=' inside the value survives.""" from build import _apply_set spec = {} rc = _apply_set(spec, ["extra_css=.x { content: 'a=b'; }"]) assert rc == 0 assert spec["extra_css"] == ".x { content: 'a=b'; }" def test_apply_set_loads_file_with_at_prefix(): """KEY=@FILE loads the file's raw contents — newlines, quotes, all OK.""" import tempfile from build import _apply_set with tempfile.TemporaryDirectory() as td: p = Path(td) / "body.html" body = '
\n "multi-line" & special content\n
' p.write_text(body, encoding="utf-8") spec = {} rc = _apply_set(spec, [f"body_html=@{p}"]) assert rc == 0 assert spec["body_html"] == body # The whole point: content can include newlines and quotes that # would otherwise need careful JSON-string escaping. assert "\n" in spec["body_html"] assert '"' in spec["body_html"] def test_apply_set_overrides_existing_field(): from build import _apply_set spec = {"title": "from-json", "extra_css": "/* old */"} rc = _apply_set(spec, ["title=from-set"]) assert rc == 0 assert spec == {"title": "from-set", "extra_css": "/* old */"} def test_apply_set_rejects_bad_syntax(): from build import _apply_set spec = {} rc = _apply_set(spec, ["no_equals_sign"]) assert rc == 2 rc = _apply_set({}, ["=missing-key"]) assert rc == 2 def test_apply_set_rejects_missing_file(): from build import _apply_set spec = {} rc = _apply_set(spec, ["body_html=@/tmp/definitely-does-not-exist-xyz.html"]) assert rc == 2 def test_cli_build_with_only_set_and_no_spec(): """End-to-end: --set alone (no --spec) renders a valid page.""" import subprocess import tempfile cli = ROOT / "scripts" / "build.py" with tempfile.TemporaryDirectory() as td: body = Path(td) / "body.html" body.write_text( '

Multi-line

\n

Has "quotes" & tags.

', encoding="utf-8", ) out = Path(td) / "out.html" result = subprocess.run( [sys.executable, str(cli), "build", "freeform", "--set", "title=No-spec demo", "--set", f"body_html=@{body}", "--out", str(out)], capture_output=True, text=True, ) assert result.returncode == 0, f"CLI failed: {result.stderr}" rendered = out.read_text(encoding="utf-8") assert "" in rendered.lower() assert "Multi-line" in rendered assert '"quotes"' in rendered assert "No-spec demo" in rendered # title made it through def test_cli_build_set_overrides_spec_file(): """When --spec and --set both supply the same key, --set wins.""" import subprocess import tempfile cli = ROOT / "scripts" / "build.py" with tempfile.TemporaryDirectory() as td: spec = Path(td) / "spec.json" spec.write_text( json.dumps({"title": "from-spec", "body_html": "

spec body

"}), encoding="utf-8", ) body = Path(td) / "body.html" body.write_text("

set body wins

", encoding="utf-8") out = Path(td) / "out.html" result = subprocess.run( [sys.executable, str(cli), "build", "freeform", "--spec", str(spec), "--set", f"body_html=@{body}", "--out", str(out)], capture_output=True, text=True, ) assert result.returncode == 0, f"CLI failed: {result.stderr}" rendered = out.read_text(encoding="utf-8") assert "set body wins" in rendered assert "spec body" not in rendered assert "from-spec" in rendered # title from spec was kept # --------------------------------------------------------------------------- # # direct entrypoint # # --------------------------------------------------------------------------- # def _run_directly() -> int: """Plain runner so the suite works without pytest installed.""" failed = 0 fns = [v for k, v in globals().items() if k.startswith("test_") and isinstance(v, types.FunctionType)] for fn in fns: # Stub `capsys` for the one test that uses it. import io import sys as _sys if "capsys" in fn.__code__.co_varnames: buf_err = io.StringIO() old_err = _sys.stderr _sys.stderr = buf_err try: class _CS: # minimal capsys stand-in def readouterr(self_inner, _buf=buf_err): return types.SimpleNamespace(out="", err=_buf.getvalue()) fn(_CS()) print(f" ✓ {fn.__name__}") except AssertionError as e: failed += 1; print(f" ✗ {fn.__name__}: {e}") finally: _sys.stderr = old_err else: try: fn(); print(f" ✓ {fn.__name__}") except AssertionError as e: failed += 1; print(f" ✗ {fn.__name__}: {e}") except Exception as e: failed += 1; print(f" ✗ {fn.__name__}: {type(e).__name__}: {e}") print(f"\n{len(fns) - failed}/{len(fns)} passed") return 1 if failed else 0 if __name__ == "__main__": raise SystemExit(_run_directly())