SPB Git

Repository Public MIT Research preview

test_lab.py 10.7 KB 200 lines python

1"""Tests du laboratoire S14 : le corrigé réussit, le point de départ échoue proprement, rien ne fuit."""2from __future__ import annotations34import hashlib5import json6import os7import re8import shutil9import subprocess10import sys11from pathlib import Path1213SESSION = Path(__file__).resolve().parents[2]14LABS = SESSION / "labs"15ENV = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONIOENCODING="utf-8")16IGNORER = shutil.ignore_patterns("__pycache__", "*.pyc")171819def lancer(dossier, *commande: str, entree: str | None = None) -> subprocess.CompletedProcess:20    return subprocess.run([sys.executable, *commande], cwd=dossier, capture_output=True, text=True,21                          encoding="utf-8", env=ENV, input=entree)222324def copie(nom: str, tmp_path: Path) -> Path:25    """Copie de travail d'un dossier du laboratoire, avec revue/ à côté comme chez l'apprenant."""26    shutil.copytree(LABS / "revue", tmp_path / "revue", ignore=IGNORER)27    return Path(shutil.copytree(LABS / nom, tmp_path / nom, ignore=IGNORER))282930def test_corrige_reussit_le_verificateur():31    r = lancer(LABS / "solution", "verifier.py")32    assert r.returncode == 0, r.stdout + r.stderr33    assert "4/4 étapes obligatoires réussies" in r.stdout and r.stdout.count("[ RÉUSSI  ]") == 5343536def test_point_de_depart_echoue_sans_planter():37    r = lancer(LABS / "starter", "verifier.py")38    assert r.returncode == 1 and "Traceback" not in r.stderr + r.stdout39    assert r.stdout.count("[ RÉUSSI  ]") == 1 and r.stdout.count("[ À FAIRE ]") == 440    assert "[ RÉUSSI  ] Étape 1 — le comportement est préservé" in r.stdout41    assert "la fonction produire compte 77 lignes" in r.stdout and "obtient 0/6" in r.stdout42    assert "1/4 étapes obligatoires réussies" in r.stdout434445def test_suites_unittest():46    depart = lancer(LABS / "starter", "-m", "unittest")47    assert depart.returncode == 0 and "Ran 10 tests" in depart.stderr       # le code hérité fonctionne48    corrige = lancer(LABS / "solution", "-m", "unittest")49    assert corrige.returncode == 0 and "Ran 11 tests" in corrige.stderr505152def test_empreintes_du_filet_a_jour():53    """Les empreintes inscrites dans le vérificateur sont celles des fichiers du point de départ."""54    source = (LABS / "starter" / "verifier.py").read_text(encoding="utf-8")55    for relatif, empreinte in re.findall(r'"((?:attendu|donnees|tests)/[\w\-./]+)": "([0-9a-f]{16})"', source):56        texte = (LABS / "starter" / relatif).read_text(encoding="utf-8")57        assert hashlib.sha256(texte.encode("utf-8")).hexdigest()[:16] == empreinte, relatif58    assert source.count('": "') == 6596061def test_fichiers_communs_identiques():62    for relatif in ("verifier.py", "journal.md", "outils/lint_consignes.py", "boutique/__init__.py",63                    "boutique/__main__.py", "donnees/ventes-mars.csv", "attendu/rapport-mars.txt",64                    "attendu/rapport-mars.csv", "tests/__init__.py", "tests/test_base.py",65                    "tests/test_caracterisation.py"):66        assert (LABS / "starter" / relatif).read_bytes() == (LABS / "solution" / relatif).read_bytes(), relatif676869def test_point_de_depart_ne_contient_pas_le_corrige():70    garde = (LABS / "starter" / "garde.py").read_text(encoding="utf-8")71    assert garde.count("raise NotImplementedError") == 2 and "return sorted(interdits)" not in garde72    assert not (LABS / "starter" / "tests" / "test_regression.py").exists()73    rapport = (LABS / "starter" / "boutique" / "rapport.py").read_text(encoding="utf-8")74    assert "global NB" in rapport and "def lire_ventes" not in rapport75    assert "## Commandes" not in (LABS / "starter" / "consignes-projet.md").read_text(encoding="utf-8")76    assert "Objectif suivant\n\n##" in (LABS / "starter" / "passation.md").read_text(encoding="utf-8")777879def test_fichiers_attendus_produits_par_le_code_herite():80    for fmt, nom in (("texte", "rapport-mars.txt"), ("csv", "rapport-mars.csv")):81        r = lancer(LABS / "starter", "-m", "boutique", "donnees/ventes-mars.csv", "--format", fmt)82        assert r.returncode == 0 and r.stdout == (LABS / "starter" / "attendu" / nom).read_text(encoding="utf-8")83    r = lancer(LABS / "starter", "-m", "boutique", "donnees/absent.csv")84    assert r.returncode == 2 and r.stderr == "Erreur : fichier introuvable : donnees/absent.csv\n"858687def test_verificateur_detecte_un_filet_modifie(tmp_path):88    projet = copie("solution", tmp_path)89    attendu = projet / "attendu" / "rapport-mars.txt"90    attendu.write_text(attendu.read_text(encoding="utf-8").replace("50.53", "50.54"), encoding="utf-8")91    r = lancer(projet, "verifier.py")92    assert r.returncode == 1 and "[ ERREUR  ] Étape 1" in r.stdout and "attendu/rapport-mars.txt a été modifié" in r.stdout939495def test_verificateur_refuse_le_candidat_b_et_un_test_qui_ne_voit_rien(tmp_path):96    projet = copie("solution", tmp_path)97    shutil.copyfile(LABS / "revue" / "candidats" / "candidat-b" / "boutique" / "rapport.py", projet / "boutique" / "rapport.py")98    r = lancer(projet, "verifier.py")99    assert r.returncode == 1 and "[ ERREUR  ] Étape 1" in r.stdout          # le comportement a changé100    projet2 = copie("solution", tmp_path / "bis")101    (projet2 / "tests" / "test_regression.py").write_text(102        "import unittest\n\n\nclass T(unittest.TestCase):\n    def test_rien(self):\n        self.assertTrue(True)\n", encoding="utf-8")103    r = lancer(projet2, "verifier.py")104    assert "[ ERREUR  ] Étape 3" in r.stdout and "ne le détectent pas" in r.stdout105106107def test_garde_du_corrige(tmp_path):108    projet = copie("solution", tmp_path)109    assert lancer(projet, "garde.py").returncode == 1                       # pas d'état de référence110    r = lancer(projet, "garde.py", "--enregistrer")111    assert r.returncode == 0 and "fichiers surveillés" in r.stdout112    r = lancer(projet, "garde.py")113    assert r.returncode == 0 and "ACCEPTABLE : périmètre respecté, suite de tests réussie" in r.stdout114    (projet / "journal.md").write_text("notes\n", encoding="utf-8")         # document de travail : ignoré115    (projet / "tests" / "test_nouveau.py").write_text("", encoding="utf-8")  # nouveau test : permis116    assert lancer(projet, "garde.py").returncode == 0117    (projet / "donnees" / "ventes-mars.csv").write_text("x\n", encoding="utf-8")118    r = lancer(projet, "garde.py")119    assert r.returncode == 2 and "REFUSÉ : fichier touché hors du périmètre (donnees/ventes-mars.csv)" in r.stderr120    assert "Suite de tests : non lancée" in r.stdout121    assert json.loads((projet / ".garde-empreintes.json").read_text(encoding="utf-8"))122123124def test_garde_refuse_des_tests_en_echec(tmp_path):125    projet = copie("solution", tmp_path)126    lancer(projet, "garde.py", "--enregistrer")127    shutil.copyfile(LABS / "revue" / "candidats" / "candidat-b" / "boutique" / "rapport.py", projet / "boutique" / "rapport.py")128    r = lancer(projet, "garde.py")129    assert r.returncode == 2 and "REFUSÉ : la suite de tests échoue" in r.stderr130131132def test_garde_en_mode_hook(tmp_path):133    """Entrée JSON construite d'après le format décrit par la documentation (tool_input.file_path) ; aucun outil n'est appelé."""134    projet = copie("solution", tmp_path)135    def hook(chemin: str) -> subprocess.CompletedProcess:136        entree = json.dumps({"hook_event_name": "PreToolUse", "tool_name": "Edit", "tool_input": {"file_path": chemin}})137        return lancer(projet, "garde.py", "--hook", entree=entree)138    assert hook(str(projet / "boutique" / "rapport.py")).returncode == 0139    assert hook(str(projet / "tests" / "test_autre.py")).returncode == 0140    r = hook(str(projet / "attendu" / "rapport-mars.txt"))141    assert r.returncode == 2 and "REFUSÉ : attendu/rapport-mars.txt est hors du périmètre" in r.stderr142    assert hook(str(projet / "tests" / "test_base.py")).returncode == 2     # un test existant ne se modifie pas143    assert hook(str(tmp_path / "ailleurs.txt")).returncode == 2144    assert lancer(projet, "garde.py", "--hook", entree="pas du json").returncode == 1145146147def test_garde_du_point_de_depart_reste_a_ecrire(tmp_path):148    projet = copie("starter", tmp_path)149    lancer(projet, "garde.py", "--enregistrer")150    r = lancer(projet, "garde.py")151    assert r.returncode == 1 and "pas terminée" in r.stdout and "Traceback" not in r.stderr152153154def test_essayer_concorde_avec_la_demonstration():155    sys.path.insert(0, str(SESSION / "demos" / "src"))156    from atlas_s14.harnais import tout_evaluer157158    bilans = {b.nom: b for b in tout_evaluer()}159    for lettre in "ab":160        r = lancer(LABS / "revue", "essayer.py", lettre)161        b = bilans[f"candidat {lettre.upper()}"]162        assert r.returncode == 0, r.stderr163        assert f"Tests de base : {b.base[0]}/{b.base[1]} réussis" in r.stdout164        assert f"Tests de caractérisation : {b.caracterisation[0]}/{b.caracterisation[1]} réussis" in r.stdout165        assert "    boutique/rapport.py\n" in r.stdout166        assert "ACCEPTER" not in r.stdout and "REFUSER" not in r.stdout     # le script ne rend aucun verdict167    assert "obtenu   livres,18,336.88,50.54,387.42" in lancer(LABS / "revue", "essayer.py", "b").stdout168169170def test_essayer_refuse_un_projet_deja_modifie():171    r = lancer(LABS / "revue", "essayer.py", "a", "--projet", str(LABS / "solution"))172    assert r.returncode == 2 and "plus le point de départ intact" in r.stdout173174175def test_fichiers_diff_etiquetes():176    for lettre in "ab":177        texte = (LABS / "revue" / f"candidat-{lettre}.diff").read_text(encoding="utf-8")178        assert texte.startswith(f"# Candidat {lettre.upper()} — rédigé pour le cours ATLAS IA (S14). Ce n'est pas la sortie d'un outil.")179        assert "--- a/boutique/rapport.py" in texte180181182def test_aucun_fichier_du_depot_ne_s_appelle_claude_md():183    """Un CLAUDE.md placé ici serait lu comme consigne par un agent travaillant dans le dépôt du cours."""184    assert not [p for p in SESSION.rglob("*") if p.name in ("CLAUDE.md", "CLAUDE.local.md", "AGENTS.md") or p.name == ".claude"]185186187def test_consignes_sures():188    """Aucune commande d'installation par script distant, aucune élévation de privilèges, aucune clé réelle."""189    for relatif in ("labs/instructions.md", "demos/README.md", "README.md", "labs/rubric.md"):190        texte = (SESSION / relatif).read_text(encoding="utf-8")191        assert not re.search(r"(curl|wget|irm)[^\n|]*\|", texte), relatif192        assert not re.search(r"\bsudo\b", texte), relatif193        assert not re.search(r"\brm\s+-|git\s+push\s+[^\n]*--force|git\s+reset\s+--hard", texte), relatif194        assert not re.search(r"sk-ant-|ANTHROPIC_API_KEY\s*=\s*\S", texte), relatif195    consignes = (SESSION / "labs" / "instructions.md").read_text(encoding="utf-8")196    assert "compte" in consignes and "facturé" in consignes and "claude.com/pricing" in consignes197    assert "n'a pas été exécuté" in consignes198    faible = (LABS / "starter" / "consignes-projet.md").read_text(encoding="utf-8")199    assert "CLE_EXEMPLE_NE_PAS_UTILISER" in faible200
Files main
Menu

Theme