test_status_broadcast_ams_slot_config.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. nozzles=[],
  54. raw_data={"ams": [{"id": "0", "dry_time": 0, "tray": trays}]},
  55. stg_cur=0,
  56. # Real PrinterState always carries these; the status-broadcast dedup
  57. # key reads them so a Filament Track Switch rebind reaches the card.
  58. fila_switch=None,
  59. ams_switch_inlet={},
  60. extruder_slots={},
  61. cooling_fan_speed=0,
  62. big_fan1_speed=0,
  63. big_fan2_speed=0,
  64. chamber_light="",
  65. active_extruder=0,
  66. tray_now=0,
  67. door_open=False,
  68. subtask_name="",
  69. gcode_file="",
  70. remaining_time=None,
  71. hms_errors=[],
  72. ams_filament_backup=None,
  73. )
  74. @pytest.fixture(autouse=True)
  75. def _reset_edge_state():
  76. main_module._last_status_broadcast.clear()
  77. main_module._printer_last_connected.clear()
  78. main_module._printer_reconciled_since_connect.clear()
  79. yield
  80. main_module._last_status_broadcast.clear()
  81. main_module._printer_last_connected.clear()
  82. main_module._printer_reconciled_since_connect.clear()
  83. async def _push(ws_mgr, trays: list[dict]) -> None:
  84. """Deliver one status push to the handler."""
  85. relay = MagicMock()
  86. relay.on_printer_status = AsyncMock()
  87. pm = MagicMock()
  88. pm.get_printer.return_value = None # Skip the relay payload branch.
  89. pm.get_model.return_value = ""
  90. with (
  91. patch("backend.app.main.ws_manager", ws_mgr),
  92. patch("backend.app.main.mqtt_relay", relay),
  93. patch("backend.app.main.printer_manager", pm),
  94. _spawn_patch(),
  95. patch("backend.app.main.printer_state_to_dict", return_value={}),
  96. ):
  97. await main_module.on_printer_status_change(1, _state(trays))
  98. @pytest.fixture
  99. def ws_mgr():
  100. mgr = MagicMock()
  101. mgr.send_printer_status = AsyncMock()
  102. return mgr
  103. class TestConfigureSlotBroadcasts:
  104. """Each field Configure Slot writes must break the dedup on its own —
  105. the user may change only the colour, or only the K-profile."""
  106. @pytest.mark.asyncio
  107. @pytest.mark.parametrize(
  108. "field,new_value",
  109. [
  110. ("tray_color", "FF0000FF"),
  111. ("tray_info_idx", "GFA01"),
  112. ("tray_sub_brands", "PLA Matte"),
  113. ("cali_idx", 7),
  114. ],
  115. )
  116. async def test_a_changed_filament_field_broadcasts(self, ws_mgr, field, new_value):
  117. await _push(ws_mgr, [_tray()])
  118. assert ws_mgr.send_printer_status.await_count == 1
  119. await _push(ws_mgr, [_tray(**{field: new_value})])
  120. assert ws_mgr.send_printer_status.await_count == 2, (
  121. f"changing {field} did not reach the frontend — the card would keep "
  122. "showing the old filament until the fallback poll"
  123. )
  124. @pytest.mark.asyncio
  125. async def test_the_realistic_reconfigure_broadcasts(self, ws_mgr):
  126. """Black Bambu PLA Basic → red eSUN PLA+ with its own K-profile.
  127. The whole point of the report: same material, so every field the old key
  128. looked at is unchanged.
  129. """
  130. await _push(ws_mgr, [_tray()])
  131. await _push(
  132. ws_mgr,
  133. [
  134. _tray(
  135. tray_color="C1121FFF",
  136. tray_info_idx="GFL99",
  137. tray_sub_brands="eSUN PLA+",
  138. cali_idx=5,
  139. )
  140. ],
  141. )
  142. assert ws_mgr.send_printer_status.await_count == 2
  143. @pytest.mark.asyncio
  144. async def test_a_second_slot_is_watched_too(self, ws_mgr):
  145. """The key spans every tray, so configuring slot 2 must broadcast even
  146. though slot 1 is untouched."""
  147. trays = [_tray(id="0"), _tray(id="1", tray_type="PETG", tray_info_idx="GFG00")]
  148. await _push(ws_mgr, trays)
  149. changed = [_tray(id="0"), _tray(id="1", tray_type="PETG", tray_info_idx="GFG01")]
  150. await _push(ws_mgr, changed)
  151. assert ws_mgr.send_printer_status.await_count == 2
  152. class TestDedupStillHolds:
  153. """The dedup exists to keep a printing machine from flooding the socket.
  154. Widening the key must not have cost that."""
  155. @pytest.mark.asyncio
  156. async def test_an_identical_push_is_still_suppressed(self, ws_mgr):
  157. await _push(ws_mgr, [_tray()])
  158. await _push(ws_mgr, [_tray()])
  159. assert ws_mgr.send_printer_status.await_count == 1
  160. @pytest.mark.asyncio
  161. async def test_remaining_filament_does_not_broadcast(self, ws_mgr):
  162. """`remain` ticks down throughout a print and is deliberately absent
  163. from the key. It sits in the same tray dict as the fields we added, so
  164. this pins that we widened the key rather than hashing the whole tray."""
  165. await _push(ws_mgr, [_tray(remain=42)])
  166. await _push(ws_mgr, [_tray(remain=41)])
  167. assert ws_mgr.send_printer_status.await_count == 1
  168. class TestExistingBehaviourUnchanged:
  169. """The cases that already worked, kept working."""
  170. @pytest.mark.asyncio
  171. async def test_a_load_unload_transition_still_broadcasts(self, ws_mgr):
  172. """#784 — tray state 11→10."""
  173. await _push(ws_mgr, [_tray(state=11)])
  174. await _push(ws_mgr, [_tray(state=10)])
  175. assert ws_mgr.send_printer_status.await_count == 2
  176. @pytest.mark.asyncio
  177. async def test_resetting_a_slot_still_broadcasts(self, ws_mgr):
  178. """Reset clears the filament identity outright."""
  179. await _push(ws_mgr, [_tray()])
  180. await _push(
  181. ws_mgr,
  182. [_tray(tray_type="", tray_color="", tray_info_idx="", tray_sub_brands="", cali_idx=-1)],
  183. )
  184. assert ws_mgr.send_printer_status.await_count == 2
  185. @pytest.mark.asyncio
  186. async def test_a_printer_with_no_ams_still_broadcasts_once(self, ws_mgr):
  187. """The `else ()` branch — an AMS-less printer must not crash or
  188. double-broadcast."""
  189. relay = MagicMock()
  190. relay.on_printer_status = AsyncMock()
  191. pm = MagicMock()
  192. pm.get_printer.return_value = None
  193. pm.get_model.return_value = ""
  194. state = _state([])
  195. state.raw_data = {}
  196. for _ in range(2):
  197. with (
  198. patch("backend.app.main.ws_manager", ws_mgr),
  199. patch("backend.app.main.mqtt_relay", relay),
  200. patch("backend.app.main.printer_manager", pm),
  201. _spawn_patch(),
  202. patch("backend.app.main.printer_state_to_dict", return_value={}),
  203. ):
  204. await main_module.on_printer_status_change(1, state)
  205. assert ws_mgr.send_printer_status.await_count == 1
  206. class TestFilamentTrackSwitchBroadcasts:
  207. """Moving an AMS to the other switch inlet has to reach the printer card.
  208. The inlet binding lives in AMS ``info`` bits, so it is in neither the tray
  209. component of this key nor the AMS change-hash (which covers tray fields only
  210. — widening that would fire spurious Spoolman syncs). Without its own term
  211. here, "Join IN-B" on the printer's Manual AMS Setup screen moved no key at
  212. all and the card's inlet badges stayed stale until a page reload.
  213. """
  214. @staticmethod
  215. def _fts_state(inlets: dict[str, str], installed: bool = True):
  216. from backend.app.services.bambu_mqtt import FilaSwitchState
  217. state = _state([_tray()])
  218. state.fila_switch = FilaSwitchState(installed=installed)
  219. state.ams_switch_inlet = inlets
  220. return state
  221. async def _push_state(self, ws_mgr, state) -> None:
  222. relay = MagicMock()
  223. relay.on_printer_status = AsyncMock()
  224. pm = MagicMock()
  225. pm.get_printer.return_value = None
  226. pm.get_model.return_value = ""
  227. with (
  228. patch("backend.app.main.ws_manager", ws_mgr),
  229. patch("backend.app.main.mqtt_relay", relay),
  230. patch("backend.app.main.printer_manager", pm),
  231. _spawn_patch(),
  232. patch("backend.app.main.printer_state_to_dict", return_value={}),
  233. ):
  234. await main_module.on_printer_status_change(1, state)
  235. @pytest.mark.asyncio
  236. async def test_a_rebind_broadcasts(self, ws_mgr):
  237. await self._push_state(ws_mgr, self._fts_state({"0": "A", "1": "B"}))
  238. assert ws_mgr.send_printer_status.await_count == 1
  239. await self._push_state(ws_mgr, self._fts_state({"0": "B", "1": "B"}))
  240. assert ws_mgr.send_printer_status.await_count == 2, (
  241. "moving an AMS to the other inlet did not reach the frontend — the "
  242. "card would keep showing the old inlet badge until a page reload"
  243. )
  244. @pytest.mark.asyncio
  245. async def test_fitting_the_accessory_broadcasts(self, ws_mgr):
  246. await self._push_state(ws_mgr, self._fts_state({}, installed=False))
  247. await self._push_state(ws_mgr, self._fts_state({}, installed=True))
  248. assert ws_mgr.send_printer_status.await_count == 2
  249. @pytest.mark.asyncio
  250. async def test_an_unchanged_binding_is_still_suppressed(self, ws_mgr):
  251. """The binding only moves when someone reconfigures the machine, so it
  252. must not add a broadcast to every push mid-print."""
  253. for _ in range(3):
  254. await self._push_state(ws_mgr, self._fts_state({"0": "A", "1": "B"}))
  255. assert ws_mgr.send_printer_status.await_count == 1
  256. @pytest.mark.asyncio
  257. async def test_key_order_does_not_matter(self, ws_mgr):
  258. """Dict iteration order must not masquerade as a rebind."""
  259. await self._push_state(ws_mgr, self._fts_state({"0": "A", "1": "B"}))
  260. await self._push_state(ws_mgr, self._fts_state({"1": "B", "0": "A"}))
  261. assert ws_mgr.send_printer_status.await_count == 1