import os from pathlib import Path import pytest from lib.utils import ( get_template_files, render_template, set_active_page_by_url, minify_html, js_minifier, ) def test_get_template_files_filters_partials_and_non_html( tmp_path: Path) -> None: template_dir = tmp_path / "templates" template_dir.mkdir() (template_dir / "page.html").write_text("

Page

", encoding="utf-8") (template_dir / "_partial.html").write_text("

Ignore

", encoding="utf-8") (template_dir / "notes.txt").write_text("ignore", encoding="utf-8") result = get_template_files(str(template_dir)) assert sorted(result) == ["page.html"] def test_render_template_renders_with_context(tmp_path: Path) -> None: template_dir = tmp_path / "templates" template_dir.mkdir() (template_dir / "hello.html").write_text("Hello {{ name }}!", encoding="utf-8") rendered = render_template( "hello.html", { "name": "World"}, template_dir=str(template_dir)) assert rendered == "Hello World!" def test_set_active_page_by_url_marks_only_requested_page_active() -> None: nav = { "index.html": {"active": False}, "about.html": {"active": False}, } set_active_page_by_url(nav, "about.html") assert nav["about.html"]["active"] is True assert nav["index.html"]["active"] is False def test_minify_html_removes_comments_and_extra_whitespace() -> None: html = "
Text
\n" minified = minify_html(html) assert minified == "
Text
" def test_js_minifier_strips_comments_and_rewrites_files( tmp_path: Path) -> None: output_dir = tmp_path / "site" js_dir = output_dir / "js" js_dir.mkdir(parents=True) js_path = js_dir / "app.js" js_path.write_text( "// comment\nvar x = 1; \n/* block */\nfunction test() { console.log(x); }\n", encoding="utf-8", ) # Ensure non-JS files are ignored (js_dir / "readme.txt").write_text("skip", encoding="utf-8") js_minifier(str(output_dir)) content = js_path.read_text(encoding="utf-8") assert content == "var x = 1; function test() { console.log(x); }" assert os.path.exists(js_dir / "readme.txt") @pytest.mark.parametrize( "initial, expected", [ ({"a.js": "const a = 1;"}, "const a = 1;"), ], ) def test_js_minifier_handles_multiple_invocations( tmp_path: Path, initial, expected) -> None: output_dir = tmp_path / "dist" js_dir = output_dir / "js" js_dir.mkdir(parents=True) for filename, content in initial.items(): (js_dir / filename).write_text(content, encoding="utf-8") js_minifier(str(output_dir)) js_minifier(str(output_dir)) for filename in initial: content = (js_dir / filename).read_text(encoding="utf-8") assert content == expected