test_status_broadcast_ams_slot_config.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. """Configuring an AMS slot must reach the printer card without a page reload.
  2. `on_printer_status_change` deduplicates WebSocket broadcasts against a
  3. `status_key`. Its AMS component used to carry only id / tray_type / state, so
  4. re-configuring a slot to a different brand or colour of the SAME material
  5. produced an identical key: the printer's pushall arrived with the new values,
  6. the handler compared, found no change, and returned without broadcasting. The
  7. card then showed the old filament until the 30s fallback poll or an F5.
  8. Reset never had the bug — it clears tray_type, which was always in the key.
  9. That asymmetry is what these tests pin: every field Configure Slot writes has
  10. to move the key, and the fields that churn every second still must not.
  11. """
  12. from types import SimpleNamespace
  13. from unittest.mock import AsyncMock, MagicMock, patch
  14. import pytest
  15. from backend.app import main as main_module
  16. def _spawn_patch():
  17. """Close the reconcile coroutine the handler builds as a call argument.
  18. Same reason as test_printer_offline_notification.py: a bare MagicMock keeps
  19. it alive in call_args and it finalises unawaited during a later test's GC.
  20. """
  21. return patch(
  22. "backend.app.main.spawn_background_task",
  23. side_effect=lambda coro, **kwargs: coro.close(),
  24. )
  25. def _tray(**overrides) -> dict:
  26. """One AMS tray as the firmware reports it, mid-way through a print job.
  27. Defaults describe a configured slot: Bambu PLA Basic in black, bound to
  28. calibration slot 3.
  29. """
  30. tray = {
  31. "id": "0",
  32. "tray_type": "PLA",
  33. "state": 10,
  34. "tray_color": "000000FF",
  35. "tray_info_idx": "GFA00",
  36. "tray_sub_brands": "PLA Basic",
  37. "cali_idx": 3,
  38. "remain": 42,
  39. }
  40. tray.update(overrides)
  41. return tray
  42. def _state(trays: list[dict]) -> SimpleNamespace:
  43. """Minimal PrinterState stub carrying one AMS unit.
  44. Idle and unheated, so the handler runs straight from the dedup check to the
  45. broadcast without touching progress milestones, HMS notifications or the DB.
  46. """
  47. return SimpleNamespace(
  48. connected=True,
  49. state="IDLE",
  50. progress=0,
  51. layer_num=0,
  52. temperatures={},
  53. raw_data={"ams": [{"id": "0", "dry_time": 0, "tray": trays}]},
  54. stg_cur=0,
  55. cooling_fan_speed=0,
  56. big_fan1_speed=0,
  57. big_fan2_speed=0,
  58. chamber_light="",
  59. active_extruder=0,
  60. tray_now=0,
  61. door_open=False,
  62. subtask_name="",
  63. gcode_file="",
  64. remaining_time=None,
  65. hms_errors=[],
  66. ams_filament_backup=None,
  67. )
  68. @pytest.fixture(autouse=True)
  69. def _reset_edge_state():
  70. main_module._last_status_broadcast.clear()
  71. main_module._printer_last_connected.clear()
  72. main_module._printer_reconciled_since_connect.clear()
  73. yield
  74. main_module._last_status_broadcast.clear()
  75. main_module._printer_last_connected.clear()
  76. main_module._printer_reconciled_since_connect.clear()
  77. async def _push(ws_mgr, trays: list[dict]) -> None:
  78. """Deliver one status push to the handler."""
  79. relay = MagicMock()
  80. relay.on_printer_status = AsyncMock()
  81. pm = MagicMock()
  82. pm.get_printer.return_value = None # Skip the relay payload branch.
  83. pm.get_model.return_value = ""
  84. with (
  85. patch("backend.app.main.ws_manager", ws_mgr),
  86. patch("backend.app.main.mqtt_relay", relay),
  87. patch("backend.app.main.printer_manager", pm),
  88. _spawn_patch(),
  89. patch("backend.app.main.printer_state_to_dict", return_value={}),
  90. ):
  91. await main_module.on_printer_status_change(1, _state(trays))
  92. @pytest.fixture
  93. def ws_mgr():
  94. mgr = MagicMock()
  95. mgr.send_printer_status = AsyncMock()
  96. return mgr
  97. class TestConfigureSlotBroadcasts:
  98. """Each field Configure Slot writes must break the dedup on its own —
  99. the user may change only the colour, or only the K-profile."""
  100. @pytest.mark.asyncio
  101. @pytest.mark.parametrize(
  102. "field,new_value",
  103. [
  104. ("tray_color", "FF0000FF"),
  105. ("tray_info_idx", "GFA01"),
  106. ("tray_sub_brands", "PLA Matte"),
  107. ("cali_idx", 7),
  108. ],
  109. )
  110. async def test_a_changed_filament_field_broadcasts(self, ws_mgr, field, new_value):
  111. await _push(ws_mgr, [_tray()])
  112. assert ws_mgr.send_printer_status.await_count == 1
  113. await _push(ws_mgr, [_tray(**{field: new_value})])
  114. assert ws_mgr.send_printer_status.await_count == 2, (
  115. f"changing {field} did not reach the frontend — the card would keep "
  116. "showing the old filament until the fallback poll"
  117. )
  118. @pytest.mark.asyncio
  119. async def test_the_realistic_reconfigure_broadcasts(self, ws_mgr):
  120. """Black Bambu PLA Basic → red eSUN PLA+ with its own K-profile.
  121. The whole point of the report: same material, so every field the old key
  122. looked at is unchanged.
  123. """
  124. await _push(ws_mgr, [_tray()])
  125. await _push(
  126. ws_mgr,
  127. [
  128. _tray(
  129. tray_color="C1121FFF",
  130. tray_info_idx="GFL99",
  131. tray_sub_brands="eSUN PLA+",
  132. cali_idx=5,
  133. )
  134. ],
  135. )
  136. assert ws_mgr.send_printer_status.await_count == 2
  137. @pytest.mark.asyncio
  138. async def test_a_second_slot_is_watched_too(self, ws_mgr):
  139. """The key spans every tray, so configuring slot 2 must broadcast even
  140. though slot 1 is untouched."""
  141. trays = [_tray(id="0"), _tray(id="1", tray_type="PETG", tray_info_idx="GFG00")]
  142. await _push(ws_mgr, trays)
  143. changed = [_tray(id="0"), _tray(id="1", tray_type="PETG", tray_info_idx="GFG01")]
  144. await _push(ws_mgr, changed)
  145. assert ws_mgr.send_printer_status.await_count == 2
  146. class TestDedupStillHolds:
  147. """The dedup exists to keep a printing machine from flooding the socket.
  148. Widening the key must not have cost that."""
  149. @pytest.mark.asyncio
  150. async def test_an_identical_push_is_still_suppressed(self, ws_mgr):
  151. await _push(ws_mgr, [_tray()])
  152. await _push(ws_mgr, [_tray()])
  153. assert ws_mgr.send_printer_status.await_count == 1
  154. @pytest.mark.asyncio
  155. async def test_remaining_filament_does_not_broadcast(self, ws_mgr):
  156. """`remain` ticks down throughout a print and is deliberately absent
  157. from the key. It sits in the same tray dict as the fields we added, so
  158. this pins that we widened the key rather than hashing the whole tray."""
  159. await _push(ws_mgr, [_tray(remain=42)])
  160. await _push(ws_mgr, [_tray(remain=41)])
  161. assert ws_mgr.send_printer_status.await_count == 1
  162. class TestExistingBehaviourUnchanged:
  163. """The cases that already worked, kept working."""
  164. @pytest.mark.asyncio
  165. async def test_a_load_unload_transition_still_broadcasts(self, ws_mgr):
  166. """#784 — tray state 11→10."""
  167. await _push(ws_mgr, [_tray(state=11)])
  168. await _push(ws_mgr, [_tray(state=10)])
  169. assert ws_mgr.send_printer_status.await_count == 2
  170. @pytest.mark.asyncio
  171. async def test_resetting_a_slot_still_broadcasts(self, ws_mgr):
  172. """Reset clears the filament identity outright."""
  173. await _push(ws_mgr, [_tray()])
  174. await _push(
  175. ws_mgr,
  176. [_tray(tray_type="", tray_color="", tray_info_idx="", tray_sub_brands="", cali_idx=-1)],
  177. )
  178. assert ws_mgr.send_printer_status.await_count == 2
  179. @pytest.mark.asyncio
  180. async def test_a_printer_with_no_ams_still_broadcasts_once(self, ws_mgr):
  181. """The `else ()` branch — an AMS-less printer must not crash or
  182. double-broadcast."""
  183. relay = MagicMock()
  184. relay.on_printer_status = AsyncMock()
  185. pm = MagicMock()
  186. pm.get_printer.return_value = None
  187. pm.get_model.return_value = ""
  188. state = _state([])
  189. state.raw_data = {}
  190. for _ in range(2):
  191. with (
  192. patch("backend.app.main.ws_manager", ws_mgr),
  193. patch("backend.app.main.mqtt_relay", relay),
  194. patch("backend.app.main.printer_manager", pm),
  195. _spawn_patch(),
  196. patch("backend.app.main.printer_state_to_dict", return_value={}),
  197. ):
  198. await main_module.on_printer_status_change(1, state)
  199. assert ws_mgr.send_printer_status.await_count == 1