test_print_queue_api.py 160 KB

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