import subprocess import sys import threading import unittest from unittest.mock import Mock, patch import win32service from kurgan import paths from kurgan.hw import winservice from kurgan.hw.winservice import KurganHwService def bare_service() -> KurganHwService: """The service object without registering with a service manager we aren't running under.""" service = KurganHwService.__new__(KurganHwService) service.stop = threading.Event() service.ReportServiceStatus = Mock() return service class WinServiceTest(unittest.TestCase): def test_accepts_stop_and_shutdown_and_both_end_the_loop(self): accepted = bare_service().GetAcceptedControls() self.assertTrue(accepted & win32service.SERVICE_ACCEPT_STOP) self.assertTrue(accepted & win32service.SERVICE_ACCEPT_SHUTDOWN) for control in ("SvcStop", "SvcShutdown"): with self.subTest(control=control): service = bare_service() getattr(service, control)() self.assertTrue(service.stop.is_set()) self.assertEqual(service.ReportServiceStatus.call_args.args[0], win32service.SERVICE_STOP_PENDING) def test_runs_until_stopped(self): service = bare_service() with patch("kurgan.hw.main.setup_logging"), patch("kurgan.hw.main.single_instance", return_value=1), \ patch("kurgan.hw.main.configured_user_sid", return_value="S-1-5-21-1-2-3-1001"), \ patch("kurgan.hw.main.serve") as serve, patch("kurgan.hw.winservice.fail") as fail: service.SvcDoRun() serve.assert_called_once_with(service.stop, "S-1-5-21-1-2-3-1001") fail.assert_not_called() def test_an_unexpected_failure_exits_so_the_service_manager_restarts_it(self): service = bare_service() with patch("kurgan.hw.main.setup_logging"), patch("kurgan.hw.main.single_instance", return_value=None), \ patch("kurgan.hw.main.serve") as serve, patch("kurgan.hw.winservice.fail") as fail: service.SvcDoRun() # a console copy already holds the mutex serve.assert_not_called() fail.assert_called_once() def test_started_from_a_console_it_runs_there(self): with patch("kurgan.hw.main.main", return_value=7) as console: self.assertEqual(winservice.main([]), 7) # the service manager refused us: not a service console.assert_called_once_with([]) with patch("kurgan.hw.main.main", return_value=0) as console: winservice.main(["-v"]) console.assert_called_once_with(["-v"]) def test_the_bootstrap_loads_under_the_base_interpreter_in_isolated_mode(self): result = subprocess.run([sys._base_executable, "-I", "-S", "-B", f"{paths.PROJECT_DIR}\\hw_service.py", "--check"], capture_output=True, text=True, timeout=60) self.assertEqual(result.returncode, 0, result.stderr) self.assertTrue(result.stdout.startswith("ok: The Kurgan hardware"), result.stdout) if __name__ == "__main__": unittest.main()