"""Profile selection regressions; run on the Debian deployment host.""" import importlib.util import json import os from pathlib import Path import tempfile import unittest from unittest.mock import patch SPEC = importlib.util.spec_from_file_location( "runtime_context", Path(__file__).resolve().parents[2] / "scripts/cluster_runtime_context.py" ) MODULE = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(MODULE) class ClusterRuntimeContextTests(unittest.TestCase): def setUp(self): temporary = tempfile.TemporaryDirectory() self.addCleanup(temporary.cleanup) self.root = Path(temporary.name) profiles = { name: {"runtime": "k3s" if name == "k3s" else "kubeadm", "control_plane": {"node_name": name, "lan_ip": host, "kubeconfig": f"/mock/{name}-config"}} for name, host in (("debian", "192.0.2.1"), ("pimox", "192.0.2.2"), ("k3s", "192.0.2.3")) } inventory = self.root / "inventory.json" inventory.write_text(json.dumps({"cluster": {"active_profile": "pimox", "profiles": profiles}})) (self.root / "active-cluster.json").write_text(json.dumps({"profile": "k3s"})) binding = self.root / "clusters/k3s/identity.json" binding.parent.mkdir(parents=True) binding.write_text(json.dumps({"kube_system_uid": "native-uid"})) environment = patch.dict(os.environ, { "HOMELAB_STATE_DIR": str(self.root), "HOMELAB_INVENTORY_FILE": str(inventory), "LAB_CLUSTER_PROFILE": "debian", "KUBECONFIG": "/retired/config", "TF_VAR_control_plane_host": "192.0.2.99", }, clear=True) environment.start() self.addCleanup(environment.stop) def test_local_override_and_persisted_default(self): self.assertEqual(MODULE.resolve()["profile"], "debian") del os.environ["LAB_CLUSTER_PROFILE"] self.assertEqual(MODULE.resolve()["profile"], "k3s") def test_api_ignores_stale_profile_and_kubeconfig(self): os.environ["JEANNIE_REMOTE_SERVER"] = "true" selected = MODULE.environment() self.assertEqual(selected["LAB_CLUSTER_PROFILE"], "k3s") self.assertEqual(selected["KUBECONFIG"], "/mock/k3s-config") self.assertEqual(selected["TF_VAR_control_plane_host"], "192.0.2.3") self.assertEqual(selected["TF_VAR_cluster_identity_uid"], "native-uid") def test_operation_pin_and_fresh_webhook_selection(self): os.environ.update(JEANNIE_SERVICE_CONTEXT="true", JEANNIE_CLUSTER_PROFILE_PIN="pimox") self.assertEqual(MODULE.resolve()["profile"], "pimox") self.assertEqual(MODULE.resolve(follow_active=True)["profile"], "k3s") def test_unknown_selection_refused(self): with self.assertRaises(ValueError): MODULE.resolve("unknown") if __name__ == "__main__": unittest.main()