test_print_queue_api.py 126 KB

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