test_print_queue_api.py 147 KB

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