test_printer_manager.py 74 KB

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