test_printer_manager.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  1. """Unit tests for PrinterManager service.
  2. Tests printer connection management, status tracking, and print control.
  3. """
  4. import logging
  5. from unittest.mock import AsyncMock, MagicMock, patch
  6. import pytest
  7. from backend.app.services.printer_manager import (
  8. PrinterManager,
  9. display_temperatures,
  10. drying_screen_only,
  11. get_derived_status_name,
  12. has_stg_cur_idle_bug,
  13. init_printer_connections,
  14. parse_plate_id,
  15. printer_state_to_dict,
  16. supports_chamber_temp,
  17. supports_drying,
  18. supports_drying_while_printing,
  19. )
  20. class TestPrinterManager:
  21. """Tests for PrinterManager class."""
  22. @pytest.fixture
  23. def manager(self):
  24. """Create a fresh PrinterManager instance."""
  25. return PrinterManager()
  26. @pytest.fixture
  27. def mock_printer(self):
  28. """Create a mock Printer object."""
  29. printer = MagicMock()
  30. printer.id = 1
  31. printer.ip_address = "192.168.1.100"
  32. printer.serial_number = "00M09A123456789"
  33. printer.access_code = "12345678"
  34. printer.is_active = True
  35. return printer
  36. @pytest.fixture
  37. def mock_client(self):
  38. """Create a mock BambuMQTTClient."""
  39. client = MagicMock()
  40. client.state = MagicMock()
  41. client.state.connected = True
  42. client.state.state = "IDLE"
  43. client.state.progress = 0
  44. client.state.temperatures = {"nozzle": 25, "bed": 25}
  45. client.state.raw_data = {}
  46. client.logging_enabled = False
  47. # mark_power_off is real logic on BambuMQTTClient (#2629) — mirror it so
  48. # the manager tests still exercise the state transition they assert on.
  49. # The real implementation (and its recovery path) is covered in
  50. # test_bambu_mqtt.py::TestPresumedPowerOffRecovery.
  51. def _mark_power_off():
  52. if not client.state.connected:
  53. return False
  54. client.state.connected = False
  55. client.state.state = "unknown"
  56. return True
  57. client.mark_power_off.side_effect = _mark_power_off
  58. return client
  59. # ========================================================================
  60. # Tests for initialization
  61. # ========================================================================
  62. def test_init_creates_empty_clients_dict(self, manager):
  63. """Verify manager initializes with empty clients dict."""
  64. assert manager._clients == {}
  65. def test_init_callbacks_are_none(self, manager):
  66. """Verify all callbacks are initially None."""
  67. assert manager._on_print_start is None
  68. assert manager._on_print_complete is None
  69. assert manager._on_status_change is None
  70. assert manager._on_ams_change is None
  71. def test_init_loop_is_none(self, manager):
  72. """Verify event loop is initially None."""
  73. assert manager._loop is None
  74. # ========================================================================
  75. # Tests for callback setters
  76. # ========================================================================
  77. def test_set_event_loop(self, manager):
  78. """Verify event loop can be set."""
  79. mock_loop = MagicMock()
  80. manager.set_event_loop(mock_loop)
  81. assert manager._loop == mock_loop
  82. def test_set_print_start_callback(self, manager):
  83. """Verify print start callback can be set."""
  84. callback = MagicMock()
  85. manager.set_print_start_callback(callback)
  86. assert manager._on_print_start == callback
  87. def test_set_print_complete_callback(self, manager):
  88. """Verify print complete callback can be set."""
  89. callback = MagicMock()
  90. manager.set_print_complete_callback(callback)
  91. assert manager._on_print_complete == callback
  92. def test_set_status_change_callback(self, manager):
  93. """Verify status change callback can be set."""
  94. callback = MagicMock()
  95. manager.set_status_change_callback(callback)
  96. assert manager._on_status_change == callback
  97. def test_set_ams_change_callback(self, manager):
  98. """Verify AMS change callback can be set."""
  99. callback = MagicMock()
  100. manager.set_ams_change_callback(callback)
  101. assert manager._on_ams_change == callback
  102. # ========================================================================
  103. # Tests for _schedule_async
  104. # ========================================================================
  105. def test_schedule_async_with_running_loop(self, manager):
  106. """Verify async coroutine is scheduled when loop is running."""
  107. mock_loop = MagicMock()
  108. mock_loop.is_running.return_value = True
  109. manager._loop = mock_loop
  110. async def dummy_coro():
  111. pass
  112. coro = dummy_coro()
  113. manager._schedule_async(coro)
  114. mock_loop.is_running.assert_called_once()
  115. # Clean up the coroutine
  116. coro.close()
  117. def test_schedule_async_without_loop(self, manager):
  118. """Verify nothing happens when no loop is set."""
  119. async def dummy_coro():
  120. pass
  121. coro = dummy_coro()
  122. # Should not raise
  123. manager._schedule_async(coro)
  124. coro.close()
  125. def test_schedule_async_with_stopped_loop(self, manager):
  126. """Verify nothing happens when loop is not running."""
  127. mock_loop = MagicMock()
  128. mock_loop.is_running.return_value = False
  129. manager._loop = mock_loop
  130. async def dummy_coro():
  131. pass
  132. coro = dummy_coro()
  133. manager._schedule_async(coro)
  134. coro.close()
  135. # ========================================================================
  136. # Tests for connect_printer
  137. # ========================================================================
  138. @pytest.mark.asyncio
  139. async def test_connect_printer_creates_client(self, manager, mock_printer):
  140. """Verify connecting creates an MQTT client."""
  141. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  142. mock_instance = MagicMock()
  143. mock_instance.state = MagicMock()
  144. mock_instance.state.connected = True
  145. MockClient.return_value = mock_instance
  146. result = await manager.connect_printer(mock_printer)
  147. MockClient.assert_called_once()
  148. mock_instance.connect.assert_called_once()
  149. assert mock_printer.id in manager._clients
  150. assert result is True
  151. @pytest.mark.asyncio
  152. async def test_connect_printer_disconnects_existing(self, manager, mock_printer, mock_client):
  153. """Verify connecting disconnects existing client first."""
  154. manager._clients[mock_printer.id] = mock_client
  155. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  156. new_client = MagicMock()
  157. new_client.state = MagicMock()
  158. new_client.state.connected = True
  159. MockClient.return_value = new_client
  160. await manager.connect_printer(mock_printer)
  161. mock_client.disconnect.assert_called_once()
  162. @pytest.mark.asyncio
  163. async def test_connect_printer_returns_false_on_failure(self, manager, mock_printer):
  164. """Verify returns False when connection fails."""
  165. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  166. mock_instance = MagicMock()
  167. mock_instance.state = MagicMock()
  168. mock_instance.state.connected = False
  169. MockClient.return_value = mock_instance
  170. result = await manager.connect_printer(mock_printer)
  171. assert result is False
  172. # ========================================================================
  173. # Tests for disconnect_printer
  174. # ========================================================================
  175. def test_disconnect_printer_removes_client(self, manager, mock_client):
  176. """Verify disconnecting removes and disconnects client."""
  177. manager._clients[1] = mock_client
  178. manager.disconnect_printer(1)
  179. mock_client.disconnect.assert_called_once()
  180. assert 1 not in manager._clients
  181. def test_disconnect_printer_handles_missing(self, manager):
  182. """Verify disconnecting non-existent printer doesn't raise."""
  183. manager.disconnect_printer(999) # Should not raise
  184. # ========================================================================
  185. # Tests for disconnect_all
  186. # ========================================================================
  187. def test_disconnect_all_disconnects_all_clients(self, manager):
  188. """Verify all clients are disconnected."""
  189. client1 = MagicMock()
  190. client2 = MagicMock()
  191. manager._clients[1] = client1
  192. manager._clients[2] = client2
  193. manager.disconnect_all()
  194. client1.disconnect.assert_called_once()
  195. client2.disconnect.assert_called_once()
  196. assert len(manager._clients) == 0
  197. # ========================================================================
  198. # Tests for get_status
  199. # ========================================================================
  200. def test_get_status_returns_state(self, manager, mock_client):
  201. """Verify get_status returns client state."""
  202. manager._clients[1] = mock_client
  203. result = manager.get_status(1)
  204. mock_client.check_staleness.assert_called_once()
  205. assert result == mock_client.state
  206. def test_get_status_returns_none_for_unknown(self, manager):
  207. """Verify get_status returns None for unknown printer."""
  208. result = manager.get_status(999)
  209. assert result is None
  210. # ========================================================================
  211. # Tests for get_all_statuses
  212. # ========================================================================
  213. def test_get_all_statuses_returns_all(self, manager):
  214. """Verify all statuses are returned."""
  215. client1 = MagicMock()
  216. client1.state = MagicMock(connected=True)
  217. client2 = MagicMock()
  218. client2.state = MagicMock(connected=False)
  219. manager._clients[1] = client1
  220. manager._clients[2] = client2
  221. result = manager.get_all_statuses()
  222. assert len(result) == 2
  223. assert 1 in result
  224. assert 2 in result
  225. client1.check_staleness.assert_called_once()
  226. client2.check_staleness.assert_called_once()
  227. # ========================================================================
  228. # Tests for is_connected
  229. # ========================================================================
  230. def test_is_connected_returns_true(self, manager, mock_client):
  231. """Verify is_connected returns True for connected printer."""
  232. mock_client.check_staleness.return_value = True
  233. manager._clients[1] = mock_client
  234. result = manager.is_connected(1)
  235. assert result is True
  236. def test_is_connected_returns_false_for_unknown(self, manager):
  237. """Verify is_connected returns False for unknown printer."""
  238. result = manager.is_connected(999)
  239. assert result is False
  240. # ========================================================================
  241. # Tests for get_client
  242. # ========================================================================
  243. def test_get_client_returns_client(self, manager, mock_client):
  244. """Verify get_client returns the client."""
  245. manager._clients[1] = mock_client
  246. result = manager.get_client(1)
  247. assert result == mock_client
  248. def test_get_client_returns_none_for_unknown(self, manager):
  249. """Verify get_client returns None for unknown printer."""
  250. result = manager.get_client(999)
  251. assert result is None
  252. # ========================================================================
  253. # Tests for mark_printer_offline
  254. # ========================================================================
  255. def test_mark_printer_offline_updates_state(self, manager, mock_client):
  256. """Verify mark_printer_offline updates client state."""
  257. mock_client.state.connected = True
  258. manager._clients[1] = mock_client
  259. manager.mark_printer_offline(1)
  260. assert mock_client.state.connected is False
  261. assert mock_client.state.state == "unknown"
  262. def test_mark_printer_offline_triggers_callback(self, manager, mock_client):
  263. """Verify mark_printer_offline triggers status callback."""
  264. mock_client.state.connected = True
  265. manager._clients[1] = mock_client
  266. # Callback must return a coroutine
  267. async def async_callback(printer_id, state):
  268. pass
  269. manager._on_status_change = async_callback
  270. # Need a running loop for callback
  271. mock_loop = MagicMock()
  272. mock_loop.is_running.return_value = True
  273. manager._loop = mock_loop
  274. manager.mark_printer_offline(1)
  275. # Callback should be scheduled via run_coroutine_threadsafe
  276. mock_loop.is_running.assert_called()
  277. # State should be updated
  278. assert mock_client.state.connected is False
  279. def test_mark_printer_offline_handles_unknown(self, manager):
  280. """Verify mark_printer_offline handles unknown printer."""
  281. manager.mark_printer_offline(999) # Should not raise
  282. def test_mark_printer_offline_skips_already_offline(self, manager, mock_client):
  283. """Verify mark_printer_offline skips already offline printer."""
  284. mock_client.state.connected = False
  285. manager._clients[1] = mock_client
  286. manager.mark_printer_offline(1)
  287. # State should remain unchanged
  288. assert mock_client.state.connected is False
  289. # ========================================================================
  290. # Tests for start_print
  291. # ========================================================================
  292. def test_start_print_calls_client(self, manager, mock_client):
  293. """Verify start_print calls client method."""
  294. mock_client.start_print.return_value = True
  295. manager._clients[1] = mock_client
  296. result = manager.start_print(1, "test.gcode")
  297. mock_client.start_print.assert_called_once_with(
  298. "test.gcode",
  299. 1,
  300. ams_mapping=None,
  301. timelapse=False,
  302. bed_levelling="auto",
  303. flow_cali="auto",
  304. vibration_cali=True,
  305. layer_inspect=False,
  306. use_ams=True,
  307. nozzle_offset_cali="auto",
  308. nozzle_mapping=None,
  309. )
  310. assert result is True
  311. def test_start_print_returns_false_for_unknown(self, manager):
  312. """Verify start_print returns False for unknown printer."""
  313. result = manager.start_print(999, "test.gcode")
  314. assert result is False
  315. def test_start_print_logs_print_command_with_caller(self, manager, mock_client, caplog):
  316. """Verify start_print logs PRINT COMMAND with caller info (#374)."""
  317. mock_client.start_print.return_value = True
  318. manager._clients[1] = mock_client
  319. with caplog.at_level(logging.INFO, logger="backend.app.services.printer_manager"):
  320. manager.start_print(1, "benchy.3mf")
  321. print_cmd_logs = [r for r in caplog.records if "PRINT COMMAND" in r.message]
  322. assert len(print_cmd_logs) == 1
  323. log_msg = print_cmd_logs[0].message
  324. assert "printer=1" in log_msg
  325. assert "file=benchy.3mf" in log_msg
  326. assert "caller=" in log_msg
  327. def test_start_print_logs_even_when_printer_unknown(self, manager, caplog):
  328. """Verify PRINT COMMAND is logged even for unknown printers (#374)."""
  329. with caplog.at_level(logging.INFO, logger="backend.app.services.printer_manager"):
  330. result = manager.start_print(999, "ghost.3mf")
  331. assert result is False
  332. print_cmd_logs = [r for r in caplog.records if "PRINT COMMAND" in r.message]
  333. assert len(print_cmd_logs) == 1
  334. # ========================================================================
  335. # Tests for stop_print
  336. # ========================================================================
  337. def test_stop_print_calls_client(self, manager, mock_client):
  338. """Verify stop_print calls client method."""
  339. mock_client.stop_print.return_value = True
  340. manager._clients[1] = mock_client
  341. result = manager.stop_print(1)
  342. mock_client.stop_print.assert_called_once()
  343. assert result is True
  344. def test_stop_print_returns_false_for_unknown(self, manager):
  345. """Verify stop_print returns False for unknown printer."""
  346. result = manager.stop_print(999)
  347. assert result is False
  348. # ========================================================================
  349. # Tests for wait_for_cooldown
  350. # ========================================================================
  351. @pytest.mark.asyncio
  352. async def test_wait_for_cooldown_returns_true_when_cool(self, manager, mock_client):
  353. """Verify wait_for_cooldown returns True when printer is cool."""
  354. mock_client.state.connected = True
  355. mock_client.state.temperatures = {"nozzle": 40, "bed": 30}
  356. mock_client.check_staleness.return_value = True
  357. manager._clients[1] = mock_client
  358. result = await manager.wait_for_cooldown(1, target_temp=50)
  359. assert result is True
  360. @pytest.mark.asyncio
  361. async def test_wait_for_cooldown_returns_false_on_disconnect(self, manager, mock_client):
  362. """Verify wait_for_cooldown returns False when printer disconnects."""
  363. mock_client.state.connected = False
  364. mock_client.check_staleness.return_value = False
  365. manager._clients[1] = mock_client
  366. result = await manager.wait_for_cooldown(1, target_temp=50, timeout=1)
  367. assert result is False
  368. @pytest.mark.asyncio
  369. async def test_wait_for_cooldown_returns_false_for_unknown(self, manager):
  370. """Verify wait_for_cooldown returns False for unknown printer."""
  371. result = await manager.wait_for_cooldown(999, target_temp=50, timeout=1)
  372. assert result is False
  373. @pytest.mark.asyncio
  374. async def test_wait_for_cooldown_checks_both_nozzles(self, manager, mock_client):
  375. """Verify wait_for_cooldown checks both nozzles for dual extruders."""
  376. mock_client.state.connected = True
  377. mock_client.state.temperatures = {"nozzle": 40, "nozzle_2": 45, "bed": 30}
  378. mock_client.check_staleness.return_value = True
  379. manager._clients[1] = mock_client
  380. result = await manager.wait_for_cooldown(1, target_temp=50)
  381. assert result is True
  382. # ========================================================================
  383. # Tests for is_print_active (#1890)
  384. # ========================================================================
  385. @pytest.mark.parametrize(
  386. "state,expected",
  387. [
  388. ("RUNNING", True),
  389. ("PAUSE", True),
  390. ("PREPARE", True),
  391. ("SLICING", True),
  392. ("FINISH", False),
  393. ("IDLE", False),
  394. ("FAILED", False),
  395. ("unknown", False),
  396. ],
  397. )
  398. def test_is_print_active_state_matrix(self, manager, mock_client, state, expected):
  399. """A job-loaded state is 'active'; idle/terminal states are not."""
  400. mock_client.state.connected = True
  401. mock_client.state.state = state
  402. mock_client.check_staleness.return_value = True
  403. manager._clients[1] = mock_client
  404. assert manager.is_print_active(1) is expected
  405. def test_is_print_active_false_when_disconnected(self, manager, mock_client):
  406. """Even in RUNNING, a disconnected printer is not treated as active —
  407. we fail safe (no active print) only for the 'nothing printing' cases."""
  408. mock_client.state.connected = False
  409. mock_client.state.state = "RUNNING"
  410. mock_client.check_staleness.return_value = False
  411. manager._clients[1] = mock_client
  412. assert manager.is_print_active(1) is False
  413. def test_is_print_active_false_for_unknown_printer(self, manager):
  414. """Unknown printer id → not active (no client)."""
  415. assert manager.is_print_active(999) is False
  416. # ========================================================================
  417. # Tests for logging methods
  418. # ========================================================================
  419. def test_enable_logging_calls_client(self, manager, mock_client):
  420. """Verify enable_logging calls client method."""
  421. manager._clients[1] = mock_client
  422. result = manager.enable_logging(1, True)
  423. mock_client.enable_logging.assert_called_once_with(True)
  424. assert result is True
  425. def test_enable_logging_returns_false_for_unknown(self, manager):
  426. """Verify enable_logging returns False for unknown printer."""
  427. result = manager.enable_logging(999, True)
  428. assert result is False
  429. def test_get_logs_returns_logs(self, manager, mock_client):
  430. """Verify get_logs returns client logs."""
  431. mock_logs = [MagicMock(), MagicMock()]
  432. mock_client.get_logs.return_value = mock_logs
  433. manager._clients[1] = mock_client
  434. result = manager.get_logs(1)
  435. assert result == mock_logs
  436. def test_get_logs_returns_empty_for_unknown(self, manager):
  437. """Verify get_logs returns empty list for unknown printer."""
  438. result = manager.get_logs(999)
  439. assert result == []
  440. def test_clear_logs_calls_client(self, manager, mock_client):
  441. """Verify clear_logs calls client method."""
  442. manager._clients[1] = mock_client
  443. result = manager.clear_logs(1)
  444. mock_client.clear_logs.assert_called_once()
  445. assert result is True
  446. def test_clear_logs_returns_false_for_unknown(self, manager):
  447. """Verify clear_logs returns False for unknown printer."""
  448. result = manager.clear_logs(999)
  449. assert result is False
  450. def test_is_logging_enabled_returns_status(self, manager, mock_client):
  451. """Verify is_logging_enabled returns client status."""
  452. mock_client.logging_enabled = True
  453. manager._clients[1] = mock_client
  454. result = manager.is_logging_enabled(1)
  455. assert result is True
  456. def test_is_logging_enabled_returns_false_for_unknown(self, manager):
  457. """Verify is_logging_enabled returns False for unknown printer."""
  458. result = manager.is_logging_enabled(999)
  459. assert result is False
  460. # ========================================================================
  461. # Tests for request_status_update
  462. # ========================================================================
  463. def test_request_status_update_calls_client(self, manager, mock_client):
  464. """Verify request_status_update calls client method."""
  465. mock_client.request_status_update.return_value = True
  466. manager._clients[1] = mock_client
  467. result = manager.request_status_update(1)
  468. mock_client.request_status_update.assert_called_once()
  469. assert result is True
  470. def test_request_status_update_returns_false_for_unknown(self, manager):
  471. """Verify request_status_update returns False for unknown printer."""
  472. result = manager.request_status_update(999)
  473. assert result is False
  474. # ========================================================================
  475. # Tests for test_connection
  476. # ========================================================================
  477. @pytest.mark.asyncio
  478. async def test_test_connection_success(self, manager):
  479. """Verify test_connection returns success on connection."""
  480. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  481. mock_instance = MagicMock()
  482. mock_instance.state = MagicMock()
  483. mock_instance.state.connected = True
  484. mock_instance.state.state = "IDLE"
  485. mock_instance.state.raw_data = {"device_model": "X1C"}
  486. MockClient.return_value = mock_instance
  487. result = await manager.test_connection("192.168.1.100", "00M09A123456789", "12345678")
  488. assert result["success"] is True
  489. assert result["state"] == "IDLE"
  490. assert result["model"] == "X1C"
  491. mock_instance.disconnect.assert_called_once()
  492. @pytest.mark.asyncio
  493. async def test_test_connection_failure(self, manager):
  494. """Verify test_connection returns failure on connection error."""
  495. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  496. mock_instance = MagicMock()
  497. mock_instance.state = MagicMock()
  498. mock_instance.state.connected = False
  499. MockClient.return_value = mock_instance
  500. # Shorten the probe budget so the test doesn't burn the full
  501. # 8-second production timeout while polling a failing connection.
  502. with (
  503. patch.object(manager, "PROBE_TIMEOUT_SECONDS", 0.4),
  504. patch.object(manager, "PROBE_POLL_INTERVAL_SECONDS", 0.1),
  505. ):
  506. result = await manager.test_connection("192.168.1.100", "00M09A123456789", "12345678")
  507. assert result["success"] is False
  508. assert result["state"] is None
  509. mock_instance.disconnect.assert_called_once()
  510. @pytest.mark.asyncio
  511. async def test_test_connection_polls_and_returns_early_on_connect(self, manager):
  512. """#1445: a slow printer that finishes its handshake mid-probe must
  513. not be reported as a failure. Previously a fixed 2s sleep meant P1S
  514. TLS / CONNACK that took 3-5s got falsely rejected; now we poll and
  515. early-return as soon as connected flips True.
  516. """
  517. import asyncio
  518. import time
  519. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  520. mock_instance = MagicMock()
  521. mock_instance.state = MagicMock()
  522. mock_instance.state.connected = False # not connected at probe start
  523. mock_instance.state.state = "IDLE"
  524. mock_instance.state.raw_data = {"device_model": "P1S"}
  525. MockClient.return_value = mock_instance
  526. async def flip_connected_after(delay: float):
  527. await asyncio.sleep(delay)
  528. mock_instance.state.connected = True
  529. # Simulates the P1S broker finishing its slow handshake ~0.5s in,
  530. # well past the old 2s-or-fail boundary's natural variance.
  531. with (
  532. patch.object(manager, "PROBE_TIMEOUT_SECONDS", 3.0),
  533. patch.object(manager, "PROBE_POLL_INTERVAL_SECONDS", 0.05),
  534. ):
  535. start = time.monotonic()
  536. flip_task = asyncio.create_task(flip_connected_after(0.5))
  537. try:
  538. result = await manager.test_connection("192.168.1.100", "00M09A123456789", "12345678")
  539. finally:
  540. await flip_task
  541. elapsed = time.monotonic() - start
  542. assert result["success"] is True
  543. assert result["state"] == "IDLE"
  544. # Early-return guarantee: must come back well before the configured
  545. # timeout once connected flips. ~0.5s + one poll interval is plenty.
  546. assert elapsed < 1.5, f"probe should have early-returned shortly after 0.5s, took {elapsed:.2f}s"
  547. @pytest.mark.asyncio
  548. async def test_test_connection_disconnect_runs_off_loop(self, manager):
  549. """#1445: the root cause of the "Docker container hangs" symptom was
  550. `client.disconnect()` running on the asyncio thread — paho's
  551. `loop_stop()` does a thread-join that blocks until its network
  552. thread exits, which on a slow P1S TLS handshake could take many
  553. seconds. This test pins the off-loop teardown so a regression that
  554. reintroduces sync disconnect breaks CI immediately.
  555. """
  556. import asyncio
  557. import threading
  558. import time
  559. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  560. asyncio_thread_id = threading.get_ident()
  561. disconnect_thread_ids: list[int] = []
  562. disconnect_blocked_for: list[float] = []
  563. def slow_blocking_disconnect():
  564. # Mirrors paho.Client.loop_stop()'s thread-join semantics —
  565. # if this runs on the asyncio thread the event loop stalls.
  566. disconnect_thread_ids.append(threading.get_ident())
  567. start = time.monotonic()
  568. time.sleep(0.4)
  569. disconnect_blocked_for.append(time.monotonic() - start)
  570. mock_instance = MagicMock()
  571. mock_instance.state = MagicMock()
  572. mock_instance.state.connected = True
  573. mock_instance.state.state = "IDLE"
  574. mock_instance.state.raw_data = {"device_model": "P1S"}
  575. mock_instance.disconnect = slow_blocking_disconnect
  576. MockClient.return_value = mock_instance
  577. # Another coroutine must keep making progress while disconnect()
  578. # runs — proves the event loop was not blocked.
  579. event_loop_alive_ticks = 0
  580. async def heartbeat():
  581. nonlocal event_loop_alive_ticks
  582. while True:
  583. await asyncio.sleep(0.05)
  584. event_loop_alive_ticks += 1
  585. heartbeat_task = asyncio.create_task(heartbeat())
  586. try:
  587. await manager.test_connection("192.168.1.100", "00M09A123456789", "12345678")
  588. finally:
  589. heartbeat_task.cancel()
  590. try:
  591. await heartbeat_task
  592. except asyncio.CancelledError:
  593. pass
  594. # disconnect ran on a different thread than asyncio's
  595. assert disconnect_thread_ids, "disconnect was never called"
  596. assert disconnect_thread_ids[0] != asyncio_thread_id, (
  597. "disconnect ran on the asyncio thread — this blocks the event loop (#1445)"
  598. )
  599. # Heartbeat made progress while the 0.4s disconnect was blocking
  600. # the worker thread (proves the loop wasn't stalled).
  601. assert event_loop_alive_ticks >= 3, (
  602. f"event loop appears to have stalled during disconnect "
  603. f"(only {event_loop_alive_ticks} heartbeats; expected >=3)"
  604. )
  605. # ========================================================================
  606. # Tests for current print user tracking (Issue #206)
  607. # ========================================================================
  608. def test_set_current_print_user(self, manager):
  609. """Verify current print user can be set."""
  610. manager.set_current_print_user(1, 42, "testuser")
  611. assert 1 in manager._current_print_user
  612. assert manager._current_print_user[1]["user_id"] == 42
  613. assert manager._current_print_user[1]["username"] == "testuser"
  614. def test_get_current_print_user_returns_user(self, manager):
  615. """Verify get_current_print_user returns the stored user."""
  616. manager.set_current_print_user(1, 42, "testuser")
  617. result = manager.get_current_print_user(1)
  618. assert result is not None
  619. assert result["user_id"] == 42
  620. assert result["username"] == "testuser"
  621. def test_get_current_print_user_returns_none_for_unknown(self, manager):
  622. """Verify get_current_print_user returns None for unknown printer."""
  623. result = manager.get_current_print_user(999)
  624. assert result is None
  625. def test_clear_current_print_user(self, manager):
  626. """Verify current print user can be cleared."""
  627. manager.set_current_print_user(1, 42, "testuser")
  628. manager.clear_current_print_user(1)
  629. result = manager.get_current_print_user(1)
  630. assert result is None
  631. def test_clear_current_print_user_no_error_for_unknown(self, manager):
  632. """Verify clearing unknown printer doesn't raise error."""
  633. # Should not raise
  634. manager.clear_current_print_user(999)
  635. def test_set_current_print_user_overwrites_existing(self, manager):
  636. """Verify setting user overwrites existing value."""
  637. manager.set_current_print_user(1, 42, "user1")
  638. manager.set_current_print_user(1, 99, "user2")
  639. result = manager.get_current_print_user(1)
  640. assert result["user_id"] == 99
  641. assert result["username"] == "user2"
  642. def test_multiple_printers_have_separate_users(self, manager):
  643. """Verify each printer tracks its own user separately."""
  644. manager.set_current_print_user(1, 42, "user1")
  645. manager.set_current_print_user(2, 99, "user2")
  646. result1 = manager.get_current_print_user(1)
  647. result2 = manager.get_current_print_user(2)
  648. assert result1["username"] == "user1"
  649. assert result2["username"] == "user2"
  650. class TestPrinterStateToDict:
  651. """Tests for printer_state_to_dict helper function."""
  652. @pytest.fixture
  653. def mock_state(self):
  654. """Create a mock PrinterState."""
  655. state = MagicMock()
  656. state.connected = True
  657. state.state = "RUNNING"
  658. state.current_print = "test.3mf"
  659. state.subtask_name = "Test Print"
  660. state.gcode_file = "/sdcard/test.gcode"
  661. state.progress = 50
  662. state.remaining_time = 3600
  663. state.layer_num = 10
  664. state.total_layers = 20
  665. state.temperatures = {"nozzle": 200, "bed": 60}
  666. state.hms_errors = []
  667. state.ams_status_main = 0
  668. state.ams_status_sub = 0
  669. state.tray_now = "1"
  670. state.wifi_signal = -50
  671. state.raw_data = {}
  672. state.stg_cur = -1 # No calibration stage active
  673. state.firmware_version = None
  674. return state
  675. def test_basic_conversion(self, mock_state):
  676. """Verify basic state fields are converted."""
  677. result = printer_state_to_dict(mock_state)
  678. assert result["connected"] is True
  679. assert result["state"] == "RUNNING"
  680. assert result["progress"] == 50
  681. assert result["temperatures"] == {"nozzle": 200, "bed": 60}
  682. def test_ams_data_parsing(self, mock_state):
  683. """Verify AMS data is parsed correctly."""
  684. mock_state.raw_data = {
  685. "ams": [
  686. {
  687. "id": 0,
  688. "humidity_raw": 45,
  689. "temp": 25,
  690. "tray": [
  691. {
  692. "id": 0,
  693. "tray_color": "FF0000",
  694. "tray_type": "PLA",
  695. "tray_sub_brands": "Generic",
  696. "remain": 80,
  697. "k": 0.5,
  698. "tag_uid": "ABC123",
  699. "tray_uuid": "uuid-123",
  700. }
  701. ],
  702. }
  703. ]
  704. }
  705. result = printer_state_to_dict(mock_state)
  706. assert result["ams"] is not None
  707. assert len(result["ams"]) == 1
  708. assert result["ams"][0]["humidity"] == 45
  709. assert len(result["ams"][0]["tray"]) == 1
  710. assert result["ams"][0]["tray"][0]["tray_color"] == "FF0000"
  711. def test_empty_tag_uid_becomes_none(self, mock_state):
  712. """Verify empty tag_uid is converted to None."""
  713. mock_state.raw_data = {
  714. "ams": [
  715. {
  716. "id": 0,
  717. "tray": [
  718. {
  719. "id": 0,
  720. "tag_uid": "",
  721. "tray_uuid": "00000000000000000000000000000000",
  722. }
  723. ],
  724. }
  725. ]
  726. }
  727. result = printer_state_to_dict(mock_state)
  728. assert result["ams"][0]["tray"][0]["tag_uid"] is None
  729. assert result["ams"][0]["tray"][0]["tray_uuid"] is None
  730. def test_bare_tray_emulates_state_9(self, mock_state):
  731. """P1S / A1 Mini physically-empty-slot signal (#1322 follow-up by @RosdasHH):
  732. the firmware sends only `{"id": N}` for a truly empty slot. Treat that as
  733. the firmware's "no spool" state (state=9) so the inventory assign-spool
  734. path can short-circuit the doomed MQTT publish.
  735. """
  736. mock_state.raw_data = {
  737. "ams": [
  738. {
  739. "id": 0,
  740. "tray": [
  741. {"id": 0, "state": 11, "tray_type": "PLA"}, # loaded slot
  742. {"id": 1}, # P1S empty-slot signal — only id
  743. ],
  744. }
  745. ]
  746. }
  747. result = printer_state_to_dict(mock_state)
  748. trays = result["ams"][0]["tray"]
  749. assert trays[0]["state"] == 11, "loaded slot keeps its firmware state"
  750. assert trays[1]["state"] == 9, "bare {id} tray must be promoted to state=9"
  751. def test_populated_payload_with_empty_state_3_is_not_promoted(self, mock_state):
  752. """A1 Mini BMCU / P1S Standard AMS post-Reset-Slot case (#1322 root):
  753. firmware sends state=3 + tray_type="" but with the FULL field set
  754. populated. Must NOT be confused with the bare-tray empty signal —
  755. else inventory.py would short-circuit MQTT and we'd reintroduce the
  756. deadlock the #1322 fix removed.
  757. """
  758. mock_state.raw_data = {
  759. "ams": [
  760. {
  761. "id": 0,
  762. "tray": [
  763. {
  764. "id": 0,
  765. "state": 3,
  766. "tray_type": "", # cleared
  767. "tray_color": "",
  768. "tag_uid": "0000000000000000",
  769. "remain": 0,
  770. }
  771. ],
  772. }
  773. ]
  774. }
  775. result = printer_state_to_dict(mock_state)
  776. # state stays at 3 — the bare-tray promotion requires the dict to have
  777. # ONLY the id key, not just empty/falsy values for the other fields.
  778. assert result["ams"][0]["tray"][0]["state"] == 3
  779. def test_zero_tag_uid_becomes_none(self, mock_state):
  780. """Verify zero tag_uid is converted to None."""
  781. mock_state.raw_data = {
  782. "ams": [
  783. {
  784. "id": 0,
  785. "tray": [
  786. {
  787. "id": 0,
  788. "tag_uid": "0000000000000000",
  789. }
  790. ],
  791. }
  792. ]
  793. }
  794. result = printer_state_to_dict(mock_state)
  795. assert result["ams"][0]["tray"][0]["tag_uid"] is None
  796. def test_exists_bit_is_serialized_for_websocket(self, mock_state):
  797. """#2670: the WS status payload must carry the firmware presence bit
  798. `exists` (set by apply_tray_exist_bits) — the REST serializer already
  799. does. Without it the frontend shallow-merge drops `exists` after the
  800. first WS frame and getEmptySlotKind falls back to the firmware-variant
  801. state 9/10 heuristic, which is wrong for AMS-HT in both directions.
  802. """
  803. mock_state.raw_data = {
  804. "ams": [
  805. {
  806. "id": 128,
  807. "tray": [
  808. # Empty HT: apply_tray_exist_bits cleared it and set exists=False.
  809. {"id": 0, "state": 9, "tray_type": "", "exists": False},
  810. ],
  811. },
  812. {
  813. "id": 0,
  814. "tray": [
  815. # Present non-RFID spool: exists=True, no tray_type ("?").
  816. {"id": 0, "state": 10, "tray_type": "", "exists": True},
  817. ],
  818. },
  819. ]
  820. }
  821. result = printer_state_to_dict(mock_state)
  822. ht_tray = result["ams"][0]["tray"][0]
  823. reg_tray = result["ams"][1]["tray"][0]
  824. assert ht_tray["exists"] is False
  825. assert reg_tray["exists"] is True
  826. def test_vt_tray_parsing(self, mock_state):
  827. """Verify virtual tray is parsed correctly as a list."""
  828. mock_state.raw_data = {
  829. "vt_tray": [
  830. {
  831. "tray_color": "00FF00",
  832. "tray_type": "PETG",
  833. "tray_sub_brands": "Generic",
  834. "remain": 60,
  835. "tag_uid": "VT123",
  836. }
  837. ]
  838. }
  839. result = printer_state_to_dict(mock_state)
  840. assert isinstance(result["vt_tray"], list)
  841. assert len(result["vt_tray"]) == 1
  842. assert result["vt_tray"][0]["id"] == 254
  843. assert result["vt_tray"][0]["tray_color"] == "00FF00"
  844. assert result["vt_tray"][0]["tray_type"] == "PETG"
  845. def test_vt_tray_dict_normalized_to_list(self, mock_state):
  846. """Verify vt_tray as a raw dict (from MQTT) is normalized to a list."""
  847. mock_state.raw_data = {
  848. "vt_tray": {
  849. "id": "254",
  850. "tray_color": "FF0000",
  851. "tray_type": "PLA",
  852. "tray_sub_brands": "Generic",
  853. "tag_uid": "0000000000000000",
  854. "tray_uuid": "00000000000000000000000000000000",
  855. "remain": 0,
  856. }
  857. }
  858. result = printer_state_to_dict(mock_state)
  859. assert isinstance(result["vt_tray"], list)
  860. assert len(result["vt_tray"]) == 1
  861. assert result["vt_tray"][0]["tray_color"] == "FF0000"
  862. assert result["vt_tray"][0]["tray_type"] == "PLA"
  863. assert result["vt_tray"][0]["tag_uid"] is None
  864. assert result["vt_tray"][0]["tray_uuid"] is None
  865. def test_vt_tray_non_list_non_dict_ignored(self, mock_state):
  866. """Verify unexpected vt_tray types (e.g. string) produce empty list."""
  867. mock_state.raw_data = {"vt_tray": "unexpected_string"}
  868. result = printer_state_to_dict(mock_state)
  869. assert result["vt_tray"] == []
  870. def test_hms_errors_conversion(self, mock_state):
  871. """Verify HMS errors are converted correctly."""
  872. error = MagicMock()
  873. error.code = "0700_0100"
  874. error.attr = 1
  875. error.module = "AMS"
  876. error.severity = 2
  877. mock_state.hms_errors = [error]
  878. result = printer_state_to_dict(mock_state)
  879. assert len(result["hms_errors"]) == 1
  880. assert result["hms_errors"][0]["code"] == "0700_0100"
  881. assert result["hms_errors"][0]["module"] == "AMS"
  882. def test_cover_url_added_for_running_print(self, mock_state):
  883. """Verify cover_url is added for running prints."""
  884. result = printer_state_to_dict(mock_state, printer_id=1)
  885. assert result["cover_url"] == "/api/v1/printers/1/cover"
  886. def test_current_plate_id_extracted_from_gcode_file(self, mock_state):
  887. """Verify current_plate_id is parsed from a Bambu plate path (#881)."""
  888. mock_state.gcode_file = "/Metadata/plate_3.gcode"
  889. result = printer_state_to_dict(mock_state)
  890. assert result["current_plate_id"] == 3
  891. def test_current_plate_id_none_when_no_plate_segment(self, mock_state):
  892. """Verify current_plate_id stays None when gcode_file has no plate marker."""
  893. mock_state.gcode_file = "/sdcard/test.gcode"
  894. result = printer_state_to_dict(mock_state)
  895. assert result["current_plate_id"] is None
  896. def test_cover_url_none_when_not_running(self, mock_state):
  897. """Verify cover_url is None when not printing."""
  898. mock_state.state = "IDLE"
  899. result = printer_state_to_dict(mock_state, printer_id=1)
  900. assert result["cover_url"] is None
  901. def test_ams_ht_detection(self, mock_state):
  902. """Verify AMS-HT is detected (1 tray vs 4)."""
  903. mock_state.raw_data = {
  904. "ams": [
  905. {
  906. "id": 0,
  907. "tray": [{"id": 0}], # Only 1 tray = AMS-HT
  908. }
  909. ]
  910. }
  911. result = printer_state_to_dict(mock_state)
  912. assert result["ams"][0]["is_ams_ht"] is True
  913. def test_regular_ams_detection(self, mock_state):
  914. """Verify regular AMS is detected (4 trays)."""
  915. mock_state.raw_data = {"ams": [{"id": 0, "tray": [{"id": 0}, {"id": 1}, {"id": 2}, {"id": 3}]}]}
  916. result = printer_state_to_dict(mock_state)
  917. assert result["ams"][0]["is_ams_ht"] is False
  918. def test_chamber_temp_filtered_for_p1s(self, mock_state):
  919. """Verify chamber temperature is filtered out for P1S (no chamber sensor)."""
  920. mock_state.temperatures = {
  921. "nozzle": 200,
  922. "bed": 60,
  923. "chamber": 5,
  924. "chamber_target": 0,
  925. "chamber_heating": False,
  926. }
  927. result = printer_state_to_dict(mock_state, model="P1S")
  928. assert "chamber" not in result["temperatures"]
  929. assert "chamber_target" not in result["temperatures"]
  930. assert "chamber_heating" not in result["temperatures"]
  931. assert result["temperatures"]["nozzle"] == 200
  932. assert result["temperatures"]["bed"] == 60
  933. def test_chamber_temp_kept_for_x1c(self, mock_state):
  934. """Verify chamber temperature is kept for X1C (has chamber sensor)."""
  935. mock_state.temperatures = {
  936. "nozzle": 200,
  937. "bed": 60,
  938. "chamber": 25,
  939. "chamber_target": 45,
  940. "chamber_heating": True,
  941. }
  942. result = printer_state_to_dict(mock_state, model="X1C")
  943. assert result["temperatures"]["chamber"] == 25
  944. assert result["temperatures"]["chamber_target"] == 45
  945. assert result["temperatures"]["chamber_heating"] is True
  946. def test_chamber_temp_filtered_for_a1(self, mock_state):
  947. """Verify chamber temperature is filtered out for A1 (no chamber sensor)."""
  948. mock_state.temperatures = {"nozzle": 200, "bed": 60, "chamber": 5}
  949. result = printer_state_to_dict(mock_state, model="A1")
  950. assert "chamber" not in result["temperatures"]
  951. def test_chamber_temp_kept_when_no_model(self, mock_state):
  952. """Verify chamber temperature is kept when model is not specified (conservative approach)."""
  953. mock_state.temperatures = {"nozzle": 200, "bed": 60, "chamber": 25}
  954. result = printer_state_to_dict(mock_state) # No model specified
  955. # When model is unknown, we can't filter - leave as is
  956. # Actually supports_chamber_temp returns False for None, so it will filter
  957. # Let's check the actual behavior
  958. assert "chamber" not in result["temperatures"]
  959. def test_ams_drying_fields_included(self, mock_state):
  960. """Verify AMS drying fields (dry_time, module_type) are included in output."""
  961. mock_state.raw_data = {
  962. "ams": [
  963. {
  964. "id": 0,
  965. "dry_time": 42,
  966. "module_type": "n3f",
  967. "tray": [
  968. {
  969. "id": 0,
  970. "tray_color": "FF0000",
  971. "tray_type": "PLA",
  972. "drying_temp": 55,
  973. "drying_time": 240,
  974. }
  975. ],
  976. }
  977. ]
  978. }
  979. result = printer_state_to_dict(mock_state)
  980. ams_unit = result["ams"][0]
  981. assert ams_unit["dry_time"] == 42
  982. assert ams_unit["module_type"] == "n3f"
  983. # Tray-level drying fields
  984. tray = ams_unit["tray"][0]
  985. assert tray["drying_temp"] == 55
  986. assert tray["drying_time"] == 240
  987. def test_awaiting_plate_clear_defaults_false(self, mock_state):
  988. """Without a printer_id, awaiting_plate_clear is False (no lookup possible)."""
  989. result = printer_state_to_dict(mock_state)
  990. assert result["awaiting_plate_clear"] is False
  991. def test_awaiting_plate_clear_surfaced_when_set(self, mock_state):
  992. """With printer_id, awaiting_plate_clear reflects PrinterManager state.
  993. Regression: PR #939 left this flag off the WebSocket payload, so the
  994. "Clear Plate" button only appeared after the 30 s REST fallback poll.
  995. """
  996. from backend.app.services.printer_manager import printer_manager
  997. printer_manager.set_awaiting_plate_clear(12345, True)
  998. try:
  999. result = printer_state_to_dict(mock_state, printer_id=12345)
  1000. assert result["awaiting_plate_clear"] is True
  1001. finally:
  1002. printer_manager.set_awaiting_plate_clear(12345, False)
  1003. def test_name_and_model_surfaced_when_registered(self, mock_state):
  1004. """Registered PrinterInfo name + model arg should land in the WS payload.
  1005. Regression for #963 follow-up: without this, the gcode viewer's printer
  1006. selector had to wait on a /printers fetch before it could render real
  1007. names, and the initial WS snapshot showed "Printer 1" fallbacks.
  1008. """
  1009. from backend.app.services.printer_manager import PrinterInfo, printer_manager
  1010. # Register a stub PrinterInfo; the real manager writes this on connect.
  1011. printer_manager._printer_info[98765] = PrinterInfo(name="My X1C", serial_number="01S00-0")
  1012. try:
  1013. result = printer_state_to_dict(mock_state, printer_id=98765, model="X1C")
  1014. assert result["name"] == "My X1C"
  1015. assert result["model"] == "X1C"
  1016. finally:
  1017. printer_manager._printer_info.pop(98765, None)
  1018. def test_name_and_model_absent_when_no_printer_id(self, mock_state):
  1019. """Without a printer_id (unusual callsites), name/model keys stay absent.
  1020. The consumers (gcode viewer, frontend card) tolerate missing keys; what
  1021. they can't tolerate is an unrelated printer's name accidentally leaking
  1022. into a status meant for a different one.
  1023. """
  1024. result = printer_state_to_dict(mock_state)
  1025. assert "name" not in result
  1026. assert "model" not in result
  1027. def test_model_absent_when_arg_is_none(self, mock_state):
  1028. """`model` arg=None must not plant a `model` key at all.
  1029. If the arg is None, callers didn't know the model yet; emitting a
  1030. `model: null` field would overwrite a good value cached client-side.
  1031. """
  1032. from backend.app.services.printer_manager import PrinterInfo, printer_manager
  1033. printer_manager._printer_info[55555] = PrinterInfo(name="N", serial_number="S")
  1034. try:
  1035. result = printer_state_to_dict(mock_state, printer_id=55555, model=None)
  1036. assert "model" not in result
  1037. assert result["name"] == "N"
  1038. finally:
  1039. printer_manager._printer_info.pop(55555, None)
  1040. class TestStatusKeyDryingDedup:
  1041. """Regression tests for WebSocket dedup including drying fields.
  1042. The WebSocket broadcast deduplication uses printer_state_to_dict output
  1043. to detect changes. If drying fields (like dry_time) are missing from
  1044. the dict, changes to those fields won't trigger broadcasts.
  1045. """
  1046. def test_dry_time_change_changes_status_key(self):
  1047. """Verify dry_time is present in AMS unit data so dedup can detect changes."""
  1048. state = MagicMock()
  1049. state.connected = True
  1050. state.state = "IDLE"
  1051. state.current_print = None
  1052. state.subtask_name = None
  1053. state.gcode_file = None
  1054. state.progress = 0
  1055. state.remaining_time = 0
  1056. state.layer_num = 0
  1057. state.total_layers = 0
  1058. state.temperatures = {"nozzle": 25, "bed": 25}
  1059. state.hms_errors = []
  1060. state.ams_status_main = 0
  1061. state.ams_status_sub = 0
  1062. state.tray_now = None
  1063. state.wifi_signal = -50
  1064. state.stg_cur = -1
  1065. # First state: drying active with 30 minutes remaining
  1066. state.raw_data = {"ams": [{"id": 0, "dry_time": 30, "module_type": "n3f", "tray": [{"id": 0}]}]}
  1067. result1 = printer_state_to_dict(state)
  1068. # Second state: drying time decreased
  1069. state.raw_data = {"ams": [{"id": 0, "dry_time": 29, "module_type": "n3f", "tray": [{"id": 0}]}]}
  1070. result2 = printer_state_to_dict(state)
  1071. # The dicts should differ — dry_time changed
  1072. assert result1["ams"][0]["dry_time"] == 30
  1073. assert result2["ams"][0]["dry_time"] == 29
  1074. assert result1["ams"] != result2["ams"]
  1075. class TestDryingTargetExposure:
  1076. """Tests for dry_target_temp / dry_filament surfacing on AMS state dict.
  1077. Bambu does not echo the active cycle's chosen filament + target
  1078. temperature on the per-tick AMS push, only the dry_time countdown.
  1079. The badge needs the cached target so it can render "PETG @ 65°C".
  1080. """
  1081. def _state_with_ams(self, ams_data: dict) -> object:
  1082. state = MagicMock()
  1083. state.connected = True
  1084. state.state = "IDLE"
  1085. state.current_print = None
  1086. state.subtask_name = None
  1087. state.gcode_file = None
  1088. state.progress = 0
  1089. state.remaining_time = 0
  1090. state.layer_num = 0
  1091. state.total_layers = 0
  1092. state.temperatures = {"nozzle": 25, "bed": 25}
  1093. state.hms_errors = []
  1094. state.ams_status_main = 0
  1095. state.ams_status_sub = 0
  1096. state.tray_now = None
  1097. state.wifi_signal = -50
  1098. state.stg_cur = -1
  1099. state.raw_data = {"ams": [ams_data]}
  1100. return state
  1101. def test_cached_target_wins_over_tray_fallback(self):
  1102. """When the cache has a target for this AMS, use it verbatim — even
  1103. if the loaded tray's filament/recommended-drying-temp differ."""
  1104. state = self._state_with_ams(
  1105. {
  1106. "id": 0,
  1107. "dry_time": 600,
  1108. "tray": [
  1109. {"id": 0, "tray_type": "PLA", "drying_temp": 50, "state": 11},
  1110. ],
  1111. }
  1112. )
  1113. result = printer_state_to_dict(state, drying_targets={0: {"filament": "PETG", "temp": 65}})
  1114. assert result["ams"][0]["dry_filament"] == "PETG"
  1115. assert result["ams"][0]["dry_target_temp"] == 65
  1116. def test_falls_back_to_loaded_tray_filament_when_no_cache(self):
  1117. """No cached target → name the filament from the loaded trays when they
  1118. agree on a type. The temperature stays unknown: only the cache records
  1119. what we actually sent."""
  1120. state = self._state_with_ams(
  1121. {
  1122. "id": 0,
  1123. "dry_time": 600,
  1124. "tray": [
  1125. {"id": 0, "tray_type": "ABS", "drying_temp": 70, "state": 11},
  1126. ],
  1127. }
  1128. )
  1129. result = printer_state_to_dict(state, drying_targets=None)
  1130. assert result["ams"][0]["dry_filament"] == "ABS"
  1131. assert result["ams"][0]["dry_target_temp"] is None
  1132. def test_returns_none_when_no_cache_and_empty_trays(self):
  1133. """No cache + no loaded tray with tray_type → both fields are None."""
  1134. state = self._state_with_ams(
  1135. {
  1136. "id": 0,
  1137. "dry_time": 600,
  1138. "tray": [{"id": 0}],
  1139. }
  1140. )
  1141. result = printer_state_to_dict(state, drying_targets={})
  1142. assert result["ams"][0]["dry_filament"] is None
  1143. assert result["ams"][0]["dry_target_temp"] is None
  1144. def test_targets_for_other_ams_id_dont_leak(self):
  1145. """A cached target for AMS 1 must not surface on AMS 0."""
  1146. state = self._state_with_ams(
  1147. {
  1148. "id": 0,
  1149. "dry_time": 600,
  1150. "tray": [{"id": 0}],
  1151. }
  1152. )
  1153. result = printer_state_to_dict(state, drying_targets={1: {"filament": "PETG", "temp": 65}})
  1154. assert result["ams"][0]["dry_filament"] is None
  1155. assert result["ams"][0]["dry_target_temp"] is None
  1156. def test_no_fallback_when_loaded_trays_disagree(self):
  1157. """#2759 — the reporter's AMS held 2 PETG and 2 PLA and was drying the
  1158. PLA at 45°C, but the fallback read slot 1 and labelled it "PETG @ 65°C".
  1159. A mixed unit gives no evidence of what the cycle is running, so the
  1160. badge must show the countdown alone rather than a confident wrong
  1161. answer."""
  1162. state = self._state_with_ams(
  1163. {
  1164. "id": 0,
  1165. "dry_time": 719,
  1166. "tray": [
  1167. {"id": 0, "tray_type": "PETG", "drying_temp": 65, "state": 11},
  1168. {"id": 1, "tray_type": "PETG", "drying_temp": 65, "state": 11},
  1169. {"id": 2, "tray_type": "PLA", "drying_temp": 45, "state": 11},
  1170. {"id": 3, "tray_type": "PLA", "drying_temp": 45, "state": 11},
  1171. ],
  1172. }
  1173. )
  1174. result = printer_state_to_dict(state, drying_targets={})
  1175. assert result["ams"][0]["dry_filament"] is None
  1176. assert result["ams"][0]["dry_target_temp"] is None
  1177. def test_fallback_survives_multiple_trays_of_one_type(self):
  1178. """Agreement across slots is still evidence of the filament — a unit
  1179. loaded entirely with PLA keeps the name the mixed case gives up."""
  1180. state = self._state_with_ams(
  1181. {
  1182. "id": 0,
  1183. "dry_time": 719,
  1184. "tray": [
  1185. {"id": 0, "tray_type": "PLA", "drying_temp": 45, "state": 11},
  1186. {"id": 1, "tray_type": "PLA", "drying_temp": 45, "state": 11},
  1187. {"id": 2},
  1188. ],
  1189. }
  1190. )
  1191. result = printer_state_to_dict(state, drying_targets={})
  1192. assert result["ams"][0]["dry_filament"] == "PLA"
  1193. def test_uniform_unit_never_invents_a_temperature(self):
  1194. """#2759 follow-up — the reporter's second AMS held only PLA and was
  1195. drying at the 45°C they picked, but with no cached target the badge
  1196. answered with the RFID recommendation and read "PLA @ 55°C". Every
  1197. spool agreeing tells us the filament; it tells us nothing about a
  1198. temperature the user chose freely in the popover."""
  1199. state = self._state_with_ams(
  1200. {
  1201. "id": 0,
  1202. "dry_time": 719,
  1203. "tray": [
  1204. {"id": 0, "tray_type": "PLA", "drying_temp": 55, "state": 11},
  1205. {"id": 1, "tray_type": "PLA", "drying_temp": 55, "state": 11},
  1206. ],
  1207. }
  1208. )
  1209. result = printer_state_to_dict(state, drying_targets={})
  1210. assert result["ams"][0]["dry_filament"] == "PLA"
  1211. assert result["ams"][0]["dry_target_temp"] is None
  1212. def test_cached_temp_survives_a_unit_whose_trays_disagree(self):
  1213. """The cache is authoritative for both fields. A mixed unit costs us the
  1214. filament fallback but must not touch a target we actually sent."""
  1215. state = self._state_with_ams(
  1216. {
  1217. "id": 0,
  1218. "dry_time": 719,
  1219. "tray": [
  1220. {"id": 0, "tray_type": "PETG", "drying_temp": 65, "state": 11},
  1221. {"id": 1, "tray_type": "PLA", "drying_temp": 55, "state": 11},
  1222. ],
  1223. }
  1224. )
  1225. result = printer_state_to_dict(state, drying_targets={0: {"filament": "PLA", "temp": 45}})
  1226. assert result["ams"][0]["dry_filament"] == "PLA"
  1227. assert result["ams"][0]["dry_target_temp"] == 45
  1228. class TestDisplayTemperatures:
  1229. """#1422 — the readings handed to the streaming overlay.
  1230. `state.temperatures` doubles as the MQTT client's working memory: alongside
  1231. the readings it carries derived heater flags and private timestamps. The
  1232. overlay feed is reached by a token rather than a login, so it gets an
  1233. allow-list rather than the dict.
  1234. """
  1235. def test_keeps_the_readings_the_overlay_draws(self):
  1236. result = display_temperatures({"nozzle": 219.5, "nozzle_target": 220.0, "bed": 60.0, "bed_target": 60.0}, "X1C")
  1237. assert result == {"nozzle": 219.5, "nozzle_target": 220.0, "bed": 60.0, "bed_target": 60.0}
  1238. def test_drops_heater_flags_and_private_bookkeeping(self):
  1239. result = display_temperatures(
  1240. {
  1241. "nozzle": 219.5,
  1242. "nozzle_heating": True,
  1243. "bed_heating": False,
  1244. "_nozzle_target_set_time": 1754300000.0,
  1245. "_chamber_target_set_time": 1754300000.0,
  1246. },
  1247. "X1C",
  1248. )
  1249. assert result == {"nozzle": 219.5}
  1250. def test_chamber_kept_on_models_with_a_real_sensor(self):
  1251. result = display_temperatures({"chamber": 38.0, "chamber_target": 40.0}, "X1C")
  1252. assert result == {"chamber": 38.0, "chamber_target": 40.0}
  1253. def test_chamber_dropped_on_models_without_one(self):
  1254. """P1P, P1S, A1 and A1 mini publish a meaningless chamber_temper. Drawing
  1255. it on a live stream would state a measurement that doesn't exist."""
  1256. for model in ("P1S", "P1P", "A1", "A1MINI"):
  1257. assert display_temperatures({"nozzle": 200.0, "chamber": 38.0}, model) == {"nozzle": 200.0}
  1258. def test_second_nozzle_is_included(self):
  1259. result = display_temperatures({"nozzle": 220.0, "nozzle_2": 240.0, "nozzle_2_target": 250.0}, "H2D")
  1260. assert result == {"nozzle": 220.0, "nozzle_2": 240.0, "nozzle_2_target": 250.0}
  1261. def test_unparseable_and_missing_values_are_skipped(self):
  1262. """A reading that isn't a number is dropped rather than crashing the
  1263. feed or reaching the page as a string."""
  1264. assert display_temperatures({"nozzle": None, "bed": "warm", "chamber": 38.0}, "X1C") == {"chamber": 38.0}
  1265. def test_empty_and_none_are_empty(self):
  1266. assert display_temperatures(None, "X1C") == {}
  1267. assert display_temperatures({}, "X1C") == {}
  1268. class TestSupportsChamberTemp:
  1269. """Tests for supports_chamber_temp helper function."""
  1270. def test_x1_series_supported(self):
  1271. """Verify X1 series printers support chamber temp."""
  1272. assert supports_chamber_temp("X1") is True
  1273. assert supports_chamber_temp("X1C") is True
  1274. assert supports_chamber_temp("X1E") is True
  1275. def test_p2_series_supported(self):
  1276. """Verify P2 series printers support chamber temp."""
  1277. assert supports_chamber_temp("P2S") is True
  1278. def test_h2_series_supported(self):
  1279. """Verify H2 series printers support chamber temp."""
  1280. assert supports_chamber_temp("H2C") is True
  1281. assert supports_chamber_temp("H2D") is True
  1282. assert supports_chamber_temp("H2DPRO") is True
  1283. assert supports_chamber_temp("H2S") is True
  1284. def test_p1_series_not_supported(self):
  1285. """Verify P1 series printers do NOT support chamber temp."""
  1286. assert supports_chamber_temp("P1P") is False
  1287. assert supports_chamber_temp("P1S") is False
  1288. def test_a1_series_not_supported(self):
  1289. """Verify A1 series printers do NOT support chamber temp."""
  1290. assert supports_chamber_temp("A1") is False
  1291. assert supports_chamber_temp("A1MINI") is False
  1292. def test_none_model_not_supported(self):
  1293. """Verify None model returns False."""
  1294. assert supports_chamber_temp(None) is False
  1295. def test_case_insensitive(self):
  1296. """Verify model matching is case-insensitive."""
  1297. assert supports_chamber_temp("x1c") is True
  1298. assert supports_chamber_temp("X1c") is True
  1299. assert supports_chamber_temp("p1s") is False
  1300. def test_internal_model_codes_supported(self):
  1301. """Verify internal model codes from MQTT/SSDP are recognized."""
  1302. # X1/X1C
  1303. assert supports_chamber_temp("BL-P001") is True
  1304. # X1E
  1305. assert supports_chamber_temp("C13") is True
  1306. # H2D
  1307. assert supports_chamber_temp("O1D") is True
  1308. # H2C
  1309. assert supports_chamber_temp("O1C") is True
  1310. # H2S
  1311. assert supports_chamber_temp("O1S") is True
  1312. # H2D Pro
  1313. assert supports_chamber_temp("O1E") is True
  1314. # P2S
  1315. assert supports_chamber_temp("N7") is True
  1316. def test_internal_model_codes_not_supported(self):
  1317. """Verify A1/P1 internal codes are NOT supported."""
  1318. # P1P
  1319. assert supports_chamber_temp("C11") is False
  1320. # P1S
  1321. assert supports_chamber_temp("C12") is False
  1322. # A1
  1323. assert supports_chamber_temp("N2S") is False
  1324. # A1 Mini
  1325. assert supports_chamber_temp("N1") is False
  1326. class TestIsBedSlinger:
  1327. """Tests for is_bed_slinger helper function (#1334)."""
  1328. def test_a1_series_is_bed_slinger(self):
  1329. """A1 / A1 Mini are open-frame bed-slingers — Z axis is the toolhead."""
  1330. from backend.app.services.printer_manager import is_bed_slinger
  1331. assert is_bed_slinger("A1") is True
  1332. assert is_bed_slinger("A1 Mini") is True
  1333. assert is_bed_slinger("A1MINI") is True
  1334. assert is_bed_slinger("A1-MINI") is True
  1335. def test_a1_internal_codes_recognised(self):
  1336. """Internal MQTT/SSDP codes for A1 family must also classify as bed-slinger."""
  1337. from backend.app.services.printer_manager import is_bed_slinger
  1338. # A1 Mini
  1339. assert is_bed_slinger("N1") is True
  1340. # A1
  1341. assert is_bed_slinger("N2S") is True
  1342. def test_bed_on_z_models_not_bed_slingers(self):
  1343. """X1 / P1 / H2 / H2C / H2D / H2S / P2S all have the bed on Z."""
  1344. from backend.app.services.printer_manager import is_bed_slinger
  1345. for model in ("X1", "X1C", "X1E", "P1P", "P1S", "P2S", "H2C", "H2D", "H2DPRO", "H2S"):
  1346. assert is_bed_slinger(model) is False, f"{model} should NOT be classified as bed-slinger"
  1347. def test_none_model_returns_false(self):
  1348. from backend.app.services.printer_manager import is_bed_slinger
  1349. assert is_bed_slinger(None) is False
  1350. assert is_bed_slinger("") is False
  1351. def test_case_insensitive(self):
  1352. from backend.app.services.printer_manager import is_bed_slinger
  1353. assert is_bed_slinger("a1") is True
  1354. assert is_bed_slinger("a1 mini") is True
  1355. assert is_bed_slinger("x1c") is False
  1356. class TestSupportsDrying:
  1357. """Tests for supports_drying helper function."""
  1358. def test_known_supported_with_firmware(self):
  1359. """Verify known models with sufficient firmware return True."""
  1360. assert supports_drying("X1C", "01.09.00.00") is True
  1361. assert supports_drying("H2D", "01.02.30.00") is True
  1362. assert supports_drying("H2S", "01.02.00.00") is True
  1363. assert supports_drying("H2C", "01.02.00.00") is True
  1364. assert supports_drying("O1C", "01.02.00.00") is True
  1365. assert supports_drying("O1C2", "01.02.00.00") is True
  1366. assert supports_drying("P2S", "01.02.00.00") is True
  1367. assert supports_drying("N7", "01.02.00.00") is True
  1368. def test_known_supported_old_firmware(self):
  1369. """Verify known models with old firmware return False."""
  1370. assert supports_drying("X1C", "01.08.00.00") is False
  1371. assert supports_drying("H2S", "01.01.00.00") is False
  1372. assert supports_drying("H2C", "01.01.99.99") is False
  1373. assert supports_drying("O1C", "01.01.99.99") is False
  1374. assert supports_drying("O1C2", "01.01.99.99") is False
  1375. assert supports_drying("P2S", "01.01.99.99") is False
  1376. assert supports_drying("N7", "01.01.99.99") is False
  1377. def test_known_supported_no_firmware(self):
  1378. """Verify known models with no firmware return False."""
  1379. assert supports_drying("X1C", None) is False
  1380. assert supports_drying("P2S", None) is False
  1381. def test_unsupported_models(self):
  1382. """Verify models without AMS drying support return False regardless of firmware."""
  1383. for model in ["A1", "A1MINI", "A1-MINI", "N1", "N2S"]:
  1384. assert supports_drying(model, "99.99.99.99") is False, f"Expected False for {model}"
  1385. def test_unknown_models_allowed(self):
  1386. """Verify unknown models are allowed (graceful fallback).
  1387. Models not in the unsupported set AND not matching any known firmware-gated
  1388. model substring get the benefit of the doubt and return True.
  1389. "H2D Pro" contains "H2D" so it IS firmware-gated (needs firmware).
  1390. """
  1391. # Truly unknown models: no substring match in _DRYING_MIN_FIRMWARE
  1392. assert supports_drying("FUTURE_MODEL", None) is True
  1393. # X1E contains "X1" substring, so it IS firmware-gated
  1394. assert supports_drying("X1E", "01.09.00.00") is True
  1395. # H2D Pro contains "H2D" substring, so it IS firmware-gated
  1396. assert supports_drying("H2D Pro", "01.02.30.00") is True
  1397. def test_none_model(self):
  1398. """Verify None model returns False."""
  1399. assert supports_drying(None, "01.09.00.00") is False
  1400. def test_case_insensitive(self):
  1401. """Verify model matching is case-insensitive."""
  1402. assert supports_drying("x1c", "01.09.00.00") is True
  1403. assert supports_drying("p2s", "01.02.00.00") is True
  1404. assert supports_drying("a1", "99.99.99.99") is False
  1405. class TestDryingScreenOnly:
  1406. """P1-series AMS drying is screen-only (#2533).
  1407. Bambu's P1 manual: "P1S connected AMS drying functions may only be controlled
  1408. from the P1S screen." The firmware acks `ams_filament_drying` with
  1409. result: success and then does nothing — so no command we send can ever start a
  1410. cycle, whatever the firmware version.
  1411. """
  1412. @pytest.mark.parametrize("model", ["P1S", "P1P", "p1s", " p1p "])
  1413. def test_screen_only_models_reject_remote_drying(self, model):
  1414. assert drying_screen_only(model) is True
  1415. # Not firmware-gated: even the newest firmware won't take the command.
  1416. assert supports_drying(model, "99.99.99.99") is False
  1417. @pytest.mark.parametrize("model", ["X1C", "P2S", "H2D", "A1", None])
  1418. def test_other_models_are_not_screen_only(self, model):
  1419. assert drying_screen_only(model) is False
  1420. def test_screen_only_is_not_the_same_as_unsupported(self):
  1421. # The A1 has no drying-capable AMS at all; the P1S does, it just can't be
  1422. # driven remotely. The UI needs to tell those two apart.
  1423. assert drying_screen_only("A1") is False
  1424. assert supports_drying("A1", "99.99.99.99") is False
  1425. class TestSupportsDryingWhilePrinting:
  1426. """Tests for the supports_drying_while_printing gate (concurrent drying during print).
  1427. Stricter than supports_drying — only models explicitly confirmed by Bambu wiki
  1428. release notes are allowed (verified phrase: "printing while filament is drying"
  1429. / "Print While Drying").
  1430. """
  1431. def test_known_supported_with_firmware(self):
  1432. """Matrix-confirmed models with min firmware return True."""
  1433. assert supports_drying_while_printing("H2D", "01.03.00.00") is True
  1434. assert supports_drying_while_printing("H2D Pro", "01.02.00.00") is True
  1435. assert supports_drying_while_printing("O1E", "01.02.00.00") is True
  1436. assert supports_drying_while_printing("O2D", "01.02.00.00") is True
  1437. assert supports_drying_while_printing("H2C", "01.02.00.00") is True
  1438. assert supports_drying_while_printing("O1C", "01.02.00.00") is True
  1439. assert supports_drying_while_printing("O1C2", "01.02.00.00") is True
  1440. assert supports_drying_while_printing("H2S", "01.02.00.00") is True
  1441. assert supports_drying_while_printing("X2D", "01.01.00.00") is True
  1442. assert supports_drying_while_printing("N6", "01.01.00.00") is True
  1443. assert supports_drying_while_printing("X1C", "01.11.02.00") is True
  1444. assert supports_drying_while_printing("BL-P001", "01.11.02.00") is True
  1445. assert supports_drying_while_printing("P2S", "01.02.00.00") is True
  1446. assert supports_drying_while_printing("N7", "01.02.00.00") is True
  1447. assert supports_drying_while_printing("A2L", "01.01.00.00") is True
  1448. assert supports_drying_while_printing("N9", "01.01.00.00") is True
  1449. def test_known_supported_below_min_firmware(self):
  1450. """Matrix-confirmed models on too-old firmware return False."""
  1451. assert supports_drying_while_printing("H2D", "01.02.30.00") is False
  1452. assert supports_drying_while_printing("X1C", "01.11.01.00") is False
  1453. assert supports_drying_while_printing("P2S", "01.01.99.99") is False
  1454. assert supports_drying_while_printing("H2S", "01.01.99.99") is False
  1455. assert supports_drying_while_printing("A2L", "01.00.99.99") is False
  1456. def test_not_in_matrix_excluded(self):
  1457. """Models absent from the matrix return False regardless of firmware.
  1458. P1*, A1, A1 Mini, X1 (non-C), X1E are intentionally excluded — their wiki
  1459. release notes never mention "Print While Drying" / "printing while filament
  1460. is drying".
  1461. """
  1462. for model in [
  1463. "P1P",
  1464. "P1S",
  1465. "C11",
  1466. "C12",
  1467. "A1",
  1468. "A1 MINI",
  1469. "A1MINI",
  1470. "N1",
  1471. "N2S",
  1472. "X1",
  1473. "X1E",
  1474. "BL-P002",
  1475. "C13",
  1476. ]:
  1477. assert supports_drying_while_printing(model, "99.99.99.99") is False, f"Expected False for {model}"
  1478. def test_no_firmware_returns_false(self):
  1479. """Missing firmware version returns False even for supported models."""
  1480. assert supports_drying_while_printing("H2D", None) is False
  1481. assert supports_drying_while_printing("P2S", None) is False
  1482. def test_none_model_returns_false(self):
  1483. """None model returns False."""
  1484. assert supports_drying_while_printing(None, "01.03.00.00") is False
  1485. def test_case_insensitive(self):
  1486. """Model matching is case-insensitive."""
  1487. assert supports_drying_while_printing("h2d", "01.03.00.00") is True
  1488. assert supports_drying_while_printing("p2s", "01.02.00.00") is True
  1489. assert supports_drying_while_printing("a1", "99.99.99.99") is False
  1490. def test_unknown_model_returns_false(self):
  1491. """Unknown models default to FALSE (strict gate — not the lenient default-allow).
  1492. This contrasts with supports_drying which defaults to True for unknown
  1493. models. For while-printing the cost of being wrong is real (firmware
  1494. rejection mid-print is annoying; melted spool is worse), so we err
  1495. toward conservative.
  1496. """
  1497. assert supports_drying_while_printing("FUTURE_MODEL", "99.99.99.99") is False
  1498. class TestGetDerivedStatusName:
  1499. """Tests for get_derived_status_name function."""
  1500. def test_stg_cur_255_returns_none(self):
  1501. """Verify stg_cur=255 (A1/P1 idle) returns None, not 'Unknown stage (255)'."""
  1502. state = MagicMock()
  1503. state.stg_cur = 255
  1504. state.state = "IDLE"
  1505. result = get_derived_status_name(state)
  1506. assert result is None
  1507. def test_stg_cur_negative_one_returns_none_when_idle(self):
  1508. """Verify stg_cur=-1 (X1 idle) returns None."""
  1509. state = MagicMock()
  1510. state.stg_cur = -1
  1511. state.state = "IDLE"
  1512. result = get_derived_status_name(state)
  1513. assert result is None
  1514. def test_valid_stage_returns_name(self):
  1515. """Verify valid stg_cur values return stage name."""
  1516. state = MagicMock()
  1517. state.stg_cur = 1 # Auto bed leveling
  1518. result = get_derived_status_name(state)
  1519. assert result == "Auto bed leveling"
  1520. def test_stg_cur_zero_returns_printing(self):
  1521. """Verify stg_cur=0 returns 'Printing' when no model specified."""
  1522. state = MagicMock()
  1523. state.stg_cur = 0
  1524. result = get_derived_status_name(state)
  1525. assert result == "Printing"
  1526. def test_a1_idle_with_stg_cur_zero_returns_none(self):
  1527. """Verify A1 with IDLE state and stg_cur=0 returns None (bug workaround)."""
  1528. state = MagicMock()
  1529. state.stg_cur = 0
  1530. state.state = "IDLE"
  1531. # Test various A1 model names
  1532. for model in ["A1", "A1 Mini", "A1-Mini", "A1MINI", "N1", "N2S"]:
  1533. result = get_derived_status_name(state, model)
  1534. assert result is None, f"Expected None for model {model}"
  1535. def test_a1_running_with_stg_cur_zero_returns_printing(self):
  1536. """Verify A1 with RUNNING state and stg_cur=0 still returns 'Printing'."""
  1537. state = MagicMock()
  1538. state.stg_cur = 0
  1539. state.state = "RUNNING"
  1540. result = get_derived_status_name(state, "A1")
  1541. assert result == "Printing"
  1542. def test_non_a1_idle_with_stg_cur_zero_returns_printing(self):
  1543. """Verify non-A1 models with IDLE and stg_cur=0 still return 'Printing'."""
  1544. state = MagicMock()
  1545. state.stg_cur = 0
  1546. state.state = "IDLE"
  1547. # X1C should not get the workaround
  1548. result = get_derived_status_name(state, "X1C")
  1549. assert result == "Printing"
  1550. class TestHasStgCurIdleBug:
  1551. """Tests for has_stg_cur_idle_bug function."""
  1552. def test_a1_models_return_true(self):
  1553. """Verify A1 model variants return True."""
  1554. assert has_stg_cur_idle_bug("A1") is True
  1555. assert has_stg_cur_idle_bug("A1 Mini") is True
  1556. assert has_stg_cur_idle_bug("A1-Mini") is True
  1557. assert has_stg_cur_idle_bug("A1MINI") is True
  1558. assert has_stg_cur_idle_bug("a1") is True # case insensitive
  1559. assert has_stg_cur_idle_bug("a1 mini") is True
  1560. def test_p1_models_return_true(self):
  1561. """Verify P1P/P1S model variants return True."""
  1562. assert has_stg_cur_idle_bug("P1P") is True
  1563. assert has_stg_cur_idle_bug("P1S") is True
  1564. assert has_stg_cur_idle_bug("p1p") is True # case insensitive
  1565. def test_internal_codes_return_true(self):
  1566. """Verify internal model codes return True."""
  1567. assert has_stg_cur_idle_bug("N1") is True # A1 Mini
  1568. assert has_stg_cur_idle_bug("N2S") is True # A1
  1569. assert has_stg_cur_idle_bug("C11") is True # P1P
  1570. assert has_stg_cur_idle_bug("C12") is True # P1S
  1571. def test_non_affected_models_return_false(self):
  1572. """Verify non-affected models return False."""
  1573. assert has_stg_cur_idle_bug("X1C") is False
  1574. assert has_stg_cur_idle_bug("X1") is False
  1575. assert has_stg_cur_idle_bug("H2D") is False
  1576. def test_none_model_returns_false(self):
  1577. """Verify None model returns False."""
  1578. assert has_stg_cur_idle_bug(None) is False
  1579. def test_empty_model_returns_false(self):
  1580. """Verify empty model returns False."""
  1581. assert has_stg_cur_idle_bug("") is False
  1582. class TestInitPrinterConnections:
  1583. """Tests for init_printer_connections function."""
  1584. @pytest.mark.asyncio
  1585. async def test_connects_all_active_printers(self):
  1586. """Verify all active printers are connected."""
  1587. mock_db = AsyncMock()
  1588. mock_printer1 = MagicMock(id=1, is_active=True)
  1589. mock_printer2 = MagicMock(id=2, is_active=True)
  1590. mock_result = MagicMock()
  1591. mock_result.scalars.return_value.all.return_value = [mock_printer1, mock_printer2]
  1592. mock_db.execute.return_value = mock_result
  1593. with patch("backend.app.services.printer_manager.printer_manager") as mock_manager:
  1594. mock_manager.connect_printer = AsyncMock()
  1595. await init_printer_connections(mock_db)
  1596. assert mock_manager.connect_printer.call_count == 2
  1597. @pytest.mark.asyncio
  1598. async def test_handles_empty_printer_list(self):
  1599. """Verify empty printer list is handled."""
  1600. mock_db = AsyncMock()
  1601. mock_result = MagicMock()
  1602. mock_result.scalars.return_value.all.return_value = []
  1603. mock_db.execute.return_value = mock_result
  1604. with patch("backend.app.services.printer_manager.printer_manager") as mock_manager:
  1605. mock_manager.connect_printer = AsyncMock()
  1606. await init_printer_connections(mock_db)
  1607. mock_manager.connect_printer.assert_not_called()
  1608. @pytest.mark.asyncio
  1609. async def test_one_failing_printer_does_not_abort_the_rest(self):
  1610. """A single unreachable printer must not abort startup or the others (#2572).
  1611. The connections are gathered with return_exceptions=True. The old serial
  1612. ``await`` loop had no error handling, so the first printer that raised
  1613. propagated straight out of init_printer_connections and failed the
  1614. FastAPI lifespan — taking the whole app down over one bad row, and
  1615. skipping every printer after it. This asserts the isolation: every
  1616. printer is still attempted and the exception never escapes.
  1617. """
  1618. mock_db = AsyncMock()
  1619. printers = [MagicMock(id=i, name=f"p{i}", is_active=True) for i in range(3)]
  1620. mock_result = MagicMock()
  1621. mock_result.scalars.return_value.all.return_value = printers
  1622. mock_db.execute.return_value = mock_result
  1623. async def connect(printer):
  1624. if printer.id == 1:
  1625. raise ConnectionError("printer 1 is unreachable")
  1626. return True
  1627. with patch("backend.app.services.printer_manager.printer_manager") as mock_manager:
  1628. mock_manager.connect_printer = AsyncMock(side_effect=connect)
  1629. # Must not raise despite printer 1 failing.
  1630. await init_printer_connections(mock_db)
  1631. # All three were still attempted (not aborted at the failing one).
  1632. assert mock_manager.connect_printer.call_count == 3
  1633. class TestAmsChangeCallback:
  1634. """Tests for AMS change callback functionality."""
  1635. @pytest.fixture
  1636. def manager(self):
  1637. """Create a fresh PrinterManager instance."""
  1638. return PrinterManager()
  1639. def test_ams_change_callback_is_triggered(self, manager):
  1640. """Verify AMS change callback is called when AMS data changes."""
  1641. callback = MagicMock()
  1642. manager.set_ams_change_callback(callback)
  1643. # Verify callback was set
  1644. assert manager._on_ams_change == callback
  1645. def test_ams_change_callback_receives_correct_data(self, manager):
  1646. """Verify AMS change callback receives the correct AMS data format."""
  1647. received_data = []
  1648. def capture_callback(printer_id, ams_data):
  1649. received_data.append((printer_id, ams_data))
  1650. manager.set_ams_change_callback(capture_callback)
  1651. # The callback should accept printer_id and ams_data
  1652. # This tests the callback signature
  1653. assert manager._on_ams_change is not None
  1654. assert callable(manager._on_ams_change)
  1655. class TestParsePlateId:
  1656. """Tests for parse_plate_id() — active-print plate extraction from gcode paths.
  1657. Regression coverage for #881 follow-up: the REST /status endpoint and the
  1658. WebSocket push path both use this helper, so they must agree on the plate
  1659. number the frontend sees.
  1660. """
  1661. def test_bambu_metadata_path(self):
  1662. # Canonical path that Bambu Studio / OrcaSlicer stamp into the 3MF.
  1663. assert parse_plate_id("/Metadata/plate_2.gcode") == 2
  1664. def test_plate_one(self):
  1665. assert parse_plate_id("/Metadata/plate_1.gcode") == 1
  1666. def test_double_digit_plate(self):
  1667. assert parse_plate_id("/Metadata/plate_12.gcode") == 12
  1668. def test_none_input(self):
  1669. assert parse_plate_id(None) is None
  1670. def test_empty_string(self):
  1671. assert parse_plate_id("") is None
  1672. def test_path_without_plate_segment(self):
  1673. # Some firmware / slicers report a bare filename without the plate marker.
  1674. assert parse_plate_id("/upload/my-model.gcode") is None
  1675. def test_similar_but_non_matching_names(self):
  1676. # "plate.gcode" (no number) and "nameplate_2.gcode" (substring) must not
  1677. # be mistaken for real plate markers. The regex anchors on `plate_<num>`.
  1678. assert parse_plate_id("/Metadata/plate.gcode") is None
  1679. assert parse_plate_id("/plates/3.gcode") is None
  1680. def test_substring_match_still_extracts(self):
  1681. # The regex isn't anchored to the start of a segment — any occurrence
  1682. # wins. This matches real Bambu paths where the segment is preceded by
  1683. # arbitrary directory noise, and matches the equivalent frontend regex.
  1684. assert parse_plate_id("/uploads/project/plate_5.gcode.md5") == 5
  1685. class TestResolvePlateId:
  1686. """Tests for resolve_plate_id() — plate resolution with dispatch precedence.
  1687. Regression coverage for #1166: P1S firmware 01.10.00.00 only puts the .3mf
  1688. filename in print.gcode_file, so parse_plate_id() returns None and the
  1689. printer card falls back to plate 1. When Bambuddy dispatches the print
  1690. itself we know the right plate; resolve_plate_id() prefers that record over
  1691. the gcode_file regex when subtask_name matches.
  1692. """
  1693. def _make_state(self, **kwargs):
  1694. from backend.app.services.bambu_mqtt import PrinterState
  1695. state = PrinterState()
  1696. for k, v in kwargs.items():
  1697. setattr(state, k, v)
  1698. return state
  1699. def test_dispatched_plate_wins_when_subtask_matches(self):
  1700. # User dispatches plate 4 via Bambuddy. Printer reflects subtask_name
  1701. # but firmware drops the plate path from gcode_file. Without the dispatch
  1702. # record we'd default to plate 1.
  1703. from backend.app.services.printer_manager import resolve_plate_id
  1704. state = self._make_state(
  1705. gcode_file="MyModel.3mf", # No plate path — firmware bug
  1706. subtask_name="MyModel",
  1707. dispatched_plate_id=4,
  1708. dispatched_subtask="MyModel",
  1709. )
  1710. assert resolve_plate_id(state) == 4
  1711. def test_dispatched_ignored_when_subtask_differs(self):
  1712. # Bambuddy's dispatch record is for a previous print; the printer is
  1713. # now running a different subtask (Studio-direct dispatch). The stale
  1714. # record must not be used — fall back to gcode_file regex.
  1715. from backend.app.services.printer_manager import resolve_plate_id
  1716. state = self._make_state(
  1717. gcode_file="/Metadata/plate_2.gcode",
  1718. subtask_name="DifferentPrint",
  1719. dispatched_plate_id=4,
  1720. dispatched_subtask="MyModel",
  1721. )
  1722. assert resolve_plate_id(state) == 2
  1723. def test_falls_back_to_gcode_regex_without_dispatch(self):
  1724. # Studio-direct dispatch — no Bambuddy dispatch record. Existing logic
  1725. # (parse_plate_id on gcode_file) must still work.
  1726. from backend.app.services.printer_manager import resolve_plate_id
  1727. state = self._make_state(
  1728. gcode_file="/Metadata/plate_3.gcode",
  1729. subtask_name="MyModel",
  1730. )
  1731. assert resolve_plate_id(state) == 3
  1732. def test_returns_none_when_nothing_resolvable(self):
  1733. # No dispatch record AND firmware swallowed the plate path. The route
  1734. # uses this signal to invoke the 3MF-scan fallback.
  1735. from backend.app.services.printer_manager import resolve_plate_id
  1736. state = self._make_state(
  1737. gcode_file="MyModel.3mf",
  1738. subtask_name="MyModel",
  1739. )
  1740. assert resolve_plate_id(state) is None
  1741. def test_dispatched_subtask_required_to_avoid_false_match(self):
  1742. # dispatched_plate_id without dispatched_subtask is incomplete — we
  1743. # can't validate it points at the current print, so we ignore it.
  1744. from backend.app.services.printer_manager import resolve_plate_id
  1745. state = self._make_state(
  1746. gcode_file="MyModel.3mf",
  1747. subtask_name="MyModel",
  1748. dispatched_plate_id=4,
  1749. dispatched_subtask=None,
  1750. )
  1751. assert resolve_plate_id(state) is None