91 lines
2.8 KiB
Python
91 lines
2.8 KiB
Python
import importlib.util
|
|
from contextlib import redirect_stdout
|
|
import io
|
|
from pathlib import Path
|
|
import time
|
|
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_flying_disconnect_reports_active_pathfinding_duration(self):
|
|
started_at = time.monotonic() - 0.5
|
|
state = Munch(pathfinding_active={42: {
|
|
'started_at': started_at, 'timeout': 2.0,
|
|
'start': (0, 64, 0), 'goal': (5, 64, 0),
|
|
'thread': 'mosfet-movement',
|
|
}}, pathfinding_history=[])
|
|
packet = Munch(reason={'translate': 'multiplayer.disconnect.flying'})
|
|
output = io.StringIO()
|
|
|
|
with redirect_stdout(output):
|
|
connect._log_flying_pathfinding(state, packet)
|
|
|
|
logged = output.getvalue()
|
|
self.assertIn('[pathfinding] flying disconnect diagnostics', logged)
|
|
self.assertIn('active for', logged)
|
|
self.assertIn('(0, 64, 0) -> (5, 64, 0)', logged)
|
|
self.assertIn('mosfet-movement', logged)
|
|
|
|
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()
|