test_print_queue_api.py 158 KB

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