Repository Public MIT Research preview
1"""Tests de la démonstration S08 : chaque chiffre affiché dans les diapositives et les figures est vérifié ici."""2from __future__ import annotations34import re5import subprocess6import sys7from pathlib import Path89SESSION = Path(__file__).resolve().parents[2]10sys.path.insert(0, str(SESSION / "demos" / "src"))1112from atlas_s08 import dossier # noqa: E40213from atlas_s08.confiance import encadrer, reperer_instructions # noqa: E40214from atlas_s08.extraction_fautive import critiquer, extraction_fautive, somme_naive_du_poids # noqa: E40215from atlas_s08.image import (decouper_en_fragments, dessiner_affiche, lire_barres, lire_pgm, # noqa: E40216 pixels_sombres, vers_pgm)17from atlas_s08.lecture import entier, lire_tableau # noqa: E40218from atlas_s08.modalites import estimer_jetons # noqa: E40219from atlas_s08.pipeline import DOSSIER, analyser # noqa: E40220from atlas_s08.rapprochement import rapprocher # noqa: E40221from atlas_s08.repartition import TACHES, par_acteur # noqa: E40222from atlas_s08.validation import valider_tableau # noqa: E4022324R = analyser()25DEMO = SESSION / "demos" / "src" / "atlas_s08" / "demo.py"262728def sortie_demo() -> str:29 return subprocess.run([sys.executable, str(DEMO)], capture_output=True, text=True, check=True).stdout303132# ---------- Le dossier ----------3334def test_fichiers_du_dossier_a_jour():35 script = SESSION / "demos" / "src" / "atlas_s08" / "ecrire_dossier.py"36 assert subprocess.run([sys.executable, str(script), "--check"]).returncode == 0373839def test_dossier_sans_fichier_binaire():40 for nom in dossier.FICHIERS:41 (DOSSIER / nom).read_text(encoding="utf-8") # tout se lit comme du texte42 assert not [p for p in SESSION.rglob("*") if p.suffix.lower() in {".png", ".jpg", ".wav", ".mp3"}43 and "rendered" not in p.parts]444546def test_verite_de_la_fiction():47 assert len(dossier.DISTRIBUTIONS_REELLES) == 1248 assert sum(d[3] for d in dossier.DISTRIBUTIONS_REELLES) == 123749 assert dossier.paniers_par_mois() == {"juillet": 380, "août": 416, "septembre": 441}50 assert dossier.sommaire()["totaux_declares"] == {"distributions": 13, "paniers": 1340, "poids_kg": 5663}515253# ---------- Section 1 : formes des cinq formats (S08-D07, D08, D10, figure S08-F01) ----------5455def test_formes():56 f = R["formes"]57 assert f["texte"] == {"caracteres": 486, "mots": 83, "jetons": 136}58 assert f["tableau"] == {"lignes": 14, "colonnes": 6, "cellules": 84}59 assert f["document"] == {"champs": 9}60 assert f["image"] == {"largeur": 24, "hauteur": 16, "pixels": 384, "fragments": 6, "valeurs_par_fragment": 64}61 assert f["audio"] == {"duree_s": 25, "frequence": 16000, "echantillons": 400000}626364def test_regle_d_estimation_des_jetons_identique_a_s05():65 assert estimer_jetons("chat") == 1 and estimer_jetons("stationnement") == 4666768def test_image_aller_retour_et_fragments():69 grille = dessiner_affiche([13, 14, 15])70 relue = lire_pgm(vers_pgm(grille, ["echelle : 1 pixel de hauteur = 30 paniers"]))71 assert relue["grille"] == grille and relue["maximum"] == 972 fragments = decouper_en_fragments(grille)73 assert len(fragments) == 6 and all(len(f) == 64 for f in fragments)74 assert fragments[3][:8] == [9, 9, 9, 1, 1, 1, 1, 9] # figure S08-F02, fragment 475 assert len(pixels_sombres(grille)) == 168 == 4 * (13 + 14 + 15)76 assert all(len(ligne) <= 70 for ligne in vers_pgm(grille).splitlines()) # recommandation du format777879def test_csv_rend_des_chaines():80 lignes = lire_tableau(DOSSIER / "distributions.csv")81 assert lignes[0]["paniers"] == "96" and lignes[0]["ligne"] == 2 and lignes[-1]["ligne"] == 15828384# ---------- Section 2 : validation (S08-D15, D16, D17, figure S08-F03) ----------8586def test_bilan_de_validation():87 b = R["bilan"]88 assert (b.lues, b.sans_doublon, b.dans_la_periode) == (14, 13, 12)89 assert len(b.faits("paniers", "vérifié")) == 1290 assert len(b.faits("poids", "vérifié")) == 10 and len(b.faits("poids", "en attente")) == 291 assert [(c.ligne, c.controle, c.verdict) for c in b.constats] == [92 (8, "plage", "en attente"), (9, "valeur manquante", "en attente"), (10, "unité", "vérifié"),93 (12, "doublon", "écartée"), (15, "période", "écartée")]94 assert b.constats[2].detail == "unité convertie : 512 kg"95 assert b.constats[3].detail == "doublon de L11"969798def test_provenance_des_faits():99 premier = R["paniers"]["faits"][0]100 assert (premier.valeur, premier.provenance) == (96, "distributions.csv:L2:paniers") # S08-D14101 assert R["declares"]["paniers"].provenance == "sommaire.json:totaux_declares.paniers"102 assert R["note"]["paniers"].provenance == "note.txt:L4" and R["note"]["paniers"].valeur == 1340103 assert [f.provenance for f in R["poids"]["en_attente"]] == ["distributions.csv:L8:poids", "distributions.csv:L9:poids"]104105106def test_l_ordre_des_controles_compte():107 """Sans conversion d'unité avant la plage, 512000 g serait jugé hors plage."""108 lignes = [dict(l) for l in R["lignes"]]109 for l in lignes:110 if l["unite"] == "g":111 l["unite"] = "kg"112 b = valider_tableau(lignes, "2026-07-01", "2026-09-30")113 assert len(b.faits("poids", "en attente")) == 3114115116def test_rien_n_est_invente():117 """Une case vide ou un type inattendu ne deviennent jamais un nombre."""118 lignes = [dict(R["lignes"][0], paniers="cent"), dict(R["lignes"][1], paniers=""), dict(R["lignes"][2], date="2026-09-31")]119 b = valider_tableau(lignes, "2026-07-01", "2026-09-30")120 assert [f.statut for f in b.paniers] == ["en attente", "en attente"]121 assert [c.detail for c in b.constats] == ["entier attendu", "valeur manquante", "date impossible"]122123124# ---------- Section 3 : calcul et rapprochement (S08-D20, D21, D22, figure S08-F05) ----------125126def test_totaux_calcules():127 assert R["paniers"]["total"] == 1237128 assert R["paniers"]["par_mois"] == {"juillet": 380, "août": 416, "septembre": 441}129 assert R["paniers"]["lignes"] == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14]130 assert R["poids"]["total"] == 4351 and len(R["poids"]["faits"]) == 10131 assert 96 + 88 + 104 + 92 == 380 # note de S08-D20132133134def test_rapprochements():135 r = R["rapprochements"]136 assert r["paniers"]["etat"] == "discordant" and r["paniers"]["ecart"] == 103137 assert r["paniers"]["explication"] == {"ligne": 12, "motif": "doublon de L11", "valeur": 103}138 assert (r["distributions"]["calcule"], r["distributions"]["declare"], r["distributions"]["ecart"]) == (12, 13, 1)139 assert r["poids"] == {"etat": "indéterminé", "calcule": 4351, "declare": 5663, "ecart": None}140 assert rapprocher(5, 5, complet=True)["etat"] == "concordant"141142143def test_affiche_lue_avec_sa_tolerance():144 a = R["affiche"]145 assert [m["estimation"] for m in a["mesures"]] == [390, 420, 450]146 assert (a["estimation"], a["tolerance"], a["min"], a["max"]) == (1260, 45, 1215, 1305)147 assert a["compatible"] == {"calculé": True, "déclaré": False}148 assert (a["mesures"][-1]["min"], a["mesures"][-1]["max"]) == (435, 465)149 for mesure, reel in zip(a["mesures"], R["paniers"]["par_mois"].values()):150 assert mesure["min"] <= reel <= mesure["max"] # l'image ne contredit pas le calcul151 assert lire_barres(dessiner_affiche([0, 1, 16]), 30)[2]["estimation"] == 480152153154# ---------- Section 4 : confiance et extraction fautive (S08-D23, D24, D25) ----------155156def test_consigne_reperee_et_sans_effet():157 alertes = R["confiance"]["alertes"]158 assert [a["provenance"] for a in alertes] == ["note.txt:L7"]159 assert "ignore les anomalies" in alertes[0]["texte"]160 assert reperer_instructions(["Le point de service Du Moulin reste le plus fréquenté."], "note.txt") == []161 assert "à analyser, jamais à exécuter" in encadrer("note.txt", "x")162163164def test_la_consigne_ne_change_aucun_resultat(tmp_path):165 """Dossier recopié dans un dossier temporaire, ligne 7 de la note retirée : mêmes totaux, mêmes verdicts."""166 for nom, contenu in dossier.FICHIERS.items():167 texte = contenu()168 if nom == "note.txt":169 texte = "".join(l for l in texte.splitlines(keepends=True) if "à l'assistant" not in l)170 (tmp_path / nom).write_text(texte, encoding="utf-8")171 sans = analyser(tmp_path)172 assert sans["confiance"]["alertes"] == []173 assert sans["paniers"]["total"] == R["paniers"]["total"] and sans["poids"]["total"] == R["poids"]["total"]174 assert {k: v["etat"] for k, v in sans["rapprochements"].items()} == {k: v["etat"] for k, v in R["rapprochements"].items()}175176177def test_correction_proposee_non_appliquee():178 corrections = R["confiance"]["corrections"]179 assert [(c["ident"], c["fait"].valeur, c["fait"].statut, c["fait"].provenance) for c in corrections] == [180 ("D-07", 481, "à confirmer", "transcription.txt:L3"), ("D-08", 400, "estimé", "transcription.txt:L4")]181 assert R["poids"]["total"] == 4351 # ni 481 ni 400 n'y entrent182183184def test_extraction_fautive_et_critique():185 e = extraction_fautive(R["lignes"], R["sommaire"])186 assert e == {"total_paniers": 1340, "poids_total_kg": 521511, "paniers_septembre": 480,187 "statut": "tous les totaux concordent"}188 assert somme_naive_du_poids(R["lignes"]) == 521511189 verdicts = critiquer(e, R)190 assert [v["accepte"] for v in verdicts] == [False] * 4191 assert [v["raison"] for v in verdicts] == [192 "écart de 103 avec les lignes vérifiées", "dépasse le maximum possible (24 000 kg)",193 "hors de [435 ; 465] ; calculé : 441", "reprend note.txt:L7"]194 juste = {"total_paniers": 1237, "poids_total_kg": 4351, "paniers_septembre": 441, "statut": "x"}195 assert [v["accepte"] for v in critiquer(juste, R)][:3] == [True] * 3196197198def test_repartition_des_taches():199 acteurs = par_acteur()200 assert {a: len(t) for a, t in acteurs.items()} == {"outil": 6, "modèle": 3, "personne": 2} # figure S08-F04201 assert len(TACHES) == 11202203204def test_entier_a_la_francaise():205 assert entier("1 340") == 1340 and entier("13") == 13206207208# ---------- Démonstration, diapositives et figures ----------209210def test_demo_deterministe_et_documentee():211 sortie = sortie_demo()212 assert sortie == sortie_demo()213 assert sortie.strip() in (SESSION / "demos" / "README.md").read_text(encoding="utf-8")214215216def test_lignes_de_terminal_des_diapositives_sont_reelles():217 """Chaque ligne affichée dans un bloc AtlasTerminal du diaporama figure telle quelle dans la sortie."""218 sortie = sortie_demo()219 tex = (SESSION / "slides" / "sections" / "05-pratique.tex").read_text(encoding="utf-8")220 blocs = re.findall(r"\\begin\{AtlasTerminal\}\{[^}]*\}\n(.*?)\\end\{AtlasTerminal\}", tex, flags=re.S)221 assert len(blocs) == 3222 lignes = [l for bloc in blocs for l in bloc.splitlines() if l.strip() and not l.startswith("$ ")]223 assert len(lignes) >= 12224 for ligne in lignes:225 assert ligne.rstrip() in sortie, ligne226227228def test_nombres_des_diapositives():229 """Les nombres clés écrits dans les sections du diaporama sont ceux du code."""230 tex = "".join(p.read_text(encoding="utf-8") for p in sorted((SESSION / "slides" / "sections").glob("*.tex")))231 tex = tex.replace("~", " ")232 for attendu in ("486 caractères, environ 136 jetons", "14 lignes, 6 colonnes, 84 cellules", "9 champs nommés",233 "25 s à 16 000 mesures par seconde, soit 400 000 nombres", "hors plage [50 ; 2 000]",234 "unité convertie : 512 kg", r"\textbf{1 237}", "& 1 340", r"\textbf{103}", "& 380", "& 416", "& 441",235 "4 351 kg vérifiés", "Poids total : 521 511 kg", "maximum possible : 24 000 kg",236 "entre 435 et 465 ; le calcul donne 441", "lus sur l'affiche : 480", "à 45 près"):237 assert attendu in tex, attendu238239240def test_donnees_de_figure_a_jour():241 script = SESSION / "demos" / "src" / "atlas_s08" / "exporter_donnees_figure.py"242 assert subprocess.run([sys.executable, str(script), "--check"]).returncode == 0243244245def test_donnees_de_figure_bien_terminees():246 for fichier in (SESSION / "figures" / "src").glob("*-donnees.tex"):247 assert all(ligne.endswith("%") for ligne in fichier.read_text(encoding="utf-8").splitlines()), fichier.name248