import importlib.util from pathlib import Path import shlex import unittest from unittest.mock import patch ROOT = Path(__file__).resolve().parents[1] spec = importlib.util.spec_from_file_location('kube_route', ROOT / 'scripts/kube_route.py') route = importlib.util.module_from_spec(spec) spec.loader.exec_module(route) class KubeRouteTest(unittest.TestCase): def test_default_is_agent_without_escalation(self): argv = route.ssh_argv(['kubectl', 'get', 'nodes'], environ={}) self.assertEqual(argv[:-1], route.SSH) self.assertEqual(shlex.split(argv[-1]), ['kubectl', 'get', 'nodes']) self.assertNotIn('sudo', argv[-1]) def test_founder_sudo_never_prompts_and_never_allocates_tty(self): argv = route.ssh_argv(['python3', '-'], environ={'KUBECTL_ROUTE': 'founder-sudo'}) self.assertEqual(shlex.split(argv[-1]), ['sudo', '-n', 'python3', '-']) self.assertNotIn('-t', argv) self.assertIn('BatchMode=yes', argv) def test_unknown_or_shell_route_refused(self): for value in ('', 'root', 'sudo kubectl', 'founder-sudo; rm -rf /'): with self.assertRaises(ValueError): route.ssh_argv(['kubectl'], environ={'KUBECTL_ROUTE': value}) def test_remote_arguments_are_quoted(self): argv = route.ssh_argv(['kubectl', 'patch', '-p', '{"a": "b c"}'], environ={}) self.assertEqual(shlex.split(argv[-1])[-1], '{"a": "b c"}') def test_environment_is_read_when_not_given(self): with patch.dict('os.environ', {'KUBECTL_ROUTE': 'founder-sudo'}): self.assertEqual(route.remote_prefix(), ['sudo', '-n']) def test_empty_command_refused(self): with self.assertRaises(ValueError): route.ssh_argv([], environ={}) def test_bounded_scripts_use_the_route(self): for name in ('argocd_public_transport.py', 'argocd_adoption_proof.py', 'workload_adoption_proof.py', 'activity_promotion_readiness.py', 'argocd_child_pin_drift.py', 'capture_service_observation.py'): text = (ROOT / 'scripts' / name).read_text() self.assertIn('ssh_argv(', text, name) self.assertNotIn("'railiance01', shlex.join(['kubectl'", text, name) self.assertNotIn("['ssh', 'railiance01', 'python3'", text, name) self.assertNotIn("['ssh','railiance01','python3'", text, name) if __name__ == '__main__': unittest.main()