SPB Git

Repository Public MIT Research preview

test_demo.py 14.4 KB 287 lines python

1"""Tests de la démonstration S11 : chaque sortie et chaque nombre affichés dans les diapositives sont vérifiés ici."""2from __future__ import annotations34import os5import shutil6import subprocess7import sys8from pathlib import Path910import pytest1112SESSION = Path(__file__).resolve().parents[2]13SRC = SESSION / "demos" / "src"14sys.path.insert(0, str(SRC))1516from atlas_s11 import garde, scenarios  # noqa: E40217from atlas_s11.fichiers import SystemeFichiers, est_dans, normaliser  # noqa: E40218from atlas_s11.monde import ARBRE, BAC, DEPART, HORS_BAC, NOTES, monde_initial  # noqa: E40219from atlas_s11.shell import ShellSimule, analyser  # noqa: E402202122def shell() -> ShellSimule:23    return ShellSimule(monde_initial(), BAC, maison=DEPART)242526# --- Chemins et système de fichiers en mémoire ------------------------------------------------27def test_normaliser_et_confinement():28    assert normaliser(DEPART, "atelier/notes") == BAC + "/notes"29    assert normaliser(BAC, "../documents/budget.txt") == HORS_BAC30    assert normaliser("/home", "../../..") == "/"31    assert est_dans(BAC, BAC) and est_dans(BAC, BAC + "/notes/lundi.txt")32    assert not est_dans(BAC, "/home/camille/atelier-secret") and not est_dans(BAC, HORS_BAC)333435def test_monde_initial_identique_a_chaque_appel_et_arbre_de_la_figure():36    a, b = monde_initial(), monde_initial()37    a.ecrire(BAC + "/x.txt", "x")38    assert not b.existe(BAC + "/x.txt") and "x.txt" not in ARBRE["home"]["camille"]["atelier"]39    dans = [c for c in b.parcourir(BAC)]40    assert sum(b.est_dossier(c) for c in dans) == 3 and sum(b.est_fichier(c) for c in dans) == 5   # figure S11-F0241    assert len(b.instantane()) == 6424344# --- Le flux de travail des diapositives S11-D12, D13, D14 et D19 ----------------------------45def test_flux_de_travail_sorties_exactes():46    sorties = {r.ligne: (r.sortie, r.code) for r in scenarios.flux_de_travail()}47    assert sorties["pwd"] == ("/home/camille\n", 0)48    assert sorties["cd atelier && pwd"] == ("/home/camille/atelier\n", 0)49    assert sorties["ls"] == ("donnees\nlisezmoi.txt\nnotes\n", 0)50    assert sorties['find . -name "*.txt"'][0].splitlines() == [51        "./lisezmoi.txt", "./notes/lundi.txt", "./notes/mardi.txt", "./notes/mercredi.txt"]52    assert sorties["cat notes/lundi.txt"][0] == NOTES["lundi.txt"]53    assert sorties["grep retard notes/lundi.txt"] == ("colis 102 : retard\n", 0)54    assert sorties["echo notes/*.txt"][0] == "notes/lundi.txt notes/mardi.txt notes/mercredi.txt\n"55    assert sorties["cat rapports/retards.txt"][0] == "colis 102 : retard\ncolis 104 : retard\ncolis 105 : retard\n"56    assert sorties["cat notes/*.txt | grep -c retard"][0] == "3\n"57    assert sorties["grep -c retard rapports/retards.txt"][0] == "3\n"58    assert len(sorties) == 13 and all(code == 0 for _, code in sorties.values())596061def test_reprise_idempotente_et_mkdir_sans_p():62    r = scenarios.reprise()63    assert r["rapports_identiques"] and r["lignes"] == 364    assert all(code == 0 for passe in r["codes"] for code in passe)65    assert r["mkdir_sans_p"] == [0, 1]                       # S11-D19666768def test_codes_de_sortie():69    codes = scenarios.codes_de_sortie()70    assert [c["code"] for c in codes] == [0, 1, 2, 127]      # S11-D1571    assert [c["affiche"] for c in codes] == ["0", "1", "2", "127"]   # « echo $? »727374def test_enchainement_et():75    e = scenarios.enchainement()76    assert e["echec"].code == 1 and e["lancees_apres_echec"] == 1 and e["echec"].sortie == ""77    assert e["reussite"].code == 0 and e["lancees_apres_reussite"] == 278    assert e["reussite"].sortie.endswith("suite\n")798081def test_tube_et_echec_masque():82    t = scenarios.tube()83    cat, grep = t["normal"].commandes84    assert (len(cat.mots) - 1, cat.lignes_sortie, grep.lignes_entree, grep.lignes_sortie) == (3, 8, 8, 3)85    assert (cat.code, grep.code, t["normal"].code, t["lignes_ecrites"]) == (0, 0, 0, 3)86    assert t["normal"].sortie == ""                          # tout est parti dans le fichier87    cat2, grep2 = t["masque"].commandes88    assert (cat2.code, grep2.code, t["masque"].code) == (1, 0, 0)    # figure S11-F0389    assert t["masque"].sortie == "1\n" and "introuvable" in t["masque"].erreurs909192def test_remplacer_ou_ajouter():93    assert scenarios.remplacer_ou_ajouter() == {"apres_ajout": 3, "apres_remplacement": 1}   # S11-D14949596def test_redirection_ouverte_par_le_shell_avant_la_commande():97    s = shell()98    r = s.executer("grip retard > vide.txt")99    assert r.code == 127 and s.fichiers.lire(BAC + "/vide.txt") == ""100    r = s.executer("echo x > absent/fichier.txt")101    assert r.code == 1 and r.commandes[0].lignes_sortie == 0 and not s.fichiers.existe(BAC + "/absent")102103104# --- Limites du simulateur --------------------------------------------------------------------105@pytest.mark.parametrize("ligne", ["echo a ; echo b", "cat < notes/lundi.txt", "echo $HOME", "ls || pwd",106                                   "echo `pwd`", "grep 'col.s' notes/lundi.txt", "ls -l", "echo a &",107                                   "ls |", "> x.txt", "echo 'abc"])108def test_syntaxe_non_prise_en_charge_refusee_sans_effet(ligne):109    s = shell()110    avant = s.fichiers.instantane()111    assert s.executer(ligne).code == 2112    assert s.fichiers.instantane() == avant113114115@pytest.mark.parametrize("nom", ["rm", "mv", "cp", "chmod", "sudo", "curl", "sh", "python"])116def test_aucune_commande_dangereuse_dans_le_simulateur(nom):117    s = shell()118    avant = s.fichiers.instantane()119    r = s.executer(f"{nom} notes")120    assert r.code == 127 and "commande introuvable" in r.erreurs and s.fichiers.instantane() == avant121122123def test_guillemets_jokers_et_tilde():124    s = shell()125    assert s.executer("echo 'notes/*.txt' \"$?\"").sortie == "notes/*.txt 0\n"126    assert s.executer("echo notes/m*.txt *.zip").sortie == "notes/mardi.txt notes/mercredi.txt *.zip\n"127    assert s.executer("cd ~ && pwd").sortie == DEPART + "\n"128    assert s.executer("ls atelier | grep -v notes").sortie == "donnees\nlisezmoi.txt\n"129    assert s.executer("grep -n -i RETARD atelier/notes/mardi.txt").sortie == "1:colis 104 : retard\n2:colis 105 : retard\n"130    assert s.executer("grep -c retard atelier/notes/lundi.txt atelier/notes/mercredi.txt").sortie == \131        "atelier/notes/lundi.txt:1\natelier/notes/mercredi.txt:0\n"132    assert s.executer("find atelier -type d").sortie == "atelier\natelier/donnees\natelier/notes\n"133134135def test_analyse_syntaxique():136    tubes = analyser("cat a b | grep -c x > f.txt && echo fini")137    assert [len(t) for t in tubes] == [2, 1]138    assert tubes[0][1].textes() == ["grep", "-c", "x"] and tubes[0][1].cible.valeur == "f.txt"139    assert analyser("   # commentaire seul") == []140141142# --- Hôte ou bac à sable (figure S11-F04, diapositives S11-D22 et D23) ------------------------143def test_script_inconnu_hote_contre_bac():144    s = scenarios.script_inconnu()145    h, b = s["hote"], s["bac"]146    assert (h["reussies"], h["lus_hors_bac"], h["modifies_hors_bac"]) == (5, 1, 1)147    assert (h["budget_lignes_avant"], h["budget_lignes_apres"], h["copie_lignes"]) == (3, 1, 3)148    assert (b["reussies"], b["lus_hors_bac"], b["modifies_hors_bac"]) == (3, 0, 0)149    assert (b["budget_lignes_avant"], b["budget_lignes_apres"], b["copie_lignes"]) == (3, 3, 0)150    assert b["codes"] == [0, 0, 1, 1, 0]151    assert h["derniere_sortie"] == b["derniere_sortie"] == "installation terminee"152    assert h["lignes_script"] == len(scenarios.SCRIPT_INCONNU) == 5153154155def test_vue_restreinte_ne_contient_que_le_bac():156    vue = monde_initial().vue_restreinte(BAC)157    assert not vue.existe("/home/camille/documents") and vue.existe(BAC + "/notes/lundi.txt")158    assert set(vue.instantane()) == {c for c in monde_initial().instantane() if est_dans(BAC, c)}159160161# --- La garde (figure S11-F05, diapositives S11-D26 et D30) -----------------------------------162def test_garde_verdicts_des_huit_propositions():163    p = scenarios.propositions()164    assert [x.decision.verdict for x in p["passages"]] == [165        "autoriser", "autoriser", "autoriser", "approuver", "approuver", "refuser", "refuser", "refuser"]166    assert [x.decision.regle for x in p["passages"]][-3:] == ["bac", "bac", "liste"]167    assert p["compte"] == {"autoriser": 3, "approuver": 2, "refuser": 3} and p["total"] == 8168    assert p["executees"] == 5 and p["modifies_hors_bac"] == 0169    assert p["rapport"] == "colis 104 : retard\ncolis 105 : retard\n"170171172def test_garde_si_la_personne_refuse():173    p = scenarios.propositions(lambda ligne: False)174    assert p["executees"] == 3 and p["rapport"] == "" and p["modifies_hors_bac"] == 0175    assert [x.approuvee for x in p["passages"]] == [None, None, None, False, False, None, None, None]176177178@pytest.mark.parametrize("ligne, verdict", [179    ("cd .. && cat documents/budget.txt", garde.REFUSER),180    ("cat /home/camille/documents/budget.txt", garde.REFUSER),181    ("ls | grep notes > ../liste.txt", garde.REFUSER),182    ("find / -name budget.txt", garde.REFUSER),183    ("echo bonjour ; ls", garde.REFUSER),184    ("cd notes && cat ../lisezmoi.txt", garde.AUTORISER),185    ("cd notes && grep retard lundi.txt >> ../bilan.txt", garde.APPROUVER),186    ("pwd", garde.AUTORISER),187])188def test_garde_cas_limites(ligne, verdict):189    assert garde.evaluer(ligne, BAC, BAC).verdict == verdict190191192# --- Le flux réel, dans un dossier temporaire -------------------------------------------------193def test_flux_reel_identique_et_sans_trace():194    v = scenarios.reel()195    assert v["identique_au_simulateur"] and v["lignes_rapport"] == 3196    assert v["tout_dans_le_dossier_temporaire"] and v["existait_pendant"] and not v["existe_apres"]197    assert v["fichiers_texte"] == ["notes/lundi.txt", "notes/mardi.txt", "notes/mercredi.txt"]198199200def test_le_code_de_la_seance_ne_lance_aucune_commande_du_systeme():201    for fichier in (SRC / "atlas_s11").glob("*.py"):202        code = fichier.read_text(encoding="utf-8")203        for interdit in ("import subprocess", "os.system", "os.popen", "shutil.rmtree", "os.remove", "unlink("):204            assert interdit not in code, f"{fichier.name} : {interdit}"205206207# --- Démonstration, README et données des figures ---------------------------------------------208def sortie_demo() -> str:209    return subprocess.run([sys.executable, str(SRC / "atlas_s11" / "demo.py")],210                          capture_output=True, text=True, check=True).stdout211212213def test_demo_s_execute_et_affiche_les_lignes_des_diapositives():214    sortie = sortie_demo()215    for ligne in ("SIMULATEUR, pas un vrai shell", "Bilan : 13 lignes, 13 codes de sortie à 0.",216                  "grip retard notes/lundi.txt        -> code 127  la commande n'existe pas",217                  "cat  : 3 fichiers lus  -> 8 lignes   code 0",218                  "code du tube : 0 -> l'échec de cat passe inaperçu",219                  "commandes réussies                         5 / 5         3 / 5",220                  "echo vide > ../documents/budget.txt                 refuser   hors bac",221                  "Bilan : 3 autorisées, 2 soumises à une personne, 3 refusées, sur 8.",222                  "Dossier temporaire encore présent à la fin : non."):223        assert ligne in sortie, ligne224    assert all(len(ligne) <= 80 for ligne in sortie.splitlines())225    assert sortie == sortie_demo()                          # déterministe226227228def test_readme_contient_la_sortie_exacte_et_aucune_commande_dangereuse():229    import re230    readme = (SESSION / "demos" / "README.md").read_text(encoding="utf-8")231    assert sortie_demo().strip() in readme232    consignes = (SESSION / "labs" / "instructions.md").read_text(encoding="utf-8")233    for texte in (readme, consignes):234        assert not re.search(r"\brm\s+-", texte) and not re.search(r"\bsudo\b", texte)235        assert not re.search(r"(curl|wget)[^\n|]*\|", texte)236237238def test_donnees_de_figures_a_jour():239    r = subprocess.run([sys.executable, str(SRC / "atlas_s11" / "exporter_donnees_figures.py"), "--check"])240    assert r.returncode == 0, "relancer exporter_donnees_figures.py"241242243def test_simulateur_interactif():244    from atlas_s11.simulateur import boucle245    entrees = iter(["aide", "arbre", "cd atelier", "ls | grep n", "recommencer", "pwd", "quitter"])246    ecrit: list[str] = []247    boucle(lire=lambda invite: next(entrees), ecrire=ecrit.append)248    assert "pas un vrai shell" in ecrit[0] and "donnees\nnotes" in ecrit and ecrit[-2] == DEPART249    assert any("`-- budget.txt" in bloc for bloc in ecrit)250251252# --- Contre-épreuve : le simulateur concorde-t-il avec de vrais shells ? ----------------------253# Lancée dans un dossier temporaire de pytest, avec les seules commandes inoffensives du flux.254LIGNES_COMPAREES = scenarios.FLUX + [255    "grep retard notes/mercredi.txt", "echo $?", "grep retard notes/lundi.txt notes/mardi.txt",256    "cat notes/jeudi.txt && echo suite", "echo $?", "cat notes/jeudi.txt notes/lundi.txt | grep -c retard",257    "echo $?", "grep -c retard notes/lundi.txt notes/mercredi.txt", "ls notes | grep mar",258    "find notes -type f", "grep retard notes/jeudi.txt", "grip-atlas-s11 retard", "echo 'a  b' \"$?\"",259    "mkdir rapports", "echo un > rapports/essai.txt && echo deux >> rapports/essai.txt && cat rapports/essai.txt",260]261262263@pytest.mark.parametrize("nom", ["bash", "zsh", "sh"])264def test_concordance_avec_un_vrai_shell(nom, tmp_path):265    if os.name == "nt" or not shutil.which(nom):266        pytest.skip(f"{nom} absent : contre-épreuve non applicable sur cette machine")267    maison = tmp_path / "home" / "camille"268    monde = monde_initial()269    for chemin, contenu in monde.instantane().items():270        cible = tmp_path / chemin.lstrip("/")271        cible.parent.mkdir(parents=True, exist_ok=True)272        cible.write_text(contenu, encoding="utf-8")273    script = "".join(f"{ligne}\n__c=$?; printf '\\n@@%s@@\\n' \"$__c\"; (exit $__c)\n" for ligne in LIGNES_COMPAREES)274    env = {"PATH": os.environ["PATH"], "LC_ALL": "C", "HOME": str(maison)}275    brut = subprocess.run([nom], input=script, capture_output=True, text=True, cwd=maison, env=env, timeout=60).stdout276    morceaux = brut.split("@@")277    reels = [(morceaux[i].strip("\n"), int(morceaux[i + 1])) for i in range(0, len(morceaux) - 1, 2)]278    assert len(reels) == len(LIGNES_COMPAREES)279    simule = ShellSimule(monde, DEPART)280    for ligne, (sortie_reelle, code_reel) in zip(LIGNES_COMPAREES, reels):281        r = simule.executer(ligne)282        attendu = r.sortie.replace(DEPART, str(maison)).strip("\n")283        if ligne.startswith("find"):                        # l'ordre de find n'est pas garanti284            attendu, sortie_reelle = sorted(attendu.splitlines()), sorted(sortie_reelle.splitlines())285        assert sortie_reelle == attendu, f"{nom} : sortie différente pour « {ligne} »"286        assert code_reel == r.code, f"{nom} : code {code_reel} contre {r.code} pour « {ligne} »"287
Files main
Menu

Theme