test_printer_offline_notification.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. """Tests for the connected → disconnected edge that fires the
  2. `on_printer_offline` notification (#1752).
  3. The provider toggle, schema, and dispatcher already existed; what was missing
  4. was a caller that fires `notification_service.on_printer_offline` when a
  5. printer goes offline. These tests pin both layers:
  6. * `_maybe_notify_printer_offline` — the debounced background task. Must
  7. fire when the printer is still offline at the end of the window, and
  8. must NOT fire if the printer reconnected during the window.
  9. * Edge detection inside `on_printer_status_change` — schedules the task
  10. only on the True → False transition, cancels any pending task on
  11. reconnect, and stays silent on startup (no prior connected state).
  12. """
  13. import asyncio
  14. from types import SimpleNamespace
  15. from unittest.mock import AsyncMock, MagicMock, patch
  16. import pytest
  17. from backend.app import main as main_module
  18. def _state(connected: bool, state: str = "IDLE") -> SimpleNamespace:
  19. """Minimal PrinterState stub. `state="IDLE"` keeps the reconcile-edge
  20. branch quiescent (it only fires on `connected=True` with a non-unknown
  21. state-string, which we exercise separately) but otherwise lets the
  22. handler thread through without doing extra DB / WS work."""
  23. return SimpleNamespace(
  24. connected=connected,
  25. state=state,
  26. progress=0,
  27. layer_num=0,
  28. temperatures={},
  29. raw_data={},
  30. stg_cur=0,
  31. cooling_fan_speed=0,
  32. big_fan1_speed=0,
  33. big_fan2_speed=0,
  34. chamber_light="",
  35. active_extruder=0,
  36. tray_now=0,
  37. door_open=False,
  38. subtask_name="",
  39. )
  40. @pytest.fixture(autouse=True)
  41. def _reset_edge_state():
  42. """Clear the module-level edge dicts between tests so one test's
  43. True-edge doesn't leak into the next."""
  44. main_module._printer_last_connected.clear()
  45. for task in list(main_module._printer_offline_notify_tasks.values()):
  46. if not task.done():
  47. task.cancel()
  48. main_module._printer_offline_notify_tasks.clear()
  49. main_module._printer_reconciled_since_connect.clear()
  50. main_module._last_status_broadcast.clear()
  51. yield
  52. main_module._printer_last_connected.clear()
  53. for task in list(main_module._printer_offline_notify_tasks.values()):
  54. if not task.done():
  55. task.cancel()
  56. main_module._printer_offline_notify_tasks.clear()
  57. class TestMaybeNotifyPrinterOffline:
  58. """The debounced background task — fires notification at the end of the
  59. window only if the printer is still offline."""
  60. @pytest.mark.asyncio
  61. async def test_fires_notification_when_still_offline_after_debounce(self):
  62. printer = SimpleNamespace(id=1, name="Workshop")
  63. scalar = MagicMock()
  64. scalar.scalar_one_or_none.return_value = printer
  65. db = AsyncMock()
  66. db.execute = AsyncMock(return_value=scalar)
  67. session_cm = MagicMock()
  68. session_cm.__aenter__ = AsyncMock(return_value=db)
  69. session_cm.__aexit__ = AsyncMock(return_value=False)
  70. with (
  71. patch("backend.app.main.asyncio.sleep", new=AsyncMock()),
  72. patch("backend.app.main.printer_manager") as mock_pm,
  73. patch("backend.app.main.async_session", return_value=session_cm),
  74. patch("backend.app.main.notification_service") as mock_notif,
  75. ):
  76. mock_pm.is_connected.return_value = False
  77. mock_notif.on_printer_offline = AsyncMock()
  78. await main_module._maybe_notify_printer_offline(printer_id=1)
  79. mock_notif.on_printer_offline.assert_awaited_once_with(1, "Workshop", db)
  80. @pytest.mark.asyncio
  81. async def test_does_not_fire_when_printer_reconnected_during_debounce(self):
  82. with (
  83. patch("backend.app.main.asyncio.sleep", new=AsyncMock()),
  84. patch("backend.app.main.printer_manager") as mock_pm,
  85. patch("backend.app.main.notification_service") as mock_notif,
  86. ):
  87. mock_pm.is_connected.return_value = True
  88. mock_notif.on_printer_offline = AsyncMock()
  89. await main_module._maybe_notify_printer_offline(printer_id=1)
  90. mock_notif.on_printer_offline.assert_not_awaited()
  91. @pytest.mark.asyncio
  92. async def test_does_not_fire_when_printer_missing_from_db(self):
  93. scalar = MagicMock()
  94. scalar.scalar_one_or_none.return_value = None
  95. db = AsyncMock()
  96. db.execute = AsyncMock(return_value=scalar)
  97. session_cm = MagicMock()
  98. session_cm.__aenter__ = AsyncMock(return_value=db)
  99. session_cm.__aexit__ = AsyncMock(return_value=False)
  100. with (
  101. patch("backend.app.main.asyncio.sleep", new=AsyncMock()),
  102. patch("backend.app.main.printer_manager") as mock_pm,
  103. patch("backend.app.main.async_session", return_value=session_cm),
  104. patch("backend.app.main.notification_service") as mock_notif,
  105. ):
  106. mock_pm.is_connected.return_value = False
  107. mock_notif.on_printer_offline = AsyncMock()
  108. await main_module._maybe_notify_printer_offline(printer_id=1)
  109. mock_notif.on_printer_offline.assert_not_awaited()
  110. @pytest.mark.asyncio
  111. async def test_clears_task_entry_after_run(self):
  112. with (
  113. patch("backend.app.main.asyncio.sleep", new=AsyncMock()),
  114. patch("backend.app.main.printer_manager") as mock_pm,
  115. ):
  116. mock_pm.is_connected.return_value = True # No notification path
  117. main_module._printer_offline_notify_tasks[1] = MagicMock()
  118. await main_module._maybe_notify_printer_offline(printer_id=1)
  119. assert 1 not in main_module._printer_offline_notify_tasks
  120. class TestOfflineEdgeDetection:
  121. """Edge detection inside `on_printer_status_change` — only the
  122. True → False transition schedules a task. Reconnects cancel pending
  123. tasks. Startup-with-disconnected does not fire."""
  124. @staticmethod
  125. def _patch_handler_deps():
  126. """Patch out the heavy side-effects of `on_printer_status_change`
  127. (MQTT relay, WebSocket broadcast, state serializer) so we can focus
  128. on edge state."""
  129. ws_mgr = MagicMock()
  130. ws_mgr.send_printer_status = AsyncMock()
  131. relay = MagicMock()
  132. relay.on_printer_status = AsyncMock()
  133. pm = MagicMock()
  134. pm.get_printer.return_value = None # Skip the relay payload branch.
  135. pm.get_model.return_value = ""
  136. return ws_mgr, relay, pm
  137. @pytest.mark.asyncio
  138. async def test_first_call_connected_does_not_schedule(self):
  139. ws_mgr, relay, pm = self._patch_handler_deps()
  140. with (
  141. patch("backend.app.main.ws_manager", ws_mgr),
  142. patch("backend.app.main.mqtt_relay", relay),
  143. patch("backend.app.main.printer_manager", pm),
  144. patch("backend.app.main.spawn_background_task"),
  145. patch("backend.app.main.printer_state_to_dict", return_value={}),
  146. ):
  147. await main_module.on_printer_status_change(1, _state(connected=True))
  148. assert 1 not in main_module._printer_offline_notify_tasks
  149. assert main_module._printer_last_connected[1] is True
  150. @pytest.mark.asyncio
  151. async def test_first_call_disconnected_does_not_schedule(self):
  152. """Startup with an already-offline printer must not fire — there's
  153. no prior True observation, so we have no edge to trigger on."""
  154. ws_mgr, relay, pm = self._patch_handler_deps()
  155. with (
  156. patch("backend.app.main.ws_manager", ws_mgr),
  157. patch("backend.app.main.mqtt_relay", relay),
  158. patch("backend.app.main.printer_manager", pm),
  159. patch("backend.app.main.spawn_background_task"),
  160. patch("backend.app.main.printer_state_to_dict", return_value={}),
  161. ):
  162. await main_module.on_printer_status_change(1, _state(connected=False))
  163. assert 1 not in main_module._printer_offline_notify_tasks
  164. assert main_module._printer_last_connected[1] is False
  165. @pytest.mark.asyncio
  166. async def test_connected_to_disconnected_schedules_task(self):
  167. ws_mgr, relay, pm = self._patch_handler_deps()
  168. with (
  169. patch("backend.app.main.ws_manager", ws_mgr),
  170. patch("backend.app.main.mqtt_relay", relay),
  171. patch("backend.app.main.printer_manager", pm),
  172. patch("backend.app.main.spawn_background_task"),
  173. patch("backend.app.main._maybe_notify_printer_offline", new=AsyncMock()),
  174. patch("backend.app.main.printer_state_to_dict", return_value={}),
  175. ):
  176. await main_module.on_printer_status_change(1, _state(connected=True))
  177. await main_module.on_printer_status_change(1, _state(connected=False))
  178. task = main_module._printer_offline_notify_tasks.get(1)
  179. assert task is not None
  180. task.cancel()
  181. @pytest.mark.asyncio
  182. async def test_reconnect_cancels_pending_task(self):
  183. ws_mgr, relay, pm = self._patch_handler_deps()
  184. with (
  185. patch("backend.app.main.ws_manager", ws_mgr),
  186. patch("backend.app.main.mqtt_relay", relay),
  187. patch("backend.app.main.printer_manager", pm),
  188. patch("backend.app.main.spawn_background_task"),
  189. patch("backend.app.main._maybe_notify_printer_offline", new=AsyncMock()),
  190. patch("backend.app.main.printer_state_to_dict", return_value={}),
  191. ):
  192. await main_module.on_printer_status_change(1, _state(connected=True))
  193. await main_module.on_printer_status_change(1, _state(connected=False))
  194. scheduled = main_module._printer_offline_notify_tasks.get(1)
  195. assert scheduled is not None
  196. await main_module.on_printer_status_change(1, _state(connected=True))
  197. # Yield so the cancellation propagates through the event loop.
  198. await asyncio.sleep(0)
  199. assert 1 not in main_module._printer_offline_notify_tasks
  200. assert scheduled.cancelled() or scheduled.done()
  201. @pytest.mark.asyncio
  202. async def test_repeated_disconnected_does_not_reschedule(self):
  203. """A second False observation while a task is already pending must
  204. not replace the in-flight task — otherwise the debounce clock
  205. resets on every status callback and the notification never fires."""
  206. ws_mgr, relay, pm = self._patch_handler_deps()
  207. with (
  208. patch("backend.app.main.ws_manager", ws_mgr),
  209. patch("backend.app.main.mqtt_relay", relay),
  210. patch("backend.app.main.printer_manager", pm),
  211. patch("backend.app.main.spawn_background_task"),
  212. patch("backend.app.main._maybe_notify_printer_offline", new=AsyncMock()),
  213. patch("backend.app.main.printer_state_to_dict", return_value={}),
  214. ):
  215. await main_module.on_printer_status_change(1, _state(connected=True))
  216. await main_module.on_printer_status_change(1, _state(connected=False))
  217. first_task = main_module._printer_offline_notify_tasks.get(1)
  218. await main_module.on_printer_status_change(1, _state(connected=False))
  219. second_task = main_module._printer_offline_notify_tasks.get(1)
  220. assert first_task is second_task
  221. if first_task is not None:
  222. first_task.cancel()