test_print_queue_api.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  1. """Integration tests for Print Queue API endpoints."""
  2. import pytest
  3. from httpx import AsyncClient
  4. class TestPrintQueueAPI:
  5. """Integration tests for /api/v1/queue endpoints."""
  6. @pytest.fixture
  7. async def printer_factory(self, db_session):
  8. """Factory to create test printers."""
  9. _counter = [0]
  10. async def _create_printer(**kwargs):
  11. from backend.app.models.printer import Printer
  12. _counter[0] += 1
  13. counter = _counter[0]
  14. defaults = {
  15. "name": f"Test Printer {counter}",
  16. "ip_address": f"192.168.1.{100 + counter}",
  17. "serial_number": f"TESTSERIAL{counter:04d}",
  18. "access_code": "12345678",
  19. "model": "X1C",
  20. }
  21. defaults.update(kwargs)
  22. printer = Printer(**defaults)
  23. db_session.add(printer)
  24. await db_session.commit()
  25. await db_session.refresh(printer)
  26. return printer
  27. return _create_printer
  28. @pytest.fixture
  29. async def archive_factory(self, db_session):
  30. """Factory to create test archives."""
  31. _counter = [0]
  32. async def _create_archive(**kwargs):
  33. from backend.app.models.archive import PrintArchive
  34. _counter[0] += 1
  35. counter = _counter[0]
  36. defaults = {
  37. "filename": f"test_print_{counter}.3mf",
  38. "print_name": f"Test Print {counter}",
  39. "file_path": f"/tmp/test_print_{counter}.3mf",
  40. "file_size": 1024,
  41. "content_hash": f"testhash{counter:08d}",
  42. "status": "completed",
  43. }
  44. defaults.update(kwargs)
  45. archive = PrintArchive(**defaults)
  46. db_session.add(archive)
  47. await db_session.commit()
  48. await db_session.refresh(archive)
  49. return archive
  50. return _create_archive
  51. @pytest.fixture
  52. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  53. """Factory to create test queue items."""
  54. _counter = [0]
  55. async def _create_queue_item(**kwargs):
  56. from backend.app.models.print_queue import PrintQueueItem
  57. _counter[0] += 1
  58. counter = _counter[0]
  59. # Create printer and archive if not provided
  60. if "printer_id" not in kwargs:
  61. printer = await printer_factory()
  62. kwargs["printer_id"] = printer.id
  63. if "archive_id" not in kwargs:
  64. archive = await archive_factory()
  65. kwargs["archive_id"] = archive.id
  66. defaults = {
  67. "status": "pending",
  68. "position": counter,
  69. }
  70. defaults.update(kwargs)
  71. item = PrintQueueItem(**defaults)
  72. db_session.add(item)
  73. await db_session.commit()
  74. await db_session.refresh(item)
  75. return item
  76. return _create_queue_item
  77. @pytest.mark.asyncio
  78. @pytest.mark.integration
  79. async def test_list_queue_empty(self, async_client: AsyncClient):
  80. """Verify empty list when no queue items exist."""
  81. response = await async_client.get("/api/v1/queue/")
  82. assert response.status_code == 200
  83. assert isinstance(response.json(), list)
  84. @pytest.mark.asyncio
  85. @pytest.mark.integration
  86. async def test_add_to_queue(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  87. """Verify item can be added to queue."""
  88. printer = await printer_factory()
  89. archive = await archive_factory()
  90. data = {
  91. "printer_id": printer.id,
  92. "archive_id": archive.id,
  93. }
  94. response = await async_client.post("/api/v1/queue/", json=data)
  95. assert response.status_code == 200
  96. result = response.json()
  97. assert result["printer_id"] == printer.id
  98. assert result["archive_id"] == archive.id
  99. assert result["status"] == "pending"
  100. assert result["manual_start"] is False
  101. @pytest.mark.asyncio
  102. @pytest.mark.integration
  103. async def test_add_to_queue_with_manual_start(
  104. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  105. ):
  106. """Verify item can be added to queue with manual_start=True."""
  107. printer = await printer_factory()
  108. archive = await archive_factory()
  109. data = {
  110. "printer_id": printer.id,
  111. "archive_id": archive.id,
  112. "manual_start": True,
  113. }
  114. response = await async_client.post("/api/v1/queue/", json=data)
  115. assert response.status_code == 200
  116. result = response.json()
  117. assert result["printer_id"] == printer.id
  118. assert result["archive_id"] == archive.id
  119. assert result["status"] == "pending"
  120. assert result["manual_start"] is True
  121. @pytest.mark.asyncio
  122. @pytest.mark.integration
  123. async def test_add_to_queue_with_ams_mapping(
  124. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  125. ):
  126. """Verify item can be added to queue with ams_mapping."""
  127. printer = await printer_factory()
  128. archive = await archive_factory()
  129. data = {
  130. "printer_id": printer.id,
  131. "archive_id": archive.id,
  132. "ams_mapping": [5, -1, 2, -1], # Slot 1 -> tray 5, slot 3 -> tray 2
  133. }
  134. response = await async_client.post("/api/v1/queue/", json=data)
  135. assert response.status_code == 200
  136. result = response.json()
  137. assert result["printer_id"] == printer.id
  138. assert result["archive_id"] == archive.id
  139. assert result["ams_mapping"] == [5, -1, 2, -1]
  140. @pytest.mark.asyncio
  141. @pytest.mark.integration
  142. async def test_add_to_queue_with_plate_id(
  143. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  144. ):
  145. """Verify item can be added to queue with plate_id for multi-plate 3MF."""
  146. printer = await printer_factory()
  147. archive = await archive_factory()
  148. data = {
  149. "printer_id": printer.id,
  150. "archive_id": archive.id,
  151. "plate_id": 3,
  152. }
  153. response = await async_client.post("/api/v1/queue/", json=data)
  154. assert response.status_code == 200
  155. result = response.json()
  156. assert result["plate_id"] == 3
  157. @pytest.mark.asyncio
  158. @pytest.mark.integration
  159. async def test_add_to_queue_with_print_options(
  160. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  161. ):
  162. """Verify item can be added to queue with print options."""
  163. printer = await printer_factory()
  164. archive = await archive_factory()
  165. data = {
  166. "printer_id": printer.id,
  167. "archive_id": archive.id,
  168. "bed_levelling": False,
  169. "flow_cali": True,
  170. "vibration_cali": False,
  171. "layer_inspect": True,
  172. "timelapse": True,
  173. "use_ams": False,
  174. }
  175. response = await async_client.post("/api/v1/queue/", json=data)
  176. assert response.status_code == 200
  177. result = response.json()
  178. assert result["bed_levelling"] is False
  179. assert result["flow_cali"] is True
  180. assert result["vibration_cali"] is False
  181. assert result["layer_inspect"] is True
  182. assert result["timelapse"] is True
  183. assert result["use_ams"] is False
  184. @pytest.mark.asyncio
  185. @pytest.mark.integration
  186. async def test_update_queue_item_plate_id(self, async_client: AsyncClient, queue_item_factory, db_session):
  187. """Verify queue item plate_id can be updated."""
  188. item = await queue_item_factory()
  189. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"plate_id": 5})
  190. assert response.status_code == 200
  191. result = response.json()
  192. assert result["plate_id"] == 5
  193. @pytest.mark.asyncio
  194. @pytest.mark.integration
  195. async def test_update_queue_item_print_options(self, async_client: AsyncClient, queue_item_factory, db_session):
  196. """Verify queue item print options can be updated."""
  197. item = await queue_item_factory()
  198. response = await async_client.patch(
  199. f"/api/v1/queue/{item.id}",
  200. json={
  201. "bed_levelling": False,
  202. "timelapse": True,
  203. },
  204. )
  205. assert response.status_code == 200
  206. result = response.json()
  207. assert result["bed_levelling"] is False
  208. assert result["timelapse"] is True
  209. @pytest.mark.asyncio
  210. @pytest.mark.integration
  211. async def test_get_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  212. """Verify single queue item can be retrieved."""
  213. item = await queue_item_factory()
  214. response = await async_client.get(f"/api/v1/queue/{item.id}")
  215. assert response.status_code == 200
  216. assert response.json()["id"] == item.id
  217. @pytest.mark.asyncio
  218. @pytest.mark.integration
  219. async def test_get_queue_item_not_found(self, async_client: AsyncClient):
  220. """Verify 404 for non-existent queue item."""
  221. response = await async_client.get("/api/v1/queue/9999")
  222. assert response.status_code == 404
  223. @pytest.mark.asyncio
  224. @pytest.mark.integration
  225. async def test_update_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  226. """Verify queue item can be updated."""
  227. item = await queue_item_factory()
  228. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"auto_off_after": True})
  229. assert response.status_code == 200
  230. result = response.json()
  231. assert result["auto_off_after"] is True
  232. @pytest.mark.asyncio
  233. @pytest.mark.integration
  234. async def test_update_queue_item_manual_start(self, async_client: AsyncClient, queue_item_factory, db_session):
  235. """Verify queue item manual_start can be updated."""
  236. item = await queue_item_factory(manual_start=False)
  237. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"manual_start": True})
  238. assert response.status_code == 200
  239. result = response.json()
  240. assert result["manual_start"] is True
  241. @pytest.mark.asyncio
  242. @pytest.mark.integration
  243. async def test_delete_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  244. """Verify queue item can be deleted."""
  245. item = await queue_item_factory()
  246. response = await async_client.delete(f"/api/v1/queue/{item.id}")
  247. assert response.status_code == 200
  248. assert response.json()["message"] == "Queue item deleted"
  249. @pytest.mark.asyncio
  250. @pytest.mark.integration
  251. async def test_delete_queue_item_not_found(self, async_client: AsyncClient):
  252. """Verify 404 for deleting non-existent queue item."""
  253. response = await async_client.delete("/api/v1/queue/9999")
  254. assert response.status_code == 404
  255. class TestQueueStartEndpoint:
  256. """Tests for the /queue/{item_id}/start endpoint."""
  257. @pytest.fixture
  258. async def printer_factory(self, db_session):
  259. """Factory to create test printers."""
  260. _counter = [0]
  261. async def _create_printer(**kwargs):
  262. from backend.app.models.printer import Printer
  263. _counter[0] += 1
  264. counter = _counter[0]
  265. defaults = {
  266. "name": f"Test Printer {counter}",
  267. "ip_address": f"192.168.1.{100 + counter}",
  268. "serial_number": f"TESTSERIAL{counter:04d}",
  269. "access_code": "12345678",
  270. "model": "X1C",
  271. }
  272. defaults.update(kwargs)
  273. printer = Printer(**defaults)
  274. db_session.add(printer)
  275. await db_session.commit()
  276. await db_session.refresh(printer)
  277. return printer
  278. return _create_printer
  279. @pytest.fixture
  280. async def archive_factory(self, db_session):
  281. """Factory to create test archives."""
  282. _counter = [0]
  283. async def _create_archive(**kwargs):
  284. from backend.app.models.archive import PrintArchive
  285. _counter[0] += 1
  286. counter = _counter[0]
  287. defaults = {
  288. "filename": f"test_print_{counter}.3mf",
  289. "print_name": f"Test Print {counter}",
  290. "file_path": f"/tmp/test_print_{counter}.3mf",
  291. "file_size": 1024,
  292. "content_hash": f"testhash{counter:08d}",
  293. "status": "completed",
  294. }
  295. defaults.update(kwargs)
  296. archive = PrintArchive(**defaults)
  297. db_session.add(archive)
  298. await db_session.commit()
  299. await db_session.refresh(archive)
  300. return archive
  301. return _create_archive
  302. @pytest.fixture
  303. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  304. """Factory to create test queue items."""
  305. _counter = [0]
  306. async def _create_queue_item(**kwargs):
  307. from backend.app.models.print_queue import PrintQueueItem
  308. _counter[0] += 1
  309. counter = _counter[0]
  310. if "printer_id" not in kwargs:
  311. printer = await printer_factory()
  312. kwargs["printer_id"] = printer.id
  313. if "archive_id" not in kwargs:
  314. archive = await archive_factory()
  315. kwargs["archive_id"] = archive.id
  316. defaults = {
  317. "status": "pending",
  318. "position": counter,
  319. }
  320. defaults.update(kwargs)
  321. item = PrintQueueItem(**defaults)
  322. db_session.add(item)
  323. await db_session.commit()
  324. await db_session.refresh(item)
  325. return item
  326. return _create_queue_item
  327. @pytest.mark.asyncio
  328. @pytest.mark.integration
  329. async def test_start_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  330. """Verify starting a staged (manual_start=True) queue item clears the flag."""
  331. item = await queue_item_factory(manual_start=True)
  332. assert item.manual_start is True
  333. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  334. assert response.status_code == 200
  335. result = response.json()
  336. assert result["manual_start"] is False
  337. assert result["status"] == "pending"
  338. @pytest.mark.asyncio
  339. @pytest.mark.integration
  340. async def test_start_non_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  341. """Verify starting a non-staged queue item still works (idempotent)."""
  342. item = await queue_item_factory(manual_start=False)
  343. assert item.manual_start is False
  344. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  345. assert response.status_code == 200
  346. result = response.json()
  347. assert result["manual_start"] is False
  348. @pytest.mark.asyncio
  349. @pytest.mark.integration
  350. async def test_start_queue_item_not_found(self, async_client: AsyncClient):
  351. """Verify 404 for non-existent queue item."""
  352. response = await async_client.post("/api/v1/queue/9999/start")
  353. assert response.status_code == 404
  354. @pytest.mark.asyncio
  355. @pytest.mark.integration
  356. async def test_start_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  357. """Verify 400 error when trying to start a non-pending queue item."""
  358. item = await queue_item_factory(status="printing", manual_start=True)
  359. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  360. assert response.status_code == 400
  361. assert "pending" in response.json()["detail"].lower()
  362. @pytest.mark.asyncio
  363. @pytest.mark.integration
  364. async def test_start_completed_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  365. """Verify 400 error when trying to start a completed queue item."""
  366. item = await queue_item_factory(status="completed", manual_start=True)
  367. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  368. assert response.status_code == 400
  369. class TestQueueCancelEndpoint:
  370. """Tests for the /queue/{item_id}/cancel endpoint."""
  371. @pytest.fixture
  372. async def printer_factory(self, db_session):
  373. """Factory to create test printers."""
  374. async def _create_printer(**kwargs):
  375. from backend.app.models.printer import Printer
  376. defaults = {
  377. "name": "Cancel Test Printer",
  378. "ip_address": "192.168.1.200",
  379. "serial_number": "TESTCANCEL001",
  380. "access_code": "12345678",
  381. "model": "X1C",
  382. }
  383. defaults.update(kwargs)
  384. printer = Printer(**defaults)
  385. db_session.add(printer)
  386. await db_session.commit()
  387. await db_session.refresh(printer)
  388. return printer
  389. return _create_printer
  390. @pytest.fixture
  391. async def archive_factory(self, db_session):
  392. """Factory to create test archives."""
  393. async def _create_archive(**kwargs):
  394. from backend.app.models.archive import PrintArchive
  395. defaults = {
  396. "filename": "cancel_test.3mf",
  397. "print_name": "Cancel Test Print",
  398. "file_path": "/tmp/cancel_test.3mf",
  399. "file_size": 1024,
  400. "content_hash": "cancelhash001",
  401. "status": "completed",
  402. }
  403. defaults.update(kwargs)
  404. archive = PrintArchive(**defaults)
  405. db_session.add(archive)
  406. await db_session.commit()
  407. await db_session.refresh(archive)
  408. return archive
  409. return _create_archive
  410. @pytest.fixture
  411. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  412. """Factory to create test queue items."""
  413. async def _create_queue_item(**kwargs):
  414. from backend.app.models.print_queue import PrintQueueItem
  415. if "printer_id" not in kwargs:
  416. printer = await printer_factory()
  417. kwargs["printer_id"] = printer.id
  418. if "archive_id" not in kwargs:
  419. archive = await archive_factory()
  420. kwargs["archive_id"] = archive.id
  421. defaults = {
  422. "status": "pending",
  423. "position": 1,
  424. }
  425. defaults.update(kwargs)
  426. item = PrintQueueItem(**defaults)
  427. db_session.add(item)
  428. await db_session.commit()
  429. await db_session.refresh(item)
  430. return item
  431. return _create_queue_item
  432. @pytest.mark.asyncio
  433. @pytest.mark.integration
  434. async def test_cancel_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  435. """Verify cancelling a pending queue item."""
  436. item = await queue_item_factory(status="pending")
  437. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  438. assert response.status_code == 200
  439. assert response.json()["message"] == "Queue item cancelled"
  440. @pytest.mark.asyncio
  441. @pytest.mark.integration
  442. async def test_cancel_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  443. """Verify 400 error when trying to cancel a non-pending queue item."""
  444. item = await queue_item_factory(status="printing")
  445. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  446. assert response.status_code == 400
  447. class TestQueueLibraryFileSupport:
  448. """Tests for queue items with library_file_id (instead of archive_id)."""
  449. @pytest.fixture
  450. async def printer_factory(self, db_session):
  451. """Factory to create test printers."""
  452. _counter = [0]
  453. async def _create_printer(**kwargs):
  454. from backend.app.models.printer import Printer
  455. _counter[0] += 1
  456. counter = _counter[0]
  457. defaults = {
  458. "name": f"Library Test Printer {counter}",
  459. "ip_address": f"192.168.1.{150 + counter}",
  460. "serial_number": f"TESTLIB{counter:04d}",
  461. "access_code": "12345678",
  462. "model": "X1C",
  463. }
  464. defaults.update(kwargs)
  465. printer = Printer(**defaults)
  466. db_session.add(printer)
  467. await db_session.commit()
  468. await db_session.refresh(printer)
  469. return printer
  470. return _create_printer
  471. @pytest.fixture
  472. async def library_file_factory(self, db_session):
  473. """Factory to create test library files."""
  474. _counter = [0]
  475. async def _create_library_file(**kwargs):
  476. from backend.app.models.library import LibraryFile
  477. _counter[0] += 1
  478. counter = _counter[0]
  479. defaults = {
  480. "filename": f"library_test_{counter}.3mf",
  481. "file_path": f"/test/library/library_test_{counter}.3mf",
  482. "file_size": 2048,
  483. "file_type": "3mf",
  484. "file_metadata": {"print_name": f"Library Print {counter}", "print_time_seconds": 3600},
  485. }
  486. defaults.update(kwargs)
  487. lib_file = LibraryFile(**defaults)
  488. db_session.add(lib_file)
  489. await db_session.commit()
  490. await db_session.refresh(lib_file)
  491. return lib_file
  492. return _create_library_file
  493. @pytest.mark.asyncio
  494. @pytest.mark.integration
  495. async def test_add_to_queue_with_library_file(
  496. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  497. ):
  498. """Verify item can be added to queue using library_file_id instead of archive_id."""
  499. printer = await printer_factory()
  500. lib_file = await library_file_factory()
  501. data = {
  502. "printer_id": printer.id,
  503. "library_file_id": lib_file.id,
  504. }
  505. response = await async_client.post("/api/v1/queue/", json=data)
  506. assert response.status_code == 200
  507. result = response.json()
  508. assert result["printer_id"] == printer.id
  509. assert result["library_file_id"] == lib_file.id
  510. assert result["archive_id"] is None
  511. assert result["status"] == "pending"
  512. assert result["library_file_name"] == "Library Print 1"
  513. assert result["print_time_seconds"] == 3600
  514. @pytest.mark.asyncio
  515. @pytest.mark.integration
  516. async def test_add_to_queue_library_file_with_options(
  517. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  518. ):
  519. """Verify library file queue item can have all options set."""
  520. printer = await printer_factory()
  521. lib_file = await library_file_factory()
  522. data = {
  523. "printer_id": printer.id,
  524. "library_file_id": lib_file.id,
  525. "ams_mapping": [1, 2, -1, -1],
  526. "plate_id": 2,
  527. "bed_levelling": False,
  528. "timelapse": True,
  529. "manual_start": True,
  530. }
  531. response = await async_client.post("/api/v1/queue/", json=data)
  532. assert response.status_code == 200
  533. result = response.json()
  534. assert result["library_file_id"] == lib_file.id
  535. assert result["ams_mapping"] == [1, 2, -1, -1]
  536. assert result["plate_id"] == 2
  537. assert result["bed_levelling"] is False
  538. assert result["timelapse"] is True
  539. assert result["manual_start"] is True
  540. @pytest.mark.asyncio
  541. @pytest.mark.integration
  542. async def test_add_to_queue_requires_archive_or_library_file(
  543. self, async_client: AsyncClient, printer_factory, db_session
  544. ):
  545. """Verify 400 error when neither archive_id nor library_file_id provided."""
  546. printer = await printer_factory()
  547. data = {
  548. "printer_id": printer.id,
  549. }
  550. response = await async_client.post("/api/v1/queue/", json=data)
  551. assert response.status_code == 400
  552. assert (
  553. "archive_id" in response.json()["detail"].lower() or "library_file_id" in response.json()["detail"].lower()
  554. )
  555. @pytest.mark.asyncio
  556. @pytest.mark.integration
  557. async def test_update_queue_item_with_library_file(
  558. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  559. ):
  560. """Verify queue item with library_file_id can be updated."""
  561. from backend.app.models.print_queue import PrintQueueItem
  562. printer = await printer_factory()
  563. lib_file = await library_file_factory()
  564. # Create queue item directly
  565. item = PrintQueueItem(
  566. printer_id=printer.id,
  567. library_file_id=lib_file.id,
  568. status="pending",
  569. position=1,
  570. )
  571. db_session.add(item)
  572. await db_session.commit()
  573. await db_session.refresh(item)
  574. # Update the item
  575. response = await async_client.patch(
  576. f"/api/v1/queue/{item.id}",
  577. json={"auto_off_after": True, "plate_id": 3},
  578. )
  579. assert response.status_code == 200
  580. result = response.json()
  581. assert result["auto_off_after"] is True
  582. assert result["plate_id"] == 3
  583. assert result["library_file_id"] == lib_file.id
  584. @pytest.mark.asyncio
  585. @pytest.mark.integration
  586. async def test_list_queue_includes_library_file_info(
  587. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  588. ):
  589. """Verify queue list includes library file metadata."""
  590. from backend.app.models.print_queue import PrintQueueItem
  591. printer = await printer_factory()
  592. lib_file = await library_file_factory(
  593. file_metadata={"print_name": "Custom Print Name", "print_time_seconds": 7200}
  594. )
  595. item = PrintQueueItem(
  596. printer_id=printer.id,
  597. library_file_id=lib_file.id,
  598. status="pending",
  599. position=1,
  600. )
  601. db_session.add(item)
  602. await db_session.commit()
  603. response = await async_client.get("/api/v1/queue/")
  604. assert response.status_code == 200
  605. items = response.json()
  606. assert len(items) >= 1
  607. # Find our item
  608. our_item = next((i for i in items if i["library_file_id"] == lib_file.id), None)
  609. assert our_item is not None
  610. assert our_item["library_file_name"] == "Custom Print Name"
  611. assert our_item["print_time_seconds"] == 7200
  612. class TestBulkUpdateEndpoint:
  613. """Tests for the /queue/bulk endpoint."""
  614. @pytest.fixture
  615. async def printer_factory(self, db_session):
  616. """Factory to create test printers."""
  617. _counter = [0]
  618. async def _create_printer(**kwargs):
  619. from backend.app.models.printer import Printer
  620. _counter[0] += 1
  621. counter = _counter[0]
  622. defaults = {
  623. "name": f"Bulk Test Printer {counter}",
  624. "ip_address": f"192.168.1.{150 + counter}",
  625. "serial_number": f"TESTBULK{counter:04d}",
  626. "access_code": "12345678",
  627. "model": "X1C",
  628. }
  629. defaults.update(kwargs)
  630. printer = Printer(**defaults)
  631. db_session.add(printer)
  632. await db_session.commit()
  633. await db_session.refresh(printer)
  634. return printer
  635. return _create_printer
  636. @pytest.fixture
  637. async def archive_factory(self, db_session):
  638. """Factory to create test archives."""
  639. _counter = [0]
  640. async def _create_archive(**kwargs):
  641. from backend.app.models.archive import PrintArchive
  642. _counter[0] += 1
  643. counter = _counter[0]
  644. defaults = {
  645. "filename": f"bulk_test_{counter}.3mf",
  646. "print_name": f"Bulk Test Print {counter}",
  647. "file_path": f"/tmp/bulk_test_{counter}.3mf",
  648. "file_size": 1024,
  649. "content_hash": f"bulkhash{counter:04d}",
  650. "status": "completed",
  651. }
  652. defaults.update(kwargs)
  653. archive = PrintArchive(**defaults)
  654. db_session.add(archive)
  655. await db_session.commit()
  656. await db_session.refresh(archive)
  657. return archive
  658. return _create_archive
  659. @pytest.fixture
  660. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  661. """Factory to create test queue items."""
  662. async def _create_item(**kwargs):
  663. from backend.app.models.print_queue import PrintQueueItem
  664. if "printer_id" not in kwargs:
  665. printer = await printer_factory()
  666. kwargs["printer_id"] = printer.id
  667. if "archive_id" not in kwargs:
  668. archive = await archive_factory()
  669. kwargs["archive_id"] = archive.id
  670. defaults = {
  671. "status": "pending",
  672. "position": 1,
  673. "bed_levelling": True,
  674. "flow_cali": False,
  675. "vibration_cali": True,
  676. }
  677. defaults.update(kwargs)
  678. item = PrintQueueItem(**defaults)
  679. db_session.add(item)
  680. await db_session.commit()
  681. await db_session.refresh(item)
  682. return item
  683. return _create_item
  684. @pytest.mark.asyncio
  685. @pytest.mark.integration
  686. async def test_bulk_update_single_field(self, async_client: AsyncClient, queue_item_factory, db_session):
  687. """Verify bulk update can change a single field on multiple items."""
  688. item1 = await queue_item_factory(bed_levelling=True)
  689. item2 = await queue_item_factory(bed_levelling=True)
  690. response = await async_client.patch(
  691. "/api/v1/queue/bulk",
  692. json={"item_ids": [item1.id, item2.id], "bed_levelling": False},
  693. )
  694. assert response.status_code == 200
  695. result = response.json()
  696. assert result["updated_count"] == 2
  697. assert result["skipped_count"] == 0
  698. # Verify items were updated
  699. await db_session.refresh(item1)
  700. await db_session.refresh(item2)
  701. assert item1.bed_levelling is False
  702. assert item2.bed_levelling is False
  703. @pytest.mark.asyncio
  704. @pytest.mark.integration
  705. async def test_bulk_update_multiple_fields(self, async_client: AsyncClient, queue_item_factory, db_session):
  706. """Verify bulk update can change multiple fields at once."""
  707. item1 = await queue_item_factory(bed_levelling=True, flow_cali=False, manual_start=False)
  708. item2 = await queue_item_factory(bed_levelling=True, flow_cali=False, manual_start=False)
  709. response = await async_client.patch(
  710. "/api/v1/queue/bulk",
  711. json={
  712. "item_ids": [item1.id, item2.id],
  713. "bed_levelling": False,
  714. "flow_cali": True,
  715. "manual_start": True,
  716. },
  717. )
  718. assert response.status_code == 200
  719. result = response.json()
  720. assert result["updated_count"] == 2
  721. await db_session.refresh(item1)
  722. assert item1.bed_levelling is False
  723. assert item1.flow_cali is True
  724. assert item1.manual_start is True
  725. @pytest.mark.asyncio
  726. @pytest.mark.integration
  727. async def test_bulk_update_skips_non_pending(self, async_client: AsyncClient, queue_item_factory, db_session):
  728. """Verify bulk update skips non-pending items."""
  729. pending_item = await queue_item_factory(status="pending", bed_levelling=True)
  730. printing_item = await queue_item_factory(status="printing", bed_levelling=True)
  731. completed_item = await queue_item_factory(status="completed", bed_levelling=True)
  732. response = await async_client.patch(
  733. "/api/v1/queue/bulk",
  734. json={
  735. "item_ids": [pending_item.id, printing_item.id, completed_item.id],
  736. "bed_levelling": False,
  737. },
  738. )
  739. assert response.status_code == 200
  740. result = response.json()
  741. assert result["updated_count"] == 1
  742. assert result["skipped_count"] == 2
  743. # Only pending item should be updated
  744. await db_session.refresh(pending_item)
  745. await db_session.refresh(printing_item)
  746. await db_session.refresh(completed_item)
  747. assert pending_item.bed_levelling is False
  748. assert printing_item.bed_levelling is True
  749. assert completed_item.bed_levelling is True
  750. @pytest.mark.asyncio
  751. @pytest.mark.integration
  752. async def test_bulk_update_change_printer(
  753. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  754. ):
  755. """Verify bulk update can reassign items to a different printer."""
  756. new_printer = await printer_factory(name="New Target Printer")
  757. item1 = await queue_item_factory()
  758. item2 = await queue_item_factory()
  759. original_printer_id = item1.printer_id
  760. response = await async_client.patch(
  761. "/api/v1/queue/bulk",
  762. json={"item_ids": [item1.id, item2.id], "printer_id": new_printer.id},
  763. )
  764. assert response.status_code == 200
  765. await db_session.refresh(item1)
  766. await db_session.refresh(item2)
  767. assert item1.printer_id == new_printer.id
  768. assert item2.printer_id == new_printer.id
  769. assert item1.printer_id != original_printer_id
  770. @pytest.mark.asyncio
  771. @pytest.mark.integration
  772. async def test_bulk_update_empty_item_ids(self, async_client: AsyncClient):
  773. """Verify 400 error when item_ids is empty."""
  774. response = await async_client.patch(
  775. "/api/v1/queue/bulk",
  776. json={"item_ids": [], "bed_levelling": False},
  777. )
  778. assert response.status_code == 400
  779. assert "no item" in response.json()["detail"].lower()
  780. @pytest.mark.asyncio
  781. @pytest.mark.integration
  782. async def test_bulk_update_no_fields(self, async_client: AsyncClient, queue_item_factory):
  783. """Verify 400 error when no fields to update."""
  784. item = await queue_item_factory()
  785. response = await async_client.patch(
  786. "/api/v1/queue/bulk",
  787. json={"item_ids": [item.id]},
  788. )
  789. assert response.status_code == 400
  790. assert "no fields" in response.json()["detail"].lower()
  791. @pytest.mark.asyncio
  792. @pytest.mark.integration
  793. async def test_bulk_update_invalid_printer(self, async_client: AsyncClient, queue_item_factory):
  794. """Verify 400 error when printer_id doesn't exist."""
  795. item = await queue_item_factory()
  796. response = await async_client.patch(
  797. "/api/v1/queue/bulk",
  798. json={"item_ids": [item.id], "printer_id": 99999},
  799. )
  800. assert response.status_code == 400
  801. assert "printer not found" in response.json()["detail"].lower()
  802. class TestTargetLocationFeature:
  803. """Tests for queue items with target_location (Issue #220)."""
  804. @pytest.fixture
  805. async def printer_factory(self, db_session):
  806. """Factory to create test printers."""
  807. _counter = [0]
  808. async def _create_printer(**kwargs):
  809. from backend.app.models.printer import Printer
  810. _counter[0] += 1
  811. counter = _counter[0]
  812. defaults = {
  813. "name": f"Location Test Printer {counter}",
  814. "ip_address": f"192.168.1.{50 + counter}",
  815. "serial_number": f"TESTLOC{counter:04d}",
  816. "access_code": "12345678",
  817. "model": "X1C",
  818. }
  819. defaults.update(kwargs)
  820. printer = Printer(**defaults)
  821. db_session.add(printer)
  822. await db_session.commit()
  823. await db_session.refresh(printer)
  824. return printer
  825. return _create_printer
  826. @pytest.fixture
  827. async def archive_factory(self, db_session):
  828. """Factory to create test archives."""
  829. _counter = [0]
  830. async def _create_archive(**kwargs):
  831. from backend.app.models.archive import PrintArchive
  832. _counter[0] += 1
  833. counter = _counter[0]
  834. defaults = {
  835. "filename": f"location_test_{counter}.3mf",
  836. "print_name": f"Location Test Print {counter}",
  837. "file_path": f"/tmp/location_test_{counter}.3mf",
  838. "file_size": 1024,
  839. "content_hash": f"lochash{counter:08d}",
  840. "status": "completed",
  841. }
  842. defaults.update(kwargs)
  843. archive = PrintArchive(**defaults)
  844. db_session.add(archive)
  845. await db_session.commit()
  846. await db_session.refresh(archive)
  847. return archive
  848. return _create_archive
  849. @pytest.fixture
  850. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  851. """Factory to create test queue items."""
  852. _counter = [0]
  853. async def _create_queue_item(**kwargs):
  854. from backend.app.models.print_queue import PrintQueueItem
  855. _counter[0] += 1
  856. counter = _counter[0]
  857. if "printer_id" not in kwargs and "target_model" not in kwargs:
  858. printer = await printer_factory()
  859. kwargs["printer_id"] = printer.id
  860. if "archive_id" not in kwargs:
  861. archive = await archive_factory()
  862. kwargs["archive_id"] = archive.id
  863. defaults = {
  864. "status": "pending",
  865. "position": counter,
  866. }
  867. defaults.update(kwargs)
  868. item = PrintQueueItem(**defaults)
  869. db_session.add(item)
  870. await db_session.commit()
  871. await db_session.refresh(item)
  872. return item
  873. return _create_queue_item
  874. @pytest.mark.asyncio
  875. @pytest.mark.integration
  876. async def test_add_to_queue_with_target_location(
  877. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  878. ):
  879. """Verify item can be added with target_model and target_location."""
  880. # Create a printer with model X1C so the API can validate
  881. await printer_factory(model="X1C", location="Office")
  882. archive = await archive_factory()
  883. data = {
  884. "target_model": "X1C",
  885. "target_location": "Workbench",
  886. "archive_id": archive.id,
  887. }
  888. response = await async_client.post("/api/v1/queue/", json=data)
  889. assert response.status_code == 200
  890. result = response.json()
  891. assert result["target_model"] == "X1C"
  892. assert result["target_location"] == "Workbench"
  893. assert result["printer_id"] is None
  894. @pytest.mark.asyncio
  895. @pytest.mark.integration
  896. async def test_add_to_queue_location_without_model_ignored(
  897. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  898. ):
  899. """Verify target_location without target_model is allowed (location is just ignored)."""
  900. printer = await printer_factory()
  901. archive = await archive_factory()
  902. data = {
  903. "printer_id": printer.id,
  904. "target_location": "Workbench", # This gets ignored since printer_id is set
  905. "archive_id": archive.id,
  906. }
  907. response = await async_client.post("/api/v1/queue/", json=data)
  908. # The API accepts this but the location is only used with target_model
  909. assert response.status_code == 200
  910. result = response.json()
  911. assert result["printer_id"] == printer.id
  912. # Location may or may not be stored since it's meaningless without target_model
  913. # The important thing is the request succeeds
  914. @pytest.mark.asyncio
  915. @pytest.mark.integration
  916. async def test_queue_item_target_location_in_response(
  917. self, async_client: AsyncClient, queue_item_factory, db_session
  918. ):
  919. """Verify target_location is returned in queue item response."""
  920. item = await queue_item_factory(
  921. printer_id=None,
  922. target_model="X1C",
  923. target_location="Workshop",
  924. )
  925. response = await async_client.get(f"/api/v1/queue/{item.id}")
  926. assert response.status_code == 200
  927. result = response.json()
  928. assert result["target_model"] == "X1C"
  929. assert result["target_location"] == "Workshop"
  930. @pytest.mark.asyncio
  931. @pytest.mark.integration
  932. async def test_queue_list_includes_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  933. """Verify target_location is included in queue list."""
  934. await queue_item_factory(
  935. printer_id=None,
  936. target_model="P1S",
  937. target_location="Garage",
  938. )
  939. response = await async_client.get("/api/v1/queue/")
  940. assert response.status_code == 200
  941. items = response.json()
  942. assert len(items) >= 1
  943. # Find our item
  944. our_item = next((i for i in items if i["target_location"] == "Garage"), None)
  945. assert our_item is not None
  946. assert our_item["target_model"] == "P1S"
  947. @pytest.mark.asyncio
  948. @pytest.mark.integration
  949. async def test_update_queue_item_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  950. """Verify target_location can be updated on existing queue item."""
  951. item = await queue_item_factory(
  952. printer_id=None,
  953. target_model="X1C",
  954. target_location="Office",
  955. )
  956. response = await async_client.patch(
  957. f"/api/v1/queue/{item.id}",
  958. json={"target_location": "Basement"},
  959. )
  960. assert response.status_code == 200
  961. result = response.json()
  962. assert result["target_location"] == "Basement"
  963. @pytest.mark.asyncio
  964. @pytest.mark.integration
  965. async def test_clear_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  966. """Verify target_location can be cleared (set to None)."""
  967. item = await queue_item_factory(
  968. printer_id=None,
  969. target_model="X1C",
  970. target_location="Office",
  971. )
  972. # Note: Setting to empty string should clear it
  973. response = await async_client.patch(
  974. f"/api/v1/queue/{item.id}",
  975. json={"target_location": None},
  976. )
  977. assert response.status_code == 200
  978. result = response.json()
  979. assert result["target_location"] is None
  980. class TestAbortedStatusNormalisation:
  981. """Tests for issue #558: 'aborted' queue status causes 500 error."""
  982. @pytest.fixture
  983. async def printer_factory(self, db_session):
  984. """Factory to create test printers."""
  985. _counter = [0]
  986. async def _create_printer(**kwargs):
  987. from backend.app.models.printer import Printer
  988. _counter[0] += 1
  989. counter = _counter[0]
  990. defaults = {
  991. "name": f"Abort Test Printer {counter}",
  992. "ip_address": f"192.168.1.{60 + counter}",
  993. "serial_number": f"TESTABORT{counter:04d}",
  994. "access_code": "12345678",
  995. "model": "P1S",
  996. }
  997. defaults.update(kwargs)
  998. printer = Printer(**defaults)
  999. db_session.add(printer)
  1000. await db_session.commit()
  1001. await db_session.refresh(printer)
  1002. return printer
  1003. return _create_printer
  1004. @pytest.fixture
  1005. async def archive_factory(self, db_session):
  1006. """Factory to create test archives."""
  1007. _counter = [0]
  1008. async def _create_archive(**kwargs):
  1009. from backend.app.models.archive import PrintArchive
  1010. _counter[0] += 1
  1011. counter = _counter[0]
  1012. defaults = {
  1013. "filename": f"abort_test_{counter}.3mf",
  1014. "print_name": f"Abort Test Print {counter}",
  1015. "file_path": f"/tmp/abort_test_{counter}.3mf",
  1016. "file_size": 1024,
  1017. "content_hash": f"aborthash{counter:06d}",
  1018. "status": "completed",
  1019. }
  1020. defaults.update(kwargs)
  1021. archive = PrintArchive(**defaults)
  1022. db_session.add(archive)
  1023. await db_session.commit()
  1024. await db_session.refresh(archive)
  1025. return archive
  1026. return _create_archive
  1027. @pytest.fixture
  1028. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1029. """Factory to create test queue items."""
  1030. _counter = [0]
  1031. async def _create_queue_item(**kwargs):
  1032. from backend.app.models.print_queue import PrintQueueItem
  1033. _counter[0] += 1
  1034. counter = _counter[0]
  1035. if "printer_id" not in kwargs:
  1036. printer = await printer_factory()
  1037. kwargs["printer_id"] = printer.id
  1038. if "archive_id" not in kwargs:
  1039. archive = await archive_factory()
  1040. kwargs["archive_id"] = archive.id
  1041. defaults = {
  1042. "status": "pending",
  1043. "position": counter,
  1044. }
  1045. defaults.update(kwargs)
  1046. item = PrintQueueItem(**defaults)
  1047. db_session.add(item)
  1048. await db_session.commit()
  1049. await db_session.refresh(item)
  1050. return item
  1051. return _create_queue_item
  1052. @pytest.mark.asyncio
  1053. @pytest.mark.integration
  1054. async def test_on_print_complete_normalises_aborted_to_cancelled(self, queue_item_factory, db_session):
  1055. """Verify the completion handler maps 'aborted' → 'cancelled' for queue items."""
  1056. import asyncio
  1057. from unittest.mock import AsyncMock, MagicMock, patch
  1058. item = await queue_item_factory(status="printing")
  1059. # Build a mock session whose execute returns our item
  1060. mock_result = MagicMock()
  1061. mock_result.scalars.return_value.all.return_value = [item]
  1062. mock_session = AsyncMock()
  1063. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1064. mock_session.__aexit__ = AsyncMock(return_value=False)
  1065. mock_session.execute = AsyncMock(return_value=mock_result)
  1066. mock_session.commit = AsyncMock()
  1067. tasks_before = set(asyncio.all_tasks())
  1068. with (
  1069. patch("backend.app.main.async_session", return_value=mock_session),
  1070. patch("backend.app.main.ws_manager") as mock_ws,
  1071. patch("backend.app.main.mqtt_relay") as mock_relay,
  1072. patch("backend.app.main.notification_service") as mock_notif,
  1073. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1074. patch("backend.app.main.printer_manager") as mock_pm,
  1075. ):
  1076. mock_ws.send_print_complete = AsyncMock()
  1077. mock_ws.broadcast = AsyncMock()
  1078. mock_relay.on_print_complete = AsyncMock()
  1079. mock_relay.on_queue_job_completed = AsyncMock()
  1080. mock_notif.on_print_complete = AsyncMock()
  1081. mock_plug.on_print_complete = AsyncMock()
  1082. mock_pm.get_printer.return_value = None
  1083. from backend.app.main import on_print_complete
  1084. await on_print_complete(
  1085. item.printer_id,
  1086. {
  1087. "status": "aborted",
  1088. "filename": "test.gcode",
  1089. "subtask_name": "Test",
  1090. "timelapse_was_active": False,
  1091. },
  1092. )
  1093. # Cancel background tasks before leaving mock context
  1094. for task in asyncio.all_tasks() - tasks_before:
  1095. task.cancel()
  1096. try:
  1097. await task
  1098. except (asyncio.CancelledError, Exception):
  1099. pass
  1100. # The item status should be normalised to 'cancelled', not 'aborted'
  1101. assert item.status == "cancelled"
  1102. @pytest.mark.asyncio
  1103. @pytest.mark.integration
  1104. async def test_startup_fixup_converts_aborted_to_cancelled(self, queue_item_factory, db_session):
  1105. """Verify the startup fixup converts existing 'aborted' rows to 'cancelled'."""
  1106. from sqlalchemy import select
  1107. from backend.app.models.print_queue import PrintQueueItem
  1108. # Create items with various statuses including 'aborted'
  1109. item_aborted = await queue_item_factory(status="pending")
  1110. item_pending = await queue_item_factory(status="pending")
  1111. # Manually set the invalid status
  1112. item_aborted.status = "aborted"
  1113. db_session.add(item_aborted)
  1114. await db_session.commit()
  1115. # Run the fixup query (same logic as lifespan)
  1116. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1117. aborted_items = result.scalars().all()
  1118. for i in aborted_items:
  1119. i.status = "cancelled"
  1120. await db_session.commit()
  1121. # Verify: no more 'aborted' items
  1122. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1123. assert len(result.scalars().all()) == 0
  1124. # The previously aborted item should now be 'cancelled'
  1125. await db_session.refresh(item_aborted)
  1126. assert item_aborted.status == "cancelled"
  1127. # The pending item should be unchanged
  1128. await db_session.refresh(item_pending)
  1129. assert item_pending.status == "pending"
  1130. @pytest.mark.asyncio
  1131. @pytest.mark.integration
  1132. async def test_completed_status_passes_through_unchanged(self, queue_item_factory, db_session):
  1133. """Verify normal statuses like 'completed' are not affected by normalisation."""
  1134. import asyncio
  1135. from unittest.mock import AsyncMock, MagicMock, patch
  1136. item = await queue_item_factory(status="printing")
  1137. mock_result = MagicMock()
  1138. mock_result.scalars.return_value.all.return_value = [item]
  1139. mock_session = AsyncMock()
  1140. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1141. mock_session.__aexit__ = AsyncMock(return_value=False)
  1142. mock_session.execute = AsyncMock(return_value=mock_result)
  1143. mock_session.commit = AsyncMock()
  1144. tasks_before = set(asyncio.all_tasks())
  1145. with (
  1146. patch("backend.app.main.async_session", return_value=mock_session),
  1147. patch("backend.app.main.ws_manager") as mock_ws,
  1148. patch("backend.app.main.mqtt_relay") as mock_relay,
  1149. patch("backend.app.main.notification_service") as mock_notif,
  1150. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1151. patch("backend.app.main.printer_manager") as mock_pm,
  1152. ):
  1153. mock_ws.send_print_complete = AsyncMock()
  1154. mock_ws.broadcast = AsyncMock()
  1155. mock_relay.on_print_complete = AsyncMock()
  1156. mock_relay.on_queue_job_completed = AsyncMock()
  1157. mock_notif.on_print_complete = AsyncMock()
  1158. mock_plug.on_print_complete = AsyncMock()
  1159. mock_pm.get_printer.return_value = None
  1160. from backend.app.main import on_print_complete
  1161. await on_print_complete(
  1162. item.printer_id,
  1163. {
  1164. "status": "completed",
  1165. "filename": "test.gcode",
  1166. "subtask_name": "Test",
  1167. "timelapse_was_active": False,
  1168. },
  1169. )
  1170. # Cancel background tasks before leaving mock context
  1171. for task in asyncio.all_tasks() - tasks_before:
  1172. task.cancel()
  1173. try:
  1174. await task
  1175. except (asyncio.CancelledError, Exception):
  1176. pass
  1177. assert item.status == "completed"
  1178. # ========================================================================
  1179. # Batch quantity tests
  1180. # ========================================================================
  1181. @pytest.mark.asyncio
  1182. @pytest.mark.integration
  1183. async def test_add_to_queue_quantity_default(
  1184. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1185. ):
  1186. """Verify quantity=1 (default) creates a single item with no batch."""
  1187. printer = await printer_factory()
  1188. archive = await archive_factory()
  1189. data = {
  1190. "printer_id": printer.id,
  1191. "archive_id": archive.id,
  1192. }
  1193. response = await async_client.post("/api/v1/queue/", json=data)
  1194. assert response.status_code == 200
  1195. result = response.json()
  1196. assert result["batch_id"] is None
  1197. assert result["batch_name"] is None
  1198. @pytest.mark.asyncio
  1199. @pytest.mark.integration
  1200. async def test_add_to_queue_quantity_one_explicit(
  1201. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1202. ):
  1203. """Verify quantity=1 explicitly creates a single item with no batch."""
  1204. printer = await printer_factory()
  1205. archive = await archive_factory()
  1206. data = {
  1207. "printer_id": printer.id,
  1208. "archive_id": archive.id,
  1209. "quantity": 1,
  1210. }
  1211. response = await async_client.post("/api/v1/queue/", json=data)
  1212. assert response.status_code == 200
  1213. result = response.json()
  1214. assert result["batch_id"] is None
  1215. assert result["batch_name"] is None
  1216. @pytest.mark.asyncio
  1217. @pytest.mark.integration
  1218. async def test_add_to_queue_quantity_creates_batch(
  1219. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1220. ):
  1221. """Verify quantity > 1 creates a batch and multiple queue items."""
  1222. printer = await printer_factory()
  1223. archive = await archive_factory()
  1224. data = {
  1225. "printer_id": printer.id,
  1226. "archive_id": archive.id,
  1227. "quantity": 3,
  1228. }
  1229. response = await async_client.post("/api/v1/queue/", json=data)
  1230. assert response.status_code == 200
  1231. result = response.json()
  1232. # First item is returned, linked to a batch
  1233. assert result["batch_id"] is not None
  1234. assert result["batch_name"] is not None
  1235. assert "×3" in result["batch_name"]
  1236. # Verify all 3 items were created
  1237. list_response = await async_client.get("/api/v1/queue/")
  1238. items = list_response.json()
  1239. batch_items = [i for i in items if i["batch_id"] == result["batch_id"]]
  1240. assert len(batch_items) == 3
  1241. # All items should have the same settings
  1242. for item in batch_items:
  1243. assert item["printer_id"] == printer.id
  1244. assert item["archive_id"] == archive.id
  1245. assert item["status"] == "pending"
  1246. @pytest.mark.asyncio
  1247. @pytest.mark.integration
  1248. async def test_add_to_queue_quantity_sequential_positions(
  1249. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1250. ):
  1251. """Verify batch items get sequential positions."""
  1252. printer = await printer_factory()
  1253. archive = await archive_factory()
  1254. data = {
  1255. "printer_id": printer.id,
  1256. "archive_id": archive.id,
  1257. "quantity": 3,
  1258. }
  1259. response = await async_client.post("/api/v1/queue/", json=data)
  1260. assert response.status_code == 200
  1261. batch_id = response.json()["batch_id"]
  1262. list_response = await async_client.get("/api/v1/queue/")
  1263. items = list_response.json()
  1264. batch_items = sorted(
  1265. [i for i in items if i["batch_id"] == batch_id],
  1266. key=lambda i: i["position"],
  1267. )
  1268. positions = [i["position"] for i in batch_items]
  1269. assert positions == [positions[0], positions[0] + 1, positions[0] + 2]
  1270. @pytest.mark.asyncio
  1271. @pytest.mark.integration
  1272. async def test_add_to_queue_quantity_with_print_options(
  1273. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1274. ):
  1275. """Verify print options are applied to all batch items."""
  1276. printer = await printer_factory()
  1277. archive = await archive_factory()
  1278. data = {
  1279. "printer_id": printer.id,
  1280. "archive_id": archive.id,
  1281. "quantity": 2,
  1282. "bed_levelling": False,
  1283. "timelapse": True,
  1284. }
  1285. response = await async_client.post("/api/v1/queue/", json=data)
  1286. assert response.status_code == 200
  1287. batch_id = response.json()["batch_id"]
  1288. list_response = await async_client.get("/api/v1/queue/")
  1289. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1290. assert len(batch_items) == 2
  1291. for item in batch_items:
  1292. assert item["bed_levelling"] is False
  1293. assert item["timelapse"] is True
  1294. @pytest.mark.asyncio
  1295. @pytest.mark.integration
  1296. async def test_get_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1297. """Verify batch can be retrieved with progress stats."""
  1298. printer = await printer_factory()
  1299. archive = await archive_factory()
  1300. # Create a batch of 3
  1301. data = {
  1302. "printer_id": printer.id,
  1303. "archive_id": archive.id,
  1304. "quantity": 3,
  1305. }
  1306. response = await async_client.post("/api/v1/queue/", json=data)
  1307. batch_id = response.json()["batch_id"]
  1308. # Get batch
  1309. response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1310. assert response.status_code == 200
  1311. result = response.json()
  1312. assert result["id"] == batch_id
  1313. assert result["quantity"] == 3
  1314. assert result["status"] == "active"
  1315. assert result["pending_count"] == 3
  1316. assert result["printing_count"] == 0
  1317. assert result["completed_count"] == 0
  1318. @pytest.mark.asyncio
  1319. @pytest.mark.integration
  1320. async def test_list_batches(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1321. """Verify batches can be listed."""
  1322. printer = await printer_factory()
  1323. archive = await archive_factory()
  1324. # Create two batches
  1325. for qty in [2, 3]:
  1326. await async_client.post(
  1327. "/api/v1/queue/",
  1328. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": qty},
  1329. )
  1330. response = await async_client.get("/api/v1/queue/batches")
  1331. assert response.status_code == 200
  1332. batches = response.json()
  1333. assert len(batches) >= 2
  1334. @pytest.mark.asyncio
  1335. @pytest.mark.integration
  1336. async def test_cancel_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1337. """Verify cancelling a batch cancels all pending items."""
  1338. printer = await printer_factory()
  1339. archive = await archive_factory()
  1340. data = {
  1341. "printer_id": printer.id,
  1342. "archive_id": archive.id,
  1343. "quantity": 3,
  1344. }
  1345. response = await async_client.post("/api/v1/queue/", json=data)
  1346. batch_id = response.json()["batch_id"]
  1347. # Cancel the batch
  1348. response = await async_client.delete(f"/api/v1/queue/batches/{batch_id}")
  1349. assert response.status_code == 200
  1350. # Verify all items are cancelled
  1351. list_response = await async_client.get("/api/v1/queue/")
  1352. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1353. for item in batch_items:
  1354. assert item["status"] == "cancelled"
  1355. # Verify batch status
  1356. batch_response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1357. assert batch_response.json()["status"] == "cancelled"
  1358. @pytest.mark.asyncio
  1359. @pytest.mark.integration
  1360. async def test_get_batch_not_found(self, async_client: AsyncClient):
  1361. """Verify 404 for non-existent batch."""
  1362. response = await async_client.get("/api/v1/queue/batches/9999")
  1363. assert response.status_code == 404