my-homelab-configs/tests/jeannie/test_self_heal_context.py

104 lines
4.9 KiB
Python

"""Self-heal cluster selection and webhook routing regressions (Debian runner)."""
import importlib.machinery
import importlib.util
import json
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
REPO = Path(__file__).resolve().parents[2]
def load_script(filename, name):
loader = importlib.machinery.SourceFileLoader(name, str(REPO / "scripts" / filename))
spec = importlib.util.spec_from_loader(name, loader)
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
loader.exec_module(module)
return module
class SelfHealContextTests(unittest.TestCase):
def heal(self, **env):
defaults = {"LAB_CLUSTER_PROFILE": "pimox", "KUBECONFIG": "", "LAB_KUBECONFIG_PATH": ""}
defaults.update(env)
with patch.dict(os.environ, defaults):
return load_script("heal", "self_heal_context_test")
def test_existing_pimox_service_without_kubeconfig_uses_pimox_fallback(self):
module = self.heal()
self.assertEqual(module.DEFAULT_KUBECONFIG, Path.home() / ".kube/pimox-config")
def test_explicit_kubeconfig_takes_precedence(self):
module = self.heal(KUBECONFIG="/tmp/explicit-config", LAB_KUBECONFIG_PATH="/tmp/lab-config")
self.assertEqual(module.DEFAULT_KUBECONFIG, Path("/tmp/explicit-config"))
def test_lab_path_is_used_when_kubeconfig_is_empty(self):
module = self.heal(LAB_KUBECONFIG_PATH="/tmp/lab-config")
self.assertEqual(module.DEFAULT_KUBECONFIG, Path("/tmp/lab-config"))
def test_pending_workloads_do_not_fail_successful_residual_cleanup(self):
module = self.heal()
with patch.object(module, "stale_pods", return_value=([], [])), \
patch.object(module, "load_status") as status:
self.assertTrue(module.target_is_healed({"command": "./jeannie heal cleanup-stale-pods --yes"}))
status.assert_not_called()
def test_remaining_eligible_residual_fails_cleanup_verification(self):
module = self.heal()
with patch.object(module, "stale_pods", return_value=([{"reason": "Evicted"}], [])):
self.assertFalse(module.target_is_healed({"command": "./jeannie heal cleanup-stale-pods --yes"}))
class WebhookRoutingTests(unittest.TestCase):
def setUp(self):
self.module = load_script("jeannie-eventd", "self_heal_webhook_test")
self.payload = {"alerts": [{"labels": {"alertname": "HomelabStaleResidualPods"}}]}
def test_doctor_json_and_oci_notice_are_stored_separately(self):
completed = subprocess.CompletedProcess([], 0, stdout='{"rows": []}\n', stderr="OCI foundation config=...\n")
with tempfile.TemporaryDirectory() as temporary:
audit = Path(temporary)
with patch.object(self.module.subprocess, "run", return_value=completed) as run:
self.module.run_command(["./jeannie", "doctor-homelab", "--json"], audit, "doctor")
self.assertEqual(json.loads((audit / "doctor.log").read_text()), {"rows": []})
self.assertIn("OCI foundation config", (audit / "doctor.stderr.log").read_text())
self.assertEqual(run.call_args.kwargs["stderr"], subprocess.PIPE)
def test_eviction_alert_selects_cleanup_without_broad_doctor_or_restart(self):
completed = subprocess.CompletedProcess([], 0, stdout="cleanup complete", stderr="")
with tempfile.TemporaryDirectory() as temporary, \
patch.object(self.module, "EVENT_DIR", Path(temporary)), \
patch.object(self.module, "run_command", return_value=completed) as run:
result = self.module.handle_payload(self.payload, apply=True)
self.assertEqual(result["status"], "applied")
self.assertEqual(run.call_count, 1)
self.assertEqual(run.call_args.args[0], ["./jeannie", "heal", "cleanup-stale-pods", "--yes"])
def test_dry_run_event_never_executes_cleanup(self):
with tempfile.TemporaryDirectory() as temporary, \
patch.object(self.module, "EVENT_DIR", Path(temporary)), \
patch.object(self.module, "run_command") as run:
result = self.module.handle_payload(self.payload, apply=False)
self.assertEqual(result["mode"], "dry-run")
run.assert_not_called()
def test_disabled_debian_disk_cleanup_does_not_fall_through_to_pod_cleanup(self):
self.payload["alerts"].append({"labels": {"alertname": "HomelabHostFilesystemNearlyFull", "node": "debian"}})
with tempfile.TemporaryDirectory() as temporary, \
patch.object(self.module, "EVENT_DIR", Path(temporary)), \
patch.object(self.module, "run_command") as run:
result = self.module.handle_payload(self.payload, apply=True)
self.assertEqual(result["status"], "skipped")
run.assert_not_called()
if __name__ == "__main__":
unittest.main()