SPB Git

Repository Public License Research preview

test_repository.py 7.6 KB 155 lines python

1"""Repository-level tests: generated files in sync, attribution, language, palette, validators pass.23Run with `make test`. These tests need Python + PyYAML only; post-build checks are skipped when no deck4has been compiled (they run in the latex-build CI job after `make slides`).5"""6from __future__ import annotations78import json9import re10import subprocess11import sys12from pathlib import Path1314import pytest15import yaml1617ROOT = Path(__file__).resolve().parent.parent18sys.path.insert(0, str(ROOT / "tools"))1920import atlaslib  # noqa: E40221import validate_accessibility  # noqa: E40222import validate_structure  # noqa: E4022324COURSE = yaml.safe_load((ROOT / "course.yaml").read_text(encoding="utf-8"))252627def run_tool(name: str, *args: str) -> subprocess.CompletedProcess:28    return subprocess.run([sys.executable, str(ROOT / "tools" / name), *args], cwd=ROOT, capture_output=True, text=True)293031# --- single source of truth -------------------------------------------------------------------------32def test_course_identity():33    a, c = COURSE["author"], COURSE["course"]34    assert a["name"] == "Simon-Pierre Boucher"35    assert a["title_line"] == "Professeur | Université du Québec en Outaouais (UQO)"36    assert a["latex_institute"] == "Professeur, Université du Québec en Outaouais (UQO)"37    assert a["department"] == "Département des sciences administratives"38    assert c["language"] == "fr-CA"39    assert "ni accrédité" in c["endorsement_notice"]404142def test_curriculum_shape():43    sessions = COURSE["sessions"]44    assert [s["id"] for s in sessions] == [f"S{n:02d}" for n in range(1, 25)]45    assert len(COURSE["parts"]) == 646    for part in COURSE["parts"]:47        assert sum(s["part"] == part["id"] for s in sessions) == 448    for s in sessions:49        assert 3 <= len(s["outcomes"]) <= 650        assert all(d < s["id"] for d in s["depends_on"]), "prerequisites must be earlier sessions"51        assert (ROOT / "sessions" / f"{s['id']}-{s['slug']}" / "metadata.yaml").exists()525354@pytest.mark.parametrize("tool", ["sync_course.py", "generate_catalog.py", "render_docs.py"])55def test_generated_files_are_in_sync(tool):56    r = run_tool(tool, "--check")57    assert r.returncode == 0, r.stderr585960def test_latex_identity_macros_come_from_course_yaml():61    tex = (ROOT / "latex" / "atlas-course.tex").read_text(encoding="utf-8")62    assert "\\newcommand{\\AtlasAuthorName}{Simon-Pierre Boucher}" in tex63    assert "\\newcommand{\\AtlasAuthorTitleLine}{Professeur | Université du Québec en Outaouais (UQO)}" in tex64    assert "\\newcommand{\\AtlasFooterAttribution}{Simon-Pierre Boucher · UQO}" in tex65    theme = (ROOT / "latex" / "atlas-theme.sty").read_text(encoding="utf-8")66    assert "\\author{\\AtlasAuthorName}\\institute{\\AtlasAuthorInstitute}" in theme67    assert "\\AtlasFooterAttribution" in theme, "footer attribution must be fed from course.yaml"68    for hard_coded in ("Simon-Pierre", "Outaouais"):69        for f in (ROOT / "latex").rglob("*"):70            if f.suffix in {".sty", ".tex", ".cls"} and f.name != "atlas-course.tex":71                assert hard_coded not in f.read_text(encoding="utf-8"), f"{f.name} hard-codes {hard_coded}"727374def test_title_and_closing_frames_carry_the_author_block():75    frames = (ROOT / "latex" / "components" / "atlas-frames.tex").read_text(encoding="utf-8")76    block = re.search(r"\\newcommand\{\\atlas@authorblock\}\{(.*?)\n\n", frames, flags=re.S).group(1)77    for macro in ("\\AtlasAuthorName", "\\AtlasAuthorTitleLine", "\\AtlasAuthorDepartment"):78        assert macro in block79    assert frames.count("\\atlas@authorblock}") >= 2, "author block must be used on title AND closing slides"808182# --- validators -------------------------------------------------------------------------------------83@pytest.mark.parametrize("tool", ["validate_structure.py", "validate_assets.py", "validate_quizzes.py",84                                  "validate_accessibility.py", "validate_links.py", "validate_latex.py"])85def test_validator_passes(tool):86    r = run_tool(tool)87    assert r.returncode == 0, r.stdout[-3000:] + r.stderr[-3000:]888990def test_status_labels_are_honest():91    for s in COURSE["sessions"]:92        d = atlaslib.session_dir(s)93        status = atlaslib.session_status(s)94        if status == "planned":95            assert not (d / "slides").exists(), f"{s['id']} is planned but has slides: label it draft"96        if status == "validated":97            qa = json.loads((d / "qa" / "results.json").read_text(encoding="utf-8"))98            assert qa["visual_review"]["status"] == "passed" and qa["ci"]["passed"]99    readme = (ROOT / "README.md").read_text(encoding="utf-8")100    assert "Le cours n'est pas terminé" in readme101102103def test_status_report_matches_metadata():104    data = json.loads((ROOT / "reports" / "status.json").read_text(encoding="utf-8"))105    assert {r["id"]: r["status"] for r in data["sessions"]} == \106           {s["id"]: atlaslib.session_status(s) for s in COURSE["sessions"]}107108109# --- unit tests of the checkers themselves ----------------------------------------------------------110def test_contrast_formula():111    assert round(validate_accessibility.contrast("FFFFFF", "000000"), 1) == 21.0112    assert validate_accessibility.contrast("777777", "777777") == 1.0113    dark, light = validate_accessibility.palette()114    assert validate_accessibility.contrast(dark["atlasFg"], dark["atlasBg"]) >= 7115    assert validate_accessibility.contrast(light["atlasFg"], light["atlasBg"]) >= 7116117118def test_language_heuristic_detects_english():119    fr, en = validate_structure.language_ratio("Le modèle prédit la suite la plus plausible pour le texte.")120    assert fr > en121    fr, en = validate_structure.language_ratio("The model predicts the most likely continuation of the text for you.")122    assert en > fr123124125def test_script_duration_estimate():126    seg = validate_structure.script_durations("## Capsule 1 — Test\n\n[S01-D01] " + "mot " * 300 + "\n")127    assert seg == [{"segment": "Capsule 1 — Test", "words": 300, "estimated_minutes": 2.0}]128129130def test_no_english_only_student_strings_in_deck_sources():131    for s in atlaslib.select_sessions(COURSE, None):132        tex = atlaslib.expand_inputs(atlaslib.session_dir(s) / "slides" / "main.tex")133        for title in re.findall(r"\\begin\{frame\}(?:\[[^\]]*\])?\{([^}]*)\}", tex):134            fr, en = validate_structure.language_ratio(title)135            assert en == 0 or fr >= en, f"English-looking frame title: {title}"136137138# --- post-build evidence (skipped until a deck has been compiled) -----------------------------------139def compiled_decks():140    return sorted((ROOT / "dist" / "slides").glob("S[0-9][0-9].pdf")) if (ROOT / "dist" / "slides").exists() else []141142143@pytest.mark.skipif(not compiled_decks(), reason="no compiled deck (run `make slides`)")144def test_compiled_decks_carry_attribution_on_first_and_last_page():145    for pdf in compiled_decks():146        pages = int(re.search(r"Pages:\s+(\d+)", subprocess.run(["pdfinfo", str(pdf)], capture_output=True, text=True).stdout).group(1))147        info = subprocess.run(["pdfinfo", str(pdf)], capture_output=True, text=True).stdout148        assert re.search(r"Author:\s+Simon-Pierre Boucher", info)149        assert re.search(r"Page size:\s+453\.5\d* x 255\.1\d* pts", info), "deck must be 16:9 (160 mm × 90 mm)"150        for page in (1, pages):151            text = subprocess.run(["pdftotext", "-f", str(page), "-l", str(page), str(pdf), "-"], capture_output=True, text=True).stdout152            assert "Simon-Pierre Boucher" in text and "Université du Québec en Outaouais (UQO)" in text and "Professeur" in text153        middle = subprocess.run(["pdftotext", "-f", "3", "-l", "3", str(pdf), "-"], capture_output=True, text=True).stdout154        assert "Simon-Pierre Boucher · UQO" in middle155
Files main
Menu

Theme