test_printer_manager.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  1. """Unit tests for PrinterManager service.
  2. Tests printer connection management, status tracking, and print control.
  3. """
  4. import logging
  5. from unittest.mock import AsyncMock, MagicMock, patch
  6. import pytest
  7. from backend.app.services.printer_manager import (
  8. PrinterManager,
  9. get_derived_status_name,
  10. has_stg_cur_idle_bug,
  11. init_printer_connections,
  12. parse_plate_id,
  13. printer_state_to_dict,
  14. supports_chamber_temp,
  15. supports_drying,
  16. )
  17. class TestPrinterManager:
  18. """Tests for PrinterManager class."""
  19. @pytest.fixture
  20. def manager(self):
  21. """Create a fresh PrinterManager instance."""
  22. return PrinterManager()
  23. @pytest.fixture
  24. def mock_printer(self):
  25. """Create a mock Printer object."""
  26. printer = MagicMock()
  27. printer.id = 1
  28. printer.ip_address = "192.168.1.100"
  29. printer.serial_number = "00M09A123456789"
  30. printer.access_code = "12345678"
  31. printer.is_active = True
  32. return printer
  33. @pytest.fixture
  34. def mock_client(self):
  35. """Create a mock BambuMQTTClient."""
  36. client = MagicMock()
  37. client.state = MagicMock()
  38. client.state.connected = True
  39. client.state.state = "IDLE"
  40. client.state.progress = 0
  41. client.state.temperatures = {"nozzle": 25, "bed": 25}
  42. client.state.raw_data = {}
  43. client.logging_enabled = False
  44. return client
  45. # ========================================================================
  46. # Tests for initialization
  47. # ========================================================================
  48. def test_init_creates_empty_clients_dict(self, manager):
  49. """Verify manager initializes with empty clients dict."""
  50. assert manager._clients == {}
  51. def test_init_callbacks_are_none(self, manager):
  52. """Verify all callbacks are initially None."""
  53. assert manager._on_print_start is None
  54. assert manager._on_print_complete is None
  55. assert manager._on_status_change is None
  56. assert manager._on_ams_change is None
  57. def test_init_loop_is_none(self, manager):
  58. """Verify event loop is initially None."""
  59. assert manager._loop is None
  60. # ========================================================================
  61. # Tests for callback setters
  62. # ========================================================================
  63. def test_set_event_loop(self, manager):
  64. """Verify event loop can be set."""
  65. mock_loop = MagicMock()
  66. manager.set_event_loop(mock_loop)
  67. assert manager._loop == mock_loop
  68. def test_set_print_start_callback(self, manager):
  69. """Verify print start callback can be set."""
  70. callback = MagicMock()
  71. manager.set_print_start_callback(callback)
  72. assert manager._on_print_start == callback
  73. def test_set_print_complete_callback(self, manager):
  74. """Verify print complete callback can be set."""
  75. callback = MagicMock()
  76. manager.set_print_complete_callback(callback)
  77. assert manager._on_print_complete == callback
  78. def test_set_status_change_callback(self, manager):
  79. """Verify status change callback can be set."""
  80. callback = MagicMock()
  81. manager.set_status_change_callback(callback)
  82. assert manager._on_status_change == callback
  83. def test_set_ams_change_callback(self, manager):
  84. """Verify AMS change callback can be set."""
  85. callback = MagicMock()
  86. manager.set_ams_change_callback(callback)
  87. assert manager._on_ams_change == callback
  88. # ========================================================================
  89. # Tests for _schedule_async
  90. # ========================================================================
  91. def test_schedule_async_with_running_loop(self, manager):
  92. """Verify async coroutine is scheduled when loop is running."""
  93. mock_loop = MagicMock()
  94. mock_loop.is_running.return_value = True
  95. manager._loop = mock_loop
  96. async def dummy_coro():
  97. pass
  98. coro = dummy_coro()
  99. manager._schedule_async(coro)
  100. mock_loop.is_running.assert_called_once()
  101. # Clean up the coroutine
  102. coro.close()
  103. def test_schedule_async_without_loop(self, manager):
  104. """Verify nothing happens when no loop is set."""
  105. async def dummy_coro():
  106. pass
  107. coro = dummy_coro()
  108. # Should not raise
  109. manager._schedule_async(coro)
  110. coro.close()
  111. def test_schedule_async_with_stopped_loop(self, manager):
  112. """Verify nothing happens when loop is not running."""
  113. mock_loop = MagicMock()
  114. mock_loop.is_running.return_value = False
  115. manager._loop = mock_loop
  116. async def dummy_coro():
  117. pass
  118. coro = dummy_coro()
  119. manager._schedule_async(coro)
  120. coro.close()
  121. # ========================================================================
  122. # Tests for connect_printer
  123. # ========================================================================
  124. @pytest.mark.asyncio
  125. async def test_connect_printer_creates_client(self, manager, mock_printer):
  126. """Verify connecting creates an MQTT client."""
  127. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  128. mock_instance = MagicMock()
  129. mock_instance.state = MagicMock()
  130. mock_instance.state.connected = True
  131. MockClient.return_value = mock_instance
  132. result = await manager.connect_printer(mock_printer)
  133. MockClient.assert_called_once()
  134. mock_instance.connect.assert_called_once()
  135. assert mock_printer.id in manager._clients
  136. assert result is True
  137. @pytest.mark.asyncio
  138. async def test_connect_printer_disconnects_existing(self, manager, mock_printer, mock_client):
  139. """Verify connecting disconnects existing client first."""
  140. manager._clients[mock_printer.id] = mock_client
  141. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  142. new_client = MagicMock()
  143. new_client.state = MagicMock()
  144. new_client.state.connected = True
  145. MockClient.return_value = new_client
  146. await manager.connect_printer(mock_printer)
  147. mock_client.disconnect.assert_called_once()
  148. @pytest.mark.asyncio
  149. async def test_connect_printer_returns_false_on_failure(self, manager, mock_printer):
  150. """Verify returns False when connection fails."""
  151. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  152. mock_instance = MagicMock()
  153. mock_instance.state = MagicMock()
  154. mock_instance.state.connected = False
  155. MockClient.return_value = mock_instance
  156. result = await manager.connect_printer(mock_printer)
  157. assert result is False
  158. # ========================================================================
  159. # Tests for disconnect_printer
  160. # ========================================================================
  161. def test_disconnect_printer_removes_client(self, manager, mock_client):
  162. """Verify disconnecting removes and disconnects client."""
  163. manager._clients[1] = mock_client
  164. manager.disconnect_printer(1)
  165. mock_client.disconnect.assert_called_once()
  166. assert 1 not in manager._clients
  167. def test_disconnect_printer_handles_missing(self, manager):
  168. """Verify disconnecting non-existent printer doesn't raise."""
  169. manager.disconnect_printer(999) # Should not raise
  170. # ========================================================================
  171. # Tests for disconnect_all
  172. # ========================================================================
  173. def test_disconnect_all_disconnects_all_clients(self, manager):
  174. """Verify all clients are disconnected."""
  175. client1 = MagicMock()
  176. client2 = MagicMock()
  177. manager._clients[1] = client1
  178. manager._clients[2] = client2
  179. manager.disconnect_all()
  180. client1.disconnect.assert_called_once()
  181. client2.disconnect.assert_called_once()
  182. assert len(manager._clients) == 0
  183. # ========================================================================
  184. # Tests for get_status
  185. # ========================================================================
  186. def test_get_status_returns_state(self, manager, mock_client):
  187. """Verify get_status returns client state."""
  188. manager._clients[1] = mock_client
  189. result = manager.get_status(1)
  190. mock_client.check_staleness.assert_called_once()
  191. assert result == mock_client.state
  192. def test_get_status_returns_none_for_unknown(self, manager):
  193. """Verify get_status returns None for unknown printer."""
  194. result = manager.get_status(999)
  195. assert result is None
  196. # ========================================================================
  197. # Tests for get_all_statuses
  198. # ========================================================================
  199. def test_get_all_statuses_returns_all(self, manager):
  200. """Verify all statuses are returned."""
  201. client1 = MagicMock()
  202. client1.state = MagicMock(connected=True)
  203. client2 = MagicMock()
  204. client2.state = MagicMock(connected=False)
  205. manager._clients[1] = client1
  206. manager._clients[2] = client2
  207. result = manager.get_all_statuses()
  208. assert len(result) == 2
  209. assert 1 in result
  210. assert 2 in result
  211. client1.check_staleness.assert_called_once()
  212. client2.check_staleness.assert_called_once()
  213. # ========================================================================
  214. # Tests for is_connected
  215. # ========================================================================
  216. def test_is_connected_returns_true(self, manager, mock_client):
  217. """Verify is_connected returns True for connected printer."""
  218. mock_client.check_staleness.return_value = True
  219. manager._clients[1] = mock_client
  220. result = manager.is_connected(1)
  221. assert result is True
  222. def test_is_connected_returns_false_for_unknown(self, manager):
  223. """Verify is_connected returns False for unknown printer."""
  224. result = manager.is_connected(999)
  225. assert result is False
  226. # ========================================================================
  227. # Tests for get_client
  228. # ========================================================================
  229. def test_get_client_returns_client(self, manager, mock_client):
  230. """Verify get_client returns the client."""
  231. manager._clients[1] = mock_client
  232. result = manager.get_client(1)
  233. assert result == mock_client
  234. def test_get_client_returns_none_for_unknown(self, manager):
  235. """Verify get_client returns None for unknown printer."""
  236. result = manager.get_client(999)
  237. assert result is None
  238. # ========================================================================
  239. # Tests for mark_printer_offline
  240. # ========================================================================
  241. def test_mark_printer_offline_updates_state(self, manager, mock_client):
  242. """Verify mark_printer_offline updates client state."""
  243. mock_client.state.connected = True
  244. manager._clients[1] = mock_client
  245. manager.mark_printer_offline(1)
  246. assert mock_client.state.connected is False
  247. assert mock_client.state.state == "unknown"
  248. def test_mark_printer_offline_triggers_callback(self, manager, mock_client):
  249. """Verify mark_printer_offline triggers status callback."""
  250. mock_client.state.connected = True
  251. manager._clients[1] = mock_client
  252. # Callback must return a coroutine
  253. async def async_callback(printer_id, state):
  254. pass
  255. manager._on_status_change = async_callback
  256. # Need a running loop for callback
  257. mock_loop = MagicMock()
  258. mock_loop.is_running.return_value = True
  259. manager._loop = mock_loop
  260. manager.mark_printer_offline(1)
  261. # Callback should be scheduled via run_coroutine_threadsafe
  262. mock_loop.is_running.assert_called()
  263. # State should be updated
  264. assert mock_client.state.connected is False
  265. def test_mark_printer_offline_handles_unknown(self, manager):
  266. """Verify mark_printer_offline handles unknown printer."""
  267. manager.mark_printer_offline(999) # Should not raise
  268. def test_mark_printer_offline_skips_already_offline(self, manager, mock_client):
  269. """Verify mark_printer_offline skips already offline printer."""
  270. mock_client.state.connected = False
  271. manager._clients[1] = mock_client
  272. manager.mark_printer_offline(1)
  273. # State should remain unchanged
  274. assert mock_client.state.connected is False
  275. # ========================================================================
  276. # Tests for start_print
  277. # ========================================================================
  278. def test_start_print_calls_client(self, manager, mock_client):
  279. """Verify start_print calls client method."""
  280. mock_client.start_print.return_value = True
  281. manager._clients[1] = mock_client
  282. result = manager.start_print(1, "test.gcode")
  283. mock_client.start_print.assert_called_once_with(
  284. "test.gcode",
  285. 1,
  286. ams_mapping=None,
  287. timelapse=False,
  288. bed_levelling=True,
  289. flow_cali=False,
  290. vibration_cali=True,
  291. layer_inspect=False,
  292. use_ams=True,
  293. )
  294. assert result is True
  295. def test_start_print_returns_false_for_unknown(self, manager):
  296. """Verify start_print returns False for unknown printer."""
  297. result = manager.start_print(999, "test.gcode")
  298. assert result is False
  299. def test_start_print_logs_print_command_with_caller(self, manager, mock_client, caplog):
  300. """Verify start_print logs PRINT COMMAND with caller info (#374)."""
  301. mock_client.start_print.return_value = True
  302. manager._clients[1] = mock_client
  303. with caplog.at_level(logging.INFO, logger="backend.app.services.printer_manager"):
  304. manager.start_print(1, "benchy.3mf")
  305. print_cmd_logs = [r for r in caplog.records if "PRINT COMMAND" in r.message]
  306. assert len(print_cmd_logs) == 1
  307. log_msg = print_cmd_logs[0].message
  308. assert "printer=1" in log_msg
  309. assert "file=benchy.3mf" in log_msg
  310. assert "caller=" in log_msg
  311. def test_start_print_logs_even_when_printer_unknown(self, manager, caplog):
  312. """Verify PRINT COMMAND is logged even for unknown printers (#374)."""
  313. with caplog.at_level(logging.INFO, logger="backend.app.services.printer_manager"):
  314. result = manager.start_print(999, "ghost.3mf")
  315. assert result is False
  316. print_cmd_logs = [r for r in caplog.records if "PRINT COMMAND" in r.message]
  317. assert len(print_cmd_logs) == 1
  318. # ========================================================================
  319. # Tests for stop_print
  320. # ========================================================================
  321. def test_stop_print_calls_client(self, manager, mock_client):
  322. """Verify stop_print calls client method."""
  323. mock_client.stop_print.return_value = True
  324. manager._clients[1] = mock_client
  325. result = manager.stop_print(1)
  326. mock_client.stop_print.assert_called_once()
  327. assert result is True
  328. def test_stop_print_returns_false_for_unknown(self, manager):
  329. """Verify stop_print returns False for unknown printer."""
  330. result = manager.stop_print(999)
  331. assert result is False
  332. # ========================================================================
  333. # Tests for wait_for_cooldown
  334. # ========================================================================
  335. @pytest.mark.asyncio
  336. async def test_wait_for_cooldown_returns_true_when_cool(self, manager, mock_client):
  337. """Verify wait_for_cooldown returns True when printer is cool."""
  338. mock_client.state.connected = True
  339. mock_client.state.temperatures = {"nozzle": 40, "bed": 30}
  340. mock_client.check_staleness.return_value = True
  341. manager._clients[1] = mock_client
  342. result = await manager.wait_for_cooldown(1, target_temp=50)
  343. assert result is True
  344. @pytest.mark.asyncio
  345. async def test_wait_for_cooldown_returns_false_on_disconnect(self, manager, mock_client):
  346. """Verify wait_for_cooldown returns False when printer disconnects."""
  347. mock_client.state.connected = False
  348. mock_client.check_staleness.return_value = False
  349. manager._clients[1] = mock_client
  350. result = await manager.wait_for_cooldown(1, target_temp=50, timeout=1)
  351. assert result is False
  352. @pytest.mark.asyncio
  353. async def test_wait_for_cooldown_returns_false_for_unknown(self, manager):
  354. """Verify wait_for_cooldown returns False for unknown printer."""
  355. result = await manager.wait_for_cooldown(999, target_temp=50, timeout=1)
  356. assert result is False
  357. @pytest.mark.asyncio
  358. async def test_wait_for_cooldown_checks_both_nozzles(self, manager, mock_client):
  359. """Verify wait_for_cooldown checks both nozzles for dual extruders."""
  360. mock_client.state.connected = True
  361. mock_client.state.temperatures = {"nozzle": 40, "nozzle_2": 45, "bed": 30}
  362. mock_client.check_staleness.return_value = True
  363. manager._clients[1] = mock_client
  364. result = await manager.wait_for_cooldown(1, target_temp=50)
  365. assert result is True
  366. # ========================================================================
  367. # Tests for logging methods
  368. # ========================================================================
  369. def test_enable_logging_calls_client(self, manager, mock_client):
  370. """Verify enable_logging calls client method."""
  371. manager._clients[1] = mock_client
  372. result = manager.enable_logging(1, True)
  373. mock_client.enable_logging.assert_called_once_with(True)
  374. assert result is True
  375. def test_enable_logging_returns_false_for_unknown(self, manager):
  376. """Verify enable_logging returns False for unknown printer."""
  377. result = manager.enable_logging(999, True)
  378. assert result is False
  379. def test_get_logs_returns_logs(self, manager, mock_client):
  380. """Verify get_logs returns client logs."""
  381. mock_logs = [MagicMock(), MagicMock()]
  382. mock_client.get_logs.return_value = mock_logs
  383. manager._clients[1] = mock_client
  384. result = manager.get_logs(1)
  385. assert result == mock_logs
  386. def test_get_logs_returns_empty_for_unknown(self, manager):
  387. """Verify get_logs returns empty list for unknown printer."""
  388. result = manager.get_logs(999)
  389. assert result == []
  390. def test_clear_logs_calls_client(self, manager, mock_client):
  391. """Verify clear_logs calls client method."""
  392. manager._clients[1] = mock_client
  393. result = manager.clear_logs(1)
  394. mock_client.clear_logs.assert_called_once()
  395. assert result is True
  396. def test_clear_logs_returns_false_for_unknown(self, manager):
  397. """Verify clear_logs returns False for unknown printer."""
  398. result = manager.clear_logs(999)
  399. assert result is False
  400. def test_is_logging_enabled_returns_status(self, manager, mock_client):
  401. """Verify is_logging_enabled returns client status."""
  402. mock_client.logging_enabled = True
  403. manager._clients[1] = mock_client
  404. result = manager.is_logging_enabled(1)
  405. assert result is True
  406. def test_is_logging_enabled_returns_false_for_unknown(self, manager):
  407. """Verify is_logging_enabled returns False for unknown printer."""
  408. result = manager.is_logging_enabled(999)
  409. assert result is False
  410. # ========================================================================
  411. # Tests for request_status_update
  412. # ========================================================================
  413. def test_request_status_update_calls_client(self, manager, mock_client):
  414. """Verify request_status_update calls client method."""
  415. mock_client.request_status_update.return_value = True
  416. manager._clients[1] = mock_client
  417. result = manager.request_status_update(1)
  418. mock_client.request_status_update.assert_called_once()
  419. assert result is True
  420. def test_request_status_update_returns_false_for_unknown(self, manager):
  421. """Verify request_status_update returns False for unknown printer."""
  422. result = manager.request_status_update(999)
  423. assert result is False
  424. # ========================================================================
  425. # Tests for test_connection
  426. # ========================================================================
  427. @pytest.mark.asyncio
  428. async def test_test_connection_success(self, manager):
  429. """Verify test_connection returns success on connection."""
  430. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  431. mock_instance = MagicMock()
  432. mock_instance.state = MagicMock()
  433. mock_instance.state.connected = True
  434. mock_instance.state.state = "IDLE"
  435. mock_instance.state.raw_data = {"device_model": "X1C"}
  436. MockClient.return_value = mock_instance
  437. result = await manager.test_connection("192.168.1.100", "00M09A123456789", "12345678")
  438. assert result["success"] is True
  439. assert result["state"] == "IDLE"
  440. assert result["model"] == "X1C"
  441. mock_instance.disconnect.assert_called_once()
  442. @pytest.mark.asyncio
  443. async def test_test_connection_failure(self, manager):
  444. """Verify test_connection returns failure on connection error."""
  445. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  446. mock_instance = MagicMock()
  447. mock_instance.state = MagicMock()
  448. mock_instance.state.connected = False
  449. MockClient.return_value = mock_instance
  450. result = await manager.test_connection("192.168.1.100", "00M09A123456789", "12345678")
  451. assert result["success"] is False
  452. assert result["state"] is None
  453. mock_instance.disconnect.assert_called_once()
  454. # ========================================================================
  455. # Tests for current print user tracking (Issue #206)
  456. # ========================================================================
  457. def test_set_current_print_user(self, manager):
  458. """Verify current print user can be set."""
  459. manager.set_current_print_user(1, 42, "testuser")
  460. assert 1 in manager._current_print_user
  461. assert manager._current_print_user[1]["user_id"] == 42
  462. assert manager._current_print_user[1]["username"] == "testuser"
  463. def test_get_current_print_user_returns_user(self, manager):
  464. """Verify get_current_print_user returns the stored user."""
  465. manager.set_current_print_user(1, 42, "testuser")
  466. result = manager.get_current_print_user(1)
  467. assert result is not None
  468. assert result["user_id"] == 42
  469. assert result["username"] == "testuser"
  470. def test_get_current_print_user_returns_none_for_unknown(self, manager):
  471. """Verify get_current_print_user returns None for unknown printer."""
  472. result = manager.get_current_print_user(999)
  473. assert result is None
  474. def test_clear_current_print_user(self, manager):
  475. """Verify current print user can be cleared."""
  476. manager.set_current_print_user(1, 42, "testuser")
  477. manager.clear_current_print_user(1)
  478. result = manager.get_current_print_user(1)
  479. assert result is None
  480. def test_clear_current_print_user_no_error_for_unknown(self, manager):
  481. """Verify clearing unknown printer doesn't raise error."""
  482. # Should not raise
  483. manager.clear_current_print_user(999)
  484. def test_set_current_print_user_overwrites_existing(self, manager):
  485. """Verify setting user overwrites existing value."""
  486. manager.set_current_print_user(1, 42, "user1")
  487. manager.set_current_print_user(1, 99, "user2")
  488. result = manager.get_current_print_user(1)
  489. assert result["user_id"] == 99
  490. assert result["username"] == "user2"
  491. def test_multiple_printers_have_separate_users(self, manager):
  492. """Verify each printer tracks its own user separately."""
  493. manager.set_current_print_user(1, 42, "user1")
  494. manager.set_current_print_user(2, 99, "user2")
  495. result1 = manager.get_current_print_user(1)
  496. result2 = manager.get_current_print_user(2)
  497. assert result1["username"] == "user1"
  498. assert result2["username"] == "user2"
  499. class TestPrinterStateToDict:
  500. """Tests for printer_state_to_dict helper function."""
  501. @pytest.fixture
  502. def mock_state(self):
  503. """Create a mock PrinterState."""
  504. state = MagicMock()
  505. state.connected = True
  506. state.state = "RUNNING"
  507. state.current_print = "test.3mf"
  508. state.subtask_name = "Test Print"
  509. state.gcode_file = "/sdcard/test.gcode"
  510. state.progress = 50
  511. state.remaining_time = 3600
  512. state.layer_num = 10
  513. state.total_layers = 20
  514. state.temperatures = {"nozzle": 200, "bed": 60}
  515. state.hms_errors = []
  516. state.ams_status_main = 0
  517. state.ams_status_sub = 0
  518. state.tray_now = "1"
  519. state.wifi_signal = -50
  520. state.raw_data = {}
  521. state.stg_cur = -1 # No calibration stage active
  522. state.firmware_version = None
  523. return state
  524. def test_basic_conversion(self, mock_state):
  525. """Verify basic state fields are converted."""
  526. result = printer_state_to_dict(mock_state)
  527. assert result["connected"] is True
  528. assert result["state"] == "RUNNING"
  529. assert result["progress"] == 50
  530. assert result["temperatures"] == {"nozzle": 200, "bed": 60}
  531. def test_ams_data_parsing(self, mock_state):
  532. """Verify AMS data is parsed correctly."""
  533. mock_state.raw_data = {
  534. "ams": [
  535. {
  536. "id": 0,
  537. "humidity_raw": 45,
  538. "temp": 25,
  539. "tray": [
  540. {
  541. "id": 0,
  542. "tray_color": "FF0000",
  543. "tray_type": "PLA",
  544. "tray_sub_brands": "Generic",
  545. "remain": 80,
  546. "k": 0.5,
  547. "tag_uid": "ABC123",
  548. "tray_uuid": "uuid-123",
  549. }
  550. ],
  551. }
  552. ]
  553. }
  554. result = printer_state_to_dict(mock_state)
  555. assert result["ams"] is not None
  556. assert len(result["ams"]) == 1
  557. assert result["ams"][0]["humidity"] == 45
  558. assert len(result["ams"][0]["tray"]) == 1
  559. assert result["ams"][0]["tray"][0]["tray_color"] == "FF0000"
  560. def test_empty_tag_uid_becomes_none(self, mock_state):
  561. """Verify empty tag_uid is converted to None."""
  562. mock_state.raw_data = {
  563. "ams": [
  564. {
  565. "id": 0,
  566. "tray": [
  567. {
  568. "id": 0,
  569. "tag_uid": "",
  570. "tray_uuid": "00000000000000000000000000000000",
  571. }
  572. ],
  573. }
  574. ]
  575. }
  576. result = printer_state_to_dict(mock_state)
  577. assert result["ams"][0]["tray"][0]["tag_uid"] is None
  578. assert result["ams"][0]["tray"][0]["tray_uuid"] is None
  579. def test_zero_tag_uid_becomes_none(self, mock_state):
  580. """Verify zero tag_uid is converted to None."""
  581. mock_state.raw_data = {
  582. "ams": [
  583. {
  584. "id": 0,
  585. "tray": [
  586. {
  587. "id": 0,
  588. "tag_uid": "0000000000000000",
  589. }
  590. ],
  591. }
  592. ]
  593. }
  594. result = printer_state_to_dict(mock_state)
  595. assert result["ams"][0]["tray"][0]["tag_uid"] is None
  596. def test_vt_tray_parsing(self, mock_state):
  597. """Verify virtual tray is parsed correctly as a list."""
  598. mock_state.raw_data = {
  599. "vt_tray": [
  600. {
  601. "tray_color": "00FF00",
  602. "tray_type": "PETG",
  603. "tray_sub_brands": "Generic",
  604. "remain": 60,
  605. "tag_uid": "VT123",
  606. }
  607. ]
  608. }
  609. result = printer_state_to_dict(mock_state)
  610. assert isinstance(result["vt_tray"], list)
  611. assert len(result["vt_tray"]) == 1
  612. assert result["vt_tray"][0]["id"] == 254
  613. assert result["vt_tray"][0]["tray_color"] == "00FF00"
  614. assert result["vt_tray"][0]["tray_type"] == "PETG"
  615. def test_vt_tray_dict_normalized_to_list(self, mock_state):
  616. """Verify vt_tray as a raw dict (from MQTT) is normalized to a list."""
  617. mock_state.raw_data = {
  618. "vt_tray": {
  619. "id": "254",
  620. "tray_color": "FF0000",
  621. "tray_type": "PLA",
  622. "tray_sub_brands": "Generic",
  623. "tag_uid": "0000000000000000",
  624. "tray_uuid": "00000000000000000000000000000000",
  625. "remain": 0,
  626. }
  627. }
  628. result = printer_state_to_dict(mock_state)
  629. assert isinstance(result["vt_tray"], list)
  630. assert len(result["vt_tray"]) == 1
  631. assert result["vt_tray"][0]["tray_color"] == "FF0000"
  632. assert result["vt_tray"][0]["tray_type"] == "PLA"
  633. assert result["vt_tray"][0]["tag_uid"] is None
  634. assert result["vt_tray"][0]["tray_uuid"] is None
  635. def test_vt_tray_non_list_non_dict_ignored(self, mock_state):
  636. """Verify unexpected vt_tray types (e.g. string) produce empty list."""
  637. mock_state.raw_data = {"vt_tray": "unexpected_string"}
  638. result = printer_state_to_dict(mock_state)
  639. assert result["vt_tray"] == []
  640. def test_hms_errors_conversion(self, mock_state):
  641. """Verify HMS errors are converted correctly."""
  642. error = MagicMock()
  643. error.code = "0700_0100"
  644. error.attr = 1
  645. error.module = "AMS"
  646. error.severity = 2
  647. mock_state.hms_errors = [error]
  648. result = printer_state_to_dict(mock_state)
  649. assert len(result["hms_errors"]) == 1
  650. assert result["hms_errors"][0]["code"] == "0700_0100"
  651. assert result["hms_errors"][0]["module"] == "AMS"
  652. def test_cover_url_added_for_running_print(self, mock_state):
  653. """Verify cover_url is added for running prints."""
  654. result = printer_state_to_dict(mock_state, printer_id=1)
  655. assert result["cover_url"] == "/api/v1/printers/1/cover"
  656. def test_current_plate_id_extracted_from_gcode_file(self, mock_state):
  657. """Verify current_plate_id is parsed from a Bambu plate path (#881)."""
  658. mock_state.gcode_file = "/Metadata/plate_3.gcode"
  659. result = printer_state_to_dict(mock_state)
  660. assert result["current_plate_id"] == 3
  661. def test_current_plate_id_none_when_no_plate_segment(self, mock_state):
  662. """Verify current_plate_id stays None when gcode_file has no plate marker."""
  663. mock_state.gcode_file = "/sdcard/test.gcode"
  664. result = printer_state_to_dict(mock_state)
  665. assert result["current_plate_id"] is None
  666. def test_cover_url_none_when_not_running(self, mock_state):
  667. """Verify cover_url is None when not printing."""
  668. mock_state.state = "IDLE"
  669. result = printer_state_to_dict(mock_state, printer_id=1)
  670. assert result["cover_url"] is None
  671. def test_ams_ht_detection(self, mock_state):
  672. """Verify AMS-HT is detected (1 tray vs 4)."""
  673. mock_state.raw_data = {
  674. "ams": [
  675. {
  676. "id": 0,
  677. "tray": [{"id": 0}], # Only 1 tray = AMS-HT
  678. }
  679. ]
  680. }
  681. result = printer_state_to_dict(mock_state)
  682. assert result["ams"][0]["is_ams_ht"] is True
  683. def test_regular_ams_detection(self, mock_state):
  684. """Verify regular AMS is detected (4 trays)."""
  685. mock_state.raw_data = {"ams": [{"id": 0, "tray": [{"id": 0}, {"id": 1}, {"id": 2}, {"id": 3}]}]}
  686. result = printer_state_to_dict(mock_state)
  687. assert result["ams"][0]["is_ams_ht"] is False
  688. def test_chamber_temp_filtered_for_p1s(self, mock_state):
  689. """Verify chamber temperature is filtered out for P1S (no chamber sensor)."""
  690. mock_state.temperatures = {
  691. "nozzle": 200,
  692. "bed": 60,
  693. "chamber": 5,
  694. "chamber_target": 0,
  695. "chamber_heating": False,
  696. }
  697. result = printer_state_to_dict(mock_state, model="P1S")
  698. assert "chamber" not in result["temperatures"]
  699. assert "chamber_target" not in result["temperatures"]
  700. assert "chamber_heating" not in result["temperatures"]
  701. assert result["temperatures"]["nozzle"] == 200
  702. assert result["temperatures"]["bed"] == 60
  703. def test_chamber_temp_kept_for_x1c(self, mock_state):
  704. """Verify chamber temperature is kept for X1C (has chamber sensor)."""
  705. mock_state.temperatures = {
  706. "nozzle": 200,
  707. "bed": 60,
  708. "chamber": 25,
  709. "chamber_target": 45,
  710. "chamber_heating": True,
  711. }
  712. result = printer_state_to_dict(mock_state, model="X1C")
  713. assert result["temperatures"]["chamber"] == 25
  714. assert result["temperatures"]["chamber_target"] == 45
  715. assert result["temperatures"]["chamber_heating"] is True
  716. def test_chamber_temp_filtered_for_a1(self, mock_state):
  717. """Verify chamber temperature is filtered out for A1 (no chamber sensor)."""
  718. mock_state.temperatures = {"nozzle": 200, "bed": 60, "chamber": 5}
  719. result = printer_state_to_dict(mock_state, model="A1")
  720. assert "chamber" not in result["temperatures"]
  721. def test_chamber_temp_kept_when_no_model(self, mock_state):
  722. """Verify chamber temperature is kept when model is not specified (conservative approach)."""
  723. mock_state.temperatures = {"nozzle": 200, "bed": 60, "chamber": 25}
  724. result = printer_state_to_dict(mock_state) # No model specified
  725. # When model is unknown, we can't filter - leave as is
  726. # Actually supports_chamber_temp returns False for None, so it will filter
  727. # Let's check the actual behavior
  728. assert "chamber" not in result["temperatures"]
  729. def test_ams_drying_fields_included(self, mock_state):
  730. """Verify AMS drying fields (dry_time, module_type) are included in output."""
  731. mock_state.raw_data = {
  732. "ams": [
  733. {
  734. "id": 0,
  735. "dry_time": 42,
  736. "module_type": "n3f",
  737. "tray": [
  738. {
  739. "id": 0,
  740. "tray_color": "FF0000",
  741. "tray_type": "PLA",
  742. "drying_temp": 55,
  743. "drying_time": 240,
  744. }
  745. ],
  746. }
  747. ]
  748. }
  749. result = printer_state_to_dict(mock_state)
  750. ams_unit = result["ams"][0]
  751. assert ams_unit["dry_time"] == 42
  752. assert ams_unit["module_type"] == "n3f"
  753. # Tray-level drying fields
  754. tray = ams_unit["tray"][0]
  755. assert tray["drying_temp"] == 55
  756. assert tray["drying_time"] == 240
  757. def test_awaiting_plate_clear_defaults_false(self, mock_state):
  758. """Without a printer_id, awaiting_plate_clear is False (no lookup possible)."""
  759. result = printer_state_to_dict(mock_state)
  760. assert result["awaiting_plate_clear"] is False
  761. def test_awaiting_plate_clear_surfaced_when_set(self, mock_state):
  762. """With printer_id, awaiting_plate_clear reflects PrinterManager state.
  763. Regression: PR #939 left this flag off the WebSocket payload, so the
  764. "Clear Plate" button only appeared after the 30 s REST fallback poll.
  765. """
  766. from backend.app.services.printer_manager import printer_manager
  767. printer_manager.set_awaiting_plate_clear(12345, True)
  768. try:
  769. result = printer_state_to_dict(mock_state, printer_id=12345)
  770. assert result["awaiting_plate_clear"] is True
  771. finally:
  772. printer_manager.set_awaiting_plate_clear(12345, False)
  773. def test_name_and_model_surfaced_when_registered(self, mock_state):
  774. """Registered PrinterInfo name + model arg should land in the WS payload.
  775. Regression for #963 follow-up: without this, the gcode viewer's printer
  776. selector had to wait on a /printers fetch before it could render real
  777. names, and the initial WS snapshot showed "Printer 1" fallbacks.
  778. """
  779. from backend.app.services.printer_manager import PrinterInfo, printer_manager
  780. # Register a stub PrinterInfo; the real manager writes this on connect.
  781. printer_manager._printer_info[98765] = PrinterInfo(name="My X1C", serial_number="01S00-0")
  782. try:
  783. result = printer_state_to_dict(mock_state, printer_id=98765, model="X1C")
  784. assert result["name"] == "My X1C"
  785. assert result["model"] == "X1C"
  786. finally:
  787. printer_manager._printer_info.pop(98765, None)
  788. def test_name_and_model_absent_when_no_printer_id(self, mock_state):
  789. """Without a printer_id (unusual callsites), name/model keys stay absent.
  790. The consumers (gcode viewer, frontend card) tolerate missing keys; what
  791. they can't tolerate is an unrelated printer's name accidentally leaking
  792. into a status meant for a different one.
  793. """
  794. result = printer_state_to_dict(mock_state)
  795. assert "name" not in result
  796. assert "model" not in result
  797. def test_model_absent_when_arg_is_none(self, mock_state):
  798. """`model` arg=None must not plant a `model` key at all.
  799. If the arg is None, callers didn't know the model yet; emitting a
  800. `model: null` field would overwrite a good value cached client-side.
  801. """
  802. from backend.app.services.printer_manager import PrinterInfo, printer_manager
  803. printer_manager._printer_info[55555] = PrinterInfo(name="N", serial_number="S")
  804. try:
  805. result = printer_state_to_dict(mock_state, printer_id=55555, model=None)
  806. assert "model" not in result
  807. assert result["name"] == "N"
  808. finally:
  809. printer_manager._printer_info.pop(55555, None)
  810. class TestStatusKeyDryingDedup:
  811. """Regression tests for WebSocket dedup including drying fields.
  812. The WebSocket broadcast deduplication uses printer_state_to_dict output
  813. to detect changes. If drying fields (like dry_time) are missing from
  814. the dict, changes to those fields won't trigger broadcasts.
  815. """
  816. def test_dry_time_change_changes_status_key(self):
  817. """Verify dry_time is present in AMS unit data so dedup can detect changes."""
  818. state = MagicMock()
  819. state.connected = True
  820. state.state = "IDLE"
  821. state.current_print = None
  822. state.subtask_name = None
  823. state.gcode_file = None
  824. state.progress = 0
  825. state.remaining_time = 0
  826. state.layer_num = 0
  827. state.total_layers = 0
  828. state.temperatures = {"nozzle": 25, "bed": 25}
  829. state.hms_errors = []
  830. state.ams_status_main = 0
  831. state.ams_status_sub = 0
  832. state.tray_now = None
  833. state.wifi_signal = -50
  834. state.stg_cur = -1
  835. # First state: drying active with 30 minutes remaining
  836. state.raw_data = {"ams": [{"id": 0, "dry_time": 30, "module_type": "n3f", "tray": [{"id": 0}]}]}
  837. result1 = printer_state_to_dict(state)
  838. # Second state: drying time decreased
  839. state.raw_data = {"ams": [{"id": 0, "dry_time": 29, "module_type": "n3f", "tray": [{"id": 0}]}]}
  840. result2 = printer_state_to_dict(state)
  841. # The dicts should differ — dry_time changed
  842. assert result1["ams"][0]["dry_time"] == 30
  843. assert result2["ams"][0]["dry_time"] == 29
  844. assert result1["ams"] != result2["ams"]
  845. class TestSupportsChamberTemp:
  846. """Tests for supports_chamber_temp helper function."""
  847. def test_x1_series_supported(self):
  848. """Verify X1 series printers support chamber temp."""
  849. assert supports_chamber_temp("X1") is True
  850. assert supports_chamber_temp("X1C") is True
  851. assert supports_chamber_temp("X1E") is True
  852. def test_p2_series_supported(self):
  853. """Verify P2 series printers support chamber temp."""
  854. assert supports_chamber_temp("P2S") is True
  855. def test_h2_series_supported(self):
  856. """Verify H2 series printers support chamber temp."""
  857. assert supports_chamber_temp("H2C") is True
  858. assert supports_chamber_temp("H2D") is True
  859. assert supports_chamber_temp("H2DPRO") is True
  860. assert supports_chamber_temp("H2S") is True
  861. def test_p1_series_not_supported(self):
  862. """Verify P1 series printers do NOT support chamber temp."""
  863. assert supports_chamber_temp("P1P") is False
  864. assert supports_chamber_temp("P1S") is False
  865. def test_a1_series_not_supported(self):
  866. """Verify A1 series printers do NOT support chamber temp."""
  867. assert supports_chamber_temp("A1") is False
  868. assert supports_chamber_temp("A1MINI") is False
  869. def test_none_model_not_supported(self):
  870. """Verify None model returns False."""
  871. assert supports_chamber_temp(None) is False
  872. def test_case_insensitive(self):
  873. """Verify model matching is case-insensitive."""
  874. assert supports_chamber_temp("x1c") is True
  875. assert supports_chamber_temp("X1c") is True
  876. assert supports_chamber_temp("p1s") is False
  877. def test_internal_model_codes_supported(self):
  878. """Verify internal model codes from MQTT/SSDP are recognized."""
  879. # X1/X1C
  880. assert supports_chamber_temp("BL-P001") is True
  881. # X1E
  882. assert supports_chamber_temp("C13") is True
  883. # H2D
  884. assert supports_chamber_temp("O1D") is True
  885. # H2C
  886. assert supports_chamber_temp("O1C") is True
  887. # H2S
  888. assert supports_chamber_temp("O1S") is True
  889. # H2D Pro
  890. assert supports_chamber_temp("O1E") is True
  891. # P2S
  892. assert supports_chamber_temp("N7") is True
  893. def test_internal_model_codes_not_supported(self):
  894. """Verify A1/P1 internal codes are NOT supported."""
  895. # P1P
  896. assert supports_chamber_temp("C11") is False
  897. # P1S
  898. assert supports_chamber_temp("C12") is False
  899. # A1
  900. assert supports_chamber_temp("N2S") is False
  901. # A1 Mini
  902. assert supports_chamber_temp("N1") is False
  903. class TestSupportsDrying:
  904. """Tests for supports_drying helper function."""
  905. def test_known_supported_with_firmware(self):
  906. """Verify known models with sufficient firmware return True."""
  907. assert supports_drying("X1C", "01.09.00.00") is True
  908. assert supports_drying("P1S", "01.08.00.00") is True
  909. assert supports_drying("H2D", "01.02.30.00") is True
  910. assert supports_drying("H2S", "01.02.00.00") is True
  911. assert supports_drying("P2S", "01.02.00.00") is True
  912. assert supports_drying("N7", "01.02.00.00") is True
  913. def test_known_supported_old_firmware(self):
  914. """Verify known models with old firmware return False."""
  915. assert supports_drying("X1C", "01.08.00.00") is False
  916. assert supports_drying("P1S", "01.07.00.00") is False
  917. assert supports_drying("H2S", "01.01.00.00") is False
  918. assert supports_drying("P2S", "01.01.99.99") is False
  919. assert supports_drying("N7", "01.01.99.99") is False
  920. def test_known_supported_no_firmware(self):
  921. """Verify known models with no firmware return False."""
  922. assert supports_drying("X1C", None) is False
  923. assert supports_drying("P2S", None) is False
  924. def test_unsupported_models(self):
  925. """Verify models without AMS drying support return False regardless of firmware."""
  926. for model in ["A1", "A1MINI", "A1-MINI", "H2C", "N1", "N2S"]:
  927. assert supports_drying(model, "99.99.99.99") is False, f"Expected False for {model}"
  928. def test_unknown_models_allowed(self):
  929. """Verify unknown models are allowed (graceful fallback).
  930. Models not in the unsupported set AND not matching any known firmware-gated
  931. model substring get the benefit of the doubt and return True.
  932. "H2D Pro" contains "H2D" so it IS firmware-gated (needs firmware).
  933. """
  934. # Truly unknown models: no substring match in _DRYING_MIN_FIRMWARE
  935. assert supports_drying("FUTURE_MODEL", None) is True
  936. # X1E contains "X1" substring, so it IS firmware-gated
  937. assert supports_drying("X1E", "01.09.00.00") is True
  938. # H2D Pro contains "H2D" substring, so it IS firmware-gated
  939. assert supports_drying("H2D Pro", "01.02.30.00") is True
  940. def test_none_model(self):
  941. """Verify None model returns False."""
  942. assert supports_drying(None, "01.09.00.00") is False
  943. def test_case_insensitive(self):
  944. """Verify model matching is case-insensitive."""
  945. assert supports_drying("x1c", "01.09.00.00") is True
  946. assert supports_drying("p2s", "01.02.00.00") is True
  947. assert supports_drying("a1", "99.99.99.99") is False
  948. class TestGetDerivedStatusName:
  949. """Tests for get_derived_status_name function."""
  950. def test_stg_cur_255_returns_none(self):
  951. """Verify stg_cur=255 (A1/P1 idle) returns None, not 'Unknown stage (255)'."""
  952. state = MagicMock()
  953. state.stg_cur = 255
  954. state.state = "IDLE"
  955. result = get_derived_status_name(state)
  956. assert result is None
  957. def test_stg_cur_negative_one_returns_none_when_idle(self):
  958. """Verify stg_cur=-1 (X1 idle) returns None."""
  959. state = MagicMock()
  960. state.stg_cur = -1
  961. state.state = "IDLE"
  962. result = get_derived_status_name(state)
  963. assert result is None
  964. def test_valid_stage_returns_name(self):
  965. """Verify valid stg_cur values return stage name."""
  966. state = MagicMock()
  967. state.stg_cur = 1 # Auto bed leveling
  968. result = get_derived_status_name(state)
  969. assert result == "Auto bed leveling"
  970. def test_stg_cur_zero_returns_printing(self):
  971. """Verify stg_cur=0 returns 'Printing' when no model specified."""
  972. state = MagicMock()
  973. state.stg_cur = 0
  974. result = get_derived_status_name(state)
  975. assert result == "Printing"
  976. def test_a1_idle_with_stg_cur_zero_returns_none(self):
  977. """Verify A1 with IDLE state and stg_cur=0 returns None (bug workaround)."""
  978. state = MagicMock()
  979. state.stg_cur = 0
  980. state.state = "IDLE"
  981. # Test various A1 model names
  982. for model in ["A1", "A1 Mini", "A1-Mini", "A1MINI", "N1", "N2S"]:
  983. result = get_derived_status_name(state, model)
  984. assert result is None, f"Expected None for model {model}"
  985. def test_a1_running_with_stg_cur_zero_returns_printing(self):
  986. """Verify A1 with RUNNING state and stg_cur=0 still returns 'Printing'."""
  987. state = MagicMock()
  988. state.stg_cur = 0
  989. state.state = "RUNNING"
  990. result = get_derived_status_name(state, "A1")
  991. assert result == "Printing"
  992. def test_non_a1_idle_with_stg_cur_zero_returns_printing(self):
  993. """Verify non-A1 models with IDLE and stg_cur=0 still return 'Printing'."""
  994. state = MagicMock()
  995. state.stg_cur = 0
  996. state.state = "IDLE"
  997. # X1C should not get the workaround
  998. result = get_derived_status_name(state, "X1C")
  999. assert result == "Printing"
  1000. class TestHasStgCurIdleBug:
  1001. """Tests for has_stg_cur_idle_bug function."""
  1002. def test_a1_models_return_true(self):
  1003. """Verify A1 model variants return True."""
  1004. assert has_stg_cur_idle_bug("A1") is True
  1005. assert has_stg_cur_idle_bug("A1 Mini") is True
  1006. assert has_stg_cur_idle_bug("A1-Mini") is True
  1007. assert has_stg_cur_idle_bug("A1MINI") is True
  1008. assert has_stg_cur_idle_bug("a1") is True # case insensitive
  1009. assert has_stg_cur_idle_bug("a1 mini") is True
  1010. def test_p1_models_return_true(self):
  1011. """Verify P1P/P1S model variants return True."""
  1012. assert has_stg_cur_idle_bug("P1P") is True
  1013. assert has_stg_cur_idle_bug("P1S") is True
  1014. assert has_stg_cur_idle_bug("p1p") is True # case insensitive
  1015. def test_internal_codes_return_true(self):
  1016. """Verify internal model codes return True."""
  1017. assert has_stg_cur_idle_bug("N1") is True # A1 Mini
  1018. assert has_stg_cur_idle_bug("N2S") is True # A1
  1019. assert has_stg_cur_idle_bug("C11") is True # P1P
  1020. assert has_stg_cur_idle_bug("C12") is True # P1S
  1021. def test_non_affected_models_return_false(self):
  1022. """Verify non-affected models return False."""
  1023. assert has_stg_cur_idle_bug("X1C") is False
  1024. assert has_stg_cur_idle_bug("X1") is False
  1025. assert has_stg_cur_idle_bug("H2D") is False
  1026. def test_none_model_returns_false(self):
  1027. """Verify None model returns False."""
  1028. assert has_stg_cur_idle_bug(None) is False
  1029. def test_empty_model_returns_false(self):
  1030. """Verify empty model returns False."""
  1031. assert has_stg_cur_idle_bug("") is False
  1032. class TestInitPrinterConnections:
  1033. """Tests for init_printer_connections function."""
  1034. @pytest.mark.asyncio
  1035. async def test_connects_all_active_printers(self):
  1036. """Verify all active printers are connected."""
  1037. mock_db = AsyncMock()
  1038. mock_printer1 = MagicMock(id=1, is_active=True)
  1039. mock_printer2 = MagicMock(id=2, is_active=True)
  1040. mock_result = MagicMock()
  1041. mock_result.scalars.return_value.all.return_value = [mock_printer1, mock_printer2]
  1042. mock_db.execute.return_value = mock_result
  1043. with patch("backend.app.services.printer_manager.printer_manager") as mock_manager:
  1044. mock_manager.connect_printer = AsyncMock()
  1045. await init_printer_connections(mock_db)
  1046. assert mock_manager.connect_printer.call_count == 2
  1047. @pytest.mark.asyncio
  1048. async def test_handles_empty_printer_list(self):
  1049. """Verify empty printer list is handled."""
  1050. mock_db = AsyncMock()
  1051. mock_result = MagicMock()
  1052. mock_result.scalars.return_value.all.return_value = []
  1053. mock_db.execute.return_value = mock_result
  1054. with patch("backend.app.services.printer_manager.printer_manager") as mock_manager:
  1055. mock_manager.connect_printer = AsyncMock()
  1056. await init_printer_connections(mock_db)
  1057. mock_manager.connect_printer.assert_not_called()
  1058. class TestAmsChangeCallback:
  1059. """Tests for AMS change callback functionality."""
  1060. @pytest.fixture
  1061. def manager(self):
  1062. """Create a fresh PrinterManager instance."""
  1063. return PrinterManager()
  1064. def test_ams_change_callback_is_triggered(self, manager):
  1065. """Verify AMS change callback is called when AMS data changes."""
  1066. callback = MagicMock()
  1067. manager.set_ams_change_callback(callback)
  1068. # Verify callback was set
  1069. assert manager._on_ams_change == callback
  1070. def test_ams_change_callback_receives_correct_data(self, manager):
  1071. """Verify AMS change callback receives the correct AMS data format."""
  1072. received_data = []
  1073. def capture_callback(printer_id, ams_data):
  1074. received_data.append((printer_id, ams_data))
  1075. manager.set_ams_change_callback(capture_callback)
  1076. # The callback should accept printer_id and ams_data
  1077. # This tests the callback signature
  1078. assert manager._on_ams_change is not None
  1079. assert callable(manager._on_ams_change)
  1080. class TestParsePlateId:
  1081. """Tests for parse_plate_id() — active-print plate extraction from gcode paths.
  1082. Regression coverage for #881 follow-up: the REST /status endpoint and the
  1083. WebSocket push path both use this helper, so they must agree on the plate
  1084. number the frontend sees.
  1085. """
  1086. def test_bambu_metadata_path(self):
  1087. # Canonical path that Bambu Studio / OrcaSlicer stamp into the 3MF.
  1088. assert parse_plate_id("/Metadata/plate_2.gcode") == 2
  1089. def test_plate_one(self):
  1090. assert parse_plate_id("/Metadata/plate_1.gcode") == 1
  1091. def test_double_digit_plate(self):
  1092. assert parse_plate_id("/Metadata/plate_12.gcode") == 12
  1093. def test_none_input(self):
  1094. assert parse_plate_id(None) is None
  1095. def test_empty_string(self):
  1096. assert parse_plate_id("") is None
  1097. def test_path_without_plate_segment(self):
  1098. # Some firmware / slicers report a bare filename without the plate marker.
  1099. assert parse_plate_id("/upload/my-model.gcode") is None
  1100. def test_similar_but_non_matching_names(self):
  1101. # "plate.gcode" (no number) and "nameplate_2.gcode" (substring) must not
  1102. # be mistaken for real plate markers. The regex anchors on `plate_<num>`.
  1103. assert parse_plate_id("/Metadata/plate.gcode") is None
  1104. assert parse_plate_id("/plates/3.gcode") is None
  1105. def test_substring_match_still_extracts(self):
  1106. # The regex isn't anchored to the start of a segment — any occurrence
  1107. # wins. This matches real Bambu paths where the segment is preceded by
  1108. # arbitrary directory noise, and matches the equivalent frontend regex.
  1109. assert parse_plate_id("/uploads/project/plate_5.gcode.md5") == 5
  1110. class TestResolvePlateId:
  1111. """Tests for resolve_plate_id() — plate resolution with dispatch precedence.
  1112. Regression coverage for #1166: P1S firmware 01.10.00.00 only puts the .3mf
  1113. filename in print.gcode_file, so parse_plate_id() returns None and the
  1114. printer card falls back to plate 1. When Bambuddy dispatches the print
  1115. itself we know the right plate; resolve_plate_id() prefers that record over
  1116. the gcode_file regex when subtask_name matches.
  1117. """
  1118. def _make_state(self, **kwargs):
  1119. from backend.app.services.bambu_mqtt import PrinterState
  1120. state = PrinterState()
  1121. for k, v in kwargs.items():
  1122. setattr(state, k, v)
  1123. return state
  1124. def test_dispatched_plate_wins_when_subtask_matches(self):
  1125. # User dispatches plate 4 via Bambuddy. Printer reflects subtask_name
  1126. # but firmware drops the plate path from gcode_file. Without the dispatch
  1127. # record we'd default to plate 1.
  1128. from backend.app.services.printer_manager import resolve_plate_id
  1129. state = self._make_state(
  1130. gcode_file="MyModel.3mf", # No plate path — firmware bug
  1131. subtask_name="MyModel",
  1132. dispatched_plate_id=4,
  1133. dispatched_subtask="MyModel",
  1134. )
  1135. assert resolve_plate_id(state) == 4
  1136. def test_dispatched_ignored_when_subtask_differs(self):
  1137. # Bambuddy's dispatch record is for a previous print; the printer is
  1138. # now running a different subtask (Studio-direct dispatch). The stale
  1139. # record must not be used — fall back to gcode_file regex.
  1140. from backend.app.services.printer_manager import resolve_plate_id
  1141. state = self._make_state(
  1142. gcode_file="/Metadata/plate_2.gcode",
  1143. subtask_name="DifferentPrint",
  1144. dispatched_plate_id=4,
  1145. dispatched_subtask="MyModel",
  1146. )
  1147. assert resolve_plate_id(state) == 2
  1148. def test_falls_back_to_gcode_regex_without_dispatch(self):
  1149. # Studio-direct dispatch — no Bambuddy dispatch record. Existing logic
  1150. # (parse_plate_id on gcode_file) must still work.
  1151. from backend.app.services.printer_manager import resolve_plate_id
  1152. state = self._make_state(
  1153. gcode_file="/Metadata/plate_3.gcode",
  1154. subtask_name="MyModel",
  1155. )
  1156. assert resolve_plate_id(state) == 3
  1157. def test_returns_none_when_nothing_resolvable(self):
  1158. # No dispatch record AND firmware swallowed the plate path. The route
  1159. # uses this signal to invoke the 3MF-scan fallback.
  1160. from backend.app.services.printer_manager import resolve_plate_id
  1161. state = self._make_state(
  1162. gcode_file="MyModel.3mf",
  1163. subtask_name="MyModel",
  1164. )
  1165. assert resolve_plate_id(state) is None
  1166. def test_dispatched_subtask_required_to_avoid_false_match(self):
  1167. # dispatched_plate_id without dispatched_subtask is incomplete — we
  1168. # can't validate it points at the current print, so we ignore it.
  1169. from backend.app.services.printer_manager import resolve_plate_id
  1170. state = self._make_state(
  1171. gcode_file="MyModel.3mf",
  1172. subtask_name="MyModel",
  1173. dispatched_plate_id=4,
  1174. dispatched_subtask=None,
  1175. )
  1176. assert resolve_plate_id(state) is None