test_printer_manager.py 78 KB

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