import importlib.util from pathlib import Path import signal import tempfile import unittest from unittest.mock import Mock, patch spec = importlib.util.spec_from_file_location('guard', Path(__file__).with_name('quality-tunnel-health.py')) guard = importlib.util.module_from_spec(spec) spec.loader.exec_module(guard) class TunnelHealthTest(unittest.TestCase): def setUp(self): self.folder = tempfile.TemporaryDirectory() self.addCleanup(self.folder.cleanup) self.state = Path(self.folder.name) / 'failure.json' self.process = {'pid': 123, 'started': '456'} self.kill = Mock() def check(self, healthy=False, identify=None): return guard.check_once(self.state, lambda: healthy, identify or (lambda: self.process), self.kill) def test_two_failures_release_only_the_same_verified_process(self): self.assertEqual(self.check(), 'first_failure') self.kill.assert_not_called() self.assertEqual(self.check(), 'stale_tunnel_released') self.kill.assert_called_once_with(123, signal.SIGTERM) def test_reachable_tunnel_clears_failure_history(self): self.check() self.assertEqual(self.check(healthy=True), 'reachable') self.assertFalse(self.state.exists()) self.assertEqual(self.check(), 'first_failure') self.kill.assert_not_called() def test_unverified_owner_is_never_killed(self): self.check() self.assertEqual(self.check(identify=lambda: None), 'no_verified_tunnel') self.kill.assert_not_called() def test_new_connection_or_reused_pid_restarts_confirmation(self): self.check() self.process = {'pid': 123, 'started': '789'} self.assertEqual(self.check(), 'first_failure') self.kill.assert_not_called() def test_process_change_just_before_termination_is_rejected(self): self.check() identify = Mock(side_effect=[self.process, {'pid': 987, 'started': '789'}]) self.assertEqual(self.check(identify=identify), 'owner_changed') self.kill.assert_not_called() def test_main_sshd_or_interactive_connection_is_not_a_tunnel_owner(self): for command,children in [('sshd: admin', 0), ('sshd: admin@pts/0', 1), ('sshd: /usr/sbin/sshd -D [listener]', 1)]: with self.subTest(command=command), patch.object(guard.subprocess, 'run') as run: run.side_effect = [Mock(stdout='LISTEN 0 128 127.0.0.1:15281 0.0.0.0:* users:(("sshd",pid=123,fd=7))'), Mock(stdout=command), Mock(returncode=children)] self.assertIsNone(guard.owner()) if __name__ == '__main__': unittest.main()