test_print_queue_api.py 74 KB

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