test_printer_manager.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. """Unit tests for PrinterManager service.
  2. Tests printer connection management, status tracking, and print control.
  3. """
  4. import asyncio
  5. from datetime import datetime
  6. from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
  7. import pytest
  8. from backend.app.services.printer_manager import (
  9. PrinterManager,
  10. get_derived_status_name,
  11. has_stg_cur_idle_bug,
  12. init_printer_connections,
  13. printer_state_to_dict,
  14. supports_chamber_temp,
  15. )
  16. class TestPrinterManager:
  17. """Tests for PrinterManager class."""
  18. @pytest.fixture
  19. def manager(self):
  20. """Create a fresh PrinterManager instance."""
  21. return PrinterManager()
  22. @pytest.fixture
  23. def mock_printer(self):
  24. """Create a mock Printer object."""
  25. printer = MagicMock()
  26. printer.id = 1
  27. printer.ip_address = "192.168.1.100"
  28. printer.serial_number = "00M09A123456789"
  29. printer.access_code = "12345678"
  30. printer.is_active = True
  31. return printer
  32. @pytest.fixture
  33. def mock_client(self):
  34. """Create a mock BambuMQTTClient."""
  35. client = MagicMock()
  36. client.state = MagicMock()
  37. client.state.connected = True
  38. client.state.state = "IDLE"
  39. client.state.progress = 0
  40. client.state.temperatures = {"nozzle": 25, "bed": 25}
  41. client.state.raw_data = {}
  42. client.logging_enabled = False
  43. return client
  44. # ========================================================================
  45. # Tests for initialization
  46. # ========================================================================
  47. def test_init_creates_empty_clients_dict(self, manager):
  48. """Verify manager initializes with empty clients dict."""
  49. assert manager._clients == {}
  50. def test_init_callbacks_are_none(self, manager):
  51. """Verify all callbacks are initially None."""
  52. assert manager._on_print_start is None
  53. assert manager._on_print_complete is None
  54. assert manager._on_status_change is None
  55. assert manager._on_ams_change is None
  56. def test_init_loop_is_none(self, manager):
  57. """Verify event loop is initially None."""
  58. assert manager._loop is None
  59. # ========================================================================
  60. # Tests for callback setters
  61. # ========================================================================
  62. def test_set_event_loop(self, manager):
  63. """Verify event loop can be set."""
  64. mock_loop = MagicMock()
  65. manager.set_event_loop(mock_loop)
  66. assert manager._loop == mock_loop
  67. def test_set_print_start_callback(self, manager):
  68. """Verify print start callback can be set."""
  69. callback = MagicMock()
  70. manager.set_print_start_callback(callback)
  71. assert manager._on_print_start == callback
  72. def test_set_print_complete_callback(self, manager):
  73. """Verify print complete callback can be set."""
  74. callback = MagicMock()
  75. manager.set_print_complete_callback(callback)
  76. assert manager._on_print_complete == callback
  77. def test_set_status_change_callback(self, manager):
  78. """Verify status change callback can be set."""
  79. callback = MagicMock()
  80. manager.set_status_change_callback(callback)
  81. assert manager._on_status_change == callback
  82. def test_set_ams_change_callback(self, manager):
  83. """Verify AMS change callback can be set."""
  84. callback = MagicMock()
  85. manager.set_ams_change_callback(callback)
  86. assert manager._on_ams_change == callback
  87. # ========================================================================
  88. # Tests for _schedule_async
  89. # ========================================================================
  90. def test_schedule_async_with_running_loop(self, manager):
  91. """Verify async coroutine is scheduled when loop is running."""
  92. mock_loop = MagicMock()
  93. mock_loop.is_running.return_value = True
  94. manager._loop = mock_loop
  95. async def dummy_coro():
  96. pass
  97. coro = dummy_coro()
  98. manager._schedule_async(coro)
  99. mock_loop.is_running.assert_called_once()
  100. # Clean up the coroutine
  101. coro.close()
  102. def test_schedule_async_without_loop(self, manager):
  103. """Verify nothing happens when no loop is set."""
  104. async def dummy_coro():
  105. pass
  106. coro = dummy_coro()
  107. # Should not raise
  108. manager._schedule_async(coro)
  109. coro.close()
  110. def test_schedule_async_with_stopped_loop(self, manager):
  111. """Verify nothing happens when loop is not running."""
  112. mock_loop = MagicMock()
  113. mock_loop.is_running.return_value = False
  114. manager._loop = mock_loop
  115. async def dummy_coro():
  116. pass
  117. coro = dummy_coro()
  118. manager._schedule_async(coro)
  119. coro.close()
  120. # ========================================================================
  121. # Tests for connect_printer
  122. # ========================================================================
  123. @pytest.mark.asyncio
  124. async def test_connect_printer_creates_client(self, manager, mock_printer):
  125. """Verify connecting creates an MQTT client."""
  126. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  127. mock_instance = MagicMock()
  128. mock_instance.state = MagicMock()
  129. mock_instance.state.connected = True
  130. MockClient.return_value = mock_instance
  131. result = await manager.connect_printer(mock_printer)
  132. MockClient.assert_called_once()
  133. mock_instance.connect.assert_called_once()
  134. assert mock_printer.id in manager._clients
  135. assert result is True
  136. @pytest.mark.asyncio
  137. async def test_connect_printer_disconnects_existing(self, manager, mock_printer, mock_client):
  138. """Verify connecting disconnects existing client first."""
  139. manager._clients[mock_printer.id] = mock_client
  140. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  141. new_client = MagicMock()
  142. new_client.state = MagicMock()
  143. new_client.state.connected = True
  144. MockClient.return_value = new_client
  145. await manager.connect_printer(mock_printer)
  146. mock_client.disconnect.assert_called_once()
  147. @pytest.mark.asyncio
  148. async def test_connect_printer_returns_false_on_failure(self, manager, mock_printer):
  149. """Verify returns False when connection fails."""
  150. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  151. mock_instance = MagicMock()
  152. mock_instance.state = MagicMock()
  153. mock_instance.state.connected = False
  154. MockClient.return_value = mock_instance
  155. result = await manager.connect_printer(mock_printer)
  156. assert result is False
  157. # ========================================================================
  158. # Tests for disconnect_printer
  159. # ========================================================================
  160. def test_disconnect_printer_removes_client(self, manager, mock_client):
  161. """Verify disconnecting removes and disconnects client."""
  162. manager._clients[1] = mock_client
  163. manager.disconnect_printer(1)
  164. mock_client.disconnect.assert_called_once()
  165. assert 1 not in manager._clients
  166. def test_disconnect_printer_handles_missing(self, manager):
  167. """Verify disconnecting non-existent printer doesn't raise."""
  168. manager.disconnect_printer(999) # Should not raise
  169. # ========================================================================
  170. # Tests for disconnect_all
  171. # ========================================================================
  172. def test_disconnect_all_disconnects_all_clients(self, manager):
  173. """Verify all clients are disconnected."""
  174. client1 = MagicMock()
  175. client2 = MagicMock()
  176. manager._clients[1] = client1
  177. manager._clients[2] = client2
  178. manager.disconnect_all()
  179. client1.disconnect.assert_called_once()
  180. client2.disconnect.assert_called_once()
  181. assert len(manager._clients) == 0
  182. # ========================================================================
  183. # Tests for get_status
  184. # ========================================================================
  185. def test_get_status_returns_state(self, manager, mock_client):
  186. """Verify get_status returns client state."""
  187. manager._clients[1] = mock_client
  188. result = manager.get_status(1)
  189. mock_client.check_staleness.assert_called_once()
  190. assert result == mock_client.state
  191. def test_get_status_returns_none_for_unknown(self, manager):
  192. """Verify get_status returns None for unknown printer."""
  193. result = manager.get_status(999)
  194. assert result is None
  195. # ========================================================================
  196. # Tests for get_all_statuses
  197. # ========================================================================
  198. def test_get_all_statuses_returns_all(self, manager):
  199. """Verify all statuses are returned."""
  200. client1 = MagicMock()
  201. client1.state = MagicMock(connected=True)
  202. client2 = MagicMock()
  203. client2.state = MagicMock(connected=False)
  204. manager._clients[1] = client1
  205. manager._clients[2] = client2
  206. result = manager.get_all_statuses()
  207. assert len(result) == 2
  208. assert 1 in result
  209. assert 2 in result
  210. client1.check_staleness.assert_called_once()
  211. client2.check_staleness.assert_called_once()
  212. # ========================================================================
  213. # Tests for is_connected
  214. # ========================================================================
  215. def test_is_connected_returns_true(self, manager, mock_client):
  216. """Verify is_connected returns True for connected printer."""
  217. mock_client.check_staleness.return_value = True
  218. manager._clients[1] = mock_client
  219. result = manager.is_connected(1)
  220. assert result is True
  221. def test_is_connected_returns_false_for_unknown(self, manager):
  222. """Verify is_connected returns False for unknown printer."""
  223. result = manager.is_connected(999)
  224. assert result is False
  225. # ========================================================================
  226. # Tests for get_client
  227. # ========================================================================
  228. def test_get_client_returns_client(self, manager, mock_client):
  229. """Verify get_client returns the client."""
  230. manager._clients[1] = mock_client
  231. result = manager.get_client(1)
  232. assert result == mock_client
  233. def test_get_client_returns_none_for_unknown(self, manager):
  234. """Verify get_client returns None for unknown printer."""
  235. result = manager.get_client(999)
  236. assert result is None
  237. # ========================================================================
  238. # Tests for mark_printer_offline
  239. # ========================================================================
  240. def test_mark_printer_offline_updates_state(self, manager, mock_client):
  241. """Verify mark_printer_offline updates client state."""
  242. mock_client.state.connected = True
  243. manager._clients[1] = mock_client
  244. manager.mark_printer_offline(1)
  245. assert mock_client.state.connected is False
  246. assert mock_client.state.state == "unknown"
  247. def test_mark_printer_offline_triggers_callback(self, manager, mock_client):
  248. """Verify mark_printer_offline triggers status callback."""
  249. mock_client.state.connected = True
  250. manager._clients[1] = mock_client
  251. # Callback must return a coroutine
  252. async def async_callback(printer_id, state):
  253. pass
  254. manager._on_status_change = async_callback
  255. # Need a running loop for callback
  256. mock_loop = MagicMock()
  257. mock_loop.is_running.return_value = True
  258. manager._loop = mock_loop
  259. manager.mark_printer_offline(1)
  260. # Callback should be scheduled via run_coroutine_threadsafe
  261. mock_loop.is_running.assert_called()
  262. # State should be updated
  263. assert mock_client.state.connected is False
  264. def test_mark_printer_offline_handles_unknown(self, manager):
  265. """Verify mark_printer_offline handles unknown printer."""
  266. manager.mark_printer_offline(999) # Should not raise
  267. def test_mark_printer_offline_skips_already_offline(self, manager, mock_client):
  268. """Verify mark_printer_offline skips already offline printer."""
  269. mock_client.state.connected = False
  270. manager._clients[1] = mock_client
  271. manager.mark_printer_offline(1)
  272. # State should remain unchanged
  273. assert mock_client.state.connected is False
  274. # ========================================================================
  275. # Tests for start_print
  276. # ========================================================================
  277. def test_start_print_calls_client(self, manager, mock_client):
  278. """Verify start_print calls client method."""
  279. mock_client.start_print.return_value = True
  280. manager._clients[1] = mock_client
  281. result = manager.start_print(1, "test.gcode")
  282. mock_client.start_print.assert_called_once_with(
  283. "test.gcode",
  284. 1,
  285. ams_mapping=None,
  286. timelapse=False,
  287. bed_levelling=True,
  288. flow_cali=False,
  289. vibration_cali=True,
  290. layer_inspect=False,
  291. use_ams=True,
  292. )
  293. assert result is True
  294. def test_start_print_returns_false_for_unknown(self, manager):
  295. """Verify start_print returns False for unknown printer."""
  296. result = manager.start_print(999, "test.gcode")
  297. assert result is False
  298. # ========================================================================
  299. # Tests for stop_print
  300. # ========================================================================
  301. def test_stop_print_calls_client(self, manager, mock_client):
  302. """Verify stop_print calls client method."""
  303. mock_client.stop_print.return_value = True
  304. manager._clients[1] = mock_client
  305. result = manager.stop_print(1)
  306. mock_client.stop_print.assert_called_once()
  307. assert result is True
  308. def test_stop_print_returns_false_for_unknown(self, manager):
  309. """Verify stop_print returns False for unknown printer."""
  310. result = manager.stop_print(999)
  311. assert result is False
  312. # ========================================================================
  313. # Tests for wait_for_cooldown
  314. # ========================================================================
  315. @pytest.mark.asyncio
  316. async def test_wait_for_cooldown_returns_true_when_cool(self, manager, mock_client):
  317. """Verify wait_for_cooldown returns True when printer is cool."""
  318. mock_client.state.connected = True
  319. mock_client.state.temperatures = {"nozzle": 40, "bed": 30}
  320. mock_client.check_staleness.return_value = True
  321. manager._clients[1] = mock_client
  322. result = await manager.wait_for_cooldown(1, target_temp=50)
  323. assert result is True
  324. @pytest.mark.asyncio
  325. async def test_wait_for_cooldown_returns_false_on_disconnect(self, manager, mock_client):
  326. """Verify wait_for_cooldown returns False when printer disconnects."""
  327. mock_client.state.connected = False
  328. mock_client.check_staleness.return_value = False
  329. manager._clients[1] = mock_client
  330. result = await manager.wait_for_cooldown(1, target_temp=50, timeout=1)
  331. assert result is False
  332. @pytest.mark.asyncio
  333. async def test_wait_for_cooldown_returns_false_for_unknown(self, manager):
  334. """Verify wait_for_cooldown returns False for unknown printer."""
  335. result = await manager.wait_for_cooldown(999, target_temp=50, timeout=1)
  336. assert result is False
  337. @pytest.mark.asyncio
  338. async def test_wait_for_cooldown_checks_both_nozzles(self, manager, mock_client):
  339. """Verify wait_for_cooldown checks both nozzles for dual extruders."""
  340. mock_client.state.connected = True
  341. mock_client.state.temperatures = {"nozzle": 40, "nozzle_2": 45, "bed": 30}
  342. mock_client.check_staleness.return_value = True
  343. manager._clients[1] = mock_client
  344. result = await manager.wait_for_cooldown(1, target_temp=50)
  345. assert result is True
  346. # ========================================================================
  347. # Tests for logging methods
  348. # ========================================================================
  349. def test_enable_logging_calls_client(self, manager, mock_client):
  350. """Verify enable_logging calls client method."""
  351. manager._clients[1] = mock_client
  352. result = manager.enable_logging(1, True)
  353. mock_client.enable_logging.assert_called_once_with(True)
  354. assert result is True
  355. def test_enable_logging_returns_false_for_unknown(self, manager):
  356. """Verify enable_logging returns False for unknown printer."""
  357. result = manager.enable_logging(999, True)
  358. assert result is False
  359. def test_get_logs_returns_logs(self, manager, mock_client):
  360. """Verify get_logs returns client logs."""
  361. mock_logs = [MagicMock(), MagicMock()]
  362. mock_client.get_logs.return_value = mock_logs
  363. manager._clients[1] = mock_client
  364. result = manager.get_logs(1)
  365. assert result == mock_logs
  366. def test_get_logs_returns_empty_for_unknown(self, manager):
  367. """Verify get_logs returns empty list for unknown printer."""
  368. result = manager.get_logs(999)
  369. assert result == []
  370. def test_clear_logs_calls_client(self, manager, mock_client):
  371. """Verify clear_logs calls client method."""
  372. manager._clients[1] = mock_client
  373. result = manager.clear_logs(1)
  374. mock_client.clear_logs.assert_called_once()
  375. assert result is True
  376. def test_clear_logs_returns_false_for_unknown(self, manager):
  377. """Verify clear_logs returns False for unknown printer."""
  378. result = manager.clear_logs(999)
  379. assert result is False
  380. def test_is_logging_enabled_returns_status(self, manager, mock_client):
  381. """Verify is_logging_enabled returns client status."""
  382. mock_client.logging_enabled = True
  383. manager._clients[1] = mock_client
  384. result = manager.is_logging_enabled(1)
  385. assert result is True
  386. def test_is_logging_enabled_returns_false_for_unknown(self, manager):
  387. """Verify is_logging_enabled returns False for unknown printer."""
  388. result = manager.is_logging_enabled(999)
  389. assert result is False
  390. # ========================================================================
  391. # Tests for request_status_update
  392. # ========================================================================
  393. def test_request_status_update_calls_client(self, manager, mock_client):
  394. """Verify request_status_update calls client method."""
  395. mock_client.request_status_update.return_value = True
  396. manager._clients[1] = mock_client
  397. result = manager.request_status_update(1)
  398. mock_client.request_status_update.assert_called_once()
  399. assert result is True
  400. def test_request_status_update_returns_false_for_unknown(self, manager):
  401. """Verify request_status_update returns False for unknown printer."""
  402. result = manager.request_status_update(999)
  403. assert result is False
  404. # ========================================================================
  405. # Tests for test_connection
  406. # ========================================================================
  407. @pytest.mark.asyncio
  408. async def test_test_connection_success(self, manager):
  409. """Verify test_connection returns success on connection."""
  410. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  411. mock_instance = MagicMock()
  412. mock_instance.state = MagicMock()
  413. mock_instance.state.connected = True
  414. mock_instance.state.state = "IDLE"
  415. mock_instance.state.raw_data = {"device_model": "X1C"}
  416. MockClient.return_value = mock_instance
  417. result = await manager.test_connection("192.168.1.100", "00M09A123456789", "12345678")
  418. assert result["success"] is True
  419. assert result["state"] == "IDLE"
  420. assert result["model"] == "X1C"
  421. mock_instance.disconnect.assert_called_once()
  422. @pytest.mark.asyncio
  423. async def test_test_connection_failure(self, manager):
  424. """Verify test_connection returns failure on connection error."""
  425. with patch("backend.app.services.printer_manager.BambuMQTTClient") as MockClient:
  426. mock_instance = MagicMock()
  427. mock_instance.state = MagicMock()
  428. mock_instance.state.connected = False
  429. MockClient.return_value = mock_instance
  430. result = await manager.test_connection("192.168.1.100", "00M09A123456789", "12345678")
  431. assert result["success"] is False
  432. assert result["state"] is None
  433. mock_instance.disconnect.assert_called_once()
  434. # ========================================================================
  435. # Tests for current print user tracking (Issue #206)
  436. # ========================================================================
  437. def test_set_current_print_user(self, manager):
  438. """Verify current print user can be set."""
  439. manager.set_current_print_user(1, 42, "testuser")
  440. assert 1 in manager._current_print_user
  441. assert manager._current_print_user[1]["user_id"] == 42
  442. assert manager._current_print_user[1]["username"] == "testuser"
  443. def test_get_current_print_user_returns_user(self, manager):
  444. """Verify get_current_print_user returns the stored user."""
  445. manager.set_current_print_user(1, 42, "testuser")
  446. result = manager.get_current_print_user(1)
  447. assert result is not None
  448. assert result["user_id"] == 42
  449. assert result["username"] == "testuser"
  450. def test_get_current_print_user_returns_none_for_unknown(self, manager):
  451. """Verify get_current_print_user returns None for unknown printer."""
  452. result = manager.get_current_print_user(999)
  453. assert result is None
  454. def test_clear_current_print_user(self, manager):
  455. """Verify current print user can be cleared."""
  456. manager.set_current_print_user(1, 42, "testuser")
  457. manager.clear_current_print_user(1)
  458. result = manager.get_current_print_user(1)
  459. assert result is None
  460. def test_clear_current_print_user_no_error_for_unknown(self, manager):
  461. """Verify clearing unknown printer doesn't raise error."""
  462. # Should not raise
  463. manager.clear_current_print_user(999)
  464. def test_set_current_print_user_overwrites_existing(self, manager):
  465. """Verify setting user overwrites existing value."""
  466. manager.set_current_print_user(1, 42, "user1")
  467. manager.set_current_print_user(1, 99, "user2")
  468. result = manager.get_current_print_user(1)
  469. assert result["user_id"] == 99
  470. assert result["username"] == "user2"
  471. def test_multiple_printers_have_separate_users(self, manager):
  472. """Verify each printer tracks its own user separately."""
  473. manager.set_current_print_user(1, 42, "user1")
  474. manager.set_current_print_user(2, 99, "user2")
  475. result1 = manager.get_current_print_user(1)
  476. result2 = manager.get_current_print_user(2)
  477. assert result1["username"] == "user1"
  478. assert result2["username"] == "user2"
  479. class TestPrinterStateToDict:
  480. """Tests for printer_state_to_dict helper function."""
  481. @pytest.fixture
  482. def mock_state(self):
  483. """Create a mock PrinterState."""
  484. state = MagicMock()
  485. state.connected = True
  486. state.state = "RUNNING"
  487. state.current_print = "test.3mf"
  488. state.subtask_name = "Test Print"
  489. state.gcode_file = "/sdcard/test.gcode"
  490. state.progress = 50
  491. state.remaining_time = 3600
  492. state.layer_num = 10
  493. state.total_layers = 20
  494. state.temperatures = {"nozzle": 200, "bed": 60}
  495. state.hms_errors = []
  496. state.ams_status_main = 0
  497. state.ams_status_sub = 0
  498. state.tray_now = "1"
  499. state.wifi_signal = -50
  500. state.raw_data = {}
  501. state.stg_cur = -1 # No calibration stage active
  502. return state
  503. def test_basic_conversion(self, mock_state):
  504. """Verify basic state fields are converted."""
  505. result = printer_state_to_dict(mock_state)
  506. assert result["connected"] is True
  507. assert result["state"] == "RUNNING"
  508. assert result["progress"] == 50
  509. assert result["temperatures"] == {"nozzle": 200, "bed": 60}
  510. def test_ams_data_parsing(self, mock_state):
  511. """Verify AMS data is parsed correctly."""
  512. mock_state.raw_data = {
  513. "ams": [
  514. {
  515. "id": 0,
  516. "humidity_raw": 45,
  517. "temp": 25,
  518. "tray": [
  519. {
  520. "id": 0,
  521. "tray_color": "FF0000",
  522. "tray_type": "PLA",
  523. "tray_sub_brands": "Generic",
  524. "remain": 80,
  525. "k": 0.5,
  526. "tag_uid": "ABC123",
  527. "tray_uuid": "uuid-123",
  528. }
  529. ],
  530. }
  531. ]
  532. }
  533. result = printer_state_to_dict(mock_state)
  534. assert result["ams"] is not None
  535. assert len(result["ams"]) == 1
  536. assert result["ams"][0]["humidity"] == 45
  537. assert len(result["ams"][0]["tray"]) == 1
  538. assert result["ams"][0]["tray"][0]["tray_color"] == "FF0000"
  539. def test_empty_tag_uid_becomes_none(self, mock_state):
  540. """Verify empty tag_uid is converted to None."""
  541. mock_state.raw_data = {
  542. "ams": [
  543. {
  544. "id": 0,
  545. "tray": [
  546. {
  547. "id": 0,
  548. "tag_uid": "",
  549. "tray_uuid": "00000000000000000000000000000000",
  550. }
  551. ],
  552. }
  553. ]
  554. }
  555. result = printer_state_to_dict(mock_state)
  556. assert result["ams"][0]["tray"][0]["tag_uid"] is None
  557. assert result["ams"][0]["tray"][0]["tray_uuid"] is None
  558. def test_zero_tag_uid_becomes_none(self, mock_state):
  559. """Verify zero tag_uid is converted to None."""
  560. mock_state.raw_data = {
  561. "ams": [
  562. {
  563. "id": 0,
  564. "tray": [
  565. {
  566. "id": 0,
  567. "tag_uid": "0000000000000000",
  568. }
  569. ],
  570. }
  571. ]
  572. }
  573. result = printer_state_to_dict(mock_state)
  574. assert result["ams"][0]["tray"][0]["tag_uid"] is None
  575. def test_vt_tray_parsing(self, mock_state):
  576. """Verify virtual tray is parsed correctly."""
  577. mock_state.raw_data = {
  578. "vt_tray": {
  579. "tray_color": "00FF00",
  580. "tray_type": "PETG",
  581. "tray_sub_brands": "Generic",
  582. "remain": 60,
  583. "tag_uid": "VT123",
  584. }
  585. }
  586. result = printer_state_to_dict(mock_state)
  587. assert result["vt_tray"] is not None
  588. assert result["vt_tray"]["id"] == 254
  589. assert result["vt_tray"]["tray_color"] == "00FF00"
  590. assert result["vt_tray"]["tray_type"] == "PETG"
  591. def test_hms_errors_conversion(self, mock_state):
  592. """Verify HMS errors are converted correctly."""
  593. error = MagicMock()
  594. error.code = "0700_0100"
  595. error.attr = 1
  596. error.module = "AMS"
  597. error.severity = 2
  598. mock_state.hms_errors = [error]
  599. result = printer_state_to_dict(mock_state)
  600. assert len(result["hms_errors"]) == 1
  601. assert result["hms_errors"][0]["code"] == "0700_0100"
  602. assert result["hms_errors"][0]["module"] == "AMS"
  603. def test_cover_url_added_for_running_print(self, mock_state):
  604. """Verify cover_url is added for running prints."""
  605. result = printer_state_to_dict(mock_state, printer_id=1)
  606. assert result["cover_url"] == "/api/v1/printers/1/cover"
  607. def test_cover_url_none_when_not_running(self, mock_state):
  608. """Verify cover_url is None when not printing."""
  609. mock_state.state = "IDLE"
  610. result = printer_state_to_dict(mock_state, printer_id=1)
  611. assert result["cover_url"] is None
  612. def test_ams_ht_detection(self, mock_state):
  613. """Verify AMS-HT is detected (1 tray vs 4)."""
  614. mock_state.raw_data = {
  615. "ams": [
  616. {
  617. "id": 0,
  618. "tray": [{"id": 0}], # Only 1 tray = AMS-HT
  619. }
  620. ]
  621. }
  622. result = printer_state_to_dict(mock_state)
  623. assert result["ams"][0]["is_ams_ht"] is True
  624. def test_regular_ams_detection(self, mock_state):
  625. """Verify regular AMS is detected (4 trays)."""
  626. mock_state.raw_data = {"ams": [{"id": 0, "tray": [{"id": 0}, {"id": 1}, {"id": 2}, {"id": 3}]}]}
  627. result = printer_state_to_dict(mock_state)
  628. assert result["ams"][0]["is_ams_ht"] is False
  629. def test_chamber_temp_filtered_for_p1s(self, mock_state):
  630. """Verify chamber temperature is filtered out for P1S (no chamber sensor)."""
  631. mock_state.temperatures = {
  632. "nozzle": 200,
  633. "bed": 60,
  634. "chamber": 5,
  635. "chamber_target": 0,
  636. "chamber_heating": False,
  637. }
  638. result = printer_state_to_dict(mock_state, model="P1S")
  639. assert "chamber" not in result["temperatures"]
  640. assert "chamber_target" not in result["temperatures"]
  641. assert "chamber_heating" not in result["temperatures"]
  642. assert result["temperatures"]["nozzle"] == 200
  643. assert result["temperatures"]["bed"] == 60
  644. def test_chamber_temp_kept_for_x1c(self, mock_state):
  645. """Verify chamber temperature is kept for X1C (has chamber sensor)."""
  646. mock_state.temperatures = {
  647. "nozzle": 200,
  648. "bed": 60,
  649. "chamber": 25,
  650. "chamber_target": 45,
  651. "chamber_heating": True,
  652. }
  653. result = printer_state_to_dict(mock_state, model="X1C")
  654. assert result["temperatures"]["chamber"] == 25
  655. assert result["temperatures"]["chamber_target"] == 45
  656. assert result["temperatures"]["chamber_heating"] is True
  657. def test_chamber_temp_filtered_for_a1(self, mock_state):
  658. """Verify chamber temperature is filtered out for A1 (no chamber sensor)."""
  659. mock_state.temperatures = {"nozzle": 200, "bed": 60, "chamber": 5}
  660. result = printer_state_to_dict(mock_state, model="A1")
  661. assert "chamber" not in result["temperatures"]
  662. def test_chamber_temp_kept_when_no_model(self, mock_state):
  663. """Verify chamber temperature is kept when model is not specified (conservative approach)."""
  664. mock_state.temperatures = {"nozzle": 200, "bed": 60, "chamber": 25}
  665. result = printer_state_to_dict(mock_state) # No model specified
  666. # When model is unknown, we can't filter - leave as is
  667. # Actually supports_chamber_temp returns False for None, so it will filter
  668. # Let's check the actual behavior
  669. assert "chamber" not in result["temperatures"]
  670. class TestSupportsChamberTemp:
  671. """Tests for supports_chamber_temp helper function."""
  672. def test_x1_series_supported(self):
  673. """Verify X1 series printers support chamber temp."""
  674. assert supports_chamber_temp("X1") is True
  675. assert supports_chamber_temp("X1C") is True
  676. assert supports_chamber_temp("X1E") is True
  677. def test_p2_series_supported(self):
  678. """Verify P2 series printers support chamber temp."""
  679. assert supports_chamber_temp("P2S") is True
  680. def test_h2_series_supported(self):
  681. """Verify H2 series printers support chamber temp."""
  682. assert supports_chamber_temp("H2C") is True
  683. assert supports_chamber_temp("H2D") is True
  684. assert supports_chamber_temp("H2DPRO") is True
  685. assert supports_chamber_temp("H2S") is True
  686. def test_p1_series_not_supported(self):
  687. """Verify P1 series printers do NOT support chamber temp."""
  688. assert supports_chamber_temp("P1P") is False
  689. assert supports_chamber_temp("P1S") is False
  690. def test_a1_series_not_supported(self):
  691. """Verify A1 series printers do NOT support chamber temp."""
  692. assert supports_chamber_temp("A1") is False
  693. assert supports_chamber_temp("A1MINI") is False
  694. def test_none_model_not_supported(self):
  695. """Verify None model returns False."""
  696. assert supports_chamber_temp(None) is False
  697. def test_case_insensitive(self):
  698. """Verify model matching is case-insensitive."""
  699. assert supports_chamber_temp("x1c") is True
  700. assert supports_chamber_temp("X1c") is True
  701. assert supports_chamber_temp("p1s") is False
  702. def test_internal_model_codes_supported(self):
  703. """Verify internal model codes from MQTT/SSDP are recognized."""
  704. # X1/X1C
  705. assert supports_chamber_temp("BL-P001") is True
  706. # X1E
  707. assert supports_chamber_temp("C13") is True
  708. # H2D
  709. assert supports_chamber_temp("O1D") is True
  710. # H2C
  711. assert supports_chamber_temp("O1C") is True
  712. # H2S
  713. assert supports_chamber_temp("O1S") is True
  714. # H2D Pro
  715. assert supports_chamber_temp("O1E") is True
  716. # P2S
  717. assert supports_chamber_temp("N7") is True
  718. def test_internal_model_codes_not_supported(self):
  719. """Verify A1/P1 internal codes are NOT supported."""
  720. # P1P
  721. assert supports_chamber_temp("C11") is False
  722. # P1S
  723. assert supports_chamber_temp("C12") is False
  724. # A1
  725. assert supports_chamber_temp("N2S") is False
  726. # A1 Mini
  727. assert supports_chamber_temp("N1") is False
  728. class TestGetDerivedStatusName:
  729. """Tests for get_derived_status_name function."""
  730. def test_stg_cur_255_returns_none(self):
  731. """Verify stg_cur=255 (A1/P1 idle) returns None, not 'Unknown stage (255)'."""
  732. state = MagicMock()
  733. state.stg_cur = 255
  734. state.state = "IDLE"
  735. result = get_derived_status_name(state)
  736. assert result is None
  737. def test_stg_cur_negative_one_returns_none_when_idle(self):
  738. """Verify stg_cur=-1 (X1 idle) returns None."""
  739. state = MagicMock()
  740. state.stg_cur = -1
  741. state.state = "IDLE"
  742. result = get_derived_status_name(state)
  743. assert result is None
  744. def test_valid_stage_returns_name(self):
  745. """Verify valid stg_cur values return stage name."""
  746. state = MagicMock()
  747. state.stg_cur = 1 # Auto bed leveling
  748. result = get_derived_status_name(state)
  749. assert result == "Auto bed leveling"
  750. def test_stg_cur_zero_returns_printing(self):
  751. """Verify stg_cur=0 returns 'Printing' when no model specified."""
  752. state = MagicMock()
  753. state.stg_cur = 0
  754. result = get_derived_status_name(state)
  755. assert result == "Printing"
  756. def test_a1_idle_with_stg_cur_zero_returns_none(self):
  757. """Verify A1 with IDLE state and stg_cur=0 returns None (bug workaround)."""
  758. state = MagicMock()
  759. state.stg_cur = 0
  760. state.state = "IDLE"
  761. # Test various A1 model names
  762. for model in ["A1", "A1 Mini", "A1-Mini", "A1MINI", "N1", "N2S"]:
  763. result = get_derived_status_name(state, model)
  764. assert result is None, f"Expected None for model {model}"
  765. def test_a1_running_with_stg_cur_zero_returns_printing(self):
  766. """Verify A1 with RUNNING state and stg_cur=0 still returns 'Printing'."""
  767. state = MagicMock()
  768. state.stg_cur = 0
  769. state.state = "RUNNING"
  770. result = get_derived_status_name(state, "A1")
  771. assert result == "Printing"
  772. def test_non_a1_idle_with_stg_cur_zero_returns_printing(self):
  773. """Verify non-A1 models with IDLE and stg_cur=0 still return 'Printing'."""
  774. state = MagicMock()
  775. state.stg_cur = 0
  776. state.state = "IDLE"
  777. # X1C should not get the workaround
  778. result = get_derived_status_name(state, "X1C")
  779. assert result == "Printing"
  780. class TestHasStgCurIdleBug:
  781. """Tests for has_stg_cur_idle_bug function."""
  782. def test_a1_models_return_true(self):
  783. """Verify A1 model variants return True."""
  784. assert has_stg_cur_idle_bug("A1") is True
  785. assert has_stg_cur_idle_bug("A1 Mini") is True
  786. assert has_stg_cur_idle_bug("A1-Mini") is True
  787. assert has_stg_cur_idle_bug("A1MINI") is True
  788. assert has_stg_cur_idle_bug("a1") is True # case insensitive
  789. assert has_stg_cur_idle_bug("a1 mini") is True
  790. def test_a1_internal_codes_return_true(self):
  791. """Verify A1 internal model codes return True."""
  792. assert has_stg_cur_idle_bug("N1") is True # A1 Mini
  793. assert has_stg_cur_idle_bug("N2S") is True # A1
  794. def test_non_a1_models_return_false(self):
  795. """Verify non-A1 models return False."""
  796. assert has_stg_cur_idle_bug("X1C") is False
  797. assert has_stg_cur_idle_bug("X1") is False
  798. assert has_stg_cur_idle_bug("P1P") is False
  799. assert has_stg_cur_idle_bug("P1S") is False
  800. assert has_stg_cur_idle_bug("H2D") is False
  801. def test_none_model_returns_false(self):
  802. """Verify None model returns False."""
  803. assert has_stg_cur_idle_bug(None) is False
  804. def test_empty_model_returns_false(self):
  805. """Verify empty model returns False."""
  806. assert has_stg_cur_idle_bug("") is False
  807. class TestInitPrinterConnections:
  808. """Tests for init_printer_connections function."""
  809. @pytest.mark.asyncio
  810. async def test_connects_all_active_printers(self):
  811. """Verify all active printers are connected."""
  812. mock_db = AsyncMock()
  813. mock_printer1 = MagicMock(id=1, is_active=True)
  814. mock_printer2 = MagicMock(id=2, is_active=True)
  815. mock_result = MagicMock()
  816. mock_result.scalars.return_value.all.return_value = [mock_printer1, mock_printer2]
  817. mock_db.execute.return_value = mock_result
  818. with patch("backend.app.services.printer_manager.printer_manager") as mock_manager:
  819. mock_manager.connect_printer = AsyncMock()
  820. await init_printer_connections(mock_db)
  821. assert mock_manager.connect_printer.call_count == 2
  822. @pytest.mark.asyncio
  823. async def test_handles_empty_printer_list(self):
  824. """Verify empty printer list is handled."""
  825. mock_db = AsyncMock()
  826. mock_result = MagicMock()
  827. mock_result.scalars.return_value.all.return_value = []
  828. mock_db.execute.return_value = mock_result
  829. with patch("backend.app.services.printer_manager.printer_manager") as mock_manager:
  830. mock_manager.connect_printer = AsyncMock()
  831. await init_printer_connections(mock_db)
  832. mock_manager.connect_printer.assert_not_called()
  833. class TestAmsChangeCallback:
  834. """Tests for AMS change callback functionality."""
  835. @pytest.fixture
  836. def manager(self):
  837. """Create a fresh PrinterManager instance."""
  838. return PrinterManager()
  839. def test_ams_change_callback_is_triggered(self, manager):
  840. """Verify AMS change callback is called when AMS data changes."""
  841. callback = MagicMock()
  842. manager.set_ams_change_callback(callback)
  843. # Verify callback was set
  844. assert manager._on_ams_change == callback
  845. def test_ams_change_callback_receives_correct_data(self, manager):
  846. """Verify AMS change callback receives the correct AMS data format."""
  847. received_data = []
  848. def capture_callback(printer_id, ams_data):
  849. received_data.append((printer_id, ams_data))
  850. manager.set_ams_change_callback(capture_callback)
  851. # The callback should accept printer_id and ams_data
  852. # This tests the callback signature
  853. assert manager._on_ams_change is not None
  854. assert callable(manager._on_ams_change)