#!/usr/bin/env python3 """`fiches_site.py` : le site presente a sa forge la fiche de chaque locataire (§2.5, pas 2). Ces cas gardent : 1. le plan dit `creer` (rien de publie), `a jour` (identique a l'octet), `mettre a jour` ; 2. le depot de fiche d'un locataire est `fiche-` ; 3. le texte presente se relit en la fiche meme (`fiche_pour`), et le poste lit la fiche CALCULEE de chaque locataire frere (pas 5 : plus aucune fiche deposee) ; 4. sur les sites freres, chaque fiche calculee est identique a la fiche deposee chez son locataire actif — la coexistence ne peut pas diverger ; 5. l'ecriture cree le depot s'il manque, puis CREE le fichier (POST) sans sha, ou le MET A JOUR (PUT) avec le sha lu — jamais l'inverse ; 6. sans FORGEJO_ADMIN, publier et verifier refusent ; 7. (pas 3) le locataire lit la fiche PRESENTEE (tiree a cote de son depot) avant la deposee, et retombe sur la deposee sans elle ; `fiche_deposee` ne lit jamais que la deposee ; 8. (pas 3) `forge_cles` demande la meme cle sur `fiches/fiche-`, et vise ce depot dans son organisation a lui, pas dans celle du genome ; 9. (pas 4) une copie d'un intrant que la fiche pose est refusee par P84 (`verifier_fiche`), et chaque hote des locataires freres porte la valeur de la fiche. """ from __future__ import annotations import base64 import json import os import sys import tempfile import unittest from pathlib import Path from unittest import mock RACINE = Path(__file__).resolve().parents[2] sys.path.insert(0, str(RACINE / "scripts")) import fiches_site as fs # noqa: E402 class Plan(unittest.TestCase): def test_trois_etats(self): p = dict(fs.plan({"A": "x", "B": "y", "C": "z"}, {"A": None, "B": "y", "C": "autre"})) self.assertEqual(p, {"A": "creer", "B": "a jour", "C": "mettre a jour"}) def test_depot(self): self.assertEqual(fs.depot_de("OPS-Technolibre"), "fiche-ops-technolibre") class Texte(unittest.TestCase): def _couples(self): import contexte return contexte.couples_hebergeur() def test_le_texte_est_la_fiche(self): import yaml couples = self._couples() if not couples: self.skipTest("aucun site frere") s, l = couples[0] self.assertEqual(yaml.safe_load(s.texte_fiche(l)), s.fiche_pour(l)) def test_le_poste_lit_la_fiche_calculee(self): couples = self._couples() if not couples: self.skipTest("aucun site frere") for s, l in couples: self.assertFalse((l.depot / "fiche-site.yml").exists(), f"{l.nom} : fiche deposee") if l.fiche_presentee() is None: self.assertEqual(l.fiche_du_site(), s.fiche_pour(l), f"{s.nom} -> {l.nom}") class Ecriture(unittest.TestCase): def _forge(self, reponses): f = fs.Forge.__new__(fs.Forge) appels = [] def api(chemin, methode="GET", corps=None): appels.append((methode, chemin, corps)) return reponses(methode, chemin) f._api = api return f, appels def test_depot_absent_puis_creation(self): f, appels = self._forge(lambda m, c: (404, "") if m == "GET" else (201, {})) f.ecrire("fiche-x", "texte", None, "msg") self.assertEqual([(m, c) for m, c, _ in appels], [ ("GET", "/repos/fiches/fiche-x"), ("POST", "/orgs/fiches/repos"), ("POST", "/repos/fiches/fiche-x/contents/fiche-site.yml")]) corps = appels[-1][2] self.assertNotIn("sha", corps) self.assertEqual(base64.b64decode(corps["content"]).decode(), "texte") def test_mise_a_jour_avec_sha(self): f, appels = self._forge(lambda m, c: (200, {})) f.ecrire("fiche-x", "neuf", "abc123", "msg") self.assertEqual(appels[-1][0], "PUT") self.assertEqual(appels[-1][2]["sha"], "abc123") def test_lire(self): contenu = base64.b64encode("fiche".encode()).decode() f, _ = self._forge(lambda m, c: (200, {"content": contenu, "sha": "s1"})) self.assertEqual(f.lire("fiche-x"), ("fiche", "s1")) f, _ = self._forge(lambda m, c: (404, "")) self.assertEqual(f.lire("fiche-x"), (None, None)) class SansSecret(unittest.TestCase): def test_refus(self): d = Path(tempfile.mkdtemp()) / "f.json" d.write_text(json.dumps({"site": "S", "forge": "https://f", "fiches": {"A": "x"}})) with mock.patch.dict(os.environ, {}, clear=False): os.environ.pop("FORGEJO_ADMIN", None) for fn in (lambda: fs.publier(str(d), False), lambda: fs.verifier(str(d))): with self.assertRaises(SystemExit): fn() class Lecture(unittest.TestCase): def test_presentee_puis_deposee(self): import contexte racine = Path(tempfile.mkdtemp()) loc = racine / "OPS-Fictif" (loc / "plan").mkdir(parents=True) (loc / "plan" / "nomenclature.yml").write_text("index: 99\n", encoding="utf-8") (loc / "fiche-site.yml").write_text("source: deposee\n", encoding="utf-8") l = contexte.Locataire(loc) # Sans site connu ni fiche presentee, le repli de transition reste la fiche deposee. self.assertEqual(l.fiche_du_site(), {"source": "deposee"}) presentee = racine / "fiche-ops-fictif" / "fiche-site.yml" presentee.parent.mkdir() presentee.write_text("source: presentee\n", encoding="utf-8") self.assertEqual(l.chemin_fiche_presentee(), presentee) self.assertEqual(l.fiche_du_site(), {"source": "presentee"}) self.assertEqual(l.fiche_deposee(), {"source": "deposee"}) class ForgeCles(unittest.TestCase): def test_demande_la_fiche(self): import forge_cles d = forge_cles.demandes() if not d: self.skipTest("aucun site frere") par_loc = {} for x in d: par_loc.setdefault(x["locataire"], {})[x["depot"]] = x["cle"] for loc, depots in par_loc.items(): fiche = f"fiches/{fs.depot_de(loc)}" self.assertIn(fiche, depots, loc) autres = [c for dep, c in depots.items() if dep != fiche] self.assertTrue(autres and all(c == depots[fiche] for c in autres), loc) def test_chemin(self): import forge_cles f = forge_cles.Forge("https://f", "genome", "x") self.assertEqual(f._chemin("ops-x"), "genome/ops-x") self.assertEqual(f._chemin("fiches/fiche-ops-x"), "fiches/fiche-ops-x") class Pas4(unittest.TestCase): def test_copie_refusee_et_valeur_posee(self): import contexte import site_intrants as si couples = contexte.couples_hebergeur() if not couples: self.skipTest("aucun site frere") s, l = couples[0] self.assertEqual(contexte.verifier_fiche(s, l), []) offre = l.intrants_du_site() for h, v in contexte._hostvars(l.inventaire()).items(): for k in si.POSES_PAR_LA_FICHE: self.assertEqual(v.get(k), offre.get(k), f"{l.nom} {h} {k}") clef = si.POSES_PAR_LA_FICHE[0] fichier, variable = si.OU_LE_LOCATAIRE_LE_DIT[clef] with mock.patch.object(si, "_declare_par_le_locataire", return_value={clef: offre[clef]}): ecarts = contexte.verifier_fiche(s, l) self.assertTrue(any("copie a retirer" in e and variable in e for e in ecarts), ecarts) class Pas6b(unittest.TestCase): """Ni l'inventaire ni les flux ne se versionnent, et `derives.py` lit dans le Makefile qui les lit.""" def test_un_derive_versionne_est_refuse(self): import subprocess import contexte d = Path(tempfile.mkdtemp()) / "OPS-Fictif" (d / "plan").mkdir(parents=True) (d / "plan" / "nomenclature.yml").write_text("index: 99\n", encoding="utf-8") inv = d / "inventories" / "principal" / "hosts.yml" inv.parent.mkdir(parents=True) inv.write_text("all: {}\n", encoding="utf-8") g = lambda *a: subprocess.run(["git", "-C", str(d), *a], capture_output=True, check=True) g("init", "-q"); g("add", "plan") g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "plan") l = contexte.Locataire(d) self.assertEqual(contexte.verifier_derives_non_versionnes(l), []) g("add", "-f", "inventories/principal/hosts.yml") g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "inventaire") self.assertTrue(contexte.verifier_derives_non_versionnes(l)) # Les flux non plus, depuis le pas 6d. g("rm", "-q", "--cached", "inventories/principal/hosts.yml") g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "sans inventaire") self.assertEqual(contexte.verifier_derives_non_versionnes(l), []) (d / "flux-genere").mkdir() (d / "flux-genere" / "h.nft").write_text("table inet x {}\n", encoding="utf-8") g("add", "-f", "flux-genere"); g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "flux") self.assertTrue(contexte.verifier_derives_non_versionnes(l)) def test_une_fiche_qui_ne_se_rafraichit_pas_arrete_tout(self): import os import subprocess import derives racine = Path(tempfile.mkdtemp()) (racine / "OPS-Fictif" / "plan").mkdir(parents=True) (racine / "OPS-Fictif" / "plan" / "nomenclature.yml").write_text("index: 99\n", encoding="utf-8") fiche = racine / "fiche-ops-fictif" fiche.mkdir() (fiche / "fiche-site.yml").write_text("site: S\n", encoding="utf-8") subprocess.run(["git", "-C", str(fiche), "init", "-q"], check=True) subprocess.run(["git", "-C", str(fiche), "remote", "add", "origin", str(racine / "nulle-part")], check=True) with mock.patch.dict(os.environ, {"SETOPS_FICHE_PERIMEE": ""}): with self.assertRaises(SystemExit): derives.rafraichir_fiche(racine / "OPS-Fictif") with mock.patch.dict(os.environ, {"SETOPS_FICHE_PERIMEE": "1"}): self.assertIs(derives.rafraichir_fiche(racine / "OPS-Fictif"), False) def test_une_machine_sans_regles_arrete_la_generation(self): import derives d = Path(tempfile.mkdtemp()) / "OPS-Fictif" inv = d / "inventories" / "principal" / "hosts.yml" inv.parent.mkdir(parents=True) inv.write_text("all:\n children:\n hotes_actifs:\n hosts:\n a-01: {}\n b-01: {}\n", encoding="utf-8") (d / "flux-genere").mkdir() (d / "flux-genere" / "a-01.nft").write_text("table inet x {}\n", encoding="utf-8") self.assertEqual(derives.regles_manquantes(d), ["b-01"]) (d / "flux-genere" / "b-01.nft").write_text("table inet x {}\n", encoding="utf-8") self.assertEqual(derives.regles_manquantes(d), []) def test_les_cibles_qui_lisent_l_inventaire(self): import derives c = derives.cibles_qui_lisent() for attendue in ("appliquer", "deployer-tout", "valider", "temoins-etat", "restauration-etat", "deposer-maintenant", "rafraichir-releve"): self.assertIn(attendue, c) for jamais in ("instancier", "site-appliquer", "fiches-publier", "publier"): self.assertNotIn(jamais, c) if __name__ == "__main__": unittest.main(verbosity=1)