test_print_queue_api.py 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238
  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_library_file_rejects_cross_model_mismatch(
  711. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  712. ):
  713. """Cross-model gate (#2578) also reads sliced_for_model from library file metadata."""
  714. await printer_factory(model="H2D")
  715. lib_file = await library_file_factory(file_metadata={"print_name": "Mismatch", "sliced_for_model": "X1C"})
  716. response = await async_client.post(
  717. "/api/v1/queue/",
  718. json={"target_model": "H2D", "library_file_id": lib_file.id},
  719. )
  720. assert response.status_code == 400
  721. assert "sliced for X1C" in response.json()["detail"]
  722. @pytest.mark.asyncio
  723. @pytest.mark.integration
  724. async def test_add_to_queue_library_file_with_options(
  725. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  726. ):
  727. """Verify library file queue item can have all options set."""
  728. printer = await printer_factory()
  729. lib_file = await library_file_factory()
  730. data = {
  731. "printer_id": printer.id,
  732. "library_file_id": lib_file.id,
  733. "ams_mapping": [1, 2, -1, -1],
  734. "plate_id": 2,
  735. "bed_levelling": False,
  736. "timelapse": True,
  737. "manual_start": True,
  738. }
  739. response = await async_client.post("/api/v1/queue/", json=data)
  740. assert response.status_code == 200
  741. result = response.json()
  742. assert result["library_file_id"] == lib_file.id
  743. assert result["ams_mapping"] == [1, 2, -1, -1]
  744. assert result["plate_id"] == 2
  745. assert result["bed_levelling"] is False
  746. assert result["timelapse"] is True
  747. assert result["manual_start"] is True
  748. @pytest.mark.asyncio
  749. @pytest.mark.integration
  750. async def test_add_to_queue_requires_archive_or_library_file(
  751. self, async_client: AsyncClient, printer_factory, db_session
  752. ):
  753. """Verify 400 error when neither archive_id nor library_file_id provided."""
  754. printer = await printer_factory()
  755. data = {
  756. "printer_id": printer.id,
  757. }
  758. response = await async_client.post("/api/v1/queue/", json=data)
  759. assert response.status_code == 400
  760. assert (
  761. "archive_id" in response.json()["detail"].lower() or "library_file_id" in response.json()["detail"].lower()
  762. )
  763. @pytest.mark.asyncio
  764. @pytest.mark.integration
  765. async def test_update_queue_item_with_library_file(
  766. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  767. ):
  768. """Verify queue item with library_file_id can be updated."""
  769. from backend.app.models.print_queue import PrintQueueItem
  770. printer = await printer_factory()
  771. lib_file = await library_file_factory()
  772. # Create queue item directly
  773. item = PrintQueueItem(
  774. printer_id=printer.id,
  775. library_file_id=lib_file.id,
  776. status="pending",
  777. position=1,
  778. )
  779. db_session.add(item)
  780. await db_session.commit()
  781. await db_session.refresh(item)
  782. # Update the item
  783. response = await async_client.patch(
  784. f"/api/v1/queue/{item.id}",
  785. json={"auto_off_after": True, "plate_id": 3},
  786. )
  787. assert response.status_code == 200
  788. result = response.json()
  789. assert result["auto_off_after"] is True
  790. assert result["plate_id"] == 3
  791. assert result["library_file_id"] == lib_file.id
  792. @pytest.mark.asyncio
  793. @pytest.mark.integration
  794. async def test_list_queue_includes_library_file_info(
  795. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  796. ):
  797. """Verify queue list includes library file metadata."""
  798. from backend.app.models.print_queue import PrintQueueItem
  799. printer = await printer_factory()
  800. lib_file = await library_file_factory(
  801. file_metadata={"print_name": "Custom Print Name", "print_time_seconds": 7200}
  802. )
  803. item = PrintQueueItem(
  804. printer_id=printer.id,
  805. library_file_id=lib_file.id,
  806. status="pending",
  807. position=1,
  808. )
  809. db_session.add(item)
  810. await db_session.commit()
  811. response = await async_client.get("/api/v1/queue/")
  812. assert response.status_code == 200
  813. items = response.json()
  814. assert len(items) >= 1
  815. # Find our item
  816. our_item = next((i for i in items if i["library_file_id"] == lib_file.id), None)
  817. assert our_item is not None
  818. assert our_item["library_file_name"] == "Custom Print Name"
  819. assert our_item["print_time_seconds"] == 7200
  820. class TestBulkUpdateEndpoint:
  821. """Tests for the /queue/bulk endpoint."""
  822. @pytest.fixture
  823. async def printer_factory(self, db_session):
  824. """Factory to create test printers."""
  825. _counter = [0]
  826. async def _create_printer(**kwargs):
  827. from backend.app.models.printer import Printer
  828. _counter[0] += 1
  829. counter = _counter[0]
  830. defaults = {
  831. "name": f"Bulk Test Printer {counter}",
  832. "ip_address": f"192.168.1.{150 + counter}",
  833. "serial_number": f"TESTBULK{counter:04d}",
  834. "access_code": "12345678",
  835. "model": "X1C",
  836. }
  837. defaults.update(kwargs)
  838. printer = Printer(**defaults)
  839. db_session.add(printer)
  840. await db_session.commit()
  841. await db_session.refresh(printer)
  842. return printer
  843. return _create_printer
  844. @pytest.fixture
  845. async def archive_factory(self, db_session):
  846. """Factory to create test archives."""
  847. _counter = [0]
  848. async def _create_archive(**kwargs):
  849. from backend.app.models.archive import PrintArchive
  850. _counter[0] += 1
  851. counter = _counter[0]
  852. defaults = {
  853. "filename": f"bulk_test_{counter}.3mf",
  854. "print_name": f"Bulk Test Print {counter}",
  855. "file_path": f"/tmp/bulk_test_{counter}.3mf",
  856. "file_size": 1024,
  857. "content_hash": f"bulkhash{counter:04d}",
  858. "status": "completed",
  859. }
  860. defaults.update(kwargs)
  861. archive = PrintArchive(**defaults)
  862. db_session.add(archive)
  863. await db_session.commit()
  864. await db_session.refresh(archive)
  865. return archive
  866. return _create_archive
  867. @pytest.fixture
  868. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  869. """Factory to create test queue items."""
  870. async def _create_item(**kwargs):
  871. from backend.app.models.print_queue import PrintQueueItem
  872. if "printer_id" not in kwargs:
  873. printer = await printer_factory()
  874. kwargs["printer_id"] = printer.id
  875. if "archive_id" not in kwargs:
  876. archive = await archive_factory()
  877. kwargs["archive_id"] = archive.id
  878. defaults = {
  879. "status": "pending",
  880. "position": 1,
  881. "bed_levelling": True,
  882. "flow_cali": False,
  883. "vibration_cali": True,
  884. }
  885. defaults.update(kwargs)
  886. item = PrintQueueItem(**defaults)
  887. db_session.add(item)
  888. await db_session.commit()
  889. await db_session.refresh(item)
  890. return item
  891. return _create_item
  892. @pytest.mark.asyncio
  893. @pytest.mark.integration
  894. async def test_bulk_update_single_field(self, async_client: AsyncClient, queue_item_factory, db_session):
  895. """Verify bulk update can change a single field on multiple items."""
  896. item1 = await queue_item_factory(bed_levelling=True)
  897. item2 = await queue_item_factory(bed_levelling=True)
  898. response = await async_client.patch(
  899. "/api/v1/queue/bulk",
  900. json={"item_ids": [item1.id, item2.id], "bed_levelling": False},
  901. )
  902. assert response.status_code == 200
  903. result = response.json()
  904. assert result["updated_count"] == 2
  905. assert result["skipped_count"] == 0
  906. # Verify items were updated
  907. await db_session.refresh(item1)
  908. await db_session.refresh(item2)
  909. assert item1.bed_levelling is False
  910. assert item2.bed_levelling is False
  911. @pytest.mark.asyncio
  912. @pytest.mark.integration
  913. async def test_bulk_update_multiple_fields(self, async_client: AsyncClient, queue_item_factory, db_session):
  914. """Verify bulk update can change multiple fields at once."""
  915. item1 = await queue_item_factory(bed_levelling=True, flow_cali=False, manual_start=False)
  916. item2 = await queue_item_factory(bed_levelling=True, flow_cali=False, manual_start=False)
  917. response = await async_client.patch(
  918. "/api/v1/queue/bulk",
  919. json={
  920. "item_ids": [item1.id, item2.id],
  921. "bed_levelling": False,
  922. "flow_cali": True,
  923. "manual_start": True,
  924. },
  925. )
  926. assert response.status_code == 200
  927. result = response.json()
  928. assert result["updated_count"] == 2
  929. await db_session.refresh(item1)
  930. assert item1.bed_levelling is False
  931. assert item1.flow_cali is True
  932. assert item1.manual_start is True
  933. @pytest.mark.asyncio
  934. @pytest.mark.integration
  935. async def test_bulk_update_skips_non_pending(self, async_client: AsyncClient, queue_item_factory, db_session):
  936. """Verify bulk update skips non-pending items."""
  937. pending_item = await queue_item_factory(status="pending", bed_levelling=True)
  938. printing_item = await queue_item_factory(status="printing", bed_levelling=True)
  939. completed_item = await queue_item_factory(status="completed", bed_levelling=True)
  940. response = await async_client.patch(
  941. "/api/v1/queue/bulk",
  942. json={
  943. "item_ids": [pending_item.id, printing_item.id, completed_item.id],
  944. "bed_levelling": False,
  945. },
  946. )
  947. assert response.status_code == 200
  948. result = response.json()
  949. assert result["updated_count"] == 1
  950. assert result["skipped_count"] == 2
  951. # Only pending item should be updated
  952. await db_session.refresh(pending_item)
  953. await db_session.refresh(printing_item)
  954. await db_session.refresh(completed_item)
  955. assert pending_item.bed_levelling is False
  956. assert printing_item.bed_levelling is True
  957. assert completed_item.bed_levelling is True
  958. @pytest.mark.asyncio
  959. @pytest.mark.integration
  960. async def test_bulk_update_change_printer(
  961. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  962. ):
  963. """Verify bulk update can reassign items to a different printer."""
  964. new_printer = await printer_factory(name="New Target Printer")
  965. item1 = await queue_item_factory()
  966. item2 = await queue_item_factory()
  967. original_printer_id = item1.printer_id
  968. response = await async_client.patch(
  969. "/api/v1/queue/bulk",
  970. json={"item_ids": [item1.id, item2.id], "printer_id": new_printer.id},
  971. )
  972. assert response.status_code == 200
  973. await db_session.refresh(item1)
  974. await db_session.refresh(item2)
  975. assert item1.printer_id == new_printer.id
  976. assert item2.printer_id == new_printer.id
  977. assert item1.printer_id != original_printer_id
  978. @pytest.mark.asyncio
  979. @pytest.mark.integration
  980. async def test_bulk_update_empty_item_ids(self, async_client: AsyncClient):
  981. """Verify 400 error when item_ids is empty."""
  982. response = await async_client.patch(
  983. "/api/v1/queue/bulk",
  984. json={"item_ids": [], "bed_levelling": False},
  985. )
  986. assert response.status_code == 400
  987. assert "no item" in response.json()["detail"].lower()
  988. @pytest.mark.asyncio
  989. @pytest.mark.integration
  990. async def test_bulk_update_no_fields(self, async_client: AsyncClient, queue_item_factory):
  991. """Verify 400 error when no fields to update."""
  992. item = await queue_item_factory()
  993. response = await async_client.patch(
  994. "/api/v1/queue/bulk",
  995. json={"item_ids": [item.id]},
  996. )
  997. assert response.status_code == 400
  998. assert "no fields" in response.json()["detail"].lower()
  999. @pytest.mark.asyncio
  1000. @pytest.mark.integration
  1001. async def test_bulk_update_invalid_printer(self, async_client: AsyncClient, queue_item_factory):
  1002. """Verify 400 error when printer_id doesn't exist."""
  1003. item = await queue_item_factory()
  1004. response = await async_client.patch(
  1005. "/api/v1/queue/bulk",
  1006. json={"item_ids": [item.id], "printer_id": 99999},
  1007. )
  1008. assert response.status_code == 400
  1009. assert "printer not found" in response.json()["detail"].lower()
  1010. class TestTargetLocationFeature:
  1011. """Tests for queue items with target_location (Issue #220)."""
  1012. @pytest.fixture
  1013. async def printer_factory(self, db_session):
  1014. """Factory to create test printers."""
  1015. _counter = [0]
  1016. async def _create_printer(**kwargs):
  1017. from backend.app.models.printer import Printer
  1018. _counter[0] += 1
  1019. counter = _counter[0]
  1020. defaults = {
  1021. "name": f"Location Test Printer {counter}",
  1022. "ip_address": f"192.168.1.{50 + counter}",
  1023. "serial_number": f"TESTLOC{counter:04d}",
  1024. "access_code": "12345678",
  1025. "model": "X1C",
  1026. }
  1027. defaults.update(kwargs)
  1028. printer = Printer(**defaults)
  1029. db_session.add(printer)
  1030. await db_session.commit()
  1031. await db_session.refresh(printer)
  1032. return printer
  1033. return _create_printer
  1034. @pytest.fixture
  1035. async def archive_factory(self, db_session):
  1036. """Factory to create test archives."""
  1037. _counter = [0]
  1038. async def _create_archive(**kwargs):
  1039. from backend.app.models.archive import PrintArchive
  1040. _counter[0] += 1
  1041. counter = _counter[0]
  1042. defaults = {
  1043. "filename": f"location_test_{counter}.3mf",
  1044. "print_name": f"Location Test Print {counter}",
  1045. "file_path": f"/tmp/location_test_{counter}.3mf",
  1046. "file_size": 1024,
  1047. "content_hash": f"lochash{counter:08d}",
  1048. "status": "completed",
  1049. }
  1050. defaults.update(kwargs)
  1051. archive = PrintArchive(**defaults)
  1052. db_session.add(archive)
  1053. await db_session.commit()
  1054. await db_session.refresh(archive)
  1055. return archive
  1056. return _create_archive
  1057. @pytest.fixture
  1058. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1059. """Factory to create test queue items."""
  1060. _counter = [0]
  1061. async def _create_queue_item(**kwargs):
  1062. from backend.app.models.print_queue import PrintQueueItem
  1063. _counter[0] += 1
  1064. counter = _counter[0]
  1065. if "printer_id" not in kwargs and "target_model" not in kwargs:
  1066. printer = await printer_factory()
  1067. kwargs["printer_id"] = printer.id
  1068. if "archive_id" not in kwargs:
  1069. archive = await archive_factory()
  1070. kwargs["archive_id"] = archive.id
  1071. defaults = {
  1072. "status": "pending",
  1073. "position": counter,
  1074. }
  1075. defaults.update(kwargs)
  1076. item = PrintQueueItem(**defaults)
  1077. db_session.add(item)
  1078. await db_session.commit()
  1079. await db_session.refresh(item)
  1080. return item
  1081. return _create_queue_item
  1082. @pytest.mark.asyncio
  1083. @pytest.mark.integration
  1084. async def test_add_to_queue_with_target_location(
  1085. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1086. ):
  1087. """Verify item can be added with target_model and target_location."""
  1088. # Create a printer with model X1C so the API can validate
  1089. await printer_factory(model="X1C", location="Office")
  1090. archive = await archive_factory()
  1091. data = {
  1092. "target_model": "X1C",
  1093. "target_location": "Workbench",
  1094. "archive_id": archive.id,
  1095. }
  1096. response = await async_client.post("/api/v1/queue/", json=data)
  1097. assert response.status_code == 200
  1098. result = response.json()
  1099. assert result["target_model"] == "X1C"
  1100. assert result["target_location"] == "Workbench"
  1101. assert result["printer_id"] is None
  1102. @pytest.mark.asyncio
  1103. @pytest.mark.integration
  1104. async def test_add_to_queue_location_without_model_ignored(
  1105. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1106. ):
  1107. """Verify target_location without target_model is allowed (location is just ignored)."""
  1108. printer = await printer_factory()
  1109. archive = await archive_factory()
  1110. data = {
  1111. "printer_id": printer.id,
  1112. "target_location": "Workbench", # This gets ignored since printer_id is set
  1113. "archive_id": archive.id,
  1114. }
  1115. response = await async_client.post("/api/v1/queue/", json=data)
  1116. # The API accepts this but the location is only used with target_model
  1117. assert response.status_code == 200
  1118. result = response.json()
  1119. assert result["printer_id"] == printer.id
  1120. # Location may or may not be stored since it's meaningless without target_model
  1121. # The important thing is the request succeeds
  1122. @pytest.mark.asyncio
  1123. @pytest.mark.integration
  1124. async def test_queue_item_target_location_in_response(
  1125. self, async_client: AsyncClient, queue_item_factory, db_session
  1126. ):
  1127. """Verify target_location is returned in queue item response."""
  1128. item = await queue_item_factory(
  1129. printer_id=None,
  1130. target_model="X1C",
  1131. target_location="Workshop",
  1132. )
  1133. response = await async_client.get(f"/api/v1/queue/{item.id}")
  1134. assert response.status_code == 200
  1135. result = response.json()
  1136. assert result["target_model"] == "X1C"
  1137. assert result["target_location"] == "Workshop"
  1138. @pytest.mark.asyncio
  1139. @pytest.mark.integration
  1140. async def test_queue_list_includes_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1141. """Verify target_location is included in queue list."""
  1142. await queue_item_factory(
  1143. printer_id=None,
  1144. target_model="P1S",
  1145. target_location="Garage",
  1146. )
  1147. response = await async_client.get("/api/v1/queue/")
  1148. assert response.status_code == 200
  1149. items = response.json()
  1150. assert len(items) >= 1
  1151. # Find our item
  1152. our_item = next((i for i in items if i["target_location"] == "Garage"), None)
  1153. assert our_item is not None
  1154. assert our_item["target_model"] == "P1S"
  1155. @pytest.mark.asyncio
  1156. @pytest.mark.integration
  1157. async def test_update_queue_item_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1158. """Verify target_location can be updated on existing queue item."""
  1159. item = await queue_item_factory(
  1160. printer_id=None,
  1161. target_model="X1C",
  1162. target_location="Office",
  1163. )
  1164. response = await async_client.patch(
  1165. f"/api/v1/queue/{item.id}",
  1166. json={"target_location": "Basement"},
  1167. )
  1168. assert response.status_code == 200
  1169. result = response.json()
  1170. assert result["target_location"] == "Basement"
  1171. @pytest.mark.asyncio
  1172. @pytest.mark.integration
  1173. async def test_clear_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1174. """Verify target_location can be cleared (set to None)."""
  1175. item = await queue_item_factory(
  1176. printer_id=None,
  1177. target_model="X1C",
  1178. target_location="Office",
  1179. )
  1180. # Note: Setting to empty string should clear it
  1181. response = await async_client.patch(
  1182. f"/api/v1/queue/{item.id}",
  1183. json={"target_location": None},
  1184. )
  1185. assert response.status_code == 200
  1186. result = response.json()
  1187. assert result["target_location"] is None
  1188. # ------------------------------------------------------------------
  1189. # Cross-model dispatch gate (#2578): a G-code 3MF sliced for one model
  1190. # must not be queued for model-based dispatch to an incompatible model.
  1191. # ------------------------------------------------------------------
  1192. @pytest.mark.asyncio
  1193. @pytest.mark.integration
  1194. async def test_add_to_queue_rejects_cross_model_mismatch(
  1195. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1196. ):
  1197. """X1C-sliced archive + target_model=H2D must be rejected (#2578)."""
  1198. await printer_factory(model="H2D")
  1199. archive = await archive_factory(sliced_for_model="X1C")
  1200. response = await async_client.post(
  1201. "/api/v1/queue/",
  1202. json={"target_model": "H2D", "archive_id": archive.id},
  1203. )
  1204. assert response.status_code == 400
  1205. assert "sliced for X1C" in response.json()["detail"]
  1206. @pytest.mark.asyncio
  1207. @pytest.mark.integration
  1208. async def test_add_to_queue_allows_gcode_family_target(
  1209. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1210. ):
  1211. """X1C-sliced G-code on a P1S is an intentional mixed-farm workflow —
  1212. same kinematics/volume family, must stay allowed."""
  1213. await printer_factory(model="P1S")
  1214. archive = await archive_factory(sliced_for_model="X1C")
  1215. response = await async_client.post(
  1216. "/api/v1/queue/",
  1217. json={"target_model": "P1S", "archive_id": archive.id},
  1218. )
  1219. assert response.status_code == 200
  1220. assert response.json()["target_model"] == "P1S"
  1221. @pytest.mark.asyncio
  1222. @pytest.mark.integration
  1223. async def test_add_to_queue_without_sliced_metadata_not_blocked(
  1224. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1225. ):
  1226. """Legacy archives without sliced_for_model can't be validated — must keep working."""
  1227. await printer_factory(model="H2D")
  1228. archive = await archive_factory() # no sliced_for_model
  1229. response = await async_client.post(
  1230. "/api/v1/queue/",
  1231. json={"target_model": "H2D", "archive_id": archive.id},
  1232. )
  1233. assert response.status_code == 200
  1234. @pytest.mark.asyncio
  1235. @pytest.mark.integration
  1236. async def test_update_rejects_cross_model_mismatch(
  1237. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1238. ):
  1239. """Editing an item must not be able to introduce an incompatible target either."""
  1240. await printer_factory(model="X1C")
  1241. await printer_factory(model="H2D")
  1242. archive = await archive_factory(sliced_for_model="X1C")
  1243. item = await queue_item_factory(printer_id=None, target_model="X1C", archive_id=archive.id)
  1244. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"target_model": "H2D"})
  1245. assert response.status_code == 400
  1246. assert "sliced for X1C" in response.json()["detail"]
  1247. @pytest.mark.asyncio
  1248. @pytest.mark.integration
  1249. async def test_update_can_fix_stale_mismatched_target(
  1250. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1251. ):
  1252. """A pre-fix DB row with a wrong target (the reporter's rows 78-82) must be
  1253. repairable by editing the target back to the sliced-for model."""
  1254. await printer_factory(model="X1C")
  1255. archive = await archive_factory(sliced_for_model="X1C")
  1256. # Stale mismatched row written directly to the DB (bypasses the API gate)
  1257. item = await queue_item_factory(printer_id=None, target_model="H2D", archive_id=archive.id)
  1258. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"target_model": "X1C"})
  1259. assert response.status_code == 200
  1260. assert response.json()["target_model"] == "X1C"
  1261. class TestAbortedStatusNormalisation:
  1262. """Tests for issue #558: 'aborted' queue status causes 500 error."""
  1263. @pytest.fixture
  1264. async def printer_factory(self, db_session):
  1265. """Factory to create test printers."""
  1266. _counter = [0]
  1267. async def _create_printer(**kwargs):
  1268. from backend.app.models.printer import Printer
  1269. _counter[0] += 1
  1270. counter = _counter[0]
  1271. defaults = {
  1272. "name": f"Abort Test Printer {counter}",
  1273. "ip_address": f"192.168.1.{60 + counter}",
  1274. "serial_number": f"TESTABORT{counter:04d}",
  1275. "access_code": "12345678",
  1276. "model": "P1S",
  1277. }
  1278. defaults.update(kwargs)
  1279. printer = Printer(**defaults)
  1280. db_session.add(printer)
  1281. await db_session.commit()
  1282. await db_session.refresh(printer)
  1283. return printer
  1284. return _create_printer
  1285. @pytest.fixture
  1286. async def archive_factory(self, db_session):
  1287. """Factory to create test archives."""
  1288. _counter = [0]
  1289. async def _create_archive(**kwargs):
  1290. from backend.app.models.archive import PrintArchive
  1291. _counter[0] += 1
  1292. counter = _counter[0]
  1293. defaults = {
  1294. "filename": f"abort_test_{counter}.3mf",
  1295. "print_name": f"Abort Test Print {counter}",
  1296. "file_path": f"/tmp/abort_test_{counter}.3mf",
  1297. "file_size": 1024,
  1298. "content_hash": f"aborthash{counter:06d}",
  1299. "status": "completed",
  1300. }
  1301. defaults.update(kwargs)
  1302. archive = PrintArchive(**defaults)
  1303. db_session.add(archive)
  1304. await db_session.commit()
  1305. await db_session.refresh(archive)
  1306. return archive
  1307. return _create_archive
  1308. @pytest.fixture
  1309. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1310. """Factory to create test queue items."""
  1311. _counter = [0]
  1312. async def _create_queue_item(**kwargs):
  1313. from backend.app.models.print_queue import PrintQueueItem
  1314. _counter[0] += 1
  1315. counter = _counter[0]
  1316. if "printer_id" not in kwargs:
  1317. printer = await printer_factory()
  1318. kwargs["printer_id"] = printer.id
  1319. if "archive_id" not in kwargs:
  1320. archive = await archive_factory()
  1321. kwargs["archive_id"] = archive.id
  1322. defaults = {
  1323. "status": "pending",
  1324. "position": counter,
  1325. }
  1326. defaults.update(kwargs)
  1327. item = PrintQueueItem(**defaults)
  1328. db_session.add(item)
  1329. await db_session.commit()
  1330. await db_session.refresh(item)
  1331. return item
  1332. return _create_queue_item
  1333. @pytest.mark.asyncio
  1334. @pytest.mark.integration
  1335. async def test_on_print_complete_normalises_aborted_to_cancelled(self, queue_item_factory, db_session):
  1336. """Verify the completion handler maps 'aborted' → 'cancelled' for queue items."""
  1337. import asyncio
  1338. from unittest.mock import AsyncMock, MagicMock, patch
  1339. item = await queue_item_factory(status="printing")
  1340. # Build a mock session whose execute returns our item
  1341. mock_result = MagicMock()
  1342. mock_result.scalars.return_value.all.return_value = [item]
  1343. mock_session = AsyncMock()
  1344. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1345. mock_session.__aexit__ = AsyncMock(return_value=False)
  1346. mock_session.execute = AsyncMock(return_value=mock_result)
  1347. mock_session.commit = AsyncMock()
  1348. tasks_before = set(asyncio.all_tasks())
  1349. with (
  1350. patch("backend.app.main.async_session", return_value=mock_session),
  1351. patch("backend.app.core.database.async_session", return_value=mock_session),
  1352. patch("backend.app.main.ws_manager") as mock_ws,
  1353. patch("backend.app.main.mqtt_relay") as mock_relay,
  1354. patch("backend.app.main.notification_service") as mock_notif,
  1355. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1356. patch("backend.app.main.printer_manager") as mock_pm,
  1357. ):
  1358. mock_ws.send_print_complete = AsyncMock()
  1359. mock_ws.broadcast = AsyncMock()
  1360. mock_relay.on_print_complete = AsyncMock()
  1361. mock_relay.on_queue_job_completed = AsyncMock()
  1362. mock_notif.on_print_complete = AsyncMock()
  1363. mock_plug.on_print_complete = AsyncMock()
  1364. mock_pm.get_printer.return_value = None
  1365. from backend.app.main import on_print_complete
  1366. await on_print_complete(
  1367. item.printer_id,
  1368. {
  1369. "status": "aborted",
  1370. "filename": "test.gcode",
  1371. "subtask_name": "Test",
  1372. "timelapse_was_active": False,
  1373. },
  1374. )
  1375. # Cancel background tasks before leaving mock context
  1376. for task in asyncio.all_tasks() - tasks_before:
  1377. task.cancel()
  1378. try:
  1379. await task
  1380. except (asyncio.CancelledError, Exception):
  1381. pass
  1382. # The item status should be normalised to 'cancelled', not 'aborted'
  1383. assert item.status == "cancelled"
  1384. @pytest.mark.asyncio
  1385. @pytest.mark.integration
  1386. async def test_startup_fixup_converts_aborted_to_cancelled(self, queue_item_factory, db_session):
  1387. """Verify the startup fixup converts existing 'aborted' rows to 'cancelled'."""
  1388. from sqlalchemy import select
  1389. from backend.app.models.print_queue import PrintQueueItem
  1390. # Create items with various statuses including 'aborted'
  1391. item_aborted = await queue_item_factory(status="pending")
  1392. item_pending = await queue_item_factory(status="pending")
  1393. # Manually set the invalid status
  1394. item_aborted.status = "aborted"
  1395. db_session.add(item_aborted)
  1396. await db_session.commit()
  1397. # Run the fixup query (same logic as lifespan)
  1398. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1399. aborted_items = result.scalars().all()
  1400. for i in aborted_items:
  1401. i.status = "cancelled"
  1402. await db_session.commit()
  1403. # Verify: no more 'aborted' items
  1404. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1405. assert len(result.scalars().all()) == 0
  1406. # The previously aborted item should now be 'cancelled'
  1407. await db_session.refresh(item_aborted)
  1408. assert item_aborted.status == "cancelled"
  1409. # The pending item should be unchanged
  1410. await db_session.refresh(item_pending)
  1411. assert item_pending.status == "pending"
  1412. @pytest.mark.asyncio
  1413. @pytest.mark.integration
  1414. async def test_completed_status_passes_through_unchanged(self, queue_item_factory, db_session):
  1415. """Verify normal statuses like 'completed' are not affected by normalisation."""
  1416. import asyncio
  1417. from unittest.mock import AsyncMock, MagicMock, patch
  1418. item = await queue_item_factory(status="printing")
  1419. mock_result = MagicMock()
  1420. mock_result.scalars.return_value.all.return_value = [item]
  1421. mock_session = AsyncMock()
  1422. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1423. mock_session.__aexit__ = AsyncMock(return_value=False)
  1424. mock_session.execute = AsyncMock(return_value=mock_result)
  1425. mock_session.commit = AsyncMock()
  1426. tasks_before = set(asyncio.all_tasks())
  1427. with (
  1428. patch("backend.app.main.async_session", return_value=mock_session),
  1429. patch("backend.app.core.database.async_session", return_value=mock_session),
  1430. patch("backend.app.main.ws_manager") as mock_ws,
  1431. patch("backend.app.main.mqtt_relay") as mock_relay,
  1432. patch("backend.app.main.notification_service") as mock_notif,
  1433. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1434. patch("backend.app.main.printer_manager") as mock_pm,
  1435. ):
  1436. mock_ws.send_print_complete = AsyncMock()
  1437. mock_ws.broadcast = AsyncMock()
  1438. mock_relay.on_print_complete = AsyncMock()
  1439. mock_relay.on_queue_job_completed = AsyncMock()
  1440. mock_notif.on_print_complete = AsyncMock()
  1441. mock_plug.on_print_complete = AsyncMock()
  1442. mock_pm.get_printer.return_value = None
  1443. from backend.app.main import on_print_complete
  1444. await on_print_complete(
  1445. item.printer_id,
  1446. {
  1447. "status": "completed",
  1448. "filename": "test.gcode",
  1449. "subtask_name": "Test",
  1450. "timelapse_was_active": False,
  1451. },
  1452. )
  1453. # Cancel background tasks before leaving mock context
  1454. for task in asyncio.all_tasks() - tasks_before:
  1455. task.cancel()
  1456. try:
  1457. await task
  1458. except (asyncio.CancelledError, Exception):
  1459. pass
  1460. assert item.status == "completed"
  1461. # ========================================================================
  1462. # Library file usage tracking on print completion (#1008)
  1463. #
  1464. # These exercise the _bump_library_file_usage_if_completed helper directly
  1465. # rather than invoking the whole on_print_complete handler — that path
  1466. # spawns background asyncio tasks (notifications, MQTT relay, smart-plug)
  1467. # that are expensive to mock and have nothing to do with the bump logic.
  1468. # ========================================================================
  1469. @pytest.mark.asyncio
  1470. @pytest.mark.integration
  1471. async def test_bump_library_file_usage_on_completed(self, printer_factory, db_session):
  1472. """Successful completion increments print_count and stamps last_printed_at."""
  1473. from datetime import datetime, timezone
  1474. from backend.app.main import _bump_library_file_usage_if_completed
  1475. from backend.app.models.library import LibraryFile
  1476. from backend.app.models.print_queue import PrintQueueItem
  1477. printer = await printer_factory()
  1478. lib_file = LibraryFile(
  1479. filename="benchy.gcode.3mf",
  1480. file_path="/data/library/benchy.gcode.3mf",
  1481. file_type="gcode.3mf",
  1482. file_size=1024,
  1483. print_count=0,
  1484. last_printed_at=None,
  1485. )
  1486. db_session.add(lib_file)
  1487. await db_session.commit()
  1488. await db_session.refresh(lib_file)
  1489. item = PrintQueueItem(
  1490. printer_id=printer.id,
  1491. library_file_id=lib_file.id,
  1492. status="printing",
  1493. position=1,
  1494. )
  1495. before = datetime.now(timezone.utc).replace(tzinfo=None)
  1496. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1497. await db_session.commit()
  1498. await db_session.refresh(lib_file)
  1499. assert lib_file.print_count == 1
  1500. assert lib_file.last_printed_at is not None
  1501. assert lib_file.last_printed_at >= before
  1502. @pytest.mark.asyncio
  1503. @pytest.mark.integration
  1504. async def test_bump_library_file_usage_repeated_prints_increment_count(self, printer_factory, db_session):
  1505. """Each successful completion bumps print_count cumulatively."""
  1506. from backend.app.main import _bump_library_file_usage_if_completed
  1507. from backend.app.models.library import LibraryFile
  1508. from backend.app.models.print_queue import PrintQueueItem
  1509. printer = await printer_factory()
  1510. lib_file = LibraryFile(
  1511. filename="repeat.gcode.3mf",
  1512. file_path="/data/library/repeat.gcode.3mf",
  1513. file_type="gcode.3mf",
  1514. file_size=1024,
  1515. print_count=0,
  1516. )
  1517. db_session.add(lib_file)
  1518. await db_session.commit()
  1519. await db_session.refresh(lib_file)
  1520. item = PrintQueueItem(
  1521. printer_id=printer.id,
  1522. library_file_id=lib_file.id,
  1523. status="printing",
  1524. position=1,
  1525. )
  1526. for _ in range(3):
  1527. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1528. await db_session.commit()
  1529. await db_session.refresh(lib_file)
  1530. assert lib_file.print_count == 3
  1531. @pytest.mark.asyncio
  1532. @pytest.mark.integration
  1533. @pytest.mark.parametrize("terminal_status", ["failed", "cancelled"])
  1534. async def test_bump_library_file_usage_skips_non_completed(self, printer_factory, db_session, terminal_status):
  1535. """Failed and cancelled prints must NOT count as usage."""
  1536. from backend.app.main import _bump_library_file_usage_if_completed
  1537. from backend.app.models.library import LibraryFile
  1538. from backend.app.models.print_queue import PrintQueueItem
  1539. printer = await printer_factory()
  1540. lib_file = LibraryFile(
  1541. filename="broken.gcode.3mf",
  1542. file_path="/data/library/broken.gcode.3mf",
  1543. file_type="gcode.3mf",
  1544. file_size=1024,
  1545. print_count=0,
  1546. last_printed_at=None,
  1547. )
  1548. db_session.add(lib_file)
  1549. await db_session.commit()
  1550. await db_session.refresh(lib_file)
  1551. item = PrintQueueItem(
  1552. printer_id=printer.id,
  1553. library_file_id=lib_file.id,
  1554. status="printing",
  1555. position=1,
  1556. )
  1557. await _bump_library_file_usage_if_completed(db_session, item, terminal_status)
  1558. await db_session.commit()
  1559. await db_session.refresh(lib_file)
  1560. assert lib_file.print_count == 0
  1561. assert lib_file.last_printed_at is None
  1562. @pytest.mark.asyncio
  1563. @pytest.mark.integration
  1564. async def test_bump_library_file_usage_skips_when_no_library_file_id(
  1565. self, printer_factory, archive_factory, db_session
  1566. ):
  1567. """Queue items without library_file_id (e.g. archive reprints) are a no-op."""
  1568. from backend.app.main import _bump_library_file_usage_if_completed
  1569. from backend.app.models.print_queue import PrintQueueItem
  1570. printer = await printer_factory()
  1571. archive = await archive_factory()
  1572. item = PrintQueueItem(
  1573. printer_id=printer.id,
  1574. library_file_id=None,
  1575. archive_id=archive.id,
  1576. status="printing",
  1577. position=1,
  1578. )
  1579. # Must not raise.
  1580. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  1581. # ========================================================================
  1582. # Batch quantity tests
  1583. # ========================================================================
  1584. @pytest.mark.asyncio
  1585. @pytest.mark.integration
  1586. async def test_add_to_queue_quantity_default(
  1587. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1588. ):
  1589. """Verify quantity=1 (default) creates a single item with no batch."""
  1590. printer = await printer_factory()
  1591. archive = await archive_factory()
  1592. data = {
  1593. "printer_id": printer.id,
  1594. "archive_id": archive.id,
  1595. }
  1596. response = await async_client.post("/api/v1/queue/", json=data)
  1597. assert response.status_code == 200
  1598. result = response.json()
  1599. assert result["batch_id"] is None
  1600. assert result["batch_name"] is None
  1601. @pytest.mark.asyncio
  1602. @pytest.mark.integration
  1603. async def test_add_to_queue_quantity_one_explicit(
  1604. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1605. ):
  1606. """Verify quantity=1 explicitly creates a single item with no batch."""
  1607. printer = await printer_factory()
  1608. archive = await archive_factory()
  1609. data = {
  1610. "printer_id": printer.id,
  1611. "archive_id": archive.id,
  1612. "quantity": 1,
  1613. }
  1614. response = await async_client.post("/api/v1/queue/", json=data)
  1615. assert response.status_code == 200
  1616. result = response.json()
  1617. assert result["batch_id"] is None
  1618. assert result["batch_name"] is None
  1619. @pytest.mark.asyncio
  1620. @pytest.mark.integration
  1621. async def test_add_to_queue_quantity_creates_batch(
  1622. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1623. ):
  1624. """Verify quantity > 1 creates a batch and multiple queue items."""
  1625. printer = await printer_factory()
  1626. archive = await archive_factory()
  1627. data = {
  1628. "printer_id": printer.id,
  1629. "archive_id": archive.id,
  1630. "quantity": 3,
  1631. }
  1632. response = await async_client.post("/api/v1/queue/", json=data)
  1633. assert response.status_code == 200
  1634. result = response.json()
  1635. # First item is returned, linked to a batch
  1636. assert result["batch_id"] is not None
  1637. assert result["batch_name"] is not None
  1638. assert "×3" in result["batch_name"]
  1639. # Verify all 3 items were created
  1640. list_response = await async_client.get("/api/v1/queue/")
  1641. items = list_response.json()
  1642. batch_items = [i for i in items if i["batch_id"] == result["batch_id"]]
  1643. assert len(batch_items) == 3
  1644. # All items should have the same settings
  1645. for item in batch_items:
  1646. assert item["printer_id"] == printer.id
  1647. assert item["archive_id"] == archive.id
  1648. assert item["status"] == "pending"
  1649. @pytest.mark.asyncio
  1650. @pytest.mark.integration
  1651. async def test_add_to_queue_quantity_sequential_positions(
  1652. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1653. ):
  1654. """Verify batch items get sequential positions."""
  1655. printer = await printer_factory()
  1656. archive = await archive_factory()
  1657. data = {
  1658. "printer_id": printer.id,
  1659. "archive_id": archive.id,
  1660. "quantity": 3,
  1661. }
  1662. response = await async_client.post("/api/v1/queue/", json=data)
  1663. assert response.status_code == 200
  1664. batch_id = response.json()["batch_id"]
  1665. list_response = await async_client.get("/api/v1/queue/")
  1666. items = list_response.json()
  1667. batch_items = sorted(
  1668. [i for i in items if i["batch_id"] == batch_id],
  1669. key=lambda i: i["position"],
  1670. )
  1671. positions = [i["position"] for i in batch_items]
  1672. assert positions == [positions[0], positions[0] + 1, positions[0] + 2]
  1673. @pytest.mark.asyncio
  1674. @pytest.mark.integration
  1675. async def test_add_to_queue_insert_position_shifts_existing_items(
  1676. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1677. ):
  1678. """Verify priority insertion shifts existing pending items in the same printer queue."""
  1679. printer = await printer_factory()
  1680. first = await archive_factory(print_name="First")
  1681. second = await archive_factory(print_name="Second")
  1682. priority = await archive_factory(print_name="Priority")
  1683. assert (
  1684. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  1685. ).status_code == 200
  1686. assert (
  1687. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  1688. ).status_code == 200
  1689. response = await async_client.post(
  1690. "/api/v1/queue/",
  1691. json={
  1692. "printer_id": printer.id,
  1693. "archive_id": priority.id,
  1694. "insert_position": 1,
  1695. },
  1696. )
  1697. assert response.status_code == 200
  1698. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  1699. items = sorted(list_response.json(), key=lambda item: item["position"])
  1700. assert [item["archive_id"] for item in items[:3]] == [priority.id, first.id, second.id]
  1701. assert [item["position"] for item in items[:3]] == [1, 2, 3]
  1702. @pytest.mark.asyncio
  1703. @pytest.mark.integration
  1704. async def test_add_to_queue_insert_position_quantity_shifts_existing_by_quantity(
  1705. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1706. ):
  1707. """ASAP batch insertion shifts existing pending items by the inserted quantity."""
  1708. printer = await printer_factory()
  1709. first = await archive_factory(print_name="First")
  1710. second = await archive_factory(print_name="Second")
  1711. priority = await archive_factory(print_name="Priority")
  1712. assert (
  1713. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  1714. ).status_code == 200
  1715. assert (
  1716. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  1717. ).status_code == 200
  1718. response = await async_client.post(
  1719. "/api/v1/queue/",
  1720. json={
  1721. "printer_id": printer.id,
  1722. "archive_id": priority.id,
  1723. "quantity": 3,
  1724. "insert_position": 1,
  1725. },
  1726. )
  1727. assert response.status_code == 200
  1728. batch_id = response.json()["batch_id"]
  1729. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  1730. items = sorted(list_response.json(), key=lambda item: item["position"])
  1731. assert [item["archive_id"] for item in items] == [
  1732. priority.id,
  1733. priority.id,
  1734. priority.id,
  1735. first.id,
  1736. second.id,
  1737. ]
  1738. assert [item["position"] for item in items] == [1, 2, 3, 4, 5]
  1739. assert [item["batch_id"] for item in items[:3]] == [batch_id, batch_id, batch_id]
  1740. @pytest.mark.asyncio
  1741. @pytest.mark.integration
  1742. async def test_add_to_queue_insert_position_scopes_unassigned_items(
  1743. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1744. ):
  1745. """Unassigned inserts shift only the unassigned queue scope."""
  1746. printer = await printer_factory()
  1747. unassigned_first = await archive_factory(print_name="Unassigned First")
  1748. unassigned_second = await archive_factory(print_name="Unassigned Second")
  1749. assigned = await archive_factory(print_name="Assigned")
  1750. priority = await archive_factory(print_name="Unassigned Priority")
  1751. assert (await async_client.post("/api/v1/queue/", json={"archive_id": unassigned_first.id})).status_code == 200
  1752. assert (await async_client.post("/api/v1/queue/", json={"archive_id": unassigned_second.id})).status_code == 200
  1753. assigned_response = await async_client.post(
  1754. "/api/v1/queue/",
  1755. json={"printer_id": printer.id, "archive_id": assigned.id},
  1756. )
  1757. assert assigned_response.status_code == 200
  1758. assert assigned_response.json()["position"] == 1
  1759. response = await async_client.post(
  1760. "/api/v1/queue/",
  1761. json={
  1762. "archive_id": priority.id,
  1763. "insert_position": 1,
  1764. },
  1765. )
  1766. assert response.status_code == 200
  1767. unassigned_response = await async_client.get("/api/v1/queue/?printer_id=-1")
  1768. unassigned_items = sorted(unassigned_response.json(), key=lambda item: item["position"])
  1769. assert [item["archive_id"] for item in unassigned_items] == [
  1770. priority.id,
  1771. unassigned_first.id,
  1772. unassigned_second.id,
  1773. ]
  1774. assert [item["position"] for item in unassigned_items] == [1, 2, 3]
  1775. assigned_scope_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}&target_model=NONE")
  1776. assigned_items = sorted(assigned_scope_response.json(), key=lambda item: item["position"])
  1777. assert [item["archive_id"] for item in assigned_items] == [assigned.id]
  1778. assert [item["position"] for item in assigned_items] == [1]
  1779. @pytest.mark.asyncio
  1780. @pytest.mark.integration
  1781. async def test_add_to_queue_insert_position_greater_than_max_appends_without_gap(
  1782. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1783. ):
  1784. """Oversized explicit insert_position appends at max+1 instead of creating sparse positions."""
  1785. printer = await printer_factory()
  1786. first = await archive_factory(print_name="First")
  1787. second = await archive_factory(print_name="Second")
  1788. appended = await archive_factory(print_name="Append")
  1789. assert (
  1790. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  1791. ).status_code == 200
  1792. assert (
  1793. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  1794. ).status_code == 200
  1795. response = await async_client.post(
  1796. "/api/v1/queue/",
  1797. json={
  1798. "printer_id": printer.id,
  1799. "archive_id": appended.id,
  1800. "insert_position": 99,
  1801. },
  1802. )
  1803. assert response.status_code == 200
  1804. assert response.json()["position"] == 3
  1805. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  1806. items = sorted(list_response.json(), key=lambda item: item["position"])
  1807. assert [item["archive_id"] for item in items] == [first.id, second.id, appended.id]
  1808. assert [item["position"] for item in items] == [1, 2, 3]
  1809. @pytest.mark.asyncio
  1810. @pytest.mark.integration
  1811. async def test_add_to_queue_consecutive_asap_inserts_stack_in_submission_order(
  1812. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1813. ):
  1814. """Consecutive ASAP inserts to the same printer preserve the client submission order."""
  1815. printer = await printer_factory()
  1816. existing = await archive_factory(print_name="Existing")
  1817. first_asap = await archive_factory(print_name="First ASAP")
  1818. second_asap = await archive_factory(print_name="Second ASAP")
  1819. assert (
  1820. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": existing.id})
  1821. ).status_code == 200
  1822. first_response = await async_client.post(
  1823. "/api/v1/queue/",
  1824. json={
  1825. "printer_id": printer.id,
  1826. "archive_id": first_asap.id,
  1827. "insert_position": 1,
  1828. },
  1829. )
  1830. assert first_response.status_code == 200
  1831. second_response = await async_client.post(
  1832. "/api/v1/queue/",
  1833. json={
  1834. "printer_id": printer.id,
  1835. "archive_id": second_asap.id,
  1836. "insert_position": 2,
  1837. },
  1838. )
  1839. assert second_response.status_code == 200
  1840. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  1841. items = sorted(list_response.json(), key=lambda item: item["position"])
  1842. assert [item["archive_id"] for item in items] == [first_asap.id, second_asap.id, existing.id]
  1843. assert [item["position"] for item in items] == [1, 2, 3]
  1844. @pytest.mark.asyncio
  1845. @pytest.mark.integration
  1846. async def test_add_to_queue_quantity_with_print_options(
  1847. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1848. ):
  1849. """Verify print options are applied to all batch items."""
  1850. printer = await printer_factory()
  1851. archive = await archive_factory()
  1852. data = {
  1853. "printer_id": printer.id,
  1854. "archive_id": archive.id,
  1855. "quantity": 2,
  1856. "bed_levelling": False,
  1857. "timelapse": True,
  1858. }
  1859. response = await async_client.post("/api/v1/queue/", json=data)
  1860. assert response.status_code == 200
  1861. batch_id = response.json()["batch_id"]
  1862. list_response = await async_client.get("/api/v1/queue/")
  1863. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1864. assert len(batch_items) == 2
  1865. for item in batch_items:
  1866. assert item["bed_levelling"] is False
  1867. assert item["timelapse"] is True
  1868. @pytest.mark.asyncio
  1869. @pytest.mark.integration
  1870. async def test_get_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1871. """Verify batch can be retrieved with progress stats."""
  1872. printer = await printer_factory()
  1873. archive = await archive_factory()
  1874. # Create a batch of 3
  1875. data = {
  1876. "printer_id": printer.id,
  1877. "archive_id": archive.id,
  1878. "quantity": 3,
  1879. }
  1880. response = await async_client.post("/api/v1/queue/", json=data)
  1881. batch_id = response.json()["batch_id"]
  1882. # Get batch
  1883. response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1884. assert response.status_code == 200
  1885. result = response.json()
  1886. assert result["id"] == batch_id
  1887. assert result["quantity"] == 3
  1888. assert result["status"] == "active"
  1889. assert result["pending_count"] == 3
  1890. assert result["printing_count"] == 0
  1891. assert result["completed_count"] == 0
  1892. @pytest.mark.asyncio
  1893. @pytest.mark.integration
  1894. async def test_list_batches(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1895. """Verify batches can be listed."""
  1896. printer = await printer_factory()
  1897. archive = await archive_factory()
  1898. # Create two batches
  1899. for qty in [2, 3]:
  1900. await async_client.post(
  1901. "/api/v1/queue/",
  1902. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": qty},
  1903. )
  1904. response = await async_client.get("/api/v1/queue/batches")
  1905. assert response.status_code == 200
  1906. batches = response.json()
  1907. assert len(batches) >= 2
  1908. @pytest.mark.asyncio
  1909. @pytest.mark.integration
  1910. async def test_cancel_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  1911. """Verify cancelling a batch cancels all pending items."""
  1912. printer = await printer_factory()
  1913. archive = await archive_factory()
  1914. data = {
  1915. "printer_id": printer.id,
  1916. "archive_id": archive.id,
  1917. "quantity": 3,
  1918. }
  1919. response = await async_client.post("/api/v1/queue/", json=data)
  1920. batch_id = response.json()["batch_id"]
  1921. # Cancel the batch
  1922. response = await async_client.delete(f"/api/v1/queue/batches/{batch_id}")
  1923. assert response.status_code == 200
  1924. # Verify all items are cancelled
  1925. list_response = await async_client.get("/api/v1/queue/")
  1926. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  1927. for item in batch_items:
  1928. assert item["status"] == "cancelled"
  1929. # Verify batch status
  1930. batch_response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  1931. assert batch_response.json()["status"] == "cancelled"
  1932. @pytest.mark.asyncio
  1933. @pytest.mark.integration
  1934. async def test_get_batch_not_found(self, async_client: AsyncClient):
  1935. """Verify 404 for non-existent batch."""
  1936. response = await async_client.get("/api/v1/queue/batches/9999")
  1937. assert response.status_code == 404
  1938. # ========================================================================
  1939. # Queue redesign: create-empty + group-existing + ungroup
  1940. # ========================================================================
  1941. @pytest.mark.asyncio
  1942. @pytest.mark.integration
  1943. async def test_create_empty_batch_for_client_side_grouping(
  1944. self, async_client: AsyncClient, printer_factory, archive_factory
  1945. ):
  1946. """Verify POST /queue/batches without item_ids creates an empty batch
  1947. whose id can be passed on subsequent /queue/ POSTs (the multi-plate
  1948. auto-batch flow). Subsequent items must end up with the same batch_id."""
  1949. printer = await printer_factory()
  1950. archive = await archive_factory()
  1951. # 1. Pre-create batch
  1952. batch_resp = await async_client.post(
  1953. "/api/v1/queue/batches",
  1954. json={"name": "Plates · 2 plates", "archive_id": archive.id},
  1955. )
  1956. assert batch_resp.status_code == 200
  1957. batch = batch_resp.json()
  1958. assert batch["status"] == "active"
  1959. batch_id = batch["id"]
  1960. # 2. Add two items referencing that batch
  1961. for plate_id in (1, 2):
  1962. item_resp = await async_client.post(
  1963. "/api/v1/queue/",
  1964. json={
  1965. "printer_id": printer.id,
  1966. "archive_id": archive.id,
  1967. "plate_id": plate_id,
  1968. "batch_id": batch_id,
  1969. },
  1970. )
  1971. assert item_resp.status_code == 200
  1972. assert item_resp.json()["batch_id"] == batch_id
  1973. # 3. Verify batch now has 2 pending children
  1974. list_resp = await async_client.get("/api/v1/queue/")
  1975. siblings = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  1976. assert len(siblings) == 2
  1977. assert {i["plate_id"] for i in siblings} == {1, 2}
  1978. @pytest.mark.asyncio
  1979. @pytest.mark.integration
  1980. async def test_group_existing_items_as_batch(
  1981. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  1982. ):
  1983. """Verify POST /queue/batches with item_ids assigns batch_id to
  1984. existing pending items (the 'Group as batch' UI action)."""
  1985. printer = await printer_factory()
  1986. archive = await archive_factory()
  1987. item_a = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  1988. item_b = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  1989. resp = await async_client.post(
  1990. "/api/v1/queue/batches",
  1991. json={"name": "Manual group", "item_ids": [item_a.id, item_b.id]},
  1992. )
  1993. assert resp.status_code == 200
  1994. batch_id = resp.json()["id"]
  1995. list_resp = await async_client.get("/api/v1/queue/")
  1996. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  1997. assert {i["id"] for i in grouped} == {item_a.id, item_b.id}
  1998. @pytest.mark.asyncio
  1999. @pytest.mark.integration
  2000. async def test_group_skips_non_pending_items(
  2001. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  2002. ):
  2003. """Verify grouping doesn't pull in already-completed/cancelled items."""
  2004. printer = await printer_factory()
  2005. archive = await archive_factory()
  2006. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2007. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  2008. resp = await async_client.post(
  2009. "/api/v1/queue/batches",
  2010. json={"name": "Mixed", "item_ids": [pending.id, completed.id]},
  2011. )
  2012. assert resp.status_code == 200
  2013. batch_id = resp.json()["id"]
  2014. list_resp = await async_client.get("/api/v1/queue/")
  2015. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2016. assert {i["id"] for i in grouped} == {pending.id}
  2017. @pytest.mark.asyncio
  2018. @pytest.mark.integration
  2019. async def test_create_batch_requires_name(self, async_client: AsyncClient):
  2020. """Verify empty / whitespace-only name is rejected with 400."""
  2021. resp = await async_client.post("/api/v1/queue/batches", json={"name": " "})
  2022. assert resp.status_code == 400
  2023. @pytest.mark.asyncio
  2024. @pytest.mark.integration
  2025. async def test_ungroup_batch_clears_batch_id_and_deletes_row(
  2026. self, async_client: AsyncClient, printer_factory, archive_factory
  2027. ):
  2028. """Verify POST /queue/batches/{id}/ungroup clears batch_id from all
  2029. members and deletes the batch row when nothing remains assigned."""
  2030. printer = await printer_factory()
  2031. archive = await archive_factory()
  2032. # Create batch with two items via the existing quantity flow
  2033. add_resp = await async_client.post(
  2034. "/api/v1/queue/",
  2035. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": 2},
  2036. )
  2037. batch_id = add_resp.json()["batch_id"]
  2038. # Ungroup
  2039. ungroup_resp = await async_client.post(f"/api/v1/queue/batches/{batch_id}/ungroup")
  2040. assert ungroup_resp.status_code == 200
  2041. assert ungroup_resp.json()["ungrouped_count"] == 2
  2042. # Verify items still exist but no longer batched
  2043. list_resp = await async_client.get("/api/v1/queue/")
  2044. ex_members = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2045. assert ex_members == []
  2046. # Batch row was deleted
  2047. get_resp = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2048. assert get_resp.status_code == 404
  2049. @pytest.mark.asyncio
  2050. @pytest.mark.integration
  2051. async def test_add_to_queue_with_unknown_batch_id_404(
  2052. self, async_client: AsyncClient, printer_factory, archive_factory
  2053. ):
  2054. """Verify addToQueue with a non-existent batch_id is rejected."""
  2055. printer = await printer_factory()
  2056. archive = await archive_factory()
  2057. resp = await async_client.post(
  2058. "/api/v1/queue/",
  2059. json={
  2060. "printer_id": printer.id,
  2061. "archive_id": archive.id,
  2062. "batch_id": 99999,
  2063. },
  2064. )
  2065. assert resp.status_code == 404
  2066. # ========================================================================
  2067. # Soft-deleted archive handling (#1348 follow-up)
  2068. # ========================================================================
  2069. @pytest.mark.asyncio
  2070. @pytest.mark.integration
  2071. async def test_soft_delete_archive_deletes_all_related_queue_items(
  2072. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2073. ):
  2074. """Soft-deleting an archive removes every related queue item, regardless
  2075. of status (#1734). Pre-#1734 only ``pending`` rows were flipped to
  2076. ``cancelled`` and stayed in the DB, surprising users who expected the
  2077. queue lines to disappear with the archive — especially on multi-plate
  2078. Send All uploads (#1733), where ONE archive backed N queue items and
  2079. soft-deleting the archive left N "cancelled" rows behind. The change
  2080. keeps the printing guard (a row with ``status='printing'`` blocks the
  2081. delete one layer up at the API route), so we never delete the row of
  2082. an actively-running print here.
  2083. Print history lives in ``PrintLogEntry`` (FK ``ON DELETE SET NULL``) —
  2084. the audit trail survives independently of the queue rows.
  2085. """
  2086. from sqlalchemy import select
  2087. from backend.app.models.print_queue import PrintQueueItem
  2088. from backend.app.services.archive import ArchiveService
  2089. printer = await printer_factory()
  2090. archive = await archive_factory(thumbnail_path="archives/test/test/thumbnail.png")
  2091. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2092. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  2093. service = ArchiveService(db_session)
  2094. assert await service.soft_delete_archive(archive.id) is True
  2095. # Every queue row that referenced this archive is gone — both the
  2096. # pending and the completed rows. Print history (PrintLogEntry) is
  2097. # the authoritative record and is preserved by the FK SET NULL.
  2098. remaining = (
  2099. (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_([pending.id, completed.id]))))
  2100. .scalars()
  2101. .all()
  2102. )
  2103. assert remaining == [], (
  2104. "Soft-deleting the archive must delete every related queue row, "
  2105. f"got {[(r.id, r.status) for r in remaining]} still present"
  2106. )
  2107. @pytest.mark.asyncio
  2108. @pytest.mark.integration
  2109. async def test_queue_api_hides_archive_surface_when_soft_deleted(
  2110. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2111. ):
  2112. """Queue serializer must NOT populate archive_thumbnail / archive_name
  2113. when the archive is soft-deleted — otherwise the frontend renders a
  2114. broken <img> and 404-storms the thumbnail / plates / plate-thumbnail
  2115. endpoints. archive_deleted=True signals the soft-deleted state so
  2116. the UI can render a 'source deleted' badge."""
  2117. from datetime import datetime, timezone
  2118. printer = await printer_factory()
  2119. archive = await archive_factory(
  2120. print_name="Test Print",
  2121. thumbnail_path="archives/test/test/thumbnail.png",
  2122. deleted_at=datetime.now(timezone.utc), # Pre-soft-deleted
  2123. )
  2124. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="cancelled")
  2125. resp = await async_client.get("/api/v1/queue/")
  2126. assert resp.status_code == 200
  2127. body = resp.json()
  2128. row = next((r for r in body if r["id"] == item.id), None)
  2129. assert row is not None
  2130. assert row["archive_deleted"] is True
  2131. assert row["archive_thumbnail"] is None, "must not expose stale thumbnail path for soft-deleted archive"
  2132. assert row["archive_name"] is None
  2133. @pytest.mark.asyncio
  2134. @pytest.mark.integration
  2135. async def test_queue_api_still_exposes_archive_surface_when_live(
  2136. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2137. ):
  2138. """Sanity guard: the soft-delete suppression must not affect live
  2139. archives. archive_name / archive_thumbnail still flow through and
  2140. archive_deleted stays False."""
  2141. printer = await printer_factory()
  2142. archive = await archive_factory(
  2143. print_name="Live Archive",
  2144. thumbnail_path="archives/test/live/thumbnail.png",
  2145. )
  2146. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2147. resp = await async_client.get("/api/v1/queue/")
  2148. assert resp.status_code == 200
  2149. row = next((r for r in resp.json() if r["id"] == item.id), None)
  2150. assert row is not None
  2151. assert row["archive_deleted"] is False
  2152. assert row["archive_name"] == "Live Archive"
  2153. assert row["archive_thumbnail"] == "archives/test/live/thumbnail.png"
  2154. class TestResumeQueueAfterFailure:
  2155. """Integration tests for POST /api/v1/queue/printer/{id}/resume (#1818)."""
  2156. @pytest.fixture
  2157. async def printer_factory(self, db_session):
  2158. _counter = [0]
  2159. async def _create_printer(**kwargs):
  2160. from backend.app.models.printer import Printer
  2161. _counter[0] += 1
  2162. counter = _counter[0]
  2163. defaults = {
  2164. "name": f"Resume Printer {counter}",
  2165. "ip_address": f"192.168.42.{100 + counter}",
  2166. "serial_number": f"RESUMESERIAL{counter:04d}",
  2167. "access_code": "12345678",
  2168. "model": "P1S",
  2169. }
  2170. defaults.update(kwargs)
  2171. printer = Printer(**defaults)
  2172. db_session.add(printer)
  2173. await db_session.commit()
  2174. await db_session.refresh(printer)
  2175. return printer
  2176. return _create_printer
  2177. @pytest.fixture
  2178. async def archive_factory(self, db_session):
  2179. _counter = [0]
  2180. async def _create_archive(**kwargs):
  2181. from backend.app.models.archive import PrintArchive
  2182. _counter[0] += 1
  2183. counter = _counter[0]
  2184. defaults = {
  2185. "filename": f"resume_print_{counter}.3mf",
  2186. "print_name": f"Resume Print {counter}",
  2187. "file_path": f"/tmp/resume_print_{counter}.3mf", # nosec B108
  2188. "file_size": 1024,
  2189. "content_hash": f"resumehash{counter:08d}",
  2190. "status": "completed",
  2191. }
  2192. defaults.update(kwargs)
  2193. archive = PrintArchive(**defaults)
  2194. db_session.add(archive)
  2195. await db_session.commit()
  2196. await db_session.refresh(archive)
  2197. return archive
  2198. return _create_archive
  2199. async def _add_item(self, db_session, printer, archive_factory, **kwargs):
  2200. from backend.app.models.print_queue import PrintQueueItem
  2201. archive = await archive_factory()
  2202. defaults = {
  2203. "printer_id": printer.id,
  2204. "archive_id": archive.id,
  2205. "status": "pending",
  2206. "require_previous_success": True,
  2207. }
  2208. defaults.update(kwargs)
  2209. item = PrintQueueItem(**defaults)
  2210. db_session.add(item)
  2211. await db_session.commit()
  2212. await db_session.refresh(item)
  2213. return item
  2214. @pytest.mark.asyncio
  2215. @pytest.mark.integration
  2216. async def test_resume_unknown_printer_returns_404(self, async_client: AsyncClient):
  2217. resp = await async_client.post("/api/v1/queue/printer/999999/resume")
  2218. assert resp.status_code == 404
  2219. @pytest.mark.asyncio
  2220. @pytest.mark.integration
  2221. async def test_resume_no_op_on_clean_queue(self, async_client: AsyncClient, printer_factory):
  2222. """Calling resume on a printer with no failures and no skipped items
  2223. returns zero counts — endpoint is idempotent and safe to spam."""
  2224. printer = await printer_factory()
  2225. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2226. assert resp.status_code == 200
  2227. assert resp.json() == {"acknowledged": 0, "restored": 0}
  2228. @pytest.mark.asyncio
  2229. @pytest.mark.integration
  2230. async def test_resume_acknowledges_failed_and_restores_skipped(
  2231. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2232. ):
  2233. """Reporter's scenario: failed predecessor + N skipped downstream items.
  2234. Resume sets gate_acknowledged on the failure and flips skipped → pending."""
  2235. from sqlalchemy import select
  2236. from backend.app.models.print_queue import PrintQueueItem
  2237. printer = await printer_factory()
  2238. failed = await self._add_item(db_session, printer, archive_factory, status="failed")
  2239. skipped_1 = await self._add_item(
  2240. db_session,
  2241. printer,
  2242. archive_factory,
  2243. status="skipped",
  2244. error_message="Previous print failed or was aborted",
  2245. )
  2246. skipped_2 = await self._add_item(
  2247. db_session,
  2248. printer,
  2249. archive_factory,
  2250. status="skipped",
  2251. error_message="Previous print failed or was aborted",
  2252. )
  2253. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2254. assert resp.status_code == 200
  2255. assert resp.json() == {"acknowledged": 1, "restored": 2}
  2256. failed_id = failed.id
  2257. skipped_ids = [skipped_1.id, skipped_2.id]
  2258. db_session.expire_all()
  2259. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_id))
  2260. assert result.scalar_one().gate_acknowledged is True
  2261. for sid in skipped_ids:
  2262. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == sid))
  2263. row = result.scalar_one()
  2264. assert row.status == "pending"
  2265. assert row.error_message is None
  2266. assert row.completed_at is None
  2267. @pytest.mark.asyncio
  2268. @pytest.mark.integration
  2269. async def test_resume_preserves_skipped_items_with_other_reasons(
  2270. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2271. ):
  2272. """Skipped items whose error_message is something OTHER than the
  2273. gate string (e.g. filament-deficit promotion, future skip reasons)
  2274. must not be touched — they encode different user intent."""
  2275. from sqlalchemy import select
  2276. from backend.app.models.print_queue import PrintQueueItem
  2277. printer = await printer_factory()
  2278. gate_skip = await self._add_item(
  2279. db_session,
  2280. printer,
  2281. archive_factory,
  2282. status="skipped",
  2283. error_message="Previous print failed or was aborted",
  2284. )
  2285. other_skip = await self._add_item(
  2286. db_session,
  2287. printer,
  2288. archive_factory,
  2289. status="skipped",
  2290. error_message="User skipped via UI",
  2291. )
  2292. gate_id = gate_skip.id
  2293. other_id = other_skip.id
  2294. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2295. assert resp.json() == {"acknowledged": 0, "restored": 1}
  2296. db_session.expire_all()
  2297. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == gate_id))
  2298. assert result.scalar_one().status == "pending"
  2299. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == other_id))
  2300. assert result.scalar_one().status == "skipped"
  2301. @pytest.mark.asyncio
  2302. @pytest.mark.integration
  2303. async def test_resume_scoped_to_printer(
  2304. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2305. ):
  2306. """A resume on printer A must not clear printer B's gate — farms run
  2307. each printer's queue independently."""
  2308. from sqlalchemy import select
  2309. from backend.app.models.print_queue import PrintQueueItem
  2310. p1 = await printer_factory()
  2311. p2 = await printer_factory()
  2312. failed_p1 = await self._add_item(db_session, p1, archive_factory, status="failed")
  2313. failed_p2 = await self._add_item(db_session, p2, archive_factory, status="failed")
  2314. failed_p1_id = failed_p1.id
  2315. failed_p2_id = failed_p2.id
  2316. resp = await async_client.post(f"/api/v1/queue/printer/{p1.id}/resume")
  2317. assert resp.json() == {"acknowledged": 1, "restored": 0}
  2318. db_session.expire_all()
  2319. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_p1_id))
  2320. assert result.scalar_one().gate_acknowledged is True
  2321. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_p2_id))
  2322. assert result.scalar_one().gate_acknowledged is False
  2323. @pytest.mark.asyncio
  2324. @pytest.mark.integration
  2325. async def test_resume_handles_aborted_status(
  2326. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2327. ):
  2328. """Aborted prints (printer-detected mid-print failure) gate the same
  2329. way failed prints do and must also be acknowledgeable."""
  2330. from sqlalchemy import select
  2331. from backend.app.models.print_queue import PrintQueueItem
  2332. printer = await printer_factory()
  2333. aborted = await self._add_item(db_session, printer, archive_factory, status="aborted")
  2334. aborted_id = aborted.id
  2335. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2336. assert resp.json() == {"acknowledged": 1, "restored": 0}
  2337. db_session.expire_all()
  2338. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == aborted_id))
  2339. assert result.scalar_one().gate_acknowledged is True
  2340. @pytest.mark.asyncio
  2341. @pytest.mark.integration
  2342. async def test_resume_idempotent_second_call_is_no_op(
  2343. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2344. ):
  2345. """Calling resume twice on the same printer doesn't re-acknowledge
  2346. the same failure — the second call sees acknowledged=0, restored=0."""
  2347. printer = await printer_factory()
  2348. await self._add_item(db_session, printer, archive_factory, status="failed")
  2349. await self._add_item(
  2350. db_session,
  2351. printer,
  2352. archive_factory,
  2353. status="skipped",
  2354. error_message="Previous print failed or was aborted",
  2355. )
  2356. first = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2357. assert first.json() == {"acknowledged": 1, "restored": 1}
  2358. second = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2359. assert second.json() == {"acknowledged": 0, "restored": 0}
  2360. class TestReorderEndpoint:
  2361. """Tests for the /queue/reorder endpoint (#1625-followup duplicate-position validator)."""
  2362. @pytest.fixture
  2363. async def printer_factory(self, db_session):
  2364. async def _create(**kwargs):
  2365. from backend.app.models.printer import Printer
  2366. defaults = {
  2367. "name": "Reorder Test Printer",
  2368. "ip_address": "192.168.1.220",
  2369. "serial_number": "TESTREORDER001",
  2370. "access_code": "12345678",
  2371. "model": "X1C",
  2372. }
  2373. defaults.update(kwargs)
  2374. printer = Printer(**defaults)
  2375. db_session.add(printer)
  2376. await db_session.commit()
  2377. await db_session.refresh(printer)
  2378. return printer
  2379. return _create
  2380. @pytest.fixture
  2381. async def archive_factory(self, db_session):
  2382. _counter = [0]
  2383. async def _create(**kwargs):
  2384. from backend.app.models.archive import PrintArchive
  2385. _counter[0] += 1
  2386. defaults = {
  2387. "filename": f"reorder_{_counter[0]}.3mf",
  2388. "print_name": f"Reorder {_counter[0]}",
  2389. "file_path": f"/tmp/reorder_{_counter[0]}.3mf", # nosec B108
  2390. "file_size": 1024,
  2391. "content_hash": f"reorderhash{_counter[0]:06d}",
  2392. "status": "completed",
  2393. }
  2394. defaults.update(kwargs)
  2395. archive = PrintArchive(**defaults)
  2396. db_session.add(archive)
  2397. await db_session.commit()
  2398. await db_session.refresh(archive)
  2399. return archive
  2400. return _create
  2401. @pytest.mark.asyncio
  2402. @pytest.mark.integration
  2403. async def test_reorder_rejects_duplicate_positions(
  2404. self, async_client: AsyncClient, db_session, printer_factory, archive_factory
  2405. ):
  2406. """Reorder payload with duplicate positions → 422 at schema layer.
  2407. Regression guard: pre-fix, a buggy client sending two items at the
  2408. same position would leave the queue in an inconsistent state (the
  2409. scheduler's ORDER BY (printer_id, position) tie would be broken by
  2410. physical row order — non-deterministic dispatch order).
  2411. """
  2412. from backend.app.models.print_queue import PrintQueueItem
  2413. printer = await printer_factory()
  2414. a1 = await archive_factory()
  2415. a2 = await archive_factory()
  2416. item1 = PrintQueueItem(printer_id=printer.id, archive_id=a1.id, status="pending", position=1)
  2417. item2 = PrintQueueItem(printer_id=printer.id, archive_id=a2.id, status="pending", position=2)
  2418. db_session.add_all([item1, item2])
  2419. await db_session.commit()
  2420. await db_session.refresh(item1)
  2421. await db_session.refresh(item2)
  2422. response = await async_client.post(
  2423. "/api/v1/queue/reorder",
  2424. json={
  2425. "items": [
  2426. {"id": item1.id, "position": 1},
  2427. {"id": item2.id, "position": 1}, # duplicate
  2428. ]
  2429. },
  2430. )
  2431. assert response.status_code == 422
  2432. body = response.json()
  2433. # Pydantic v2 wraps custom validator errors; the message must mention "Duplicate"
  2434. # so the FE can surface the actionable detail.
  2435. assert any("duplicate" in str(err).lower() for err in body.get("detail", []))
  2436. @pytest.mark.asyncio
  2437. @pytest.mark.integration
  2438. async def test_reorder_accepts_unique_positions(
  2439. self, async_client: AsyncClient, db_session, printer_factory, archive_factory
  2440. ):
  2441. """Reorder with unique positions succeeds and updates them in DB."""
  2442. from backend.app.models.print_queue import PrintQueueItem
  2443. printer = await printer_factory()
  2444. a1 = await archive_factory()
  2445. a2 = await archive_factory()
  2446. item1 = PrintQueueItem(printer_id=printer.id, archive_id=a1.id, status="pending", position=1)
  2447. item2 = PrintQueueItem(printer_id=printer.id, archive_id=a2.id, status="pending", position=2)
  2448. db_session.add_all([item1, item2])
  2449. await db_session.commit()
  2450. await db_session.refresh(item1)
  2451. await db_session.refresh(item2)
  2452. response = await async_client.post(
  2453. "/api/v1/queue/reorder",
  2454. json={
  2455. "items": [
  2456. {"id": item1.id, "position": 2},
  2457. {"id": item2.id, "position": 1},
  2458. ]
  2459. },
  2460. )
  2461. assert response.status_code == 200
  2462. await db_session.refresh(item1)
  2463. await db_session.refresh(item2)
  2464. assert item1.position == 2
  2465. assert item2.position == 1
  2466. class TestForceColorOverridesAreScopedToThePlate:
  2467. """Queueing several plates of one 3MF must not make each plate wait on the
  2468. colours of its siblings (#2551).
  2469. The print dialog builds one override list from every selected plate and posts
  2470. that same list with each plate's item, so the API is what has to keep only the
  2471. slots the plate prints -- a ``force_color_match`` entry blocks dispatch until
  2472. the printer has that exact colour loaded.
  2473. """
  2474. THREE_PLATES = """<?xml version="1.0" encoding="UTF-8"?>
  2475. <config>
  2476. <plate>
  2477. <metadata key="index" value="1"/>
  2478. <filament id="1" used_g="50.0" type="PLA" color="#0B2C7A"/>
  2479. </plate>
  2480. <plate>
  2481. <metadata key="index" value="2"/>
  2482. <filament id="2" used_g="40.0" type="PLA" color="#9B9EA0"/>
  2483. </plate>
  2484. <plate>
  2485. <metadata key="index" value="3"/>
  2486. <filament id="3" used_g="30.0" type="PLA" color="#F4EE2A"/>
  2487. </plate>
  2488. </config>
  2489. """
  2490. # What the dialog posts for every plate: the union of all three plates'
  2491. # filaments, each one force-matched.
  2492. ALL_THREE_COLORS = [
  2493. {"slot_id": 1, "type": "PLA", "color": "#0B2C7A", "color_name": "Army Blue", "force_color_match": True},
  2494. {"slot_id": 2, "type": "PLA", "color": "#9B9EA0", "color_name": "Ash Grey", "force_color_match": True},
  2495. {"slot_id": 3, "type": "PLA", "color": "#F4EE2A", "color_name": "Sunshine Yellow", "force_color_match": True},
  2496. ]
  2497. @pytest.fixture
  2498. async def multi_plate_archive(self, db_session, tmp_path):
  2499. """An archive whose 3MF really exists on disk, one colour per plate."""
  2500. import zipfile
  2501. from backend.app.models.archive import PrintArchive
  2502. file_path = tmp_path / "three_plates.gcode.3mf"
  2503. with zipfile.ZipFile(file_path, "w") as zf:
  2504. zf.writestr("Metadata/slice_info.config", self.THREE_PLATES)
  2505. archive = PrintArchive(
  2506. filename="three_plates.gcode.3mf",
  2507. print_name="Three Plates",
  2508. file_path=str(file_path),
  2509. file_size=file_path.stat().st_size,
  2510. content_hash="platehash0001",
  2511. status="completed",
  2512. )
  2513. db_session.add(archive)
  2514. await db_session.commit()
  2515. await db_session.refresh(archive)
  2516. return archive
  2517. @pytest.fixture
  2518. async def x1c(self, db_session):
  2519. from backend.app.models.printer import Printer
  2520. printer = Printer(
  2521. name="Force Color X1C",
  2522. ip_address="192.168.1.210",
  2523. serial_number="FORCECOLOR01",
  2524. access_code="12345678",
  2525. model="X1C",
  2526. )
  2527. db_session.add(printer)
  2528. await db_session.commit()
  2529. await db_session.refresh(printer)
  2530. return printer
  2531. @pytest.mark.asyncio
  2532. @pytest.mark.integration
  2533. async def test_each_plate_keeps_only_the_colour_it_prints(
  2534. self, async_client: AsyncClient, multi_plate_archive, x1c
  2535. ):
  2536. """The bug: plate 1 prints Army Blue only, but was stored demanding all three."""
  2537. stored = {}
  2538. for plate_id in (1, 2, 3):
  2539. response = await async_client.post(
  2540. "/api/v1/queue/",
  2541. json={
  2542. "target_model": "X1C",
  2543. "archive_id": multi_plate_archive.id,
  2544. "plate_id": plate_id,
  2545. "filament_overrides": self.ALL_THREE_COLORS,
  2546. },
  2547. )
  2548. assert response.status_code == 200
  2549. stored[plate_id] = response.json()["filament_overrides"]
  2550. assert [o["color_name"] for o in stored[1]] == ["Army Blue"]
  2551. assert [o["color_name"] for o in stored[2]] == ["Ash Grey"]
  2552. assert [o["color_name"] for o in stored[3]] == ["Sunshine Yellow"]
  2553. # The slot each entry maps to has to survive narrowing untouched, or the
  2554. # dispatch-time AMS mapping would key the override onto the wrong slot.
  2555. assert [o["slot_id"] for o in stored[2]] == [2]
  2556. @pytest.mark.asyncio
  2557. @pytest.mark.integration
  2558. async def test_whole_file_queue_keeps_every_colour(self, async_client: AsyncClient, multi_plate_archive, x1c):
  2559. """No plate_id means the job prints the whole file, so every colour is needed."""
  2560. response = await async_client.post(
  2561. "/api/v1/queue/",
  2562. json={
  2563. "target_model": "X1C",
  2564. "archive_id": multi_plate_archive.id,
  2565. "filament_overrides": self.ALL_THREE_COLORS,
  2566. },
  2567. )
  2568. assert response.status_code == 200
  2569. assert len(response.json()["filament_overrides"]) == 3
  2570. @pytest.mark.asyncio
  2571. @pytest.mark.integration
  2572. async def test_unreadable_3mf_keeps_every_colour(self, async_client: AsyncClient, db_session, tmp_path, x1c):
  2573. """When the plate's slots can't be read, keep the overrides rather than drop them.
  2574. An item waiting on a colour it doesn't need is visible and fixable; one that
  2575. silently lost its forced colour would dispatch in the wrong filament.
  2576. """
  2577. from backend.app.models.archive import PrintArchive
  2578. file_path = tmp_path / "not_a_zip.gcode.3mf"
  2579. file_path.write_text("this is not a 3mf")
  2580. archive = PrintArchive(
  2581. filename="not_a_zip.gcode.3mf",
  2582. print_name="Corrupt",
  2583. file_path=str(file_path),
  2584. file_size=file_path.stat().st_size,
  2585. content_hash="platehash0002",
  2586. status="completed",
  2587. )
  2588. db_session.add(archive)
  2589. await db_session.commit()
  2590. await db_session.refresh(archive)
  2591. response = await async_client.post(
  2592. "/api/v1/queue/",
  2593. json={
  2594. "target_model": "X1C",
  2595. "archive_id": archive.id,
  2596. "plate_id": 1,
  2597. "filament_overrides": self.ALL_THREE_COLORS,
  2598. },
  2599. )
  2600. assert response.status_code == 200
  2601. assert len(response.json()["filament_overrides"]) == 3
  2602. @pytest.mark.asyncio
  2603. @pytest.mark.integration
  2604. async def test_required_types_stay_scoped_to_the_plate(self, async_client: AsyncClient, db_session, tmp_path, x1c):
  2605. """Override types are merged into required_filament_types, so a shared list
  2606. also widened the type gate -- a PLA-only plate demanded PETG as well."""
  2607. import zipfile
  2608. from backend.app.models.archive import PrintArchive
  2609. xml = """<?xml version="1.0" encoding="UTF-8"?>
  2610. <config>
  2611. <plate>
  2612. <metadata key="index" value="1"/>
  2613. <filament id="1" used_g="50.0" type="PLA" color="#0B2C7A"/>
  2614. </plate>
  2615. <plate>
  2616. <metadata key="index" value="2"/>
  2617. <filament id="2" used_g="40.0" type="PETG" color="#9B9EA0"/>
  2618. </plate>
  2619. </config>
  2620. """
  2621. file_path = tmp_path / "mixed_types.gcode.3mf"
  2622. with zipfile.ZipFile(file_path, "w") as zf:
  2623. zf.writestr("Metadata/slice_info.config", xml)
  2624. archive = PrintArchive(
  2625. filename="mixed_types.gcode.3mf",
  2626. print_name="Mixed",
  2627. file_path=str(file_path),
  2628. file_size=file_path.stat().st_size,
  2629. content_hash="platehash0003",
  2630. status="completed",
  2631. )
  2632. db_session.add(archive)
  2633. await db_session.commit()
  2634. await db_session.refresh(archive)
  2635. response = await async_client.post(
  2636. "/api/v1/queue/",
  2637. json={
  2638. "target_model": "X1C",
  2639. "archive_id": archive.id,
  2640. "plate_id": 1,
  2641. "filament_overrides": [
  2642. {"slot_id": 1, "type": "PLA", "color": "#0B2C7A", "force_color_match": True},
  2643. {"slot_id": 2, "type": "PETG", "color": "#9B9EA0", "force_color_match": True},
  2644. ],
  2645. },
  2646. )
  2647. assert response.status_code == 200
  2648. assert response.json()["required_filament_types"] == ["PLA"]
  2649. @pytest.mark.asyncio
  2650. @pytest.mark.integration
  2651. async def test_editing_an_item_narrows_the_overrides_too(
  2652. self, async_client: AsyncClient, db_session, multi_plate_archive, x1c
  2653. ):
  2654. """The edit dialog posts the same shared list, so PATCH narrows it as well."""
  2655. from backend.app.models.print_queue import PrintQueueItem
  2656. item = PrintQueueItem(
  2657. target_model="X1C",
  2658. archive_id=multi_plate_archive.id,
  2659. plate_id=2,
  2660. status="pending",
  2661. position=1,
  2662. )
  2663. db_session.add(item)
  2664. await db_session.commit()
  2665. await db_session.refresh(item)
  2666. response = await async_client.patch(
  2667. f"/api/v1/queue/{item.id}",
  2668. json={"filament_overrides": self.ALL_THREE_COLORS},
  2669. )
  2670. assert response.status_code == 200
  2671. assert [o["color_name"] for o in response.json()["filament_overrides"]] == ["Ash Grey"]
  2672. @pytest.mark.asyncio
  2673. @pytest.mark.integration
  2674. async def test_editing_the_plate_renarrows_against_the_new_plate(
  2675. self, async_client: AsyncClient, db_session, multi_plate_archive, x1c
  2676. ):
  2677. """Moving an item to another plate must re-scope its colours to that plate."""
  2678. from backend.app.models.print_queue import PrintQueueItem
  2679. item = PrintQueueItem(
  2680. target_model="X1C",
  2681. archive_id=multi_plate_archive.id,
  2682. plate_id=1,
  2683. status="pending",
  2684. position=1,
  2685. )
  2686. db_session.add(item)
  2687. await db_session.commit()
  2688. await db_session.refresh(item)
  2689. response = await async_client.patch(
  2690. f"/api/v1/queue/{item.id}",
  2691. json={"plate_id": 3, "filament_overrides": self.ALL_THREE_COLORS},
  2692. )
  2693. assert response.status_code == 200
  2694. assert [o["color_name"] for o in response.json()["filament_overrides"]] == ["Sunshine Yellow"]
  2695. @pytest.mark.asyncio
  2696. async def test_stop_offline_reconciles_linked_archive_status_2603(
  2697. async_client: AsyncClient, printer_factory, archive_factory, db_session
  2698. ):
  2699. """Stopping a printing item while the printer is offline must also close out its
  2700. archive (#2603).
  2701. When the stop command reaches the printer, the later MQTT completion event flips
  2702. the archive to cancelled. When the printer is offline no such event ever arrives,
  2703. so without this the archive stays "printing" forever while the queue row is
  2704. already cancelled — the reporter's archive 436. The offline branch reconciles the
  2705. archive directly.
  2706. """
  2707. from unittest.mock import MagicMock, patch
  2708. from backend.app.models.print_queue import PrintQueueItem
  2709. printer = await printer_factory(name="Offline printer")
  2710. archive = await archive_factory(
  2711. printer.id, status="printing", plate_id=22, filename="heart 3.gcode.3mf", with_run=False
  2712. )
  2713. item = PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing")
  2714. db_session.add(item)
  2715. await db_session.commit()
  2716. await db_session.refresh(item)
  2717. # stop_print returns False => printer offline / not connected.
  2718. with patch(
  2719. "backend.app.services.printer_manager.printer_manager.stop_print",
  2720. MagicMock(return_value=False),
  2721. ):
  2722. resp = await async_client.post(f"/api/v1/queue/{item.id}/stop")
  2723. assert resp.status_code == 200
  2724. await db_session.refresh(item)
  2725. await db_session.refresh(archive)
  2726. assert item.status == "cancelled"
  2727. assert archive.status == "cancelled", "an offline stop must reconcile the archive, not leave it 'printing'"
  2728. assert archive.completed_at is not None
  2729. assert archive.failure_reason == "Stopped by user (printer was offline)"
  2730. @pytest.mark.asyncio
  2731. async def test_stop_online_leaves_archive_for_mqtt_to_reconcile_2603(
  2732. async_client: AsyncClient, printer_factory, archive_factory, db_session
  2733. ):
  2734. """When the stop command reaches the printer, the archive is left to the MQTT
  2735. completion path — the offline reconcile must NOT fire and pre-empt it."""
  2736. from unittest.mock import MagicMock, patch
  2737. from backend.app.models.print_queue import PrintQueueItem
  2738. printer = await printer_factory(name="Online printer")
  2739. archive = await archive_factory(printer.id, status="printing", filename="heart 3.gcode.3mf", with_run=False)
  2740. item = PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing")
  2741. db_session.add(item)
  2742. await db_session.commit()
  2743. await db_session.refresh(item)
  2744. with patch(
  2745. "backend.app.services.printer_manager.printer_manager.stop_print",
  2746. MagicMock(return_value=True),
  2747. ):
  2748. resp = await async_client.post(f"/api/v1/queue/{item.id}/stop")
  2749. assert resp.status_code == 200
  2750. await db_session.refresh(item)
  2751. await db_session.refresh(archive)
  2752. assert item.status == "cancelled"
  2753. assert archive.status == "printing", "an online stop must leave the archive for the MQTT completion path"