test_printer_manager.py 80 KB

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