test_printer_manager_status_broadcast.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. """Regression tests for ``PrinterManager._broadcast_status_change`` and
  2. its wiring from ``set_awaiting_plate_clear`` (#1128).
  3. The bug: ``awaiting_plate_clear`` is a Bambuddy-side flag, so toggling it
  4. doesn't produce an MQTT push from the printer. Before the fix,
  5. ``set_awaiting_plate_clear()`` mutated state and persisted to DB but never
  6. notified WebSocket subscribers. The plate-clear button on the printer card
  7. disappeared "immediately" only because of an optimistic React Query cache
  8. update on the click path; any other caller (admin script, second tab, an
  9. automation that hits ``POST /printers/{id}/clear-plate``) silently left
  10. the UI stale until the next coincidental status refresh.
  11. These tests pin the contract: every flip of the flag must schedule a
  12. ``printer_status`` broadcast, and the broadcast must carry the new flag
  13. value so subscribers see the right state without polling.
  14. """
  15. from __future__ import annotations
  16. import asyncio
  17. from types import SimpleNamespace
  18. from unittest.mock import AsyncMock, MagicMock, patch
  19. import pytest
  20. from backend.app.services.printer_manager import PrinterManager
  21. @pytest.fixture
  22. def manager():
  23. """Fresh manager per test; the awaiting-plate-clear set is per-instance."""
  24. return PrinterManager()
  25. def _close_unawaited(coro):
  26. """Side effect for mocked ``_schedule_async``.
  27. ``set_awaiting_plate_clear`` evaluates the coroutine expressions
  28. ``self._persist_awaiting_plate_clear(...)`` and
  29. ``self._broadcast_status_change(...)`` before passing them to
  30. ``_schedule_async``. When that target is patched, the coroutine objects
  31. leak — Python's ``__del__`` then emits ``coroutine was never awaited``
  32. during GC, and when GC runs late enough that warning hits the interpreter
  33. shutdown path with ``KeyError: '__import__'``. Closing the coroutine here
  34. prevents both. Returns ``None`` so the mock's call signature is unchanged.
  35. """
  36. if asyncio.iscoroutine(coro):
  37. coro.close()
  38. return None
  39. def _fake_state(**overrides):
  40. """Minimal stand-in for a ``PrinterState`` — only the attributes
  41. ``printer_state_to_dict`` reads. We use a SimpleNamespace rather than
  42. constructing a real PrinterState so this test stays fast and doesn't
  43. couple to the (large, evolving) PrinterState dataclass shape."""
  44. base = {
  45. "connected": True,
  46. "state": "FINISH",
  47. "raw_data": {},
  48. "progress": 100.0,
  49. }
  50. base.update(overrides)
  51. return SimpleNamespace(**base)
  52. class TestSchedulingFromSetAwaitingPlateClear:
  53. """The hook from the public flag-mutation method into the broadcast."""
  54. def test_schedules_broadcast_when_loop_running(self, manager):
  55. """When a real event loop is attached, every call to
  56. ``set_awaiting_plate_clear`` must enqueue both the persistence
  57. coroutine and the broadcast coroutine. Both are needed: persist
  58. survives restarts, broadcast notifies live subscribers."""
  59. manager._loop = MagicMock()
  60. manager._loop.is_running.return_value = True
  61. with patch.object(manager, "_schedule_async", side_effect=_close_unawaited) as scheduled:
  62. manager.set_awaiting_plate_clear(7, True)
  63. # Two coroutines: persist + broadcast. Order doesn't matter.
  64. assert scheduled.call_count == 2
  65. def test_does_not_schedule_when_no_loop_attached(self, manager):
  66. """Sync unit-test path (no loop attached): nothing must be
  67. scheduled, otherwise Python emits 'coroutine was never awaited'
  68. runtime warnings and the test suite goes red on harmless flag
  69. twiddling."""
  70. manager._loop = None
  71. with patch.object(manager, "_schedule_async") as scheduled:
  72. manager.set_awaiting_plate_clear(7, True)
  73. scheduled.assert_not_called()
  74. def test_does_not_schedule_when_loop_not_running(self, manager):
  75. """A loop attached-but-stopped is the same situation as no loop —
  76. scheduling onto a dead loop would never fire."""
  77. manager._loop = MagicMock()
  78. manager._loop.is_running.return_value = False
  79. with patch.object(manager, "_schedule_async") as scheduled:
  80. manager.set_awaiting_plate_clear(7, True)
  81. scheduled.assert_not_called()
  82. def test_both_true_and_false_flips_schedule_broadcast(self, manager):
  83. """The bug only became visible on ``False`` flips (clear), but a
  84. regression that broadcasts only on ``True`` would re-introduce
  85. the original symptom for any future flag mutation that goes
  86. ``False → True`` outside the printer-card optimistic-update
  87. path. Make both directions a contract."""
  88. manager._loop = MagicMock()
  89. manager._loop.is_running.return_value = True
  90. with patch.object(manager, "_schedule_async", side_effect=_close_unawaited) as scheduled:
  91. manager.set_awaiting_plate_clear(7, True)
  92. scheduled.reset_mock()
  93. manager.set_awaiting_plate_clear(7, False)
  94. # Each flip = persist + broadcast = 2 calls.
  95. assert scheduled.call_count == 2
  96. class TestBroadcastStatusChange:
  97. """The broadcast coroutine itself."""
  98. @pytest.mark.asyncio
  99. async def test_emits_ws_update_when_state_present(self, manager):
  100. """Happy path: printer has a known status, broadcast goes out
  101. with the dict produced by ``printer_state_to_dict``."""
  102. state = _fake_state()
  103. with (
  104. patch.object(manager, "get_status", return_value=state),
  105. patch.object(manager, "get_model", return_value="P1S"),
  106. patch(
  107. "backend.app.core.websocket.ws_manager.send_printer_status",
  108. new_callable=AsyncMock,
  109. ) as send_status,
  110. patch(
  111. "backend.app.services.printer_manager.printer_state_to_dict",
  112. return_value={"id": 7, "awaiting_plate_clear": False},
  113. ) as to_dict,
  114. ):
  115. await manager._broadcast_status_change(7)
  116. send_status.assert_awaited_once()
  117. # First positional arg is the printer ID, second is the status dict.
  118. printer_id_arg, payload_arg = send_status.await_args.args
  119. assert printer_id_arg == 7
  120. assert payload_arg == {"id": 7, "awaiting_plate_clear": False}
  121. # Verify the dict was built from the right inputs (state + id + model).
  122. to_dict.assert_called_once_with(state, 7, "P1S")
  123. @pytest.mark.asyncio
  124. async def test_skips_when_status_unknown(self, manager):
  125. """Printer not connected / unknown ID → no point broadcasting a
  126. snapshot we don't have. A future reconnect will produce a fresh
  127. status push anyway, so we'd only be forcing a stale or bogus
  128. payload onto subscribers right now."""
  129. with (
  130. patch.object(manager, "get_status", return_value=None),
  131. patch(
  132. "backend.app.core.websocket.ws_manager.send_printer_status",
  133. new_callable=AsyncMock,
  134. ) as send_status,
  135. ):
  136. await manager._broadcast_status_change(999)
  137. send_status.assert_not_awaited()
  138. @pytest.mark.asyncio
  139. async def test_swallows_websocket_errors(self, manager):
  140. """The broadcast is a courtesy, not a correctness path — if the
  141. WS layer is down, the flag is already mutated in-memory and
  142. persisted. Letting an exception bubble out of
  143. ``_broadcast_status_change`` would surface as an
  144. ``Exception in scheduled callback`` traceback in the log AND
  145. prevent the persistence coroutine from completing if both were
  146. gathered together. Swallow + warn instead."""
  147. with (
  148. patch.object(manager, "get_status", return_value=_fake_state()),
  149. patch.object(manager, "get_model", return_value="P1S"),
  150. patch(
  151. "backend.app.services.printer_manager.printer_state_to_dict",
  152. return_value={"id": 7},
  153. ),
  154. patch(
  155. "backend.app.core.websocket.ws_manager.send_printer_status",
  156. new_callable=AsyncMock,
  157. side_effect=RuntimeError("websocket layer unavailable"),
  158. ),
  159. ):
  160. # Must not raise.
  161. await manager._broadcast_status_change(7)
  162. class TestEndToEndUnderRunningLoop:
  163. """Verify the full flow under a real running event loop — schedule
  164. → broadcast → ws_manager.send_printer_status — without mocking
  165. ``_schedule_async``. Catches regressions where individual pieces
  166. pass but the wiring breaks (e.g. ``_schedule_async`` swallowing the
  167. broadcast coroutine)."""
  168. @pytest.mark.asyncio
  169. async def test_set_false_eventually_emits_broadcast(self, manager):
  170. """Reproduces the #1128 fix path end-to-end: set the flag to
  171. False under a live loop, give the scheduler a tick, the
  172. ws broadcast must have fired with the new payload."""
  173. loop = asyncio.get_running_loop()
  174. manager._loop = loop
  175. # Pretend the printer has been seen — without a state present
  176. # the broadcast short-circuits before reaching ws_manager.
  177. manager._awaiting_plate_clear.add(7)
  178. with (
  179. patch.object(manager, "get_status", return_value=_fake_state()),
  180. patch.object(manager, "get_model", return_value="P1S"),
  181. patch(
  182. "backend.app.services.printer_manager.printer_state_to_dict",
  183. return_value={"id": 7, "awaiting_plate_clear": False},
  184. ),
  185. patch(
  186. "backend.app.core.websocket.ws_manager.send_printer_status",
  187. new_callable=AsyncMock,
  188. ) as send_status,
  189. # Persistence path opens a DB session; stub it out so this
  190. # stays a pure unit test.
  191. patch.object(manager, "_persist_awaiting_plate_clear", new_callable=AsyncMock),
  192. ):
  193. manager.set_awaiting_plate_clear(7, False)
  194. # Yield repeatedly so run_coroutine_threadsafe has a chance
  195. # to land its scheduled coroutine on this loop.
  196. for _ in range(10):
  197. await asyncio.sleep(0)
  198. send_status.assert_awaited()
  199. printer_id_arg, payload_arg = send_status.await_args.args
  200. assert printer_id_arg == 7
  201. assert payload_arg["awaiting_plate_clear"] is False