test_print_queue_api.py 129 KB

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