test_print_queue_api.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  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.core.database.async_session", return_value=mock_session),
  1071. patch("backend.app.main.ws_manager") as mock_ws,
  1072. patch("backend.app.main.mqtt_relay") as mock_relay,
  1073. patch("backend.app.main.notification_service") as mock_notif,
  1074. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1075. patch("backend.app.main.printer_manager") as mock_pm,
  1076. ):
  1077. mock_ws.send_print_complete = AsyncMock()
  1078. mock_ws.broadcast = AsyncMock()
  1079. mock_relay.on_print_complete = AsyncMock()
  1080. mock_relay.on_queue_job_completed = AsyncMock()
  1081. mock_notif.on_print_complete = AsyncMock()
  1082. mock_plug.on_print_complete = AsyncMock()
  1083. mock_pm.get_printer.return_value = None
  1084. from backend.app.main import on_print_complete
  1085. await on_print_complete(
  1086. item.printer_id,
  1087. {
  1088. "status": "aborted",
  1089. "filename": "test.gcode",
  1090. "subtask_name": "Test",
  1091. "timelapse_was_active": False,
  1092. },
  1093. )
  1094. # Cancel background tasks before leaving mock context
  1095. for task in asyncio.all_tasks() - tasks_before:
  1096. task.cancel()
  1097. try:
  1098. await task
  1099. except (asyncio.CancelledError, Exception):
  1100. pass
  1101. # The item status should be normalised to 'cancelled', not 'aborted'
  1102. assert item.status == "cancelled"
  1103. @pytest.mark.asyncio
  1104. @pytest.mark.integration
  1105. async def test_startup_fixup_converts_aborted_to_cancelled(self, queue_item_factory, db_session):
  1106. """Verify the startup fixup converts existing 'aborted' rows to 'cancelled'."""
  1107. from sqlalchemy import select
  1108. from backend.app.models.print_queue import PrintQueueItem
  1109. # Create items with various statuses including 'aborted'
  1110. item_aborted = await queue_item_factory(status="pending")
  1111. item_pending = await queue_item_factory(status="pending")
  1112. # Manually set the invalid status
  1113. item_aborted.status = "aborted"
  1114. db_session.add(item_aborted)
  1115. await db_session.commit()
  1116. # Run the fixup query (same logic as lifespan)
  1117. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1118. aborted_items = result.scalars().all()
  1119. for i in aborted_items:
  1120. i.status = "cancelled"
  1121. await db_session.commit()
  1122. # Verify: no more 'aborted' items
  1123. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1124. assert len(result.scalars().all()) == 0
  1125. # The previously aborted item should now be 'cancelled'
  1126. await db_session.refresh(item_aborted)
  1127. assert item_aborted.status == "cancelled"
  1128. # The pending item should be unchanged
  1129. await db_session.refresh(item_pending)
  1130. assert item_pending.status == "pending"
  1131. @pytest.mark.asyncio
  1132. @pytest.mark.integration
  1133. async def test_completed_status_passes_through_unchanged(self, queue_item_factory, db_session):
  1134. """Verify normal statuses like 'completed' are not affected by normalisation."""
  1135. import asyncio
  1136. from unittest.mock import AsyncMock, MagicMock, patch
  1137. item = await queue_item_factory(status="printing")
  1138. mock_result = MagicMock()
  1139. mock_result.scalars.return_value.all.return_value = [item]
  1140. mock_session = AsyncMock()
  1141. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1142. mock_session.__aexit__ = AsyncMock(return_value=False)
  1143. mock_session.execute = AsyncMock(return_value=mock_result)
  1144. mock_session.commit = AsyncMock()
  1145. tasks_before = set(asyncio.all_tasks())
  1146. with (
  1147. patch("backend.app.main.async_session", return_value=mock_session),
  1148. patch("backend.app.core.database.async_session", return_value=mock_session),
  1149. patch("backend.app.main.ws_manager") as mock_ws,
  1150. patch("backend.app.main.mqtt_relay") as mock_relay,
  1151. patch("backend.app.main.notification_service") as mock_notif,
  1152. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1153. patch("backend.app.main.printer_manager") as mock_pm,
  1154. ):
  1155. mock_ws.send_print_complete = AsyncMock()
  1156. mock_ws.broadcast = AsyncMock()
  1157. mock_relay.on_print_complete = AsyncMock()
  1158. mock_relay.on_queue_job_completed = AsyncMock()
  1159. mock_notif.on_print_complete = AsyncMock()
  1160. mock_plug.on_print_complete = AsyncMock()
  1161. mock_pm.get_printer.return_value = None
  1162. from backend.app.main import on_print_complete
  1163. await on_print_complete(
  1164. item.printer_id,
  1165. {
  1166. "status": "completed",
  1167. "filename": "test.gcode",
  1168. "subtask_name": "Test",
  1169. "timelapse_was_active": False,
  1170. },
  1171. )
  1172. # Cancel background tasks before leaving mock context
  1173. for task in asyncio.all_tasks() - tasks_before:
  1174. task.cancel()
  1175. try:
  1176. await task
  1177. except (asyncio.CancelledError, Exception):
  1178. pass
  1179. assert item.status == "completed"
  1180. # ========================================================================
  1181. # Batch quantity tests
  1182. # ========================================================================
  1183. @pytest.mark.asyncio
  1184. @pytest.mark.integration
  1185. async def test_add_to_queue_quantity_default(
  1186. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1187. ):
  1188. """Verify quantity=1 (default) creates a single item with no batch."""
  1189. printer = await printer_factory()
  1190. archive = await archive_factory()
  1191. data = {
  1192. "printer_id": printer.id,
  1193. "archive_id": archive.id,
  1194. }
  1195. response = await async_client.post("/api/v1/queue/", json=data)
  1196. assert response.status_code == 200
  1197. result = response.json()
  1198. assert result["batch_id"] is None
  1199. assert result["batch_name"] is None
  1200. @pytest.mark.asyncio
  1201. @pytest.mark.integration
  1202. async def test_add_to_queue_quantity_one_explicit(
  1203. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1204. ):
  1205. """Verify quantity=1 explicitly creates a single item with no batch."""
  1206. printer = await printer_factory()
  1207. archive = await archive_factory()
  1208. data = {
  1209. "printer_id": printer.id,
  1210. "archive_id": archive.id,
  1211. "quantity": 1,
  1212. }
  1213. response = await async_client.post("/api/v1/queue/", json=data)
  1214. assert response.status_code == 200
  1215. result = response.json()
  1216. assert result["batch_id"] is None
  1217. assert result["batch_name"] is None
  1218. @pytest.mark.asyncio
  1219. @pytest.mark.integration
  1220. async def test_add_to_queue_quantity_creates_batch(
  1221. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1222. ):
  1223. """Verify quantity > 1 creates a batch and multiple queue items."""
  1224. printer = await printer_factory()
  1225. archive = await archive_factory()
  1226. data = {
  1227. "printer_id": printer.id,
  1228. "archive_id": archive.id,
  1229. "quantity": 3,
  1230. }
  1231. response = await async_client.post("/api/v1/queue/", json=data)
  1232. assert response.status_code == 200
  1233. result = response.json()
  1234. # First item is returned, linked to a batch
  1235. assert result["batch_id"] is not None
  1236. assert result["batch_name"] is not None
  1237. assert "×3" in result["batch_name"]
  1238. # Verify all 3 items were created
  1239. list_response = await async_client.get("/api/v1/queue/")
  1240. items = list_response.json()
  1241. batch_items = [i for i in items if i["batch_id"] == result["batch_id"]]
  1242. assert len(batch_items) == 3
  1243. # All items should have the same settings
  1244. for item in batch_items:
  1245. assert item["printer_id"] == printer.id
  1246. assert item["archive_id"] == archive.id
  1247. assert item["status"] == "pending"
  1248. @pytest.mark.asyncio
  1249. @pytest.mark.integration
  1250. async def test_add_to_queue_quantity_sequential_positions(
  1251. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1252. ):
  1253. """Verify batch items get sequential positions."""
  1254. printer = await printer_factory()
  1255. archive = await archive_factory()
  1256. data = {
  1257. "printer_id": printer.id,
  1258. "archive_id": archive.id,
  1259. "quantity": 3,
  1260. }
  1261. response = await async_client.post("/api/v1/queue/", json=data)
  1262. assert response.status_code == 200
  1263. batch_id = response.json()["batch_id"]
  1264. list_response = await async_client.get("/api/v1/queue/")
  1265. items = list_response.json()
  1266. batch_items = sorted(
  1267. [i for i in items if i["batch_id"] == batch_id],
  1268. key=lambda i: i["position"],
  1269. )
  1270. positions = [i["position"] for i in batch_items]
  1271. assert positions == [positions[0], positions[0] + 1, positions[0] + 2]
  1272. @pytest.mark.asyncio
  1273. @pytest.mark.integration
  1274. async def test_add_to_queue_quantity_with_print_options(
  1275. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1276. ):
  1277. """Verify print options are applied to all batch items."""
  1278. printer = await printer_factory()
  1279. archive = await archive_factory()
  1280. data = {
  1281. "printer_id": printer.id,
  1282. "archive_id": archive.id,
  1283. "quantity": 2,
  1284. "bed_levelling": False,
  1285. "timelapse": True,
  1286. }
  1287. response = await async_client.post("/api/v1/queue/", json=data)
  1288. assert response.status_code == 200
  1289. batch_id = response.json()["batch_id"]
  1290. list_response = await async_client.get("/api/v1/queue/")
  1291. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1292. assert len(batch_items) == 2
  1293. for item in batch_items:
  1294. assert item["bed_levelling"] is False
  1295. assert item["timelapse"] is True
  1296. @pytest.mark.asyncio
  1297. @pytest.mark.integration
  1298. async def test_get_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1299. """Verify batch can be retrieved with progress stats."""
  1300. printer = await printer_factory()
  1301. archive = await archive_factory()
  1302. # Create a batch of 3
  1303. data = {
  1304. "printer_id": printer.id,
  1305. "archive_id": archive.id,
  1306. "quantity": 3,
  1307. }
  1308. response = await async_client.post("/api/v1/queue/", json=data)
  1309. batch_id = response.json()["batch_id"]
  1310. # Get batch
  1311. response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1312. assert response.status_code == 200
  1313. result = response.json()
  1314. assert result["id"] == batch_id
  1315. assert result["quantity"] == 3
  1316. assert result["status"] == "active"
  1317. assert result["pending_count"] == 3
  1318. assert result["printing_count"] == 0
  1319. assert result["completed_count"] == 0
  1320. @pytest.mark.asyncio
  1321. @pytest.mark.integration
  1322. async def test_list_batches(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1323. """Verify batches can be listed."""
  1324. printer = await printer_factory()
  1325. archive = await archive_factory()
  1326. # Create two batches
  1327. for qty in [2, 3]:
  1328. await async_client.post(
  1329. "/api/v1/queue/",
  1330. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": qty},
  1331. )
  1332. response = await async_client.get("/api/v1/queue/batches")
  1333. assert response.status_code == 200
  1334. batches = response.json()
  1335. assert len(batches) >= 2
  1336. @pytest.mark.asyncio
  1337. @pytest.mark.integration
  1338. async def test_cancel_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1339. """Verify cancelling a batch cancels all pending items."""
  1340. printer = await printer_factory()
  1341. archive = await archive_factory()
  1342. data = {
  1343. "printer_id": printer.id,
  1344. "archive_id": archive.id,
  1345. "quantity": 3,
  1346. }
  1347. response = await async_client.post("/api/v1/queue/", json=data)
  1348. batch_id = response.json()["batch_id"]
  1349. # Cancel the batch
  1350. response = await async_client.delete(f"/api/v1/queue/batches/{batch_id}")
  1351. assert response.status_code == 200
  1352. # Verify all items are cancelled
  1353. list_response = await async_client.get("/api/v1/queue/")
  1354. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1355. for item in batch_items:
  1356. assert item["status"] == "cancelled"
  1357. # Verify batch status
  1358. batch_response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1359. assert batch_response.json()["status"] == "cancelled"
  1360. @pytest.mark.asyncio
  1361. @pytest.mark.integration
  1362. async def test_get_batch_not_found(self, async_client: AsyncClient):
  1363. """Verify 404 for non-existent batch."""
  1364. response = await async_client.get("/api/v1/queue/batches/9999")
  1365. assert response.status_code == 404