test_printer_manager.py 86 KB

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