test_print_queue_api.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249
  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_skip_filament_check(
  124. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  125. ):
  126. """PrintModal "Print Anyway" persists skip_filament_check on creation (#1698-followup)."""
  127. printer = await printer_factory()
  128. archive = await archive_factory()
  129. data = {
  130. "printer_id": printer.id,
  131. "archive_id": archive.id,
  132. "skip_filament_check": True,
  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["skip_filament_check"] is True
  138. @pytest.mark.asyncio
  139. @pytest.mark.integration
  140. async def test_add_to_queue_skip_filament_check_defaults_false(
  141. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  142. ):
  143. """Default add-to-queue has skip_filament_check=False — no silent bypass."""
  144. printer = await printer_factory()
  145. archive = await archive_factory()
  146. data = {"printer_id": printer.id, "archive_id": archive.id}
  147. response = await async_client.post("/api/v1/queue/", json=data)
  148. assert response.status_code == 200
  149. result = response.json()
  150. assert result["skip_filament_check"] is False
  151. @pytest.mark.asyncio
  152. @pytest.mark.integration
  153. async def test_add_to_queue_with_project_id(
  154. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  155. ):
  156. """#932: queue items created from the project view carry project_id forward."""
  157. from backend.app.models.project import Project
  158. printer = await printer_factory()
  159. archive = await archive_factory()
  160. project = Project(name="Queue Project")
  161. db_session.add(project)
  162. await db_session.commit()
  163. await db_session.refresh(project)
  164. data = {
  165. "printer_id": printer.id,
  166. "archive_id": archive.id,
  167. "project_id": project.id,
  168. }
  169. response = await async_client.post("/api/v1/queue/", json=data)
  170. assert response.status_code == 200
  171. result = response.json()
  172. # The response schema may or may not echo project_id; the stored row is
  173. # what matters, so verify via DB.
  174. from sqlalchemy import select
  175. from backend.app.models.print_queue import PrintQueueItem
  176. row = (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == result["id"]))).scalar_one()
  177. assert row.project_id == project.id
  178. @pytest.mark.asyncio
  179. @pytest.mark.integration
  180. async def test_add_to_queue_invalid_project_id_returns_404(
  181. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  182. ):
  183. """#932: bogus project_id must be rejected before the FK constraint fires.
  184. Regression guard for the pre-check added to add_to_queue. Without the
  185. validation, a nonexistent project_id would reach db.commit() and raise
  186. an IntegrityError → 500. The pre-check must convert that to a 404 so
  187. the UI gets a clean error it can surface.
  188. """
  189. printer = await printer_factory()
  190. archive = await archive_factory()
  191. data = {
  192. "printer_id": printer.id,
  193. "archive_id": archive.id,
  194. "project_id": 999999, # nonexistent
  195. }
  196. response = await async_client.post("/api/v1/queue/", json=data)
  197. assert response.status_code == 404
  198. assert "project" in response.json()["detail"].lower()
  199. @pytest.mark.asyncio
  200. @pytest.mark.integration
  201. async def test_add_to_queue_with_ams_mapping(
  202. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  203. ):
  204. """Verify item can be added to queue with ams_mapping."""
  205. printer = await printer_factory()
  206. archive = await archive_factory()
  207. data = {
  208. "printer_id": printer.id,
  209. "archive_id": archive.id,
  210. "ams_mapping": [5, -1, 2, -1], # Slot 1 -> tray 5, slot 3 -> tray 2
  211. }
  212. response = await async_client.post("/api/v1/queue/", json=data)
  213. assert response.status_code == 200
  214. result = response.json()
  215. assert result["printer_id"] == printer.id
  216. assert result["archive_id"] == archive.id
  217. assert result["ams_mapping"] == [5, -1, 2, -1]
  218. @pytest.mark.asyncio
  219. @pytest.mark.integration
  220. async def test_add_to_queue_with_plate_id(
  221. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  222. ):
  223. """Verify item can be added to queue with plate_id for multi-plate 3MF."""
  224. printer = await printer_factory()
  225. archive = await archive_factory()
  226. data = {
  227. "printer_id": printer.id,
  228. "archive_id": archive.id,
  229. "plate_id": 3,
  230. }
  231. response = await async_client.post("/api/v1/queue/", json=data)
  232. assert response.status_code == 200
  233. result = response.json()
  234. assert result["plate_id"] == 3
  235. @pytest.mark.asyncio
  236. @pytest.mark.integration
  237. async def test_add_to_queue_with_print_options(
  238. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  239. ):
  240. """Verify item can be added to queue with print options."""
  241. printer = await printer_factory()
  242. archive = await archive_factory()
  243. data = {
  244. "printer_id": printer.id,
  245. "archive_id": archive.id,
  246. "bed_levelling": False,
  247. "flow_cali": True,
  248. "vibration_cali": False,
  249. "layer_inspect": True,
  250. "timelapse": True,
  251. "use_ams": False,
  252. }
  253. response = await async_client.post("/api/v1/queue/", json=data)
  254. assert response.status_code == 200
  255. result = response.json()
  256. assert result["bed_levelling"] is False
  257. assert result["flow_cali"] is True
  258. assert result["vibration_cali"] is False
  259. assert result["layer_inspect"] is True
  260. assert result["timelapse"] is True
  261. assert result["use_ams"] is False
  262. @pytest.mark.asyncio
  263. @pytest.mark.integration
  264. async def test_update_queue_item_plate_id(self, async_client: AsyncClient, queue_item_factory, db_session):
  265. """Verify queue item plate_id can be updated."""
  266. item = await queue_item_factory()
  267. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"plate_id": 5})
  268. assert response.status_code == 200
  269. result = response.json()
  270. assert result["plate_id"] == 5
  271. @pytest.mark.asyncio
  272. @pytest.mark.integration
  273. async def test_update_queue_item_print_options(self, async_client: AsyncClient, queue_item_factory, db_session):
  274. """Verify queue item print options can be updated."""
  275. item = await queue_item_factory()
  276. response = await async_client.patch(
  277. f"/api/v1/queue/{item.id}",
  278. json={
  279. "bed_levelling": False,
  280. "timelapse": True,
  281. },
  282. )
  283. assert response.status_code == 200
  284. result = response.json()
  285. assert result["bed_levelling"] is False
  286. assert result["timelapse"] is True
  287. @pytest.mark.asyncio
  288. @pytest.mark.integration
  289. async def test_get_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  290. """Verify single queue item can be retrieved."""
  291. item = await queue_item_factory()
  292. response = await async_client.get(f"/api/v1/queue/{item.id}")
  293. assert response.status_code == 200
  294. assert response.json()["id"] == item.id
  295. @pytest.mark.asyncio
  296. @pytest.mark.integration
  297. async def test_get_queue_item_not_found(self, async_client: AsyncClient):
  298. """Verify 404 for non-existent queue item."""
  299. response = await async_client.get("/api/v1/queue/9999")
  300. assert response.status_code == 404
  301. @pytest.mark.asyncio
  302. @pytest.mark.integration
  303. async def test_update_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  304. """Verify queue item can be updated."""
  305. item = await queue_item_factory()
  306. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"auto_off_after": True})
  307. assert response.status_code == 200
  308. result = response.json()
  309. assert result["auto_off_after"] is True
  310. @pytest.mark.asyncio
  311. @pytest.mark.integration
  312. async def test_update_queue_item_manual_start(self, async_client: AsyncClient, queue_item_factory, db_session):
  313. """Verify queue item manual_start can be updated."""
  314. item = await queue_item_factory(manual_start=False)
  315. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"manual_start": True})
  316. assert response.status_code == 200
  317. result = response.json()
  318. assert result["manual_start"] is True
  319. @pytest.mark.asyncio
  320. @pytest.mark.integration
  321. async def test_delete_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  322. """Verify queue item can be deleted."""
  323. item = await queue_item_factory()
  324. response = await async_client.delete(f"/api/v1/queue/{item.id}")
  325. assert response.status_code == 200
  326. assert response.json()["message"] == "Queue item deleted"
  327. @pytest.mark.asyncio
  328. @pytest.mark.integration
  329. async def test_delete_queue_item_not_found(self, async_client: AsyncClient):
  330. """Verify 404 for deleting non-existent queue item."""
  331. response = await async_client.delete("/api/v1/queue/9999")
  332. assert response.status_code == 404
  333. class TestQueueStartEndpoint:
  334. """Tests for the /queue/{item_id}/start endpoint."""
  335. @pytest.fixture
  336. async def printer_factory(self, db_session):
  337. """Factory to create test printers."""
  338. _counter = [0]
  339. async def _create_printer(**kwargs):
  340. from backend.app.models.printer import Printer
  341. _counter[0] += 1
  342. counter = _counter[0]
  343. defaults = {
  344. "name": f"Test Printer {counter}",
  345. "ip_address": f"192.168.1.{100 + counter}",
  346. "serial_number": f"TESTSERIAL{counter:04d}",
  347. "access_code": "12345678",
  348. "model": "X1C",
  349. }
  350. defaults.update(kwargs)
  351. printer = Printer(**defaults)
  352. db_session.add(printer)
  353. await db_session.commit()
  354. await db_session.refresh(printer)
  355. return printer
  356. return _create_printer
  357. @pytest.fixture
  358. async def archive_factory(self, db_session):
  359. """Factory to create test archives."""
  360. _counter = [0]
  361. async def _create_archive(**kwargs):
  362. from backend.app.models.archive import PrintArchive
  363. _counter[0] += 1
  364. counter = _counter[0]
  365. defaults = {
  366. "filename": f"test_print_{counter}.3mf",
  367. "print_name": f"Test Print {counter}",
  368. "file_path": f"/tmp/test_print_{counter}.3mf",
  369. "file_size": 1024,
  370. "content_hash": f"testhash{counter:08d}",
  371. "status": "completed",
  372. }
  373. defaults.update(kwargs)
  374. archive = PrintArchive(**defaults)
  375. db_session.add(archive)
  376. await db_session.commit()
  377. await db_session.refresh(archive)
  378. return archive
  379. return _create_archive
  380. @pytest.fixture
  381. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  382. """Factory to create test queue items."""
  383. _counter = [0]
  384. async def _create_queue_item(**kwargs):
  385. from backend.app.models.print_queue import PrintQueueItem
  386. _counter[0] += 1
  387. counter = _counter[0]
  388. if "printer_id" not in kwargs:
  389. printer = await printer_factory()
  390. kwargs["printer_id"] = printer.id
  391. if "archive_id" not in kwargs:
  392. archive = await archive_factory()
  393. kwargs["archive_id"] = archive.id
  394. defaults = {
  395. "status": "pending",
  396. "position": counter,
  397. }
  398. defaults.update(kwargs)
  399. item = PrintQueueItem(**defaults)
  400. db_session.add(item)
  401. await db_session.commit()
  402. await db_session.refresh(item)
  403. return item
  404. return _create_queue_item
  405. @pytest.mark.asyncio
  406. @pytest.mark.integration
  407. async def test_start_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  408. """Verify starting a staged (manual_start=True) queue item clears the flag."""
  409. item = await queue_item_factory(manual_start=True)
  410. assert item.manual_start is True
  411. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  412. assert response.status_code == 200
  413. result = response.json()
  414. assert result["manual_start"] is False
  415. assert result["status"] == "pending"
  416. @pytest.mark.asyncio
  417. @pytest.mark.integration
  418. async def test_start_non_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  419. """Verify starting a non-staged queue item still works (idempotent)."""
  420. item = await queue_item_factory(manual_start=False)
  421. assert item.manual_start is False
  422. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  423. assert response.status_code == 200
  424. result = response.json()
  425. assert result["manual_start"] is False
  426. @pytest.mark.asyncio
  427. @pytest.mark.integration
  428. async def test_start_queue_item_not_found(self, async_client: AsyncClient):
  429. """Verify 404 for non-existent queue item."""
  430. response = await async_client.post("/api/v1/queue/9999/start")
  431. assert response.status_code == 404
  432. @pytest.mark.asyncio
  433. @pytest.mark.integration
  434. async def test_start_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  435. """Verify 400 error when trying to start a non-pending queue item."""
  436. item = await queue_item_factory(status="printing", manual_start=True)
  437. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  438. assert response.status_code == 400
  439. assert "pending" in response.json()["detail"].lower()
  440. @pytest.mark.asyncio
  441. @pytest.mark.integration
  442. async def test_start_completed_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  443. """Verify 400 error when trying to start a completed queue item."""
  444. item = await queue_item_factory(status="completed", manual_start=True)
  445. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  446. assert response.status_code == 400
  447. @pytest.mark.asyncio
  448. @pytest.mark.integration
  449. async def test_start_returns_409_on_filament_deficit(
  450. self,
  451. async_client: AsyncClient,
  452. queue_item_factory,
  453. db_session,
  454. monkeypatch,
  455. ):
  456. """Filament deficit must surface as 409 + structured payload (#1496)."""
  457. from backend.app.services import filament_deficit as fd_module
  458. item = await queue_item_factory(manual_start=True)
  459. async def _fake_deficit(_db, _item):
  460. return [
  461. fd_module.FilamentDeficit(
  462. slot_id=1,
  463. ams_id=0,
  464. tray_id=0,
  465. filament_type="PLA",
  466. required_grams=270.0,
  467. remaining_grams=200.0,
  468. ),
  469. ]
  470. monkeypatch.setattr(
  471. "backend.app.api.routes.print_queue.compute_deficit_for_queue_item",
  472. _fake_deficit,
  473. )
  474. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  475. assert response.status_code == 409
  476. body = response.json()
  477. assert body["detail"]["code"] == "insufficient_filament"
  478. assert len(body["detail"]["deficit"]) == 1
  479. assert body["detail"]["deficit"][0]["slot_id"] == 1
  480. assert body["detail"]["deficit"][0]["required_grams"] == 270.0
  481. assert body["detail"]["deficit"][0]["remaining_grams"] == 200.0
  482. # Item still pending, manual_start unchanged.
  483. await db_session.refresh(item)
  484. assert item.status == "pending"
  485. assert item.manual_start is True
  486. @pytest.mark.asyncio
  487. @pytest.mark.integration
  488. async def test_start_with_skip_flag_bypasses_deficit_check(
  489. self,
  490. async_client: AsyncClient,
  491. queue_item_factory,
  492. db_session,
  493. monkeypatch,
  494. ):
  495. """With skip_filament_check=true the route dispatches even when short (#1496)."""
  496. from backend.app.services import filament_deficit as fd_module
  497. item = await queue_item_factory(manual_start=True, filament_short=True)
  498. called_with = {}
  499. async def _fake_deficit(_db, _item):
  500. called_with["called"] = True
  501. return [
  502. fd_module.FilamentDeficit(
  503. slot_id=1,
  504. ams_id=0,
  505. tray_id=0,
  506. filament_type="PLA",
  507. required_grams=270.0,
  508. remaining_grams=200.0,
  509. ),
  510. ]
  511. monkeypatch.setattr(
  512. "backend.app.api.routes.print_queue.compute_deficit_for_queue_item",
  513. _fake_deficit,
  514. )
  515. response = await async_client.post(f"/api/v1/queue/{item.id}/start?skip_filament_check=true")
  516. assert response.status_code == 200
  517. body = response.json()
  518. assert body["manual_start"] is False
  519. assert body["filament_short"] is False
  520. # Helper not called on the bypass path — we trust the operator's
  521. # decision to print anyway.
  522. assert called_with == {}
  523. @pytest.mark.asyncio
  524. @pytest.mark.integration
  525. async def test_start_with_skip_flag_persists_acknowledgement(
  526. self,
  527. async_client: AsyncClient,
  528. queue_item_factory,
  529. db_session,
  530. ):
  531. """skip_filament_check=true sets the persistent flag on the queue item
  532. so the scheduler doesn't re-flag it on the next tick (#1698-followup).
  533. Without persistence the route's flag-clearing only survives until the
  534. next scheduler tick re-runs the deficit check on identical spool
  535. state and re-promotes the item — the user has to click Play+Confirm
  536. every single tick.
  537. """
  538. item = await queue_item_factory(manual_start=True, filament_short=True)
  539. assert item.skip_filament_check is False
  540. response = await async_client.post(f"/api/v1/queue/{item.id}/start?skip_filament_check=true")
  541. assert response.status_code == 200
  542. body = response.json()
  543. assert body["skip_filament_check"] is True
  544. await db_session.refresh(item)
  545. assert item.skip_filament_check is True
  546. @pytest.mark.asyncio
  547. @pytest.mark.integration
  548. async def test_start_without_skip_flag_does_not_set_acknowledgement(
  549. self,
  550. async_client: AsyncClient,
  551. queue_item_factory,
  552. db_session,
  553. ):
  554. """A successful Play click with no deficit must NOT silently set the
  555. acknowledgement flag — only an explicit Print Anyway should.
  556. """
  557. item = await queue_item_factory(manual_start=False, filament_short=False)
  558. assert item.skip_filament_check is False
  559. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  560. assert response.status_code == 200
  561. await db_session.refresh(item)
  562. assert item.skip_filament_check is False
  563. class TestQueueCancelEndpoint:
  564. """Tests for the /queue/{item_id}/cancel endpoint."""
  565. @pytest.fixture
  566. async def printer_factory(self, db_session):
  567. """Factory to create test printers."""
  568. async def _create_printer(**kwargs):
  569. from backend.app.models.printer import Printer
  570. defaults = {
  571. "name": "Cancel Test Printer",
  572. "ip_address": "192.168.1.200",
  573. "serial_number": "TESTCANCEL001",
  574. "access_code": "12345678",
  575. "model": "X1C",
  576. }
  577. defaults.update(kwargs)
  578. printer = Printer(**defaults)
  579. db_session.add(printer)
  580. await db_session.commit()
  581. await db_session.refresh(printer)
  582. return printer
  583. return _create_printer
  584. @pytest.fixture
  585. async def archive_factory(self, db_session):
  586. """Factory to create test archives."""
  587. async def _create_archive(**kwargs):
  588. from backend.app.models.archive import PrintArchive
  589. defaults = {
  590. "filename": "cancel_test.3mf",
  591. "print_name": "Cancel Test Print",
  592. "file_path": "/tmp/cancel_test.3mf",
  593. "file_size": 1024,
  594. "content_hash": "cancelhash001",
  595. "status": "completed",
  596. }
  597. defaults.update(kwargs)
  598. archive = PrintArchive(**defaults)
  599. db_session.add(archive)
  600. await db_session.commit()
  601. await db_session.refresh(archive)
  602. return archive
  603. return _create_archive
  604. @pytest.fixture
  605. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  606. """Factory to create test queue items."""
  607. async def _create_queue_item(**kwargs):
  608. from backend.app.models.print_queue import PrintQueueItem
  609. if "printer_id" not in kwargs:
  610. printer = await printer_factory()
  611. kwargs["printer_id"] = printer.id
  612. if "archive_id" not in kwargs:
  613. archive = await archive_factory()
  614. kwargs["archive_id"] = archive.id
  615. defaults = {
  616. "status": "pending",
  617. "position": 1,
  618. }
  619. defaults.update(kwargs)
  620. item = PrintQueueItem(**defaults)
  621. db_session.add(item)
  622. await db_session.commit()
  623. await db_session.refresh(item)
  624. return item
  625. return _create_queue_item
  626. @pytest.mark.asyncio
  627. @pytest.mark.integration
  628. async def test_cancel_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  629. """Verify cancelling a pending queue item."""
  630. item = await queue_item_factory(status="pending")
  631. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  632. assert response.status_code == 200
  633. assert response.json()["message"] == "Queue item cancelled"
  634. @pytest.mark.asyncio
  635. @pytest.mark.integration
  636. async def test_cancel_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  637. """Verify 400 error when trying to cancel a non-pending queue item."""
  638. item = await queue_item_factory(status="printing")
  639. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  640. assert response.status_code == 400
  641. class TestQueueLibraryFileSupport:
  642. """Tests for queue items with library_file_id (instead of archive_id)."""
  643. @pytest.fixture
  644. async def printer_factory(self, db_session):
  645. """Factory to create test printers."""
  646. _counter = [0]
  647. async def _create_printer(**kwargs):
  648. from backend.app.models.printer import Printer
  649. _counter[0] += 1
  650. counter = _counter[0]
  651. defaults = {
  652. "name": f"Library Test Printer {counter}",
  653. "ip_address": f"192.168.1.{150 + counter}",
  654. "serial_number": f"TESTLIB{counter:04d}",
  655. "access_code": "12345678",
  656. "model": "X1C",
  657. }
  658. defaults.update(kwargs)
  659. printer = Printer(**defaults)
  660. db_session.add(printer)
  661. await db_session.commit()
  662. await db_session.refresh(printer)
  663. return printer
  664. return _create_printer
  665. @pytest.fixture
  666. async def library_file_factory(self, db_session):
  667. """Factory to create test library files."""
  668. _counter = [0]
  669. async def _create_library_file(**kwargs):
  670. from backend.app.models.library import LibraryFile
  671. _counter[0] += 1
  672. counter = _counter[0]
  673. defaults = {
  674. "filename": f"library_test_{counter}.3mf",
  675. "file_path": f"/test/library/library_test_{counter}.3mf",
  676. "file_size": 2048,
  677. "file_type": "3mf",
  678. "file_metadata": {"print_name": f"Library Print {counter}", "print_time_seconds": 3600},
  679. }
  680. defaults.update(kwargs)
  681. lib_file = LibraryFile(**defaults)
  682. db_session.add(lib_file)
  683. await db_session.commit()
  684. await db_session.refresh(lib_file)
  685. return lib_file
  686. return _create_library_file
  687. @pytest.mark.asyncio
  688. @pytest.mark.integration
  689. async def test_add_to_queue_with_library_file(
  690. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  691. ):
  692. """Verify item can be added to queue using library_file_id instead of archive_id."""
  693. printer = await printer_factory()
  694. lib_file = await library_file_factory()
  695. data = {
  696. "printer_id": printer.id,
  697. "library_file_id": lib_file.id,
  698. }
  699. response = await async_client.post("/api/v1/queue/", json=data)
  700. assert response.status_code == 200
  701. result = response.json()
  702. assert result["printer_id"] == printer.id
  703. assert result["library_file_id"] == lib_file.id
  704. assert result["archive_id"] is None
  705. assert result["status"] == "pending"
  706. assert result["library_file_name"] == "Library Print 1"
  707. assert result["print_time_seconds"] == 3600
  708. @pytest.mark.asyncio
  709. @pytest.mark.integration
  710. async def test_add_to_queue_library_file_with_options(
  711. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  712. ):
  713. """Verify library file queue item can have all options set."""
  714. printer = await printer_factory()
  715. lib_file = await library_file_factory()
  716. data = {
  717. "printer_id": printer.id,
  718. "library_file_id": lib_file.id,
  719. "ams_mapping": [1, 2, -1, -1],
  720. "plate_id": 2,
  721. "bed_levelling": False,
  722. "timelapse": True,
  723. "manual_start": True,
  724. }
  725. response = await async_client.post("/api/v1/queue/", json=data)
  726. assert response.status_code == 200
  727. result = response.json()
  728. assert result["library_file_id"] == lib_file.id
  729. assert result["ams_mapping"] == [1, 2, -1, -1]
  730. assert result["plate_id"] == 2
  731. assert result["bed_levelling"] is False
  732. assert result["timelapse"] is True
  733. assert result["manual_start"] is True
  734. @pytest.mark.asyncio
  735. @pytest.mark.integration
  736. async def test_add_to_queue_requires_archive_or_library_file(
  737. self, async_client: AsyncClient, printer_factory, db_session
  738. ):
  739. """Verify 400 error when neither archive_id nor library_file_id provided."""
  740. printer = await printer_factory()
  741. data = {
  742. "printer_id": printer.id,
  743. }
  744. response = await async_client.post("/api/v1/queue/", json=data)
  745. assert response.status_code == 400
  746. assert (
  747. "archive_id" in response.json()["detail"].lower() or "library_file_id" in response.json()["detail"].lower()
  748. )
  749. @pytest.mark.asyncio
  750. @pytest.mark.integration
  751. async def test_update_queue_item_with_library_file(
  752. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  753. ):
  754. """Verify queue item with library_file_id can be updated."""
  755. from backend.app.models.print_queue import PrintQueueItem
  756. printer = await printer_factory()
  757. lib_file = await library_file_factory()
  758. # Create queue item directly
  759. item = PrintQueueItem(
  760. printer_id=printer.id,
  761. library_file_id=lib_file.id,
  762. status="pending",
  763. position=1,
  764. )
  765. db_session.add(item)
  766. await db_session.commit()
  767. await db_session.refresh(item)
  768. # Update the item
  769. response = await async_client.patch(
  770. f"/api/v1/queue/{item.id}",
  771. json={"auto_off_after": True, "plate_id": 3},
  772. )
  773. assert response.status_code == 200
  774. result = response.json()
  775. assert result["auto_off_after"] is True
  776. assert result["plate_id"] == 3
  777. assert result["library_file_id"] == lib_file.id
  778. @pytest.mark.asyncio
  779. @pytest.mark.integration
  780. async def test_list_queue_includes_library_file_info(
  781. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  782. ):
  783. """Verify queue list includes library file metadata."""
  784. from backend.app.models.print_queue import PrintQueueItem
  785. printer = await printer_factory()
  786. lib_file = await library_file_factory(
  787. file_metadata={"print_name": "Custom Print Name", "print_time_seconds": 7200}
  788. )
  789. item = PrintQueueItem(
  790. printer_id=printer.id,
  791. library_file_id=lib_file.id,
  792. status="pending",
  793. position=1,
  794. )
  795. db_session.add(item)
  796. await db_session.commit()
  797. response = await async_client.get("/api/v1/queue/")
  798. assert response.status_code == 200
  799. items = response.json()
  800. assert len(items) >= 1
  801. # Find our item
  802. our_item = next((i for i in items if i["library_file_id"] == lib_file.id), None)
  803. assert our_item is not None
  804. assert our_item["library_file_name"] == "Custom Print Name"
  805. assert our_item["print_time_seconds"] == 7200
  806. class TestBulkUpdateEndpoint:
  807. """Tests for the /queue/bulk endpoint."""
  808. @pytest.fixture
  809. async def printer_factory(self, db_session):
  810. """Factory to create test printers."""
  811. _counter = [0]
  812. async def _create_printer(**kwargs):
  813. from backend.app.models.printer import Printer
  814. _counter[0] += 1
  815. counter = _counter[0]
  816. defaults = {
  817. "name": f"Bulk Test Printer {counter}",
  818. "ip_address": f"192.168.1.{150 + counter}",
  819. "serial_number": f"TESTBULK{counter:04d}",
  820. "access_code": "12345678",
  821. "model": "X1C",
  822. }
  823. defaults.update(kwargs)
  824. printer = Printer(**defaults)
  825. db_session.add(printer)
  826. await db_session.commit()
  827. await db_session.refresh(printer)
  828. return printer
  829. return _create_printer
  830. @pytest.fixture
  831. async def archive_factory(self, db_session):
  832. """Factory to create test archives."""
  833. _counter = [0]
  834. async def _create_archive(**kwargs):
  835. from backend.app.models.archive import PrintArchive
  836. _counter[0] += 1
  837. counter = _counter[0]
  838. defaults = {
  839. "filename": f"bulk_test_{counter}.3mf",
  840. "print_name": f"Bulk Test Print {counter}",
  841. "file_path": f"/tmp/bulk_test_{counter}.3mf",
  842. "file_size": 1024,
  843. "content_hash": f"bulkhash{counter:04d}",
  844. "status": "completed",
  845. }
  846. defaults.update(kwargs)
  847. archive = PrintArchive(**defaults)
  848. db_session.add(archive)
  849. await db_session.commit()
  850. await db_session.refresh(archive)
  851. return archive
  852. return _create_archive
  853. @pytest.fixture
  854. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  855. """Factory to create test queue items."""
  856. async def _create_item(**kwargs):
  857. from backend.app.models.print_queue import PrintQueueItem
  858. if "printer_id" not in kwargs:
  859. printer = await printer_factory()
  860. kwargs["printer_id"] = printer.id
  861. if "archive_id" not in kwargs:
  862. archive = await archive_factory()
  863. kwargs["archive_id"] = archive.id
  864. defaults = {
  865. "status": "pending",
  866. "position": 1,
  867. "bed_levelling": True,
  868. "flow_cali": False,
  869. "vibration_cali": True,
  870. }
  871. defaults.update(kwargs)
  872. item = PrintQueueItem(**defaults)
  873. db_session.add(item)
  874. await db_session.commit()
  875. await db_session.refresh(item)
  876. return item
  877. return _create_item
  878. @pytest.mark.asyncio
  879. @pytest.mark.integration
  880. async def test_bulk_update_single_field(self, async_client: AsyncClient, queue_item_factory, db_session):
  881. """Verify bulk update can change a single field on multiple items."""
  882. item1 = await queue_item_factory(bed_levelling=True)
  883. item2 = await queue_item_factory(bed_levelling=True)
  884. response = await async_client.patch(
  885. "/api/v1/queue/bulk",
  886. json={"item_ids": [item1.id, item2.id], "bed_levelling": False},
  887. )
  888. assert response.status_code == 200
  889. result = response.json()
  890. assert result["updated_count"] == 2
  891. assert result["skipped_count"] == 0
  892. # Verify items were updated
  893. await db_session.refresh(item1)
  894. await db_session.refresh(item2)
  895. assert item1.bed_levelling is False
  896. assert item2.bed_levelling is False
  897. @pytest.mark.asyncio
  898. @pytest.mark.integration
  899. async def test_bulk_update_multiple_fields(self, async_client: AsyncClient, queue_item_factory, db_session):
  900. """Verify bulk update can change multiple fields at once."""
  901. item1 = await queue_item_factory(bed_levelling=True, flow_cali=False, manual_start=False)
  902. item2 = await queue_item_factory(bed_levelling=True, flow_cali=False, manual_start=False)
  903. response = await async_client.patch(
  904. "/api/v1/queue/bulk",
  905. json={
  906. "item_ids": [item1.id, item2.id],
  907. "bed_levelling": False,
  908. "flow_cali": True,
  909. "manual_start": True,
  910. },
  911. )
  912. assert response.status_code == 200
  913. result = response.json()
  914. assert result["updated_count"] == 2
  915. await db_session.refresh(item1)
  916. assert item1.bed_levelling is False
  917. assert item1.flow_cali is True
  918. assert item1.manual_start is True
  919. @pytest.mark.asyncio
  920. @pytest.mark.integration
  921. async def test_bulk_update_skips_non_pending(self, async_client: AsyncClient, queue_item_factory, db_session):
  922. """Verify bulk update skips non-pending items."""
  923. pending_item = await queue_item_factory(status="pending", bed_levelling=True)
  924. printing_item = await queue_item_factory(status="printing", bed_levelling=True)
  925. completed_item = await queue_item_factory(status="completed", bed_levelling=True)
  926. response = await async_client.patch(
  927. "/api/v1/queue/bulk",
  928. json={
  929. "item_ids": [pending_item.id, printing_item.id, completed_item.id],
  930. "bed_levelling": False,
  931. },
  932. )
  933. assert response.status_code == 200
  934. result = response.json()
  935. assert result["updated_count"] == 1
  936. assert result["skipped_count"] == 2
  937. # Only pending item should be updated
  938. await db_session.refresh(pending_item)
  939. await db_session.refresh(printing_item)
  940. await db_session.refresh(completed_item)
  941. assert pending_item.bed_levelling is False
  942. assert printing_item.bed_levelling is True
  943. assert completed_item.bed_levelling is True
  944. @pytest.mark.asyncio
  945. @pytest.mark.integration
  946. async def test_bulk_update_change_printer(
  947. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  948. ):
  949. """Verify bulk update can reassign items to a different printer."""
  950. new_printer = await printer_factory(name="New Target Printer")
  951. item1 = await queue_item_factory()
  952. item2 = await queue_item_factory()
  953. original_printer_id = item1.printer_id
  954. response = await async_client.patch(
  955. "/api/v1/queue/bulk",
  956. json={"item_ids": [item1.id, item2.id], "printer_id": new_printer.id},
  957. )
  958. assert response.status_code == 200
  959. await db_session.refresh(item1)
  960. await db_session.refresh(item2)
  961. assert item1.printer_id == new_printer.id
  962. assert item2.printer_id == new_printer.id
  963. assert item1.printer_id != original_printer_id
  964. @pytest.mark.asyncio
  965. @pytest.mark.integration
  966. async def test_bulk_update_empty_item_ids(self, async_client: AsyncClient):
  967. """Verify 400 error when item_ids is empty."""
  968. response = await async_client.patch(
  969. "/api/v1/queue/bulk",
  970. json={"item_ids": [], "bed_levelling": False},
  971. )
  972. assert response.status_code == 400
  973. assert "no item" in response.json()["detail"].lower()
  974. @pytest.mark.asyncio
  975. @pytest.mark.integration
  976. async def test_bulk_update_no_fields(self, async_client: AsyncClient, queue_item_factory):
  977. """Verify 400 error when no fields to update."""
  978. item = await queue_item_factory()
  979. response = await async_client.patch(
  980. "/api/v1/queue/bulk",
  981. json={"item_ids": [item.id]},
  982. )
  983. assert response.status_code == 400
  984. assert "no fields" in response.json()["detail"].lower()
  985. @pytest.mark.asyncio
  986. @pytest.mark.integration
  987. async def test_bulk_update_invalid_printer(self, async_client: AsyncClient, queue_item_factory):
  988. """Verify 400 error when printer_id doesn't exist."""
  989. item = await queue_item_factory()
  990. response = await async_client.patch(
  991. "/api/v1/queue/bulk",
  992. json={"item_ids": [item.id], "printer_id": 99999},
  993. )
  994. assert response.status_code == 400
  995. assert "printer not found" in response.json()["detail"].lower()
  996. class TestTargetLocationFeature:
  997. """Tests for queue items with target_location (Issue #220)."""
  998. @pytest.fixture
  999. async def printer_factory(self, db_session):
  1000. """Factory to create test printers."""
  1001. _counter = [0]
  1002. async def _create_printer(**kwargs):
  1003. from backend.app.models.printer import Printer
  1004. _counter[0] += 1
  1005. counter = _counter[0]
  1006. defaults = {
  1007. "name": f"Location Test Printer {counter}",
  1008. "ip_address": f"192.168.1.{50 + counter}",
  1009. "serial_number": f"TESTLOC{counter:04d}",
  1010. "access_code": "12345678",
  1011. "model": "X1C",
  1012. }
  1013. defaults.update(kwargs)
  1014. printer = Printer(**defaults)
  1015. db_session.add(printer)
  1016. await db_session.commit()
  1017. await db_session.refresh(printer)
  1018. return printer
  1019. return _create_printer
  1020. @pytest.fixture
  1021. async def archive_factory(self, db_session):
  1022. """Factory to create test archives."""
  1023. _counter = [0]
  1024. async def _create_archive(**kwargs):
  1025. from backend.app.models.archive import PrintArchive
  1026. _counter[0] += 1
  1027. counter = _counter[0]
  1028. defaults = {
  1029. "filename": f"location_test_{counter}.3mf",
  1030. "print_name": f"Location Test Print {counter}",
  1031. "file_path": f"/tmp/location_test_{counter}.3mf",
  1032. "file_size": 1024,
  1033. "content_hash": f"lochash{counter:08d}",
  1034. "status": "completed",
  1035. }
  1036. defaults.update(kwargs)
  1037. archive = PrintArchive(**defaults)
  1038. db_session.add(archive)
  1039. await db_session.commit()
  1040. await db_session.refresh(archive)
  1041. return archive
  1042. return _create_archive
  1043. @pytest.fixture
  1044. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1045. """Factory to create test queue items."""
  1046. _counter = [0]
  1047. async def _create_queue_item(**kwargs):
  1048. from backend.app.models.print_queue import PrintQueueItem
  1049. _counter[0] += 1
  1050. counter = _counter[0]
  1051. if "printer_id" not in kwargs and "target_model" not in kwargs:
  1052. printer = await printer_factory()
  1053. kwargs["printer_id"] = printer.id
  1054. if "archive_id" not in kwargs:
  1055. archive = await archive_factory()
  1056. kwargs["archive_id"] = archive.id
  1057. defaults = {
  1058. "status": "pending",
  1059. "position": counter,
  1060. }
  1061. defaults.update(kwargs)
  1062. item = PrintQueueItem(**defaults)
  1063. db_session.add(item)
  1064. await db_session.commit()
  1065. await db_session.refresh(item)
  1066. return item
  1067. return _create_queue_item
  1068. @pytest.mark.asyncio
  1069. @pytest.mark.integration
  1070. async def test_add_to_queue_with_target_location(
  1071. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1072. ):
  1073. """Verify item can be added with target_model and target_location."""
  1074. # Create a printer with model X1C so the API can validate
  1075. await printer_factory(model="X1C", location="Office")
  1076. archive = await archive_factory()
  1077. data = {
  1078. "target_model": "X1C",
  1079. "target_location": "Workbench",
  1080. "archive_id": archive.id,
  1081. }
  1082. response = await async_client.post("/api/v1/queue/", json=data)
  1083. assert response.status_code == 200
  1084. result = response.json()
  1085. assert result["target_model"] == "X1C"
  1086. assert result["target_location"] == "Workbench"
  1087. assert result["printer_id"] is None
  1088. @pytest.mark.asyncio
  1089. @pytest.mark.integration
  1090. async def test_add_to_queue_location_without_model_ignored(
  1091. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1092. ):
  1093. """Verify target_location without target_model is allowed (location is just ignored)."""
  1094. printer = await printer_factory()
  1095. archive = await archive_factory()
  1096. data = {
  1097. "printer_id": printer.id,
  1098. "target_location": "Workbench", # This gets ignored since printer_id is set
  1099. "archive_id": archive.id,
  1100. }
  1101. response = await async_client.post("/api/v1/queue/", json=data)
  1102. # The API accepts this but the location is only used with target_model
  1103. assert response.status_code == 200
  1104. result = response.json()
  1105. assert result["printer_id"] == printer.id
  1106. # Location may or may not be stored since it's meaningless without target_model
  1107. # The important thing is the request succeeds
  1108. @pytest.mark.asyncio
  1109. @pytest.mark.integration
  1110. async def test_queue_item_target_location_in_response(
  1111. self, async_client: AsyncClient, queue_item_factory, db_session
  1112. ):
  1113. """Verify target_location is returned in queue item response."""
  1114. item = await queue_item_factory(
  1115. printer_id=None,
  1116. target_model="X1C",
  1117. target_location="Workshop",
  1118. )
  1119. response = await async_client.get(f"/api/v1/queue/{item.id}")
  1120. assert response.status_code == 200
  1121. result = response.json()
  1122. assert result["target_model"] == "X1C"
  1123. assert result["target_location"] == "Workshop"
  1124. @pytest.mark.asyncio
  1125. @pytest.mark.integration
  1126. async def test_queue_list_includes_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1127. """Verify target_location is included in queue list."""
  1128. await queue_item_factory(
  1129. printer_id=None,
  1130. target_model="P1S",
  1131. target_location="Garage",
  1132. )
  1133. response = await async_client.get("/api/v1/queue/")
  1134. assert response.status_code == 200
  1135. items = response.json()
  1136. assert len(items) >= 1
  1137. # Find our item
  1138. our_item = next((i for i in items if i["target_location"] == "Garage"), None)
  1139. assert our_item is not None
  1140. assert our_item["target_model"] == "P1S"
  1141. @pytest.mark.asyncio
  1142. @pytest.mark.integration
  1143. async def test_update_queue_item_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1144. """Verify target_location can be updated on existing queue item."""
  1145. item = await queue_item_factory(
  1146. printer_id=None,
  1147. target_model="X1C",
  1148. target_location="Office",
  1149. )
  1150. response = await async_client.patch(
  1151. f"/api/v1/queue/{item.id}",
  1152. json={"target_location": "Basement"},
  1153. )
  1154. assert response.status_code == 200
  1155. result = response.json()
  1156. assert result["target_location"] == "Basement"
  1157. @pytest.mark.asyncio
  1158. @pytest.mark.integration
  1159. async def test_clear_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1160. """Verify target_location can be cleared (set to None)."""
  1161. item = await queue_item_factory(
  1162. printer_id=None,
  1163. target_model="X1C",
  1164. target_location="Office",
  1165. )
  1166. # Note: Setting to empty string should clear it
  1167. response = await async_client.patch(
  1168. f"/api/v1/queue/{item.id}",
  1169. json={"target_location": None},
  1170. )
  1171. assert response.status_code == 200
  1172. result = response.json()
  1173. assert result["target_location"] is None
  1174. class TestAbortedStatusNormalisation:
  1175. """Tests for issue #558: 'aborted' queue status causes 500 error."""
  1176. @pytest.fixture
  1177. async def printer_factory(self, db_session):
  1178. """Factory to create test printers."""
  1179. _counter = [0]
  1180. async def _create_printer(**kwargs):
  1181. from backend.app.models.printer import Printer
  1182. _counter[0] += 1
  1183. counter = _counter[0]
  1184. defaults = {
  1185. "name": f"Abort Test Printer {counter}",
  1186. "ip_address": f"192.168.1.{60 + counter}",
  1187. "serial_number": f"TESTABORT{counter:04d}",
  1188. "access_code": "12345678",
  1189. "model": "P1S",
  1190. }
  1191. defaults.update(kwargs)
  1192. printer = Printer(**defaults)
  1193. db_session.add(printer)
  1194. await db_session.commit()
  1195. await db_session.refresh(printer)
  1196. return printer
  1197. return _create_printer
  1198. @pytest.fixture
  1199. async def archive_factory(self, db_session):
  1200. """Factory to create test archives."""
  1201. _counter = [0]
  1202. async def _create_archive(**kwargs):
  1203. from backend.app.models.archive import PrintArchive
  1204. _counter[0] += 1
  1205. counter = _counter[0]
  1206. defaults = {
  1207. "filename": f"abort_test_{counter}.3mf",
  1208. "print_name": f"Abort Test Print {counter}",
  1209. "file_path": f"/tmp/abort_test_{counter}.3mf",
  1210. "file_size": 1024,
  1211. "content_hash": f"aborthash{counter:06d}",
  1212. "status": "completed",
  1213. }
  1214. defaults.update(kwargs)
  1215. archive = PrintArchive(**defaults)
  1216. db_session.add(archive)
  1217. await db_session.commit()
  1218. await db_session.refresh(archive)
  1219. return archive
  1220. return _create_archive
  1221. @pytest.fixture
  1222. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1223. """Factory to create test queue items."""
  1224. _counter = [0]
  1225. async def _create_queue_item(**kwargs):
  1226. from backend.app.models.print_queue import PrintQueueItem
  1227. _counter[0] += 1
  1228. counter = _counter[0]
  1229. if "printer_id" not in kwargs:
  1230. printer = await printer_factory()
  1231. kwargs["printer_id"] = printer.id
  1232. if "archive_id" not in kwargs:
  1233. archive = await archive_factory()
  1234. kwargs["archive_id"] = archive.id
  1235. defaults = {
  1236. "status": "pending",
  1237. "position": counter,
  1238. }
  1239. defaults.update(kwargs)
  1240. item = PrintQueueItem(**defaults)
  1241. db_session.add(item)
  1242. await db_session.commit()
  1243. await db_session.refresh(item)
  1244. return item
  1245. return _create_queue_item
  1246. @pytest.mark.asyncio
  1247. @pytest.mark.integration
  1248. async def test_on_print_complete_normalises_aborted_to_cancelled(self, queue_item_factory, db_session):
  1249. """Verify the completion handler maps 'aborted' → 'cancelled' for queue items."""
  1250. import asyncio
  1251. from unittest.mock import AsyncMock, MagicMock, patch
  1252. item = await queue_item_factory(status="printing")
  1253. # Build a mock session whose execute returns our item
  1254. mock_result = MagicMock()
  1255. mock_result.scalars.return_value.all.return_value = [item]
  1256. mock_session = AsyncMock()
  1257. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1258. mock_session.__aexit__ = AsyncMock(return_value=False)
  1259. mock_session.execute = AsyncMock(return_value=mock_result)
  1260. mock_session.commit = AsyncMock()
  1261. tasks_before = set(asyncio.all_tasks())
  1262. with (
  1263. patch("backend.app.main.async_session", return_value=mock_session),
  1264. patch("backend.app.core.database.async_session", return_value=mock_session),
  1265. patch("backend.app.main.ws_manager") as mock_ws,
  1266. patch("backend.app.main.mqtt_relay") as mock_relay,
  1267. patch("backend.app.main.notification_service") as mock_notif,
  1268. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1269. patch("backend.app.main.printer_manager") as mock_pm,
  1270. ):
  1271. mock_ws.send_print_complete = AsyncMock()
  1272. mock_ws.broadcast = AsyncMock()
  1273. mock_relay.on_print_complete = AsyncMock()
  1274. mock_relay.on_queue_job_completed = AsyncMock()
  1275. mock_notif.on_print_complete = AsyncMock()
  1276. mock_plug.on_print_complete = AsyncMock()
  1277. mock_pm.get_printer.return_value = None
  1278. from backend.app.main import on_print_complete
  1279. await on_print_complete(
  1280. item.printer_id,
  1281. {
  1282. "status": "aborted",
  1283. "filename": "test.gcode",
  1284. "subtask_name": "Test",
  1285. "timelapse_was_active": False,
  1286. },
  1287. )
  1288. # Cancel background tasks before leaving mock context
  1289. for task in asyncio.all_tasks() - tasks_before:
  1290. task.cancel()
  1291. try:
  1292. await task
  1293. except (asyncio.CancelledError, Exception):
  1294. pass
  1295. # The item status should be normalised to 'cancelled', not 'aborted'
  1296. assert item.status == "cancelled"
  1297. @pytest.mark.asyncio
  1298. @pytest.mark.integration
  1299. async def test_startup_fixup_converts_aborted_to_cancelled(self, queue_item_factory, db_session):
  1300. """Verify the startup fixup converts existing 'aborted' rows to 'cancelled'."""
  1301. from sqlalchemy import select
  1302. from backend.app.models.print_queue import PrintQueueItem
  1303. # Create items with various statuses including 'aborted'
  1304. item_aborted = await queue_item_factory(status="pending")
  1305. item_pending = await queue_item_factory(status="pending")
  1306. # Manually set the invalid status
  1307. item_aborted.status = "aborted"
  1308. db_session.add(item_aborted)
  1309. await db_session.commit()
  1310. # Run the fixup query (same logic as lifespan)
  1311. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1312. aborted_items = result.scalars().all()
  1313. for i in aborted_items:
  1314. i.status = "cancelled"
  1315. await db_session.commit()
  1316. # Verify: no more 'aborted' items
  1317. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1318. assert len(result.scalars().all()) == 0
  1319. # The previously aborted item should now be 'cancelled'
  1320. await db_session.refresh(item_aborted)
  1321. assert item_aborted.status == "cancelled"
  1322. # The pending item should be unchanged
  1323. await db_session.refresh(item_pending)
  1324. assert item_pending.status == "pending"
  1325. @pytest.mark.asyncio
  1326. @pytest.mark.integration
  1327. async def test_completed_status_passes_through_unchanged(self, queue_item_factory, db_session):
  1328. """Verify normal statuses like 'completed' are not affected by normalisation."""
  1329. import asyncio
  1330. from unittest.mock import AsyncMock, MagicMock, patch
  1331. item = await queue_item_factory(status="printing")
  1332. mock_result = MagicMock()
  1333. mock_result.scalars.return_value.all.return_value = [item]
  1334. mock_session = AsyncMock()
  1335. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1336. mock_session.__aexit__ = AsyncMock(return_value=False)
  1337. mock_session.execute = AsyncMock(return_value=mock_result)
  1338. mock_session.commit = AsyncMock()
  1339. tasks_before = set(asyncio.all_tasks())
  1340. with (
  1341. patch("backend.app.main.async_session", return_value=mock_session),
  1342. patch("backend.app.core.database.async_session", return_value=mock_session),
  1343. patch("backend.app.main.ws_manager") as mock_ws,
  1344. patch("backend.app.main.mqtt_relay") as mock_relay,
  1345. patch("backend.app.main.notification_service") as mock_notif,
  1346. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1347. patch("backend.app.main.printer_manager") as mock_pm,
  1348. ):
  1349. mock_ws.send_print_complete = AsyncMock()
  1350. mock_ws.broadcast = AsyncMock()
  1351. mock_relay.on_print_complete = AsyncMock()
  1352. mock_relay.on_queue_job_completed = AsyncMock()
  1353. mock_notif.on_print_complete = AsyncMock()
  1354. mock_plug.on_print_complete = AsyncMock()
  1355. mock_pm.get_printer.return_value = None
  1356. from backend.app.main import on_print_complete
  1357. await on_print_complete(
  1358. item.printer_id,
  1359. {
  1360. "status": "completed",
  1361. "filename": "test.gcode",
  1362. "subtask_name": "Test",
  1363. "timelapse_was_active": False,
  1364. },
  1365. )
  1366. # Cancel background tasks before leaving mock context
  1367. for task in asyncio.all_tasks() - tasks_before:
  1368. task.cancel()
  1369. try:
  1370. await task
  1371. except (asyncio.CancelledError, Exception):
  1372. pass
  1373. assert item.status == "completed"
  1374. # ========================================================================
  1375. # Library file usage tracking on print completion (#1008)
  1376. #
  1377. # These exercise the _bump_library_file_usage_if_completed helper directly
  1378. # rather than invoking the whole on_print_complete handler — that path
  1379. # spawns background asyncio tasks (notifications, MQTT relay, smart-plug)
  1380. # that are expensive to mock and have nothing to do with the bump logic.
  1381. # ========================================================================
  1382. @pytest.mark.asyncio
  1383. @pytest.mark.integration
  1384. async def test_bump_library_file_usage_on_completed(self, printer_factory, db_session):
  1385. """Successful completion increments print_count and stamps last_printed_at."""
  1386. from datetime import datetime, timezone
  1387. from backend.app.main import _bump_library_file_usage_if_completed
  1388. from backend.app.models.library import LibraryFile
  1389. from backend.app.models.print_queue import PrintQueueItem
  1390. printer = await printer_factory()
  1391. lib_file = LibraryFile(
  1392. filename="benchy.gcode.3mf",
  1393. file_path="/data/library/benchy.gcode.3mf",
  1394. file_type="gcode.3mf",
  1395. file_size=1024,
  1396. print_count=0,
  1397. last_printed_at=None,
  1398. )
  1399. db_session.add(lib_file)
  1400. await db_session.commit()
  1401. await db_session.refresh(lib_file)
  1402. item = PrintQueueItem(
  1403. printer_id=printer.id,
  1404. library_file_id=lib_file.id,
  1405. status="printing",
  1406. position=1,
  1407. )
  1408. before = datetime.now(timezone.utc).replace(tzinfo=None)
  1409. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1410. await db_session.commit()
  1411. await db_session.refresh(lib_file)
  1412. assert lib_file.print_count == 1
  1413. assert lib_file.last_printed_at is not None
  1414. assert lib_file.last_printed_at >= before
  1415. @pytest.mark.asyncio
  1416. @pytest.mark.integration
  1417. async def test_bump_library_file_usage_repeated_prints_increment_count(self, printer_factory, db_session):
  1418. """Each successful completion bumps print_count cumulatively."""
  1419. from backend.app.main import _bump_library_file_usage_if_completed
  1420. from backend.app.models.library import LibraryFile
  1421. from backend.app.models.print_queue import PrintQueueItem
  1422. printer = await printer_factory()
  1423. lib_file = LibraryFile(
  1424. filename="repeat.gcode.3mf",
  1425. file_path="/data/library/repeat.gcode.3mf",
  1426. file_type="gcode.3mf",
  1427. file_size=1024,
  1428. print_count=0,
  1429. )
  1430. db_session.add(lib_file)
  1431. await db_session.commit()
  1432. await db_session.refresh(lib_file)
  1433. item = PrintQueueItem(
  1434. printer_id=printer.id,
  1435. library_file_id=lib_file.id,
  1436. status="printing",
  1437. position=1,
  1438. )
  1439. for _ in range(3):
  1440. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1441. await db_session.commit()
  1442. await db_session.refresh(lib_file)
  1443. assert lib_file.print_count == 3
  1444. @pytest.mark.asyncio
  1445. @pytest.mark.integration
  1446. @pytest.mark.parametrize("terminal_status", ["failed", "cancelled"])
  1447. async def test_bump_library_file_usage_skips_non_completed(self, printer_factory, db_session, terminal_status):
  1448. """Failed and cancelled prints must NOT count as usage."""
  1449. from backend.app.main import _bump_library_file_usage_if_completed
  1450. from backend.app.models.library import LibraryFile
  1451. from backend.app.models.print_queue import PrintQueueItem
  1452. printer = await printer_factory()
  1453. lib_file = LibraryFile(
  1454. filename="broken.gcode.3mf",
  1455. file_path="/data/library/broken.gcode.3mf",
  1456. file_type="gcode.3mf",
  1457. file_size=1024,
  1458. print_count=0,
  1459. last_printed_at=None,
  1460. )
  1461. db_session.add(lib_file)
  1462. await db_session.commit()
  1463. await db_session.refresh(lib_file)
  1464. item = PrintQueueItem(
  1465. printer_id=printer.id,
  1466. library_file_id=lib_file.id,
  1467. status="printing",
  1468. position=1,
  1469. )
  1470. await _bump_library_file_usage_if_completed(db_session, item, terminal_status)
  1471. await db_session.commit()
  1472. await db_session.refresh(lib_file)
  1473. assert lib_file.print_count == 0
  1474. assert lib_file.last_printed_at is None
  1475. @pytest.mark.asyncio
  1476. @pytest.mark.integration
  1477. async def test_bump_library_file_usage_skips_when_no_library_file_id(
  1478. self, printer_factory, archive_factory, db_session
  1479. ):
  1480. """Queue items without library_file_id (e.g. archive reprints) are a no-op."""
  1481. from backend.app.main import _bump_library_file_usage_if_completed
  1482. from backend.app.models.print_queue import PrintQueueItem
  1483. printer = await printer_factory()
  1484. archive = await archive_factory()
  1485. item = PrintQueueItem(
  1486. printer_id=printer.id,
  1487. library_file_id=None,
  1488. archive_id=archive.id,
  1489. status="printing",
  1490. position=1,
  1491. )
  1492. # Must not raise.
  1493. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1494. # ========================================================================
  1495. # Batch quantity tests
  1496. # ========================================================================
  1497. @pytest.mark.asyncio
  1498. @pytest.mark.integration
  1499. async def test_add_to_queue_quantity_default(
  1500. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1501. ):
  1502. """Verify quantity=1 (default) creates a single item with no batch."""
  1503. printer = await printer_factory()
  1504. archive = await archive_factory()
  1505. data = {
  1506. "printer_id": printer.id,
  1507. "archive_id": archive.id,
  1508. }
  1509. response = await async_client.post("/api/v1/queue/", json=data)
  1510. assert response.status_code == 200
  1511. result = response.json()
  1512. assert result["batch_id"] is None
  1513. assert result["batch_name"] is None
  1514. @pytest.mark.asyncio
  1515. @pytest.mark.integration
  1516. async def test_add_to_queue_quantity_one_explicit(
  1517. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1518. ):
  1519. """Verify quantity=1 explicitly creates a single item with no batch."""
  1520. printer = await printer_factory()
  1521. archive = await archive_factory()
  1522. data = {
  1523. "printer_id": printer.id,
  1524. "archive_id": archive.id,
  1525. "quantity": 1,
  1526. }
  1527. response = await async_client.post("/api/v1/queue/", json=data)
  1528. assert response.status_code == 200
  1529. result = response.json()
  1530. assert result["batch_id"] is None
  1531. assert result["batch_name"] is None
  1532. @pytest.mark.asyncio
  1533. @pytest.mark.integration
  1534. async def test_add_to_queue_quantity_creates_batch(
  1535. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1536. ):
  1537. """Verify quantity > 1 creates a batch and multiple queue items."""
  1538. printer = await printer_factory()
  1539. archive = await archive_factory()
  1540. data = {
  1541. "printer_id": printer.id,
  1542. "archive_id": archive.id,
  1543. "quantity": 3,
  1544. }
  1545. response = await async_client.post("/api/v1/queue/", json=data)
  1546. assert response.status_code == 200
  1547. result = response.json()
  1548. # First item is returned, linked to a batch
  1549. assert result["batch_id"] is not None
  1550. assert result["batch_name"] is not None
  1551. assert "×3" in result["batch_name"]
  1552. # Verify all 3 items were created
  1553. list_response = await async_client.get("/api/v1/queue/")
  1554. items = list_response.json()
  1555. batch_items = [i for i in items if i["batch_id"] == result["batch_id"]]
  1556. assert len(batch_items) == 3
  1557. # All items should have the same settings
  1558. for item in batch_items:
  1559. assert item["printer_id"] == printer.id
  1560. assert item["archive_id"] == archive.id
  1561. assert item["status"] == "pending"
  1562. @pytest.mark.asyncio
  1563. @pytest.mark.integration
  1564. async def test_add_to_queue_quantity_sequential_positions(
  1565. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1566. ):
  1567. """Verify batch items get sequential positions."""
  1568. printer = await printer_factory()
  1569. archive = await archive_factory()
  1570. data = {
  1571. "printer_id": printer.id,
  1572. "archive_id": archive.id,
  1573. "quantity": 3,
  1574. }
  1575. response = await async_client.post("/api/v1/queue/", json=data)
  1576. assert response.status_code == 200
  1577. batch_id = response.json()["batch_id"]
  1578. list_response = await async_client.get("/api/v1/queue/")
  1579. items = list_response.json()
  1580. batch_items = sorted(
  1581. [i for i in items if i["batch_id"] == batch_id],
  1582. key=lambda i: i["position"],
  1583. )
  1584. positions = [i["position"] for i in batch_items]
  1585. assert positions == [positions[0], positions[0] + 1, positions[0] + 2]
  1586. @pytest.mark.asyncio
  1587. @pytest.mark.integration
  1588. async def test_add_to_queue_quantity_with_print_options(
  1589. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1590. ):
  1591. """Verify print options are applied to all batch items."""
  1592. printer = await printer_factory()
  1593. archive = await archive_factory()
  1594. data = {
  1595. "printer_id": printer.id,
  1596. "archive_id": archive.id,
  1597. "quantity": 2,
  1598. "bed_levelling": False,
  1599. "timelapse": True,
  1600. }
  1601. response = await async_client.post("/api/v1/queue/", json=data)
  1602. assert response.status_code == 200
  1603. batch_id = response.json()["batch_id"]
  1604. list_response = await async_client.get("/api/v1/queue/")
  1605. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1606. assert len(batch_items) == 2
  1607. for item in batch_items:
  1608. assert item["bed_levelling"] is False
  1609. assert item["timelapse"] is True
  1610. @pytest.mark.asyncio
  1611. @pytest.mark.integration
  1612. async def test_get_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1613. """Verify batch can be retrieved with progress stats."""
  1614. printer = await printer_factory()
  1615. archive = await archive_factory()
  1616. # Create a batch of 3
  1617. data = {
  1618. "printer_id": printer.id,
  1619. "archive_id": archive.id,
  1620. "quantity": 3,
  1621. }
  1622. response = await async_client.post("/api/v1/queue/", json=data)
  1623. batch_id = response.json()["batch_id"]
  1624. # Get batch
  1625. response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1626. assert response.status_code == 200
  1627. result = response.json()
  1628. assert result["id"] == batch_id
  1629. assert result["quantity"] == 3
  1630. assert result["status"] == "active"
  1631. assert result["pending_count"] == 3
  1632. assert result["printing_count"] == 0
  1633. assert result["completed_count"] == 0
  1634. @pytest.mark.asyncio
  1635. @pytest.mark.integration
  1636. async def test_list_batches(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1637. """Verify batches can be listed."""
  1638. printer = await printer_factory()
  1639. archive = await archive_factory()
  1640. # Create two batches
  1641. for qty in [2, 3]:
  1642. await async_client.post(
  1643. "/api/v1/queue/",
  1644. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": qty},
  1645. )
  1646. response = await async_client.get("/api/v1/queue/batches")
  1647. assert response.status_code == 200
  1648. batches = response.json()
  1649. assert len(batches) >= 2
  1650. @pytest.mark.asyncio
  1651. @pytest.mark.integration
  1652. async def test_cancel_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1653. """Verify cancelling a batch cancels all pending items."""
  1654. printer = await printer_factory()
  1655. archive = await archive_factory()
  1656. data = {
  1657. "printer_id": printer.id,
  1658. "archive_id": archive.id,
  1659. "quantity": 3,
  1660. }
  1661. response = await async_client.post("/api/v1/queue/", json=data)
  1662. batch_id = response.json()["batch_id"]
  1663. # Cancel the batch
  1664. response = await async_client.delete(f"/api/v1/queue/batches/{batch_id}")
  1665. assert response.status_code == 200
  1666. # Verify all items are cancelled
  1667. list_response = await async_client.get("/api/v1/queue/")
  1668. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1669. for item in batch_items:
  1670. assert item["status"] == "cancelled"
  1671. # Verify batch status
  1672. batch_response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1673. assert batch_response.json()["status"] == "cancelled"
  1674. @pytest.mark.asyncio
  1675. @pytest.mark.integration
  1676. async def test_get_batch_not_found(self, async_client: AsyncClient):
  1677. """Verify 404 for non-existent batch."""
  1678. response = await async_client.get("/api/v1/queue/batches/9999")
  1679. assert response.status_code == 404
  1680. # ========================================================================
  1681. # Queue redesign: create-empty + group-existing + ungroup
  1682. # ========================================================================
  1683. @pytest.mark.asyncio
  1684. @pytest.mark.integration
  1685. async def test_create_empty_batch_for_client_side_grouping(
  1686. self, async_client: AsyncClient, printer_factory, archive_factory
  1687. ):
  1688. """Verify POST /queue/batches without item_ids creates an empty batch
  1689. whose id can be passed on subsequent /queue/ POSTs (the multi-plate
  1690. auto-batch flow). Subsequent items must end up with the same batch_id."""
  1691. printer = await printer_factory()
  1692. archive = await archive_factory()
  1693. # 1. Pre-create batch
  1694. batch_resp = await async_client.post(
  1695. "/api/v1/queue/batches",
  1696. json={"name": "Plates · 2 plates", "archive_id": archive.id},
  1697. )
  1698. assert batch_resp.status_code == 200
  1699. batch = batch_resp.json()
  1700. assert batch["status"] == "active"
  1701. batch_id = batch["id"]
  1702. # 2. Add two items referencing that batch
  1703. for plate_id in (1, 2):
  1704. item_resp = await async_client.post(
  1705. "/api/v1/queue/",
  1706. json={
  1707. "printer_id": printer.id,
  1708. "archive_id": archive.id,
  1709. "plate_id": plate_id,
  1710. "batch_id": batch_id,
  1711. },
  1712. )
  1713. assert item_resp.status_code == 200
  1714. assert item_resp.json()["batch_id"] == batch_id
  1715. # 3. Verify batch now has 2 pending children
  1716. list_resp = await async_client.get("/api/v1/queue/")
  1717. siblings = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  1718. assert len(siblings) == 2
  1719. assert {i["plate_id"] for i in siblings} == {1, 2}
  1720. @pytest.mark.asyncio
  1721. @pytest.mark.integration
  1722. async def test_group_existing_items_as_batch(
  1723. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  1724. ):
  1725. """Verify POST /queue/batches with item_ids assigns batch_id to
  1726. existing pending items (the 'Group as batch' UI action)."""
  1727. printer = await printer_factory()
  1728. archive = await archive_factory()
  1729. item_a = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  1730. item_b = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  1731. resp = await async_client.post(
  1732. "/api/v1/queue/batches",
  1733. json={"name": "Manual group", "item_ids": [item_a.id, item_b.id]},
  1734. )
  1735. assert resp.status_code == 200
  1736. batch_id = resp.json()["id"]
  1737. list_resp = await async_client.get("/api/v1/queue/")
  1738. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  1739. assert {i["id"] for i in grouped} == {item_a.id, item_b.id}
  1740. @pytest.mark.asyncio
  1741. @pytest.mark.integration
  1742. async def test_group_skips_non_pending_items(
  1743. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  1744. ):
  1745. """Verify grouping doesn't pull in already-completed/cancelled items."""
  1746. printer = await printer_factory()
  1747. archive = await archive_factory()
  1748. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  1749. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  1750. resp = await async_client.post(
  1751. "/api/v1/queue/batches",
  1752. json={"name": "Mixed", "item_ids": [pending.id, completed.id]},
  1753. )
  1754. assert resp.status_code == 200
  1755. batch_id = resp.json()["id"]
  1756. list_resp = await async_client.get("/api/v1/queue/")
  1757. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  1758. assert {i["id"] for i in grouped} == {pending.id}
  1759. @pytest.mark.asyncio
  1760. @pytest.mark.integration
  1761. async def test_create_batch_requires_name(self, async_client: AsyncClient):
  1762. """Verify empty / whitespace-only name is rejected with 400."""
  1763. resp = await async_client.post("/api/v1/queue/batches", json={"name": " "})
  1764. assert resp.status_code == 400
  1765. @pytest.mark.asyncio
  1766. @pytest.mark.integration
  1767. async def test_ungroup_batch_clears_batch_id_and_deletes_row(
  1768. self, async_client: AsyncClient, printer_factory, archive_factory
  1769. ):
  1770. """Verify POST /queue/batches/{id}/ungroup clears batch_id from all
  1771. members and deletes the batch row when nothing remains assigned."""
  1772. printer = await printer_factory()
  1773. archive = await archive_factory()
  1774. # Create batch with two items via the existing quantity flow
  1775. add_resp = await async_client.post(
  1776. "/api/v1/queue/",
  1777. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": 2},
  1778. )
  1779. batch_id = add_resp.json()["batch_id"]
  1780. # Ungroup
  1781. ungroup_resp = await async_client.post(f"/api/v1/queue/batches/{batch_id}/ungroup")
  1782. assert ungroup_resp.status_code == 200
  1783. assert ungroup_resp.json()["ungrouped_count"] == 2
  1784. # Verify items still exist but no longer batched
  1785. list_resp = await async_client.get("/api/v1/queue/")
  1786. ex_members = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  1787. assert ex_members == []
  1788. # Batch row was deleted
  1789. get_resp = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1790. assert get_resp.status_code == 404
  1791. @pytest.mark.asyncio
  1792. @pytest.mark.integration
  1793. async def test_add_to_queue_with_unknown_batch_id_404(
  1794. self, async_client: AsyncClient, printer_factory, archive_factory
  1795. ):
  1796. """Verify addToQueue with a non-existent batch_id is rejected."""
  1797. printer = await printer_factory()
  1798. archive = await archive_factory()
  1799. resp = await async_client.post(
  1800. "/api/v1/queue/",
  1801. json={
  1802. "printer_id": printer.id,
  1803. "archive_id": archive.id,
  1804. "batch_id": 99999,
  1805. },
  1806. )
  1807. assert resp.status_code == 404
  1808. # ========================================================================
  1809. # Soft-deleted archive handling (#1348 follow-up)
  1810. # ========================================================================
  1811. @pytest.mark.asyncio
  1812. @pytest.mark.integration
  1813. async def test_soft_delete_archive_deletes_all_related_queue_items(
  1814. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1815. ):
  1816. """Soft-deleting an archive removes every related queue item, regardless
  1817. of status (#1734). Pre-#1734 only ``pending`` rows were flipped to
  1818. ``cancelled`` and stayed in the DB, surprising users who expected the
  1819. queue lines to disappear with the archive — especially on multi-plate
  1820. Send All uploads (#1733), where ONE archive backed N queue items and
  1821. soft-deleting the archive left N "cancelled" rows behind. The change
  1822. keeps the printing guard (a row with ``status='printing'`` blocks the
  1823. delete one layer up at the API route), so we never delete the row of
  1824. an actively-running print here.
  1825. Print history lives in ``PrintLogEntry`` (FK ``ON DELETE SET NULL``) —
  1826. the audit trail survives independently of the queue rows.
  1827. """
  1828. from sqlalchemy import select
  1829. from backend.app.models.print_queue import PrintQueueItem
  1830. from backend.app.services.archive import ArchiveService
  1831. printer = await printer_factory()
  1832. archive = await archive_factory(thumbnail_path="archives/test/test/thumbnail.png")
  1833. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  1834. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  1835. service = ArchiveService(db_session)
  1836. assert await service.soft_delete_archive(archive.id) is True
  1837. # Every queue row that referenced this archive is gone — both the
  1838. # pending and the completed rows. Print history (PrintLogEntry) is
  1839. # the authoritative record and is preserved by the FK SET NULL.
  1840. remaining = (
  1841. (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_([pending.id, completed.id]))))
  1842. .scalars()
  1843. .all()
  1844. )
  1845. assert remaining == [], (
  1846. "Soft-deleting the archive must delete every related queue row, "
  1847. f"got {[(r.id, r.status) for r in remaining]} still present"
  1848. )
  1849. @pytest.mark.asyncio
  1850. @pytest.mark.integration
  1851. async def test_queue_api_hides_archive_surface_when_soft_deleted(
  1852. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1853. ):
  1854. """Queue serializer must NOT populate archive_thumbnail / archive_name
  1855. when the archive is soft-deleted — otherwise the frontend renders a
  1856. broken <img> and 404-storms the thumbnail / plates / plate-thumbnail
  1857. endpoints. archive_deleted=True signals the soft-deleted state so
  1858. the UI can render a 'source deleted' badge."""
  1859. from datetime import datetime, timezone
  1860. printer = await printer_factory()
  1861. archive = await archive_factory(
  1862. print_name="Test Print",
  1863. thumbnail_path="archives/test/test/thumbnail.png",
  1864. deleted_at=datetime.now(timezone.utc), # Pre-soft-deleted
  1865. )
  1866. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="cancelled")
  1867. resp = await async_client.get("/api/v1/queue/")
  1868. assert resp.status_code == 200
  1869. body = resp.json()
  1870. row = next((r for r in body if r["id"] == item.id), None)
  1871. assert row is not None
  1872. assert row["archive_deleted"] is True
  1873. assert row["archive_thumbnail"] is None, "must not expose stale thumbnail path for soft-deleted archive"
  1874. assert row["archive_name"] is None
  1875. @pytest.mark.asyncio
  1876. @pytest.mark.integration
  1877. async def test_queue_api_still_exposes_archive_surface_when_live(
  1878. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1879. ):
  1880. """Sanity guard: the soft-delete suppression must not affect live
  1881. archives. archive_name / archive_thumbnail still flow through and
  1882. archive_deleted stays False."""
  1883. printer = await printer_factory()
  1884. archive = await archive_factory(
  1885. print_name="Live Archive",
  1886. thumbnail_path="archives/test/live/thumbnail.png",
  1887. )
  1888. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  1889. resp = await async_client.get("/api/v1/queue/")
  1890. assert resp.status_code == 200
  1891. row = next((r for r in resp.json() if r["id"] == item.id), None)
  1892. assert row is not None
  1893. assert row["archive_deleted"] is False
  1894. assert row["archive_name"] == "Live Archive"
  1895. assert row["archive_thumbnail"] == "archives/test/live/thumbnail.png"