import copy import importlib.util from pathlib import Path import tempfile import unittest spec = importlib.util.spec_from_file_location("guard_deploy", Path(__file__).with_name("deploy-onboarding-guard.py")) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) class GuardDeploymentTest(unittest.TestCase): def test_preserves_custody_and_recovery_and_replays(self): config = {"data": {"pi.cfg": "EXISTING=True\n", "other": "unchanged"}} deployment = {"spec": {"template": {"spec": { "containers": [{"name": name, "image": "pinned", "envFrom": [{"secretRef": {"name": "existing"}}], "volumeMounts": [{"name": "data", "mountPath": "/etc/privacyidea"}]} for name in ["privacyidea", "factor-recovery", "unrelated"]], "volumes": [{"name": "data", "persistentVolumeClaim": {"claimName": "existing"}}], }}}} original = copy.deepcopy(deployment) with tempfile.TemporaryDirectory() as directory: source = Path(directory); (source / "scripts").mkdir() (source / "scripts/keycape_onboarding_guard.py").write_text("def check(request, action): return True\n") cm, updated, planned = module.plan(source, config, deployment) self.assertEqual(deployment, original) self.assertEqual(updated, config["data"]["pi.cfg"] + module.SUFFIX) self.assertTrue(cm["immutable"]) for before, after in zip(original["spec"]["template"]["spec"]["containers"], planned["containers"]): if before["name"] == "unrelated": self.assertEqual(before, after) else: self.assertEqual(before["envFrom"], after["envFrom"]) self.assertEqual(before["image"], after["image"]) self.assertEqual(after["env"], [{"name": "PYTHONPATH", "value": "/opt/keycape-onboarding"}]) self.assertIn(before["volumeMounts"][0], after["volumeMounts"]) replay = module.plan(source, {"data": {"pi.cfg": updated}}, {"spec": {"template": {"spec": planned}}}) self.assertEqual(replay, (cm, updated, planned)) with self.assertRaisesRegex(RuntimeError, "existing_hook_requires_review"): module.plan(source, {"data": {"pi.cfg": "PI_INIT_CHECK_HOOK='another.check'"}}, deployment) if __name__ == "__main__": unittest.main()