diff --git a/mosfet/connect.py b/mosfet/connect.py index 2bc2871..a75e878 100644 --- a/mosfet/connect.py +++ b/mosfet/connect.py @@ -218,6 +218,8 @@ def main(global_state=None, *, server=None, port=None, username=None, print('Connection ended.', flush=True) except KeyboardInterrupt: shutdown_requested = True + if global_state is not None: + global_state.running = False print('Disconnecting...', flush=True) connection.disconnect() finally: diff --git a/tests/test_connection_shutdown.py b/tests/test_connection_shutdown.py new file mode 100644 index 0000000..8fb6887 --- /dev/null +++ b/tests/test_connection_shutdown.py @@ -0,0 +1,68 @@ +import importlib.util +from pathlib import Path +import unittest +from unittest.mock import patch + +from munch import Munch + +from mosfet import connect + + +ENTRY = Path(__file__).resolve().parents[1] / 'mosfet.py' +SPEC = importlib.util.spec_from_file_location('mosfet_shutdown_entry', ENTRY) +mosfet_entry = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(mosfet_entry) + + +class FakeNetworkingThread: + def join(self, timeout=None): + raise KeyboardInterrupt + + +class FakeConnection: + def __init__(self, *args, **kwargs): + self.connected = False + self.networking_thread = FakeNetworkingThread() + self.exception = None + self.disconnect_calls = [] + + def listener(self, _packet_type): + return lambda handler: handler + + def connect(self): + self.connected = True + + def disconnect(self, immediate=False): + self.disconnect_calls.append(immediate) + self.connected = False + + +class ConnectionShutdownTests(unittest.TestCase): + def test_ctrl_c_stops_connection_retry_loop(self): + state = Munch(running=True) + connections = [] + delays = [] + + def make_connection(*args, **kwargs): + connection = FakeConnection(*args, **kwargs) + connections.append(connection) + return connection + + def retry_sleep(delay): + delays.append(delay) + # Bound the test if the client accidentally retries after Ctrl+C. + state.running = False + + with patch('mosfet.connect.Connection', side_effect=make_connection): + mosfet_entry._run_connection_loop( + state, connect.main, sleep=retry_sleep) + + self.assertEqual(len(connections), 1) + self.assertEqual(delays, []) + self.assertFalse(state.running) + self.assertFalse(state.connected) + self.assertEqual(connections[0].disconnect_calls, [False]) + + +if __name__ == '__main__': + unittest.main()