test_print_queue_api.py 161 KB

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