69 lines
1.9 KiB
Python
69 lines
1.9 KiB
Python
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()
|