test_print_queue_api.py 154 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959
  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_delete_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  785. """Verify queue item can be deleted."""
  786. item = await queue_item_factory()
  787. response = await async_client.delete(f"/api/v1/queue/{item.id}")
  788. assert response.status_code == 200
  789. assert response.json()["message"] == "Queue item deleted"
  790. @pytest.mark.asyncio
  791. @pytest.mark.integration
  792. async def test_delete_queue_item_releases_reserved_budget(
  793. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  794. ):
  795. """Deleting a pending cost-center queue item releases its reserved budget."""
  796. await enable_billing(db_session)
  797. printer = await printer_factory()
  798. archive = await archive_factory(cost=3.0, filament_used_grams=50.0)
  799. cost_center = CostCenter(
  800. name="Delete Releases Budget CC", is_active=True, is_private=False, monthly_budget=10.0
  801. )
  802. db_session.add(cost_center)
  803. await db_session.commit()
  804. await db_session.refresh(cost_center)
  805. item = await queue_item_factory(
  806. printer_id=printer.id,
  807. archive_id=archive.id,
  808. cost_center_id=cost_center.id,
  809. estimated_cost=8.0,
  810. status="pending",
  811. )
  812. blocked = await async_client.post(
  813. "/api/v1/queue/",
  814. json={
  815. "printer_id": printer.id,
  816. "archive_id": archive.id,
  817. "cost_center_id": cost_center.id,
  818. "estimated_cost": 0.01,
  819. },
  820. )
  821. assert blocked.status_code == 400
  822. deleted = await async_client.delete(f"/api/v1/queue/{item.id}")
  823. assert deleted.status_code == 200
  824. allowed = await async_client.post(
  825. "/api/v1/queue/",
  826. json={
  827. "printer_id": printer.id,
  828. "archive_id": archive.id,
  829. "cost_center_id": cost_center.id,
  830. "estimated_cost": 0.01,
  831. },
  832. )
  833. assert allowed.status_code == 200
  834. @pytest.mark.asyncio
  835. @pytest.mark.integration
  836. async def test_delete_queue_item_not_found(self, async_client: AsyncClient):
  837. """Verify 404 for deleting non-existent queue item."""
  838. response = await async_client.delete("/api/v1/queue/9999")
  839. assert response.status_code == 404
  840. class TestQueueStartEndpoint:
  841. """Tests for the /queue/{item_id}/start endpoint."""
  842. @pytest.fixture
  843. async def printer_factory(self, db_session):
  844. """Factory to create test printers."""
  845. _counter = [0]
  846. async def _create_printer(**kwargs):
  847. from backend.app.models.printer import Printer
  848. _counter[0] += 1
  849. counter = _counter[0]
  850. defaults = {
  851. "name": f"Test Printer {counter}",
  852. "ip_address": f"192.168.1.{100 + counter}",
  853. "serial_number": f"TESTSERIAL{counter:04d}",
  854. "access_code": "12345678",
  855. "model": "X1C",
  856. }
  857. defaults.update(kwargs)
  858. printer = Printer(**defaults)
  859. db_session.add(printer)
  860. await db_session.commit()
  861. await db_session.refresh(printer)
  862. return printer
  863. return _create_printer
  864. @pytest.fixture
  865. async def archive_factory(self, db_session):
  866. """Factory to create test archives."""
  867. _counter = [0]
  868. async def _create_archive(**kwargs):
  869. from backend.app.models.archive import PrintArchive
  870. _counter[0] += 1
  871. counter = _counter[0]
  872. defaults = {
  873. "filename": f"test_print_{counter}.3mf",
  874. "print_name": f"Test Print {counter}",
  875. "file_path": f"/tmp/test_print_{counter}.3mf",
  876. "file_size": 1024,
  877. "content_hash": f"testhash{counter:08d}",
  878. "status": "completed",
  879. }
  880. defaults.update(kwargs)
  881. archive = PrintArchive(**defaults)
  882. db_session.add(archive)
  883. await db_session.commit()
  884. await db_session.refresh(archive)
  885. return archive
  886. return _create_archive
  887. @pytest.fixture
  888. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  889. """Factory to create test queue items."""
  890. _counter = [0]
  891. async def _create_queue_item(**kwargs):
  892. from backend.app.models.print_queue import PrintQueueItem
  893. _counter[0] += 1
  894. counter = _counter[0]
  895. if "printer_id" not in kwargs:
  896. printer = await printer_factory()
  897. kwargs["printer_id"] = printer.id
  898. if "archive_id" not in kwargs:
  899. archive = await archive_factory()
  900. kwargs["archive_id"] = archive.id
  901. defaults = {
  902. "status": "pending",
  903. "position": counter,
  904. }
  905. defaults.update(kwargs)
  906. item = PrintQueueItem(**defaults)
  907. db_session.add(item)
  908. await db_session.commit()
  909. await db_session.refresh(item)
  910. return item
  911. return _create_queue_item
  912. @pytest.mark.asyncio
  913. @pytest.mark.integration
  914. async def test_start_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  915. """Verify starting a staged (manual_start=True) queue item clears the flag."""
  916. item = await queue_item_factory(manual_start=True)
  917. assert item.manual_start is True
  918. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  919. assert response.status_code == 200
  920. result = response.json()
  921. assert result["manual_start"] is False
  922. assert result["status"] == "pending"
  923. @pytest.mark.asyncio
  924. @pytest.mark.integration
  925. async def test_start_non_staged_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  926. """Verify starting a non-staged queue item still works (idempotent)."""
  927. item = await queue_item_factory(manual_start=False)
  928. assert item.manual_start is False
  929. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  930. assert response.status_code == 200
  931. result = response.json()
  932. assert result["manual_start"] is False
  933. @pytest.mark.asyncio
  934. @pytest.mark.integration
  935. async def test_start_queue_item_with_cost_center_requires_estimated_cost(
  936. self, async_client: AsyncClient, queue_item_factory, db_session
  937. ):
  938. """Starting a cost-center queue item requires a stored estimate."""
  939. await enable_billing(db_session)
  940. cost_center = CostCenter(name="Start Budget CC", is_active=True, is_private=False, monthly_budget=10.0)
  941. db_session.add(cost_center)
  942. await db_session.commit()
  943. await db_session.refresh(cost_center)
  944. item = await queue_item_factory(manual_start=True, cost_center_id=cost_center.id, estimated_cost=None)
  945. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  946. assert response.status_code == 400
  947. assert "Estimated cost is required" in response.json()["detail"]
  948. @pytest.mark.asyncio
  949. @pytest.mark.integration
  950. async def test_start_queue_item_not_found(self, async_client: AsyncClient):
  951. """Verify 404 for non-existent queue item."""
  952. response = await async_client.post("/api/v1/queue/9999/start")
  953. assert response.status_code == 404
  954. @pytest.mark.asyncio
  955. @pytest.mark.integration
  956. async def test_start_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  957. """Verify 400 error when trying to start a non-pending queue item."""
  958. item = await queue_item_factory(status="printing", manual_start=True)
  959. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  960. assert response.status_code == 400
  961. assert "pending" in response.json()["detail"].lower()
  962. @pytest.mark.asyncio
  963. @pytest.mark.integration
  964. async def test_start_completed_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  965. """Verify 400 error when trying to start a completed queue item."""
  966. item = await queue_item_factory(status="completed", manual_start=True)
  967. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  968. assert response.status_code == 400
  969. @pytest.mark.asyncio
  970. @pytest.mark.integration
  971. async def test_start_returns_409_on_filament_deficit(
  972. self,
  973. async_client: AsyncClient,
  974. queue_item_factory,
  975. db_session,
  976. monkeypatch,
  977. ):
  978. """Filament deficit must surface as 409 + structured payload (#1496)."""
  979. from backend.app.services import filament_deficit as fd_module
  980. item = await queue_item_factory(manual_start=True)
  981. async def _fake_deficit(_db, _item):
  982. return [
  983. fd_module.FilamentDeficit(
  984. slot_id=1,
  985. ams_id=0,
  986. tray_id=0,
  987. filament_type="PLA",
  988. required_grams=270.0,
  989. remaining_grams=200.0,
  990. ),
  991. ]
  992. monkeypatch.setattr(
  993. "backend.app.api.routes.print_queue.compute_deficit_for_queue_item",
  994. _fake_deficit,
  995. )
  996. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  997. assert response.status_code == 409
  998. body = response.json()
  999. assert body["detail"]["code"] == "insufficient_filament"
  1000. assert len(body["detail"]["deficit"]) == 1
  1001. assert body["detail"]["deficit"][0]["slot_id"] == 1
  1002. assert body["detail"]["deficit"][0]["required_grams"] == 270.0
  1003. assert body["detail"]["deficit"][0]["remaining_grams"] == 200.0
  1004. # Item still pending, manual_start unchanged.
  1005. await db_session.refresh(item)
  1006. assert item.status == "pending"
  1007. assert item.manual_start is True
  1008. @pytest.mark.asyncio
  1009. @pytest.mark.integration
  1010. async def test_start_with_skip_flag_bypasses_deficit_check(
  1011. self,
  1012. async_client: AsyncClient,
  1013. queue_item_factory,
  1014. db_session,
  1015. monkeypatch,
  1016. ):
  1017. """With skip_filament_check=true the route dispatches even when short (#1496)."""
  1018. from backend.app.services import filament_deficit as fd_module
  1019. item = await queue_item_factory(manual_start=True, filament_short=True)
  1020. called_with = {}
  1021. async def _fake_deficit(_db, _item):
  1022. called_with["called"] = True
  1023. return [
  1024. fd_module.FilamentDeficit(
  1025. slot_id=1,
  1026. ams_id=0,
  1027. tray_id=0,
  1028. filament_type="PLA",
  1029. required_grams=270.0,
  1030. remaining_grams=200.0,
  1031. ),
  1032. ]
  1033. monkeypatch.setattr(
  1034. "backend.app.api.routes.print_queue.compute_deficit_for_queue_item",
  1035. _fake_deficit,
  1036. )
  1037. response = await async_client.post(f"/api/v1/queue/{item.id}/start?skip_filament_check=true")
  1038. assert response.status_code == 200
  1039. body = response.json()
  1040. assert body["manual_start"] is False
  1041. assert body["filament_short"] is False
  1042. # Helper not called on the bypass path — we trust the operator's
  1043. # decision to print anyway.
  1044. assert called_with == {}
  1045. @pytest.mark.asyncio
  1046. @pytest.mark.integration
  1047. async def test_start_with_skip_flag_persists_acknowledgement(
  1048. self,
  1049. async_client: AsyncClient,
  1050. queue_item_factory,
  1051. db_session,
  1052. ):
  1053. """skip_filament_check=true sets the persistent flag on the queue item
  1054. so the scheduler doesn't re-flag it on the next tick (#1698-followup).
  1055. Without persistence the route's flag-clearing only survives until the
  1056. next scheduler tick re-runs the deficit check on identical spool
  1057. state and re-promotes the item — the user has to click Play+Confirm
  1058. every single tick.
  1059. """
  1060. item = await queue_item_factory(manual_start=True, filament_short=True)
  1061. assert item.skip_filament_check is False
  1062. response = await async_client.post(f"/api/v1/queue/{item.id}/start?skip_filament_check=true")
  1063. assert response.status_code == 200
  1064. body = response.json()
  1065. assert body["skip_filament_check"] is True
  1066. await db_session.refresh(item)
  1067. assert item.skip_filament_check is True
  1068. @pytest.mark.asyncio
  1069. @pytest.mark.integration
  1070. async def test_start_without_skip_flag_does_not_set_acknowledgement(
  1071. self,
  1072. async_client: AsyncClient,
  1073. queue_item_factory,
  1074. db_session,
  1075. ):
  1076. """A successful Play click with no deficit must NOT silently set the
  1077. acknowledgement flag — only an explicit Print Anyway should.
  1078. """
  1079. item = await queue_item_factory(manual_start=False, filament_short=False)
  1080. assert item.skip_filament_check is False
  1081. response = await async_client.post(f"/api/v1/queue/{item.id}/start")
  1082. assert response.status_code == 200
  1083. await db_session.refresh(item)
  1084. assert item.skip_filament_check is False
  1085. class TestQueueCancelEndpoint:
  1086. """Tests for the /queue/{item_id}/cancel endpoint."""
  1087. @pytest.fixture
  1088. async def printer_factory(self, db_session):
  1089. """Factory to create test printers."""
  1090. async def _create_printer(**kwargs):
  1091. from backend.app.models.printer import Printer
  1092. defaults = {
  1093. "name": "Cancel Test Printer",
  1094. "ip_address": "192.168.1.200",
  1095. "serial_number": "TESTCANCEL001",
  1096. "access_code": "12345678",
  1097. "model": "X1C",
  1098. }
  1099. defaults.update(kwargs)
  1100. printer = Printer(**defaults)
  1101. db_session.add(printer)
  1102. await db_session.commit()
  1103. await db_session.refresh(printer)
  1104. return printer
  1105. return _create_printer
  1106. @pytest.fixture
  1107. async def archive_factory(self, db_session):
  1108. """Factory to create test archives."""
  1109. async def _create_archive(**kwargs):
  1110. from backend.app.models.archive import PrintArchive
  1111. defaults = {
  1112. "filename": "cancel_test.3mf",
  1113. "print_name": "Cancel Test Print",
  1114. "file_path": "/tmp/cancel_test.3mf",
  1115. "file_size": 1024,
  1116. "content_hash": "cancelhash001",
  1117. "status": "completed",
  1118. }
  1119. defaults.update(kwargs)
  1120. archive = PrintArchive(**defaults)
  1121. db_session.add(archive)
  1122. await db_session.commit()
  1123. await db_session.refresh(archive)
  1124. return archive
  1125. return _create_archive
  1126. @pytest.fixture
  1127. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1128. """Factory to create test queue items."""
  1129. async def _create_queue_item(**kwargs):
  1130. from backend.app.models.print_queue import PrintQueueItem
  1131. if "printer_id" not in kwargs:
  1132. printer = await printer_factory()
  1133. kwargs["printer_id"] = printer.id
  1134. if "archive_id" not in kwargs:
  1135. archive = await archive_factory()
  1136. kwargs["archive_id"] = archive.id
  1137. defaults = {
  1138. "status": "pending",
  1139. "position": 1,
  1140. }
  1141. defaults.update(kwargs)
  1142. item = PrintQueueItem(**defaults)
  1143. db_session.add(item)
  1144. await db_session.commit()
  1145. await db_session.refresh(item)
  1146. return item
  1147. return _create_queue_item
  1148. @pytest.mark.asyncio
  1149. @pytest.mark.integration
  1150. async def test_cancel_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  1151. """Verify cancelling a pending queue item."""
  1152. item = await queue_item_factory(status="pending")
  1153. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  1154. assert response.status_code == 200
  1155. assert response.json()["message"] == "Queue item cancelled"
  1156. @pytest.mark.asyncio
  1157. @pytest.mark.integration
  1158. async def test_cancel_non_pending_queue_item(self, async_client: AsyncClient, queue_item_factory, db_session):
  1159. """Verify 400 error when trying to cancel a non-pending queue item."""
  1160. item = await queue_item_factory(status="printing")
  1161. response = await async_client.post(f"/api/v1/queue/{item.id}/cancel")
  1162. assert response.status_code == 400
  1163. class TestQueueLibraryFileSupport:
  1164. """Tests for queue items with library_file_id (instead of archive_id)."""
  1165. @pytest.fixture
  1166. async def printer_factory(self, db_session):
  1167. """Factory to create test printers."""
  1168. _counter = [0]
  1169. async def _create_printer(**kwargs):
  1170. from backend.app.models.printer import Printer
  1171. _counter[0] += 1
  1172. counter = _counter[0]
  1173. defaults = {
  1174. "name": f"Library Test Printer {counter}",
  1175. "ip_address": f"192.168.1.{150 + counter}",
  1176. "serial_number": f"TESTLIB{counter:04d}",
  1177. "access_code": "12345678",
  1178. "model": "X1C",
  1179. }
  1180. defaults.update(kwargs)
  1181. printer = Printer(**defaults)
  1182. db_session.add(printer)
  1183. await db_session.commit()
  1184. await db_session.refresh(printer)
  1185. return printer
  1186. return _create_printer
  1187. @pytest.fixture
  1188. async def library_file_factory(self, db_session):
  1189. """Factory to create test library files."""
  1190. _counter = [0]
  1191. async def _create_library_file(**kwargs):
  1192. from backend.app.models.library import LibraryFile
  1193. _counter[0] += 1
  1194. counter = _counter[0]
  1195. defaults = {
  1196. "filename": f"library_test_{counter}.3mf",
  1197. "file_path": f"/test/library/library_test_{counter}.3mf",
  1198. "file_size": 2048,
  1199. "file_type": "3mf",
  1200. "file_metadata": {"print_name": f"Library Print {counter}", "print_time_seconds": 3600},
  1201. }
  1202. defaults.update(kwargs)
  1203. lib_file = LibraryFile(**defaults)
  1204. db_session.add(lib_file)
  1205. await db_session.commit()
  1206. await db_session.refresh(lib_file)
  1207. return lib_file
  1208. return _create_library_file
  1209. @pytest.mark.asyncio
  1210. @pytest.mark.integration
  1211. async def test_add_to_queue_with_library_file(
  1212. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1213. ):
  1214. """Verify item can be added to queue using library_file_id instead of archive_id."""
  1215. printer = await printer_factory()
  1216. lib_file = await library_file_factory()
  1217. data = {
  1218. "printer_id": printer.id,
  1219. "library_file_id": lib_file.id,
  1220. }
  1221. response = await async_client.post("/api/v1/queue/", json=data)
  1222. assert response.status_code == 200
  1223. result = response.json()
  1224. assert result["printer_id"] == printer.id
  1225. assert result["library_file_id"] == lib_file.id
  1226. assert result["archive_id"] is None
  1227. assert result["status"] == "pending"
  1228. assert result["library_file_name"] == "Library Print 1"
  1229. assert result["print_time_seconds"] == 3600
  1230. @pytest.mark.asyncio
  1231. @pytest.mark.integration
  1232. async def test_add_library_file_rejects_cross_model_mismatch(
  1233. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1234. ):
  1235. """Cross-model gate (#2578) also reads sliced_for_model from library file metadata."""
  1236. await printer_factory(model="H2D")
  1237. lib_file = await library_file_factory(file_metadata={"print_name": "Mismatch", "sliced_for_model": "X1C"})
  1238. response = await async_client.post(
  1239. "/api/v1/queue/",
  1240. json={"target_model": "H2D", "library_file_id": lib_file.id},
  1241. )
  1242. assert response.status_code == 400
  1243. assert "sliced for X1C" in response.json()["detail"]
  1244. @pytest.mark.asyncio
  1245. @pytest.mark.integration
  1246. async def test_add_to_queue_library_file_with_options(
  1247. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1248. ):
  1249. """Verify library file queue item can have all options set."""
  1250. printer = await printer_factory()
  1251. lib_file = await library_file_factory()
  1252. data = {
  1253. "printer_id": printer.id,
  1254. "library_file_id": lib_file.id,
  1255. "ams_mapping": [1, 2, -1, -1],
  1256. "plate_id": 2,
  1257. "bed_levelling": "off",
  1258. "timelapse": True,
  1259. "manual_start": True,
  1260. }
  1261. response = await async_client.post("/api/v1/queue/", json=data)
  1262. assert response.status_code == 200
  1263. result = response.json()
  1264. assert result["library_file_id"] == lib_file.id
  1265. assert result["ams_mapping"] == [1, 2, -1, -1]
  1266. assert result["plate_id"] == 2
  1267. assert result["bed_levelling"] == "off"
  1268. assert result["timelapse"] is True
  1269. assert result["manual_start"] is True
  1270. @pytest.mark.asyncio
  1271. @pytest.mark.integration
  1272. async def test_add_to_queue_requires_archive_or_library_file(
  1273. self, async_client: AsyncClient, printer_factory, db_session
  1274. ):
  1275. """Verify 400 error when neither archive_id nor library_file_id provided."""
  1276. printer = await printer_factory()
  1277. data = {
  1278. "printer_id": printer.id,
  1279. }
  1280. response = await async_client.post("/api/v1/queue/", json=data)
  1281. assert response.status_code == 400
  1282. assert (
  1283. "archive_id" in response.json()["detail"].lower() or "library_file_id" in response.json()["detail"].lower()
  1284. )
  1285. @pytest.mark.asyncio
  1286. @pytest.mark.integration
  1287. async def test_update_queue_item_with_library_file(
  1288. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1289. ):
  1290. """Verify queue item with library_file_id can be updated."""
  1291. from backend.app.models.print_queue import PrintQueueItem
  1292. printer = await printer_factory()
  1293. lib_file = await library_file_factory()
  1294. # Create queue item directly
  1295. item = PrintQueueItem(
  1296. printer_id=printer.id,
  1297. library_file_id=lib_file.id,
  1298. status="pending",
  1299. position=1,
  1300. )
  1301. db_session.add(item)
  1302. await db_session.commit()
  1303. await db_session.refresh(item)
  1304. # Update the item
  1305. response = await async_client.patch(
  1306. f"/api/v1/queue/{item.id}",
  1307. json={"auto_off_after": True, "plate_id": 3},
  1308. )
  1309. assert response.status_code == 200
  1310. result = response.json()
  1311. assert result["auto_off_after"] is True
  1312. assert result["plate_id"] == 3
  1313. assert result["library_file_id"] == lib_file.id
  1314. @pytest.mark.asyncio
  1315. @pytest.mark.integration
  1316. async def test_list_queue_includes_library_file_info(
  1317. self, async_client: AsyncClient, printer_factory, library_file_factory, db_session
  1318. ):
  1319. """Verify queue list includes library file metadata."""
  1320. from backend.app.models.print_queue import PrintQueueItem
  1321. printer = await printer_factory()
  1322. lib_file = await library_file_factory(
  1323. file_metadata={"print_name": "Custom Print Name", "print_time_seconds": 7200}
  1324. )
  1325. item = PrintQueueItem(
  1326. printer_id=printer.id,
  1327. library_file_id=lib_file.id,
  1328. status="pending",
  1329. position=1,
  1330. )
  1331. db_session.add(item)
  1332. await db_session.commit()
  1333. response = await async_client.get("/api/v1/queue/")
  1334. assert response.status_code == 200
  1335. items = response.json()
  1336. assert len(items) >= 1
  1337. # Find our item
  1338. our_item = next((i for i in items if i["library_file_id"] == lib_file.id), None)
  1339. assert our_item is not None
  1340. assert our_item["library_file_name"] == "Custom Print Name"
  1341. assert our_item["print_time_seconds"] == 7200
  1342. class TestBulkUpdateEndpoint:
  1343. """Tests for the /queue/bulk endpoint."""
  1344. @pytest.fixture
  1345. async def printer_factory(self, db_session):
  1346. """Factory to create test printers."""
  1347. _counter = [0]
  1348. async def _create_printer(**kwargs):
  1349. from backend.app.models.printer import Printer
  1350. _counter[0] += 1
  1351. counter = _counter[0]
  1352. defaults = {
  1353. "name": f"Bulk Test Printer {counter}",
  1354. "ip_address": f"192.168.1.{150 + counter}",
  1355. "serial_number": f"TESTBULK{counter:04d}",
  1356. "access_code": "12345678",
  1357. "model": "X1C",
  1358. }
  1359. defaults.update(kwargs)
  1360. printer = Printer(**defaults)
  1361. db_session.add(printer)
  1362. await db_session.commit()
  1363. await db_session.refresh(printer)
  1364. return printer
  1365. return _create_printer
  1366. @pytest.fixture
  1367. async def archive_factory(self, db_session):
  1368. """Factory to create test archives."""
  1369. _counter = [0]
  1370. async def _create_archive(**kwargs):
  1371. from backend.app.models.archive import PrintArchive
  1372. _counter[0] += 1
  1373. counter = _counter[0]
  1374. defaults = {
  1375. "filename": f"bulk_test_{counter}.3mf",
  1376. "print_name": f"Bulk Test Print {counter}",
  1377. "file_path": f"/tmp/bulk_test_{counter}.3mf",
  1378. "file_size": 1024,
  1379. "content_hash": f"bulkhash{counter:04d}",
  1380. "status": "completed",
  1381. }
  1382. defaults.update(kwargs)
  1383. archive = PrintArchive(**defaults)
  1384. db_session.add(archive)
  1385. await db_session.commit()
  1386. await db_session.refresh(archive)
  1387. return archive
  1388. return _create_archive
  1389. @pytest.fixture
  1390. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1391. """Factory to create test queue items."""
  1392. async def _create_item(**kwargs):
  1393. from backend.app.models.print_queue import PrintQueueItem
  1394. if "printer_id" not in kwargs:
  1395. printer = await printer_factory()
  1396. kwargs["printer_id"] = printer.id
  1397. if "archive_id" not in kwargs:
  1398. archive = await archive_factory()
  1399. kwargs["archive_id"] = archive.id
  1400. defaults = {
  1401. "status": "pending",
  1402. "position": 1,
  1403. "bed_levelling": "on",
  1404. "flow_cali": "off",
  1405. "vibration_cali": True,
  1406. }
  1407. defaults.update(kwargs)
  1408. item = PrintQueueItem(**defaults)
  1409. db_session.add(item)
  1410. await db_session.commit()
  1411. await db_session.refresh(item)
  1412. return item
  1413. return _create_item
  1414. @pytest.mark.asyncio
  1415. @pytest.mark.integration
  1416. async def test_bulk_update_single_field(self, async_client: AsyncClient, queue_item_factory, db_session):
  1417. """Verify bulk update can change a single field on multiple items."""
  1418. item1 = await queue_item_factory(bed_levelling="on")
  1419. item2 = await queue_item_factory(bed_levelling="on")
  1420. response = await async_client.patch(
  1421. "/api/v1/queue/bulk",
  1422. json={"item_ids": [item1.id, item2.id], "bed_levelling": "off"},
  1423. )
  1424. assert response.status_code == 200
  1425. result = response.json()
  1426. assert result["updated_count"] == 2
  1427. assert result["skipped_count"] == 0
  1428. # Verify items were updated
  1429. await db_session.refresh(item1)
  1430. await db_session.refresh(item2)
  1431. assert item1.bed_levelling == "off"
  1432. assert item2.bed_levelling == "off"
  1433. @pytest.mark.asyncio
  1434. @pytest.mark.integration
  1435. async def test_bulk_update_multiple_fields(self, async_client: AsyncClient, queue_item_factory, db_session):
  1436. """Verify bulk update can change multiple fields at once."""
  1437. item1 = await queue_item_factory(bed_levelling="on", flow_cali="off", manual_start=False)
  1438. item2 = await queue_item_factory(bed_levelling="on", flow_cali="off", manual_start=False)
  1439. response = await async_client.patch(
  1440. "/api/v1/queue/bulk",
  1441. json={
  1442. "item_ids": [item1.id, item2.id],
  1443. "bed_levelling": "off",
  1444. "flow_cali": "on",
  1445. "manual_start": True,
  1446. },
  1447. )
  1448. assert response.status_code == 200
  1449. result = response.json()
  1450. assert result["updated_count"] == 2
  1451. await db_session.refresh(item1)
  1452. assert item1.bed_levelling == "off"
  1453. assert item1.flow_cali == "on"
  1454. assert item1.manual_start is True
  1455. @pytest.mark.asyncio
  1456. @pytest.mark.integration
  1457. async def test_bulk_update_skips_non_pending(self, async_client: AsyncClient, queue_item_factory, db_session):
  1458. """Verify bulk update skips non-pending items."""
  1459. pending_item = await queue_item_factory(status="pending", bed_levelling="on")
  1460. printing_item = await queue_item_factory(status="printing", bed_levelling="on")
  1461. completed_item = await queue_item_factory(status="completed", bed_levelling="on")
  1462. response = await async_client.patch(
  1463. "/api/v1/queue/bulk",
  1464. json={
  1465. "item_ids": [pending_item.id, printing_item.id, completed_item.id],
  1466. "bed_levelling": "off",
  1467. },
  1468. )
  1469. assert response.status_code == 200
  1470. result = response.json()
  1471. assert result["updated_count"] == 1
  1472. assert result["skipped_count"] == 2
  1473. # Only pending item should be updated
  1474. await db_session.refresh(pending_item)
  1475. await db_session.refresh(printing_item)
  1476. await db_session.refresh(completed_item)
  1477. assert pending_item.bed_levelling == "off"
  1478. assert printing_item.bed_levelling == "on"
  1479. assert completed_item.bed_levelling == "on"
  1480. @pytest.mark.asyncio
  1481. @pytest.mark.integration
  1482. async def test_bulk_update_change_printer(
  1483. self, async_client: AsyncClient, queue_item_factory, printer_factory, db_session
  1484. ):
  1485. """Verify bulk update can reassign items to a different printer."""
  1486. new_printer = await printer_factory(name="New Target Printer")
  1487. item1 = await queue_item_factory()
  1488. item2 = await queue_item_factory()
  1489. original_printer_id = item1.printer_id
  1490. response = await async_client.patch(
  1491. "/api/v1/queue/bulk",
  1492. json={"item_ids": [item1.id, item2.id], "printer_id": new_printer.id},
  1493. )
  1494. assert response.status_code == 200
  1495. await db_session.refresh(item1)
  1496. await db_session.refresh(item2)
  1497. assert item1.printer_id == new_printer.id
  1498. assert item2.printer_id == new_printer.id
  1499. assert item1.printer_id != original_printer_id
  1500. @pytest.mark.asyncio
  1501. @pytest.mark.integration
  1502. async def test_bulk_update_empty_item_ids(self, async_client: AsyncClient):
  1503. """Verify 400 error when item_ids is empty."""
  1504. response = await async_client.patch(
  1505. "/api/v1/queue/bulk",
  1506. json={"item_ids": [], "bed_levelling": False},
  1507. )
  1508. assert response.status_code == 400
  1509. assert "no item" in response.json()["detail"].lower()
  1510. @pytest.mark.asyncio
  1511. @pytest.mark.integration
  1512. async def test_bulk_update_no_fields(self, async_client: AsyncClient, queue_item_factory):
  1513. """Verify 400 error when no fields to update."""
  1514. item = await queue_item_factory()
  1515. response = await async_client.patch(
  1516. "/api/v1/queue/bulk",
  1517. json={"item_ids": [item.id]},
  1518. )
  1519. assert response.status_code == 400
  1520. assert "no fields" in response.json()["detail"].lower()
  1521. @pytest.mark.asyncio
  1522. @pytest.mark.integration
  1523. async def test_bulk_update_invalid_printer(self, async_client: AsyncClient, queue_item_factory):
  1524. """Verify 400 error when printer_id doesn't exist."""
  1525. item = await queue_item_factory()
  1526. response = await async_client.patch(
  1527. "/api/v1/queue/bulk",
  1528. json={"item_ids": [item.id], "printer_id": 99999},
  1529. )
  1530. assert response.status_code == 400
  1531. assert "printer not found" in response.json()["detail"].lower()
  1532. @pytest.mark.asyncio
  1533. @pytest.mark.integration
  1534. async def test_bulk_update_cost_center_requires_estimated_cost(
  1535. self, async_client: AsyncClient, queue_item_factory, db_session
  1536. ):
  1537. """Bulk assigning a cost center requires an estimate, same as single-item updates."""
  1538. await enable_billing(db_session)
  1539. item = await queue_item_factory()
  1540. cost_center = CostCenter(name="Bulk Budget CC", is_active=True, is_private=False, monthly_budget=10.0)
  1541. db_session.add(cost_center)
  1542. await db_session.commit()
  1543. await db_session.refresh(cost_center)
  1544. response = await async_client.patch(
  1545. "/api/v1/queue/bulk",
  1546. json={"item_ids": [item.id], "cost_center_id": cost_center.id},
  1547. )
  1548. assert response.status_code == 400
  1549. assert "Estimated cost is required" in response.json()["detail"]
  1550. @pytest.mark.asyncio
  1551. @pytest.mark.integration
  1552. async def test_bulk_update_cost_center_counts_pending_reservations(
  1553. self, async_client: AsyncClient, queue_item_factory, archive_factory, db_session
  1554. ):
  1555. """A forged bulk-update hint cannot weaken the server-derived reservation."""
  1556. await enable_billing(db_session)
  1557. archive = await archive_factory(cost=3.0, filament_used_grams=50.0)
  1558. item = await queue_item_factory(archive_id=archive.id)
  1559. existing = await queue_item_factory()
  1560. cost_center = CostCenter(name="Bulk Reserved CC", is_active=True, is_private=False, monthly_budget=10.0)
  1561. db_session.add(cost_center)
  1562. await db_session.commit()
  1563. await db_session.refresh(cost_center)
  1564. existing.cost_center_id = cost_center.id
  1565. existing.estimated_cost = 8.0
  1566. await db_session.commit()
  1567. response = await async_client.patch(
  1568. "/api/v1/queue/bulk",
  1569. json={"item_ids": [item.id], "cost_center_id": cost_center.id, "estimated_cost": 0.01},
  1570. )
  1571. assert response.status_code == 400
  1572. assert "exceeds available cost center budget" in response.json()["detail"]
  1573. await db_session.refresh(item)
  1574. assert item.cost_center_id is None
  1575. assert item.estimated_cost is None
  1576. class TestTargetLocationFeature:
  1577. """Tests for queue items with target_location (Issue #220)."""
  1578. @pytest.fixture
  1579. async def printer_factory(self, db_session):
  1580. """Factory to create test printers."""
  1581. _counter = [0]
  1582. async def _create_printer(**kwargs):
  1583. from backend.app.models.printer import Printer
  1584. _counter[0] += 1
  1585. counter = _counter[0]
  1586. defaults = {
  1587. "name": f"Location Test Printer {counter}",
  1588. "ip_address": f"192.168.1.{50 + counter}",
  1589. "serial_number": f"TESTLOC{counter:04d}",
  1590. "access_code": "12345678",
  1591. "model": "X1C",
  1592. }
  1593. defaults.update(kwargs)
  1594. printer = Printer(**defaults)
  1595. db_session.add(printer)
  1596. await db_session.commit()
  1597. await db_session.refresh(printer)
  1598. return printer
  1599. return _create_printer
  1600. @pytest.fixture
  1601. async def archive_factory(self, db_session):
  1602. """Factory to create test archives."""
  1603. _counter = [0]
  1604. async def _create_archive(**kwargs):
  1605. from backend.app.models.archive import PrintArchive
  1606. _counter[0] += 1
  1607. counter = _counter[0]
  1608. defaults = {
  1609. "filename": f"location_test_{counter}.3mf",
  1610. "print_name": f"Location Test Print {counter}",
  1611. "file_path": f"/tmp/location_test_{counter}.3mf",
  1612. "file_size": 1024,
  1613. "content_hash": f"lochash{counter:08d}",
  1614. "status": "completed",
  1615. }
  1616. defaults.update(kwargs)
  1617. archive = PrintArchive(**defaults)
  1618. db_session.add(archive)
  1619. await db_session.commit()
  1620. await db_session.refresh(archive)
  1621. return archive
  1622. return _create_archive
  1623. @pytest.fixture
  1624. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1625. """Factory to create test queue items."""
  1626. _counter = [0]
  1627. async def _create_queue_item(**kwargs):
  1628. from backend.app.models.print_queue import PrintQueueItem
  1629. _counter[0] += 1
  1630. counter = _counter[0]
  1631. if "printer_id" not in kwargs and "target_model" not in kwargs:
  1632. printer = await printer_factory()
  1633. kwargs["printer_id"] = printer.id
  1634. if "archive_id" not in kwargs:
  1635. archive = await archive_factory()
  1636. kwargs["archive_id"] = archive.id
  1637. defaults = {
  1638. "status": "pending",
  1639. "position": counter,
  1640. }
  1641. defaults.update(kwargs)
  1642. item = PrintQueueItem(**defaults)
  1643. db_session.add(item)
  1644. await db_session.commit()
  1645. await db_session.refresh(item)
  1646. return item
  1647. return _create_queue_item
  1648. @pytest.mark.asyncio
  1649. @pytest.mark.integration
  1650. async def test_add_to_queue_with_target_location(
  1651. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1652. ):
  1653. """Verify item can be added with target_model and target_location."""
  1654. # Create a printer with model X1C so the API can validate
  1655. await printer_factory(model="X1C", location="Office")
  1656. archive = await archive_factory()
  1657. data = {
  1658. "target_model": "X1C",
  1659. "target_location": "Workbench",
  1660. "archive_id": archive.id,
  1661. }
  1662. response = await async_client.post("/api/v1/queue/", json=data)
  1663. assert response.status_code == 200
  1664. result = response.json()
  1665. assert result["target_model"] == "X1C"
  1666. assert result["target_location"] == "Workbench"
  1667. assert result["printer_id"] is None
  1668. @pytest.mark.asyncio
  1669. @pytest.mark.integration
  1670. async def test_add_to_queue_location_without_model_ignored(
  1671. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1672. ):
  1673. """Verify target_location without target_model is allowed (location is just ignored)."""
  1674. printer = await printer_factory()
  1675. archive = await archive_factory()
  1676. data = {
  1677. "printer_id": printer.id,
  1678. "target_location": "Workbench", # This gets ignored since printer_id is set
  1679. "archive_id": archive.id,
  1680. }
  1681. response = await async_client.post("/api/v1/queue/", json=data)
  1682. # The API accepts this but the location is only used with target_model
  1683. assert response.status_code == 200
  1684. result = response.json()
  1685. assert result["printer_id"] == printer.id
  1686. # Location may or may not be stored since it's meaningless without target_model
  1687. # The important thing is the request succeeds
  1688. @pytest.mark.asyncio
  1689. @pytest.mark.integration
  1690. async def test_queue_item_target_location_in_response(
  1691. self, async_client: AsyncClient, queue_item_factory, db_session
  1692. ):
  1693. """Verify target_location is returned in queue item response."""
  1694. item = await queue_item_factory(
  1695. printer_id=None,
  1696. target_model="X1C",
  1697. target_location="Workshop",
  1698. )
  1699. response = await async_client.get(f"/api/v1/queue/{item.id}")
  1700. assert response.status_code == 200
  1701. result = response.json()
  1702. assert result["target_model"] == "X1C"
  1703. assert result["target_location"] == "Workshop"
  1704. @pytest.mark.asyncio
  1705. @pytest.mark.integration
  1706. async def test_queue_list_includes_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1707. """Verify target_location is included in queue list."""
  1708. await queue_item_factory(
  1709. printer_id=None,
  1710. target_model="P1S",
  1711. target_location="Garage",
  1712. )
  1713. response = await async_client.get("/api/v1/queue/")
  1714. assert response.status_code == 200
  1715. items = response.json()
  1716. assert len(items) >= 1
  1717. # Find our item
  1718. our_item = next((i for i in items if i["target_location"] == "Garage"), None)
  1719. assert our_item is not None
  1720. assert our_item["target_model"] == "P1S"
  1721. @pytest.mark.asyncio
  1722. @pytest.mark.integration
  1723. async def test_update_queue_item_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1724. """Verify target_location can be updated on existing queue item."""
  1725. item = await queue_item_factory(
  1726. printer_id=None,
  1727. target_model="X1C",
  1728. target_location="Office",
  1729. )
  1730. response = await async_client.patch(
  1731. f"/api/v1/queue/{item.id}",
  1732. json={"target_location": "Basement"},
  1733. )
  1734. assert response.status_code == 200
  1735. result = response.json()
  1736. assert result["target_location"] == "Basement"
  1737. @pytest.mark.asyncio
  1738. @pytest.mark.integration
  1739. async def test_clear_target_location(self, async_client: AsyncClient, queue_item_factory, db_session):
  1740. """Verify target_location can be cleared (set to None)."""
  1741. item = await queue_item_factory(
  1742. printer_id=None,
  1743. target_model="X1C",
  1744. target_location="Office",
  1745. )
  1746. # Note: Setting to empty string should clear it
  1747. response = await async_client.patch(
  1748. f"/api/v1/queue/{item.id}",
  1749. json={"target_location": None},
  1750. )
  1751. assert response.status_code == 200
  1752. result = response.json()
  1753. assert result["target_location"] is None
  1754. # ------------------------------------------------------------------
  1755. # Cross-model dispatch gate (#2578): a G-code 3MF sliced for one model
  1756. # must not be queued for model-based dispatch to an incompatible model.
  1757. # ------------------------------------------------------------------
  1758. @pytest.mark.asyncio
  1759. @pytest.mark.integration
  1760. async def test_add_to_queue_rejects_cross_model_mismatch(
  1761. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1762. ):
  1763. """X1C-sliced archive + target_model=H2D must be rejected (#2578)."""
  1764. await printer_factory(model="H2D")
  1765. archive = await archive_factory(sliced_for_model="X1C")
  1766. response = await async_client.post(
  1767. "/api/v1/queue/",
  1768. json={"target_model": "H2D", "archive_id": archive.id},
  1769. )
  1770. assert response.status_code == 400
  1771. assert "sliced for X1C" in response.json()["detail"]
  1772. @pytest.mark.asyncio
  1773. @pytest.mark.integration
  1774. async def test_add_to_queue_allows_gcode_family_target(
  1775. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1776. ):
  1777. """X1C-sliced G-code on a P1S is an intentional mixed-farm workflow —
  1778. same kinematics/volume family, must stay allowed."""
  1779. await printer_factory(model="P1S")
  1780. archive = await archive_factory(sliced_for_model="X1C")
  1781. response = await async_client.post(
  1782. "/api/v1/queue/",
  1783. json={"target_model": "P1S", "archive_id": archive.id},
  1784. )
  1785. assert response.status_code == 200
  1786. assert response.json()["target_model"] == "P1S"
  1787. @pytest.mark.asyncio
  1788. @pytest.mark.integration
  1789. async def test_add_to_queue_without_sliced_metadata_not_blocked(
  1790. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  1791. ):
  1792. """Legacy archives without sliced_for_model can't be validated — must keep working."""
  1793. await printer_factory(model="H2D")
  1794. archive = await archive_factory() # no sliced_for_model
  1795. response = await async_client.post(
  1796. "/api/v1/queue/",
  1797. json={"target_model": "H2D", "archive_id": archive.id},
  1798. )
  1799. assert response.status_code == 200
  1800. @pytest.mark.asyncio
  1801. @pytest.mark.integration
  1802. async def test_update_rejects_cross_model_mismatch(
  1803. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1804. ):
  1805. """Editing an item must not be able to introduce an incompatible target either."""
  1806. await printer_factory(model="X1C")
  1807. await printer_factory(model="H2D")
  1808. archive = await archive_factory(sliced_for_model="X1C")
  1809. item = await queue_item_factory(printer_id=None, target_model="X1C", archive_id=archive.id)
  1810. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"target_model": "H2D"})
  1811. assert response.status_code == 400
  1812. assert "sliced for X1C" in response.json()["detail"]
  1813. @pytest.mark.asyncio
  1814. @pytest.mark.integration
  1815. async def test_update_can_fix_stale_mismatched_target(
  1816. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  1817. ):
  1818. """A pre-fix DB row with a wrong target (the reporter's rows 78-82) must be
  1819. repairable by editing the target back to the sliced-for model."""
  1820. await printer_factory(model="X1C")
  1821. archive = await archive_factory(sliced_for_model="X1C")
  1822. # Stale mismatched row written directly to the DB (bypasses the API gate)
  1823. item = await queue_item_factory(printer_id=None, target_model="H2D", archive_id=archive.id)
  1824. response = await async_client.patch(f"/api/v1/queue/{item.id}", json={"target_model": "X1C"})
  1825. assert response.status_code == 200
  1826. assert response.json()["target_model"] == "X1C"
  1827. class TestAbortedStatusNormalisation:
  1828. """Tests for issue #558: 'aborted' queue status causes 500 error."""
  1829. @pytest.fixture
  1830. async def printer_factory(self, db_session):
  1831. """Factory to create test printers."""
  1832. _counter = [0]
  1833. async def _create_printer(**kwargs):
  1834. from backend.app.models.printer import Printer
  1835. _counter[0] += 1
  1836. counter = _counter[0]
  1837. defaults = {
  1838. "name": f"Abort Test Printer {counter}",
  1839. "ip_address": f"192.168.1.{60 + counter}",
  1840. "serial_number": f"TESTABORT{counter:04d}",
  1841. "access_code": "12345678",
  1842. "model": "P1S",
  1843. }
  1844. defaults.update(kwargs)
  1845. printer = Printer(**defaults)
  1846. db_session.add(printer)
  1847. await db_session.commit()
  1848. await db_session.refresh(printer)
  1849. return printer
  1850. return _create_printer
  1851. @pytest.fixture
  1852. async def archive_factory(self, db_session):
  1853. """Factory to create test archives."""
  1854. _counter = [0]
  1855. async def _create_archive(**kwargs):
  1856. from backend.app.models.archive import PrintArchive
  1857. _counter[0] += 1
  1858. counter = _counter[0]
  1859. defaults = {
  1860. "filename": f"abort_test_{counter}.3mf",
  1861. "print_name": f"Abort Test Print {counter}",
  1862. "file_path": f"/tmp/abort_test_{counter}.3mf",
  1863. "file_size": 1024,
  1864. "content_hash": f"aborthash{counter:06d}",
  1865. "status": "completed",
  1866. }
  1867. defaults.update(kwargs)
  1868. archive = PrintArchive(**defaults)
  1869. db_session.add(archive)
  1870. await db_session.commit()
  1871. await db_session.refresh(archive)
  1872. return archive
  1873. return _create_archive
  1874. @pytest.fixture
  1875. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  1876. """Factory to create test queue items."""
  1877. _counter = [0]
  1878. async def _create_queue_item(**kwargs):
  1879. from backend.app.models.print_queue import PrintQueueItem
  1880. _counter[0] += 1
  1881. counter = _counter[0]
  1882. if "printer_id" not in kwargs:
  1883. printer = await printer_factory()
  1884. kwargs["printer_id"] = printer.id
  1885. if "archive_id" not in kwargs:
  1886. archive = await archive_factory()
  1887. kwargs["archive_id"] = archive.id
  1888. defaults = {
  1889. "status": "pending",
  1890. "position": counter,
  1891. }
  1892. defaults.update(kwargs)
  1893. item = PrintQueueItem(**defaults)
  1894. db_session.add(item)
  1895. await db_session.commit()
  1896. await db_session.refresh(item)
  1897. return item
  1898. return _create_queue_item
  1899. @pytest.mark.asyncio
  1900. @pytest.mark.integration
  1901. async def test_on_print_complete_normalises_aborted_to_cancelled(
  1902. self, queue_item_factory, archive_factory, db_session
  1903. ):
  1904. """Verify the completion handler maps 'aborted' → 'cancelled' for queue items."""
  1905. import asyncio
  1906. from unittest.mock import AsyncMock, MagicMock, patch
  1907. archive = await archive_factory(filename="Abort_Me.gcode.3mf")
  1908. item = await queue_item_factory(status="printing", archive_id=archive.id)
  1909. # Build a mock session whose execute returns our item. `get` has to
  1910. # answer with the item's real archive: the handler checks the completion
  1911. # is about this row's print before closing it, and an archive that names
  1912. # a different subtask is exactly what it refuses.
  1913. mock_result = MagicMock()
  1914. mock_result.scalars.return_value.all.return_value = [item]
  1915. mock_session = AsyncMock()
  1916. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  1917. mock_session.__aexit__ = AsyncMock(return_value=False)
  1918. mock_session.execute = AsyncMock(return_value=mock_result)
  1919. mock_session.get = AsyncMock(return_value=archive)
  1920. mock_session.commit = AsyncMock()
  1921. tasks_before = set(asyncio.all_tasks())
  1922. with (
  1923. patch("backend.app.main.async_session", return_value=mock_session),
  1924. patch("backend.app.core.database.async_session", return_value=mock_session),
  1925. patch("backend.app.main.ws_manager") as mock_ws,
  1926. patch("backend.app.main.mqtt_relay") as mock_relay,
  1927. patch("backend.app.main.notification_service") as mock_notif,
  1928. patch("backend.app.main.smart_plug_manager") as mock_plug,
  1929. patch("backend.app.main.printer_manager") as mock_pm,
  1930. ):
  1931. mock_ws.send_print_complete = AsyncMock()
  1932. mock_ws.broadcast = AsyncMock()
  1933. mock_relay.on_print_complete = AsyncMock()
  1934. mock_relay.on_queue_job_completed = AsyncMock()
  1935. mock_notif.on_print_complete = AsyncMock()
  1936. mock_plug.on_print_complete = AsyncMock()
  1937. mock_pm.get_printer.return_value = None
  1938. from backend.app.main import on_print_complete
  1939. await on_print_complete(
  1940. item.printer_id,
  1941. {
  1942. "status": "aborted",
  1943. "filename": "test.gcode",
  1944. "subtask_name": "Abort_Me",
  1945. "timelapse_was_active": False,
  1946. },
  1947. )
  1948. # Cancel background tasks before leaving mock context
  1949. for task in asyncio.all_tasks() - tasks_before:
  1950. task.cancel()
  1951. try:
  1952. await task
  1953. except (asyncio.CancelledError, Exception):
  1954. pass
  1955. # The item status should be normalised to 'cancelled', not 'aborted'
  1956. assert item.status == "cancelled"
  1957. @pytest.mark.asyncio
  1958. @pytest.mark.integration
  1959. async def test_startup_fixup_converts_aborted_to_cancelled(self, queue_item_factory, db_session):
  1960. """Verify the startup fixup converts existing 'aborted' rows to 'cancelled'."""
  1961. from sqlalchemy import select
  1962. from backend.app.models.print_queue import PrintQueueItem
  1963. # Create items with various statuses including 'aborted'
  1964. item_aborted = await queue_item_factory(status="pending")
  1965. item_pending = await queue_item_factory(status="pending")
  1966. # Manually set the invalid status
  1967. item_aborted.status = "aborted"
  1968. db_session.add(item_aborted)
  1969. await db_session.commit()
  1970. # Run the fixup query (same logic as lifespan)
  1971. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1972. aborted_items = result.scalars().all()
  1973. for i in aborted_items:
  1974. i.status = "cancelled"
  1975. await db_session.commit()
  1976. # Verify: no more 'aborted' items
  1977. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  1978. assert len(result.scalars().all()) == 0
  1979. # The previously aborted item should now be 'cancelled'
  1980. await db_session.refresh(item_aborted)
  1981. assert item_aborted.status == "cancelled"
  1982. # The pending item should be unchanged
  1983. await db_session.refresh(item_pending)
  1984. assert item_pending.status == "pending"
  1985. @pytest.mark.asyncio
  1986. @pytest.mark.integration
  1987. async def test_leaves_a_printing_item_alone_when_the_completion_is_for_another_print(
  1988. self, queue_item_factory, archive_factory, db_session
  1989. ):
  1990. """A completion naming a different subtask must not close this row.
  1991. The handler looks its row up by printer and ``status='printing'`` only,
  1992. so before this guard any completion delivered for the printer closed
  1993. whatever was printing on it. That is how a live 14-hour job was marked
  1994. completed 18 minutes in -- by an event that had nothing to do with it --
  1995. which also stranded the second plate of its batch, since the queue will
  1996. not dispatch while the printer is still running.
  1997. """
  1998. import asyncio
  1999. from unittest.mock import AsyncMock, MagicMock, patch
  2000. archive = await archive_factory(filename="AMS_Rack.gcode.3mf")
  2001. item = await queue_item_factory(status="printing", archive_id=archive.id)
  2002. mock_result = MagicMock()
  2003. mock_result.scalars.return_value.all.return_value = [item]
  2004. mock_session = AsyncMock()
  2005. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  2006. mock_session.__aexit__ = AsyncMock(return_value=False)
  2007. mock_session.execute = AsyncMock(return_value=mock_result)
  2008. mock_session.get = AsyncMock(return_value=archive)
  2009. mock_session.commit = AsyncMock()
  2010. tasks_before = set(asyncio.all_tasks())
  2011. with (
  2012. patch("backend.app.main.async_session", return_value=mock_session),
  2013. patch("backend.app.core.database.async_session", return_value=mock_session),
  2014. patch("backend.app.main.ws_manager") as mock_ws,
  2015. patch("backend.app.main.mqtt_relay") as mock_relay,
  2016. patch("backend.app.main.notification_service") as mock_notif,
  2017. patch("backend.app.main.smart_plug_manager") as mock_plug,
  2018. patch("backend.app.main.printer_manager") as mock_pm,
  2019. ):
  2020. mock_ws.send_print_complete = AsyncMock()
  2021. mock_ws.broadcast = AsyncMock()
  2022. mock_relay.on_print_complete = AsyncMock()
  2023. mock_relay.on_queue_job_completed = AsyncMock()
  2024. mock_notif.on_print_complete = AsyncMock()
  2025. mock_plug.on_print_complete = AsyncMock()
  2026. mock_pm.get_printer.return_value = None
  2027. from backend.app.main import on_print_complete
  2028. await on_print_complete(
  2029. item.printer_id,
  2030. {
  2031. "status": "completed",
  2032. "filename": "/data/Metadata/plate_1.gcode",
  2033. "subtask_name": "Some_Other_Print",
  2034. "timelapse_was_active": False,
  2035. },
  2036. )
  2037. for task in asyncio.all_tasks() - tasks_before:
  2038. task.cancel()
  2039. try:
  2040. await task
  2041. except (asyncio.CancelledError, Exception):
  2042. pass
  2043. assert item.status == "printing"
  2044. assert item.completed_at is None
  2045. @pytest.mark.asyncio
  2046. @pytest.mark.integration
  2047. async def test_completed_status_passes_through_unchanged(self, queue_item_factory, archive_factory, db_session):
  2048. """Verify normal statuses like 'completed' are not affected by normalisation."""
  2049. import asyncio
  2050. from unittest.mock import AsyncMock, MagicMock, patch
  2051. archive = await archive_factory(filename="Finish_Me.gcode.3mf")
  2052. item = await queue_item_factory(status="printing", archive_id=archive.id)
  2053. mock_result = MagicMock()
  2054. mock_result.scalars.return_value.all.return_value = [item]
  2055. mock_session = AsyncMock()
  2056. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  2057. mock_session.__aexit__ = AsyncMock(return_value=False)
  2058. mock_session.execute = AsyncMock(return_value=mock_result)
  2059. mock_session.get = AsyncMock(return_value=archive)
  2060. mock_session.commit = AsyncMock()
  2061. tasks_before = set(asyncio.all_tasks())
  2062. with (
  2063. patch("backend.app.main.async_session", return_value=mock_session),
  2064. patch("backend.app.core.database.async_session", return_value=mock_session),
  2065. patch("backend.app.main.ws_manager") as mock_ws,
  2066. patch("backend.app.main.mqtt_relay") as mock_relay,
  2067. patch("backend.app.main.notification_service") as mock_notif,
  2068. patch("backend.app.main.smart_plug_manager") as mock_plug,
  2069. patch("backend.app.main.printer_manager") as mock_pm,
  2070. ):
  2071. mock_ws.send_print_complete = AsyncMock()
  2072. mock_ws.broadcast = AsyncMock()
  2073. mock_relay.on_print_complete = AsyncMock()
  2074. mock_relay.on_queue_job_completed = AsyncMock()
  2075. mock_notif.on_print_complete = AsyncMock()
  2076. mock_plug.on_print_complete = AsyncMock()
  2077. mock_pm.get_printer.return_value = None
  2078. from backend.app.main import on_print_complete
  2079. await on_print_complete(
  2080. item.printer_id,
  2081. {
  2082. "status": "completed",
  2083. "filename": "test.gcode",
  2084. "subtask_name": "Finish_Me",
  2085. "timelapse_was_active": False,
  2086. },
  2087. )
  2088. # Cancel background tasks before leaving mock context
  2089. for task in asyncio.all_tasks() - tasks_before:
  2090. task.cancel()
  2091. try:
  2092. await task
  2093. except (asyncio.CancelledError, Exception):
  2094. pass
  2095. assert item.status == "completed"
  2096. # ========================================================================
  2097. # Library file usage tracking on print completion (#1008)
  2098. #
  2099. # These exercise the _bump_library_file_usage_if_completed helper directly
  2100. # rather than invoking the whole on_print_complete handler — that path
  2101. # spawns background asyncio tasks (notifications, MQTT relay, smart-plug)
  2102. # that are expensive to mock and have nothing to do with the bump logic.
  2103. # ========================================================================
  2104. @pytest.mark.asyncio
  2105. @pytest.mark.integration
  2106. async def test_bump_library_file_usage_on_completed(self, printer_factory, db_session):
  2107. """Successful completion increments print_count and stamps last_printed_at."""
  2108. from datetime import datetime, timezone
  2109. from backend.app.main import _bump_library_file_usage_if_completed
  2110. from backend.app.models.library import LibraryFile
  2111. from backend.app.models.print_queue import PrintQueueItem
  2112. printer = await printer_factory()
  2113. lib_file = LibraryFile(
  2114. filename="benchy.gcode.3mf",
  2115. file_path="/data/library/benchy.gcode.3mf",
  2116. file_type="gcode.3mf",
  2117. file_size=1024,
  2118. print_count=0,
  2119. last_printed_at=None,
  2120. )
  2121. db_session.add(lib_file)
  2122. await db_session.commit()
  2123. await db_session.refresh(lib_file)
  2124. item = PrintQueueItem(
  2125. printer_id=printer.id,
  2126. library_file_id=lib_file.id,
  2127. status="printing",
  2128. position=1,
  2129. )
  2130. before = datetime.now(timezone.utc).replace(tzinfo=None)
  2131. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  2132. await db_session.commit()
  2133. await db_session.refresh(lib_file)
  2134. assert lib_file.print_count == 1
  2135. assert lib_file.last_printed_at is not None
  2136. assert lib_file.last_printed_at >= before
  2137. @pytest.mark.asyncio
  2138. @pytest.mark.integration
  2139. async def test_bump_library_file_usage_repeated_prints_increment_count(self, printer_factory, db_session):
  2140. """Each successful completion bumps print_count cumulatively."""
  2141. from backend.app.main import _bump_library_file_usage_if_completed
  2142. from backend.app.models.library import LibraryFile
  2143. from backend.app.models.print_queue import PrintQueueItem
  2144. printer = await printer_factory()
  2145. lib_file = LibraryFile(
  2146. filename="repeat.gcode.3mf",
  2147. file_path="/data/library/repeat.gcode.3mf",
  2148. file_type="gcode.3mf",
  2149. file_size=1024,
  2150. print_count=0,
  2151. )
  2152. db_session.add(lib_file)
  2153. await db_session.commit()
  2154. await db_session.refresh(lib_file)
  2155. item = PrintQueueItem(
  2156. printer_id=printer.id,
  2157. library_file_id=lib_file.id,
  2158. status="printing",
  2159. position=1,
  2160. )
  2161. for _ in range(3):
  2162. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  2163. await db_session.commit()
  2164. await db_session.refresh(lib_file)
  2165. assert lib_file.print_count == 3
  2166. @pytest.mark.asyncio
  2167. @pytest.mark.integration
  2168. @pytest.mark.parametrize("terminal_status", ["failed", "cancelled"])
  2169. async def test_bump_library_file_usage_skips_non_completed(self, printer_factory, db_session, terminal_status):
  2170. """Failed and cancelled prints must NOT count as usage."""
  2171. from backend.app.main import _bump_library_file_usage_if_completed
  2172. from backend.app.models.library import LibraryFile
  2173. from backend.app.models.print_queue import PrintQueueItem
  2174. printer = await printer_factory()
  2175. lib_file = LibraryFile(
  2176. filename="broken.gcode.3mf",
  2177. file_path="/data/library/broken.gcode.3mf",
  2178. file_type="gcode.3mf",
  2179. file_size=1024,
  2180. print_count=0,
  2181. last_printed_at=None,
  2182. )
  2183. db_session.add(lib_file)
  2184. await db_session.commit()
  2185. await db_session.refresh(lib_file)
  2186. item = PrintQueueItem(
  2187. printer_id=printer.id,
  2188. library_file_id=lib_file.id,
  2189. status="printing",
  2190. position=1,
  2191. )
  2192. await _bump_library_file_usage_if_completed(db_session, item, terminal_status)
  2193. await db_session.commit()
  2194. await db_session.refresh(lib_file)
  2195. assert lib_file.print_count == 0
  2196. assert lib_file.last_printed_at is None
  2197. @pytest.mark.asyncio
  2198. @pytest.mark.integration
  2199. async def test_bump_library_file_usage_skips_when_no_library_file_id(
  2200. self, printer_factory, archive_factory, db_session
  2201. ):
  2202. """Queue items without library_file_id (e.g. archive reprints) are a no-op."""
  2203. from backend.app.main import _bump_library_file_usage_if_completed
  2204. from backend.app.models.print_queue import PrintQueueItem
  2205. printer = await printer_factory()
  2206. archive = await archive_factory()
  2207. item = PrintQueueItem(
  2208. printer_id=printer.id,
  2209. library_file_id=None,
  2210. archive_id=archive.id,
  2211. status="printing",
  2212. position=1,
  2213. )
  2214. # Must not raise.
  2215. await _bump_library_file_usage_if_completed(db_session, item, "completed")
  2216. # ========================================================================
  2217. # Batch quantity tests
  2218. # ========================================================================
  2219. @pytest.mark.asyncio
  2220. @pytest.mark.integration
  2221. async def test_add_to_queue_quantity_default(
  2222. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2223. ):
  2224. """Verify quantity=1 (default) creates a single item with no batch."""
  2225. printer = await printer_factory()
  2226. archive = await archive_factory()
  2227. data = {
  2228. "printer_id": printer.id,
  2229. "archive_id": archive.id,
  2230. }
  2231. response = await async_client.post("/api/v1/queue/", json=data)
  2232. assert response.status_code == 200
  2233. result = response.json()
  2234. assert result["batch_id"] is None
  2235. assert result["batch_name"] is None
  2236. @pytest.mark.asyncio
  2237. @pytest.mark.integration
  2238. async def test_add_to_queue_quantity_one_explicit(
  2239. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2240. ):
  2241. """Verify quantity=1 explicitly creates a single item with no batch."""
  2242. printer = await printer_factory()
  2243. archive = await archive_factory()
  2244. data = {
  2245. "printer_id": printer.id,
  2246. "archive_id": archive.id,
  2247. "quantity": 1,
  2248. }
  2249. response = await async_client.post("/api/v1/queue/", json=data)
  2250. assert response.status_code == 200
  2251. result = response.json()
  2252. assert result["batch_id"] is None
  2253. assert result["batch_name"] is None
  2254. @pytest.mark.asyncio
  2255. @pytest.mark.integration
  2256. async def test_add_to_queue_quantity_creates_batch(
  2257. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2258. ):
  2259. """Verify quantity > 1 creates a batch and multiple queue items."""
  2260. printer = await printer_factory()
  2261. archive = await archive_factory()
  2262. data = {
  2263. "printer_id": printer.id,
  2264. "archive_id": archive.id,
  2265. "quantity": 3,
  2266. }
  2267. response = await async_client.post("/api/v1/queue/", json=data)
  2268. assert response.status_code == 200
  2269. result = response.json()
  2270. # First item is returned, linked to a batch
  2271. assert result["batch_id"] is not None
  2272. assert result["batch_name"] is not None
  2273. assert "×3" in result["batch_name"]
  2274. # Verify all 3 items were created
  2275. list_response = await async_client.get("/api/v1/queue/")
  2276. items = list_response.json()
  2277. batch_items = [i for i in items if i["batch_id"] == result["batch_id"]]
  2278. assert len(batch_items) == 3
  2279. # All items should have the same settings
  2280. for item in batch_items:
  2281. assert item["printer_id"] == printer.id
  2282. assert item["archive_id"] == archive.id
  2283. assert item["status"] == "pending"
  2284. @pytest.mark.asyncio
  2285. @pytest.mark.integration
  2286. async def test_add_to_queue_quantity_sequential_positions(
  2287. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2288. ):
  2289. """Verify batch items get sequential positions."""
  2290. printer = await printer_factory()
  2291. archive = await archive_factory()
  2292. data = {
  2293. "printer_id": printer.id,
  2294. "archive_id": archive.id,
  2295. "quantity": 3,
  2296. }
  2297. response = await async_client.post("/api/v1/queue/", json=data)
  2298. assert response.status_code == 200
  2299. batch_id = response.json()["batch_id"]
  2300. list_response = await async_client.get("/api/v1/queue/")
  2301. items = list_response.json()
  2302. batch_items = sorted(
  2303. [i for i in items if i["batch_id"] == batch_id],
  2304. key=lambda i: i["position"],
  2305. )
  2306. positions = [i["position"] for i in batch_items]
  2307. assert positions == [positions[0], positions[0] + 1, positions[0] + 2]
  2308. @pytest.mark.asyncio
  2309. @pytest.mark.integration
  2310. async def test_add_to_queue_insert_position_shifts_existing_items(
  2311. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2312. ):
  2313. """Verify priority insertion shifts existing pending items in the same printer queue."""
  2314. printer = await printer_factory()
  2315. first = await archive_factory(print_name="First")
  2316. second = await archive_factory(print_name="Second")
  2317. priority = await archive_factory(print_name="Priority")
  2318. assert (
  2319. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  2320. ).status_code == 200
  2321. assert (
  2322. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  2323. ).status_code == 200
  2324. response = await async_client.post(
  2325. "/api/v1/queue/",
  2326. json={
  2327. "printer_id": printer.id,
  2328. "archive_id": priority.id,
  2329. "insert_position": 1,
  2330. },
  2331. )
  2332. assert response.status_code == 200
  2333. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  2334. items = sorted(list_response.json(), key=lambda item: item["position"])
  2335. assert [item["archive_id"] for item in items[:3]] == [priority.id, first.id, second.id]
  2336. assert [item["position"] for item in items[:3]] == [1, 2, 3]
  2337. @pytest.mark.asyncio
  2338. @pytest.mark.integration
  2339. async def test_add_to_queue_insert_position_quantity_shifts_existing_by_quantity(
  2340. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2341. ):
  2342. """ASAP batch insertion shifts existing pending items by the inserted quantity."""
  2343. printer = await printer_factory()
  2344. first = await archive_factory(print_name="First")
  2345. second = await archive_factory(print_name="Second")
  2346. priority = await archive_factory(print_name="Priority")
  2347. assert (
  2348. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  2349. ).status_code == 200
  2350. assert (
  2351. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  2352. ).status_code == 200
  2353. response = await async_client.post(
  2354. "/api/v1/queue/",
  2355. json={
  2356. "printer_id": printer.id,
  2357. "archive_id": priority.id,
  2358. "quantity": 3,
  2359. "insert_position": 1,
  2360. },
  2361. )
  2362. assert response.status_code == 200
  2363. batch_id = response.json()["batch_id"]
  2364. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  2365. items = sorted(list_response.json(), key=lambda item: item["position"])
  2366. assert [item["archive_id"] for item in items] == [
  2367. priority.id,
  2368. priority.id,
  2369. priority.id,
  2370. first.id,
  2371. second.id,
  2372. ]
  2373. assert [item["position"] for item in items] == [1, 2, 3, 4, 5]
  2374. assert [item["batch_id"] for item in items[:3]] == [batch_id, batch_id, batch_id]
  2375. @pytest.mark.asyncio
  2376. @pytest.mark.integration
  2377. async def test_add_to_queue_positions_are_one_sequence_across_printers(
  2378. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2379. ):
  2380. """Positions are shared by pinned and unassigned items (#3200).
  2381. The queue page lists and reorders pending items as one list and the
  2382. scheduler dispatches in that order, so a pinned item added after two
  2383. unassigned ones lands after them, and an insert at the top shifts
  2384. everything, not only its own printer's items.
  2385. """
  2386. printer = await printer_factory()
  2387. unassigned_first = await archive_factory(print_name="Unassigned First")
  2388. unassigned_second = await archive_factory(print_name="Unassigned Second")
  2389. assigned = await archive_factory(print_name="Assigned")
  2390. priority = await archive_factory(print_name="Unassigned Priority")
  2391. assert (await async_client.post("/api/v1/queue/", json={"archive_id": unassigned_first.id})).status_code == 200
  2392. assert (await async_client.post("/api/v1/queue/", json={"archive_id": unassigned_second.id})).status_code == 200
  2393. assigned_response = await async_client.post(
  2394. "/api/v1/queue/",
  2395. json={"printer_id": printer.id, "archive_id": assigned.id},
  2396. )
  2397. assert assigned_response.status_code == 200
  2398. assert assigned_response.json()["position"] == 3
  2399. response = await async_client.post(
  2400. "/api/v1/queue/",
  2401. json={
  2402. "archive_id": priority.id,
  2403. "insert_position": 1,
  2404. },
  2405. )
  2406. assert response.status_code == 200
  2407. all_items = sorted((await async_client.get("/api/v1/queue/")).json(), key=lambda item: item["position"])
  2408. assert [item["archive_id"] for item in all_items] == [
  2409. priority.id,
  2410. unassigned_first.id,
  2411. unassigned_second.id,
  2412. assigned.id,
  2413. ]
  2414. assert [item["position"] for item in all_items] == [1, 2, 3, 4]
  2415. @pytest.mark.asyncio
  2416. @pytest.mark.integration
  2417. async def test_add_to_queue_insert_position_greater_than_max_appends_without_gap(
  2418. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2419. ):
  2420. """Oversized explicit insert_position appends at max+1 instead of creating sparse positions."""
  2421. printer = await printer_factory()
  2422. first = await archive_factory(print_name="First")
  2423. second = await archive_factory(print_name="Second")
  2424. appended = await archive_factory(print_name="Append")
  2425. assert (
  2426. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": first.id})
  2427. ).status_code == 200
  2428. assert (
  2429. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": second.id})
  2430. ).status_code == 200
  2431. response = await async_client.post(
  2432. "/api/v1/queue/",
  2433. json={
  2434. "printer_id": printer.id,
  2435. "archive_id": appended.id,
  2436. "insert_position": 99,
  2437. },
  2438. )
  2439. assert response.status_code == 200
  2440. assert response.json()["position"] == 3
  2441. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  2442. items = sorted(list_response.json(), key=lambda item: item["position"])
  2443. assert [item["archive_id"] for item in items] == [first.id, second.id, appended.id]
  2444. assert [item["position"] for item in items] == [1, 2, 3]
  2445. @pytest.mark.asyncio
  2446. @pytest.mark.integration
  2447. async def test_add_to_queue_consecutive_asap_inserts_stack_in_submission_order(
  2448. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2449. ):
  2450. """Consecutive ASAP inserts to the same printer preserve the client submission order."""
  2451. printer = await printer_factory()
  2452. existing = await archive_factory(print_name="Existing")
  2453. first_asap = await archive_factory(print_name="First ASAP")
  2454. second_asap = await archive_factory(print_name="Second ASAP")
  2455. assert (
  2456. await async_client.post("/api/v1/queue/", json={"printer_id": printer.id, "archive_id": existing.id})
  2457. ).status_code == 200
  2458. first_response = await async_client.post(
  2459. "/api/v1/queue/",
  2460. json={
  2461. "printer_id": printer.id,
  2462. "archive_id": first_asap.id,
  2463. "insert_position": 1,
  2464. },
  2465. )
  2466. assert first_response.status_code == 200
  2467. second_response = await async_client.post(
  2468. "/api/v1/queue/",
  2469. json={
  2470. "printer_id": printer.id,
  2471. "archive_id": second_asap.id,
  2472. "insert_position": 2,
  2473. },
  2474. )
  2475. assert second_response.status_code == 200
  2476. list_response = await async_client.get(f"/api/v1/queue/?printer_id={printer.id}")
  2477. items = sorted(list_response.json(), key=lambda item: item["position"])
  2478. assert [item["archive_id"] for item in items] == [first_asap.id, second_asap.id, existing.id]
  2479. assert [item["position"] for item in items] == [1, 2, 3]
  2480. @pytest.mark.asyncio
  2481. @pytest.mark.integration
  2482. async def test_add_to_queue_quantity_with_print_options(
  2483. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2484. ):
  2485. """Verify print options are applied to all batch items."""
  2486. printer = await printer_factory()
  2487. archive = await archive_factory()
  2488. data = {
  2489. "printer_id": printer.id,
  2490. "archive_id": archive.id,
  2491. "quantity": 2,
  2492. "bed_levelling": "off",
  2493. "timelapse": True,
  2494. }
  2495. response = await async_client.post("/api/v1/queue/", json=data)
  2496. assert response.status_code == 200
  2497. batch_id = response.json()["batch_id"]
  2498. list_response = await async_client.get("/api/v1/queue/")
  2499. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  2500. assert len(batch_items) == 2
  2501. for item in batch_items:
  2502. assert item["bed_levelling"] == "off"
  2503. assert item["timelapse"] is True
  2504. @pytest.mark.asyncio
  2505. @pytest.mark.integration
  2506. async def test_get_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  2507. """Verify batch can be retrieved with progress stats."""
  2508. printer = await printer_factory()
  2509. archive = await archive_factory()
  2510. # Create a batch of 3
  2511. data = {
  2512. "printer_id": printer.id,
  2513. "archive_id": archive.id,
  2514. "quantity": 3,
  2515. }
  2516. response = await async_client.post("/api/v1/queue/", json=data)
  2517. batch_id = response.json()["batch_id"]
  2518. # Get batch
  2519. response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2520. assert response.status_code == 200
  2521. result = response.json()
  2522. assert result["id"] == batch_id
  2523. assert result["quantity"] == 3
  2524. assert result["status"] == "active"
  2525. assert result["pending_count"] == 3
  2526. assert result["printing_count"] == 0
  2527. assert result["completed_count"] == 0
  2528. @pytest.mark.asyncio
  2529. @pytest.mark.integration
  2530. async def test_list_batches(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  2531. """Verify batches can be listed."""
  2532. printer = await printer_factory()
  2533. archive = await archive_factory()
  2534. # Create two batches
  2535. for qty in [2, 3]:
  2536. await async_client.post(
  2537. "/api/v1/queue/",
  2538. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": qty},
  2539. )
  2540. response = await async_client.get("/api/v1/queue/batches")
  2541. assert response.status_code == 200
  2542. batches = response.json()
  2543. assert len(batches) >= 2
  2544. @pytest.mark.asyncio
  2545. @pytest.mark.integration
  2546. async def test_cancel_batch(self, async_client: AsyncClient, printer_factory, archive_factory, db_session):
  2547. """Verify cancelling a batch cancels all pending items."""
  2548. printer = await printer_factory()
  2549. archive = await archive_factory()
  2550. data = {
  2551. "printer_id": printer.id,
  2552. "archive_id": archive.id,
  2553. "quantity": 3,
  2554. }
  2555. response = await async_client.post("/api/v1/queue/", json=data)
  2556. batch_id = response.json()["batch_id"]
  2557. # Cancel the batch
  2558. response = await async_client.delete(f"/api/v1/queue/batches/{batch_id}")
  2559. assert response.status_code == 200
  2560. # Verify all items are cancelled
  2561. list_response = await async_client.get("/api/v1/queue/")
  2562. batch_items = [i for i in list_response.json() if i["batch_id"] == batch_id]
  2563. for item in batch_items:
  2564. assert item["status"] == "cancelled"
  2565. # Verify batch status
  2566. batch_response = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2567. assert batch_response.json()["status"] == "cancelled"
  2568. @pytest.mark.asyncio
  2569. @pytest.mark.integration
  2570. async def test_get_batch_not_found(self, async_client: AsyncClient):
  2571. """Verify 404 for non-existent batch."""
  2572. response = await async_client.get("/api/v1/queue/batches/9999")
  2573. assert response.status_code == 404
  2574. # ========================================================================
  2575. # Queue redesign: create-empty + group-existing + ungroup
  2576. # ========================================================================
  2577. @pytest.mark.asyncio
  2578. @pytest.mark.integration
  2579. async def test_create_empty_batch_for_client_side_grouping(
  2580. self, async_client: AsyncClient, printer_factory, archive_factory
  2581. ):
  2582. """Verify POST /queue/batches without item_ids creates an empty batch
  2583. whose id can be passed on subsequent /queue/ POSTs (the multi-plate
  2584. auto-batch flow). Subsequent items must end up with the same batch_id."""
  2585. printer = await printer_factory()
  2586. archive = await archive_factory()
  2587. # 1. Pre-create batch
  2588. batch_resp = await async_client.post(
  2589. "/api/v1/queue/batches",
  2590. json={"name": "Plates · 2 plates", "archive_id": archive.id},
  2591. )
  2592. assert batch_resp.status_code == 200
  2593. batch = batch_resp.json()
  2594. assert batch["status"] == "active"
  2595. batch_id = batch["id"]
  2596. # 2. Add two items referencing that batch
  2597. for plate_id in (1, 2):
  2598. item_resp = await async_client.post(
  2599. "/api/v1/queue/",
  2600. json={
  2601. "printer_id": printer.id,
  2602. "archive_id": archive.id,
  2603. "plate_id": plate_id,
  2604. "batch_id": batch_id,
  2605. },
  2606. )
  2607. assert item_resp.status_code == 200
  2608. assert item_resp.json()["batch_id"] == batch_id
  2609. # 3. Verify batch now has 2 pending children
  2610. list_resp = await async_client.get("/api/v1/queue/")
  2611. siblings = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2612. assert len(siblings) == 2
  2613. assert {i["plate_id"] for i in siblings} == {1, 2}
  2614. @pytest.mark.asyncio
  2615. @pytest.mark.integration
  2616. async def test_group_existing_items_as_batch(
  2617. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  2618. ):
  2619. """Verify POST /queue/batches with item_ids assigns batch_id to
  2620. existing pending items (the 'Group as batch' UI action)."""
  2621. printer = await printer_factory()
  2622. archive = await archive_factory()
  2623. item_a = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2624. item_b = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2625. resp = await async_client.post(
  2626. "/api/v1/queue/batches",
  2627. json={"name": "Manual group", "item_ids": [item_a.id, item_b.id]},
  2628. )
  2629. assert resp.status_code == 200
  2630. batch_id = resp.json()["id"]
  2631. list_resp = await async_client.get("/api/v1/queue/")
  2632. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2633. assert {i["id"] for i in grouped} == {item_a.id, item_b.id}
  2634. @pytest.mark.asyncio
  2635. @pytest.mark.integration
  2636. async def test_group_skips_non_pending_items(
  2637. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory
  2638. ):
  2639. """Verify grouping doesn't pull in already-completed/cancelled items."""
  2640. printer = await printer_factory()
  2641. archive = await archive_factory()
  2642. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2643. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  2644. resp = await async_client.post(
  2645. "/api/v1/queue/batches",
  2646. json={"name": "Mixed", "item_ids": [pending.id, completed.id]},
  2647. )
  2648. assert resp.status_code == 200
  2649. batch_id = resp.json()["id"]
  2650. list_resp = await async_client.get("/api/v1/queue/")
  2651. grouped = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2652. assert {i["id"] for i in grouped} == {pending.id}
  2653. @pytest.mark.asyncio
  2654. @pytest.mark.integration
  2655. async def test_create_batch_requires_name(self, async_client: AsyncClient):
  2656. """Verify empty / whitespace-only name is rejected with 400."""
  2657. resp = await async_client.post("/api/v1/queue/batches", json={"name": " "})
  2658. assert resp.status_code == 400
  2659. @pytest.mark.asyncio
  2660. @pytest.mark.integration
  2661. async def test_ungroup_batch_clears_batch_id_and_deletes_row(
  2662. self, async_client: AsyncClient, printer_factory, archive_factory
  2663. ):
  2664. """Verify POST /queue/batches/{id}/ungroup clears batch_id from all
  2665. members and deletes the batch row when nothing remains assigned."""
  2666. printer = await printer_factory()
  2667. archive = await archive_factory()
  2668. # Create batch with two items via the existing quantity flow
  2669. add_resp = await async_client.post(
  2670. "/api/v1/queue/",
  2671. json={"printer_id": printer.id, "archive_id": archive.id, "quantity": 2},
  2672. )
  2673. batch_id = add_resp.json()["batch_id"]
  2674. # Ungroup
  2675. ungroup_resp = await async_client.post(f"/api/v1/queue/batches/{batch_id}/ungroup")
  2676. assert ungroup_resp.status_code == 200
  2677. assert ungroup_resp.json()["ungrouped_count"] == 2
  2678. # Verify items still exist but no longer batched
  2679. list_resp = await async_client.get("/api/v1/queue/")
  2680. ex_members = [i for i in list_resp.json() if i["batch_id"] == batch_id]
  2681. assert ex_members == []
  2682. # Batch row was deleted
  2683. get_resp = await async_client.get(f"/api/v1/queue/batches/{batch_id}")
  2684. assert get_resp.status_code == 404
  2685. @pytest.mark.asyncio
  2686. @pytest.mark.integration
  2687. async def test_add_to_queue_with_unknown_batch_id_404(
  2688. self, async_client: AsyncClient, printer_factory, archive_factory
  2689. ):
  2690. """Verify addToQueue with a non-existent batch_id is rejected."""
  2691. printer = await printer_factory()
  2692. archive = await archive_factory()
  2693. resp = await async_client.post(
  2694. "/api/v1/queue/",
  2695. json={
  2696. "printer_id": printer.id,
  2697. "archive_id": archive.id,
  2698. "batch_id": 99999,
  2699. },
  2700. )
  2701. assert resp.status_code == 404
  2702. # ========================================================================
  2703. # Soft-deleted archive handling (#1348 follow-up)
  2704. # ========================================================================
  2705. @pytest.mark.asyncio
  2706. @pytest.mark.integration
  2707. async def test_soft_delete_archive_deletes_all_related_queue_items(
  2708. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2709. ):
  2710. """Soft-deleting an archive removes every related queue item, regardless
  2711. of status (#1734). Pre-#1734 only ``pending`` rows were flipped to
  2712. ``cancelled`` and stayed in the DB, surprising users who expected the
  2713. queue lines to disappear with the archive — especially on multi-plate
  2714. Send All uploads (#1733), where ONE archive backed N queue items and
  2715. soft-deleting the archive left N "cancelled" rows behind. The change
  2716. keeps the printing guard (a row with ``status='printing'`` blocks the
  2717. delete one layer up at the API route), so we never delete the row of
  2718. an actively-running print here.
  2719. Print history lives in ``PrintLogEntry`` (FK ``ON DELETE SET NULL``) —
  2720. the audit trail survives independently of the queue rows.
  2721. """
  2722. from sqlalchemy import select
  2723. from backend.app.models.print_queue import PrintQueueItem
  2724. from backend.app.services.archive import ArchiveService
  2725. printer = await printer_factory()
  2726. archive = await archive_factory(thumbnail_path="archives/test/test/thumbnail.png")
  2727. pending = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2728. completed = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="completed")
  2729. service = ArchiveService(db_session)
  2730. assert await service.soft_delete_archive(archive.id) is True
  2731. # Every queue row that referenced this archive is gone — both the
  2732. # pending and the completed rows. Print history (PrintLogEntry) is
  2733. # the authoritative record and is preserved by the FK SET NULL.
  2734. remaining = (
  2735. (await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_([pending.id, completed.id]))))
  2736. .scalars()
  2737. .all()
  2738. )
  2739. assert remaining == [], (
  2740. "Soft-deleting the archive must delete every related queue row, "
  2741. f"got {[(r.id, r.status) for r in remaining]} still present"
  2742. )
  2743. @pytest.mark.asyncio
  2744. @pytest.mark.integration
  2745. async def test_queue_api_hides_archive_surface_when_soft_deleted(
  2746. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2747. ):
  2748. """Queue serializer must NOT populate archive_thumbnail / archive_name
  2749. when the archive is soft-deleted — otherwise the frontend renders a
  2750. broken <img> and 404-storms the thumbnail / plates / plate-thumbnail
  2751. endpoints. archive_deleted=True signals the soft-deleted state so
  2752. the UI can render a 'source deleted' badge."""
  2753. from datetime import datetime, timezone
  2754. printer = await printer_factory()
  2755. archive = await archive_factory(
  2756. print_name="Test Print",
  2757. thumbnail_path="archives/test/test/thumbnail.png",
  2758. deleted_at=datetime.now(timezone.utc), # Pre-soft-deleted
  2759. )
  2760. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="cancelled")
  2761. resp = await async_client.get("/api/v1/queue/")
  2762. assert resp.status_code == 200
  2763. body = resp.json()
  2764. row = next((r for r in body if r["id"] == item.id), None)
  2765. assert row is not None
  2766. assert row["archive_deleted"] is True
  2767. assert row["archive_thumbnail"] is None, "must not expose stale thumbnail path for soft-deleted archive"
  2768. assert row["archive_name"] is None
  2769. @pytest.mark.asyncio
  2770. @pytest.mark.integration
  2771. async def test_queue_api_still_exposes_archive_surface_when_live(
  2772. self, async_client: AsyncClient, printer_factory, archive_factory, queue_item_factory, db_session
  2773. ):
  2774. """Sanity guard: the soft-delete suppression must not affect live
  2775. archives. archive_name / archive_thumbnail still flow through and
  2776. archive_deleted stays False."""
  2777. printer = await printer_factory()
  2778. archive = await archive_factory(
  2779. print_name="Live Archive",
  2780. thumbnail_path="archives/test/live/thumbnail.png",
  2781. )
  2782. item = await queue_item_factory(printer_id=printer.id, archive_id=archive.id, status="pending")
  2783. resp = await async_client.get("/api/v1/queue/")
  2784. assert resp.status_code == 200
  2785. row = next((r for r in resp.json() if r["id"] == item.id), None)
  2786. assert row is not None
  2787. assert row["archive_deleted"] is False
  2788. assert row["archive_name"] == "Live Archive"
  2789. assert row["archive_thumbnail"] == "archives/test/live/thumbnail.png"
  2790. class TestResumeQueueAfterFailure:
  2791. """Integration tests for POST /api/v1/queue/printer/{id}/resume (#1818)."""
  2792. @pytest.fixture
  2793. async def printer_factory(self, db_session):
  2794. _counter = [0]
  2795. async def _create_printer(**kwargs):
  2796. from backend.app.models.printer import Printer
  2797. _counter[0] += 1
  2798. counter = _counter[0]
  2799. defaults = {
  2800. "name": f"Resume Printer {counter}",
  2801. "ip_address": f"192.168.42.{100 + counter}",
  2802. "serial_number": f"RESUMESERIAL{counter:04d}",
  2803. "access_code": "12345678",
  2804. "model": "P1S",
  2805. }
  2806. defaults.update(kwargs)
  2807. printer = Printer(**defaults)
  2808. db_session.add(printer)
  2809. await db_session.commit()
  2810. await db_session.refresh(printer)
  2811. return printer
  2812. return _create_printer
  2813. @pytest.fixture
  2814. async def archive_factory(self, db_session):
  2815. _counter = [0]
  2816. async def _create_archive(**kwargs):
  2817. from backend.app.models.archive import PrintArchive
  2818. _counter[0] += 1
  2819. counter = _counter[0]
  2820. defaults = {
  2821. "filename": f"resume_print_{counter}.3mf",
  2822. "print_name": f"Resume Print {counter}",
  2823. "file_path": f"/tmp/resume_print_{counter}.3mf", # nosec B108
  2824. "file_size": 1024,
  2825. "content_hash": f"resumehash{counter:08d}",
  2826. "status": "completed",
  2827. }
  2828. defaults.update(kwargs)
  2829. archive = PrintArchive(**defaults)
  2830. db_session.add(archive)
  2831. await db_session.commit()
  2832. await db_session.refresh(archive)
  2833. return archive
  2834. return _create_archive
  2835. async def _add_item(self, db_session, printer, archive_factory, **kwargs):
  2836. from backend.app.models.print_queue import PrintQueueItem
  2837. archive = await archive_factory()
  2838. defaults = {
  2839. "printer_id": printer.id,
  2840. "archive_id": archive.id,
  2841. "status": "pending",
  2842. "require_previous_success": True,
  2843. }
  2844. defaults.update(kwargs)
  2845. item = PrintQueueItem(**defaults)
  2846. db_session.add(item)
  2847. await db_session.commit()
  2848. await db_session.refresh(item)
  2849. return item
  2850. @pytest.mark.asyncio
  2851. @pytest.mark.integration
  2852. async def test_resume_unknown_printer_returns_404(self, async_client: AsyncClient):
  2853. resp = await async_client.post("/api/v1/queue/printer/999999/resume")
  2854. assert resp.status_code == 404
  2855. @pytest.mark.asyncio
  2856. @pytest.mark.integration
  2857. async def test_resume_no_op_on_clean_queue(self, async_client: AsyncClient, printer_factory):
  2858. """Calling resume on a printer with no failures and no skipped items
  2859. returns zero counts — endpoint is idempotent and safe to spam."""
  2860. printer = await printer_factory()
  2861. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2862. assert resp.status_code == 200
  2863. assert resp.json() == {"acknowledged": 0, "restored": 0}
  2864. @pytest.mark.asyncio
  2865. @pytest.mark.integration
  2866. async def test_resume_acknowledges_failed_and_restores_skipped(
  2867. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2868. ):
  2869. """Reporter's scenario: failed predecessor + N skipped downstream items.
  2870. Resume sets gate_acknowledged on the failure and flips skipped → pending."""
  2871. from sqlalchemy import select
  2872. from backend.app.models.print_queue import PrintQueueItem
  2873. printer = await printer_factory()
  2874. failed = await self._add_item(db_session, printer, archive_factory, status="failed")
  2875. skipped_1 = await self._add_item(
  2876. db_session,
  2877. printer,
  2878. archive_factory,
  2879. status="skipped",
  2880. error_message="Previous print failed or was aborted",
  2881. )
  2882. skipped_2 = await self._add_item(
  2883. db_session,
  2884. printer,
  2885. archive_factory,
  2886. status="skipped",
  2887. error_message="Previous print failed or was aborted",
  2888. )
  2889. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2890. assert resp.status_code == 200
  2891. assert resp.json() == {"acknowledged": 1, "restored": 2}
  2892. failed_id = failed.id
  2893. skipped_ids = [skipped_1.id, skipped_2.id]
  2894. db_session.expire_all()
  2895. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_id))
  2896. assert result.scalar_one().gate_acknowledged is True
  2897. for sid in skipped_ids:
  2898. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == sid))
  2899. row = result.scalar_one()
  2900. assert row.status == "pending"
  2901. assert row.error_message is None
  2902. assert row.completed_at is None
  2903. @pytest.mark.asyncio
  2904. @pytest.mark.integration
  2905. async def test_resume_preserves_skipped_items_with_other_reasons(
  2906. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2907. ):
  2908. """Skipped items whose error_message is something OTHER than the
  2909. gate string (e.g. filament-deficit promotion, future skip reasons)
  2910. must not be touched — they encode different user intent."""
  2911. from sqlalchemy import select
  2912. from backend.app.models.print_queue import PrintQueueItem
  2913. printer = await printer_factory()
  2914. gate_skip = await self._add_item(
  2915. db_session,
  2916. printer,
  2917. archive_factory,
  2918. status="skipped",
  2919. error_message="Previous print failed or was aborted",
  2920. )
  2921. other_skip = await self._add_item(
  2922. db_session,
  2923. printer,
  2924. archive_factory,
  2925. status="skipped",
  2926. error_message="User skipped via UI",
  2927. )
  2928. gate_id = gate_skip.id
  2929. other_id = other_skip.id
  2930. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2931. assert resp.json() == {"acknowledged": 0, "restored": 1}
  2932. db_session.expire_all()
  2933. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == gate_id))
  2934. assert result.scalar_one().status == "pending"
  2935. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == other_id))
  2936. assert result.scalar_one().status == "skipped"
  2937. @pytest.mark.asyncio
  2938. @pytest.mark.integration
  2939. async def test_resume_scoped_to_printer(
  2940. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2941. ):
  2942. """A resume on printer A must not clear printer B's gate — farms run
  2943. each printer's queue independently."""
  2944. from sqlalchemy import select
  2945. from backend.app.models.print_queue import PrintQueueItem
  2946. p1 = await printer_factory()
  2947. p2 = await printer_factory()
  2948. failed_p1 = await self._add_item(db_session, p1, archive_factory, status="failed")
  2949. failed_p2 = await self._add_item(db_session, p2, archive_factory, status="failed")
  2950. failed_p1_id = failed_p1.id
  2951. failed_p2_id = failed_p2.id
  2952. resp = await async_client.post(f"/api/v1/queue/printer/{p1.id}/resume")
  2953. assert resp.json() == {"acknowledged": 1, "restored": 0}
  2954. db_session.expire_all()
  2955. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_p1_id))
  2956. assert result.scalar_one().gate_acknowledged is True
  2957. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == failed_p2_id))
  2958. assert result.scalar_one().gate_acknowledged is False
  2959. @pytest.mark.asyncio
  2960. @pytest.mark.integration
  2961. async def test_resume_handles_aborted_status(
  2962. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2963. ):
  2964. """Aborted prints (printer-detected mid-print failure) gate the same
  2965. way failed prints do and must also be acknowledgeable."""
  2966. from sqlalchemy import select
  2967. from backend.app.models.print_queue import PrintQueueItem
  2968. printer = await printer_factory()
  2969. aborted = await self._add_item(db_session, printer, archive_factory, status="aborted")
  2970. aborted_id = aborted.id
  2971. resp = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2972. assert resp.json() == {"acknowledged": 1, "restored": 0}
  2973. db_session.expire_all()
  2974. result = await db_session.execute(select(PrintQueueItem).where(PrintQueueItem.id == aborted_id))
  2975. assert result.scalar_one().gate_acknowledged is True
  2976. @pytest.mark.asyncio
  2977. @pytest.mark.integration
  2978. async def test_resume_idempotent_second_call_is_no_op(
  2979. self, async_client: AsyncClient, printer_factory, archive_factory, db_session
  2980. ):
  2981. """Calling resume twice on the same printer doesn't re-acknowledge
  2982. the same failure — the second call sees acknowledged=0, restored=0."""
  2983. printer = await printer_factory()
  2984. await self._add_item(db_session, printer, archive_factory, status="failed")
  2985. await self._add_item(
  2986. db_session,
  2987. printer,
  2988. archive_factory,
  2989. status="skipped",
  2990. error_message="Previous print failed or was aborted",
  2991. )
  2992. first = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2993. assert first.json() == {"acknowledged": 1, "restored": 1}
  2994. second = await async_client.post(f"/api/v1/queue/printer/{printer.id}/resume")
  2995. assert second.json() == {"acknowledged": 0, "restored": 0}
  2996. class TestReorderEndpoint:
  2997. """Tests for the /queue/reorder endpoint (#1625-followup duplicate-position validator)."""
  2998. @pytest.fixture
  2999. async def printer_factory(self, db_session):
  3000. async def _create(**kwargs):
  3001. from backend.app.models.printer import Printer
  3002. defaults = {
  3003. "name": "Reorder Test Printer",
  3004. "ip_address": "192.168.1.220",
  3005. "serial_number": "TESTREORDER001",
  3006. "access_code": "12345678",
  3007. "model": "X1C",
  3008. }
  3009. defaults.update(kwargs)
  3010. printer = Printer(**defaults)
  3011. db_session.add(printer)
  3012. await db_session.commit()
  3013. await db_session.refresh(printer)
  3014. return printer
  3015. return _create
  3016. @pytest.fixture
  3017. async def archive_factory(self, db_session):
  3018. _counter = [0]
  3019. async def _create(**kwargs):
  3020. from backend.app.models.archive import PrintArchive
  3021. _counter[0] += 1
  3022. defaults = {
  3023. "filename": f"reorder_{_counter[0]}.3mf",
  3024. "print_name": f"Reorder {_counter[0]}",
  3025. "file_path": f"/tmp/reorder_{_counter[0]}.3mf", # nosec B108
  3026. "file_size": 1024,
  3027. "content_hash": f"reorderhash{_counter[0]:06d}",
  3028. "status": "completed",
  3029. }
  3030. defaults.update(kwargs)
  3031. archive = PrintArchive(**defaults)
  3032. db_session.add(archive)
  3033. await db_session.commit()
  3034. await db_session.refresh(archive)
  3035. return archive
  3036. return _create
  3037. @pytest.mark.asyncio
  3038. @pytest.mark.integration
  3039. async def test_reorder_rejects_duplicate_positions(
  3040. self, async_client: AsyncClient, db_session, printer_factory, archive_factory
  3041. ):
  3042. """Reorder payload with duplicate positions → 422 at schema layer.
  3043. Regression guard: pre-fix, a buggy client sending two items at the
  3044. same position would leave the queue in an inconsistent state (the
  3045. scheduler's ORDER BY (printer_id, position) tie would be broken by
  3046. physical row order — non-deterministic dispatch order).
  3047. """
  3048. from backend.app.models.print_queue import PrintQueueItem
  3049. printer = await printer_factory()
  3050. a1 = await archive_factory()
  3051. a2 = await archive_factory()
  3052. item1 = PrintQueueItem(printer_id=printer.id, archive_id=a1.id, status="pending", position=1)
  3053. item2 = PrintQueueItem(printer_id=printer.id, archive_id=a2.id, status="pending", position=2)
  3054. db_session.add_all([item1, item2])
  3055. await db_session.commit()
  3056. await db_session.refresh(item1)
  3057. await db_session.refresh(item2)
  3058. response = await async_client.post(
  3059. "/api/v1/queue/reorder",
  3060. json={
  3061. "items": [
  3062. {"id": item1.id, "position": 1},
  3063. {"id": item2.id, "position": 1}, # duplicate
  3064. ]
  3065. },
  3066. )
  3067. assert response.status_code == 422
  3068. body = response.json()
  3069. # Pydantic v2 wraps custom validator errors; the message must mention "Duplicate"
  3070. # so the FE can surface the actionable detail.
  3071. assert any("duplicate" in str(err).lower() for err in body.get("detail", []))
  3072. @pytest.mark.asyncio
  3073. @pytest.mark.integration
  3074. async def test_reorder_accepts_unique_positions(
  3075. self, async_client: AsyncClient, db_session, printer_factory, archive_factory
  3076. ):
  3077. """Reorder with unique positions succeeds and updates them in DB."""
  3078. from backend.app.models.print_queue import PrintQueueItem
  3079. printer = await printer_factory()
  3080. a1 = await archive_factory()
  3081. a2 = await archive_factory()
  3082. item1 = PrintQueueItem(printer_id=printer.id, archive_id=a1.id, status="pending", position=1)
  3083. item2 = PrintQueueItem(printer_id=printer.id, archive_id=a2.id, status="pending", position=2)
  3084. db_session.add_all([item1, item2])
  3085. await db_session.commit()
  3086. await db_session.refresh(item1)
  3087. await db_session.refresh(item2)
  3088. response = await async_client.post(
  3089. "/api/v1/queue/reorder",
  3090. json={
  3091. "items": [
  3092. {"id": item1.id, "position": 2},
  3093. {"id": item2.id, "position": 1},
  3094. ]
  3095. },
  3096. )
  3097. assert response.status_code == 200
  3098. await db_session.refresh(item1)
  3099. await db_session.refresh(item2)
  3100. assert item1.position == 2
  3101. assert item2.position == 1
  3102. class TestForceColorOverridesAreScopedToThePlate:
  3103. """Queueing several plates of one 3MF must not make each plate wait on the
  3104. colours of its siblings (#2551).
  3105. The print dialog builds one override list from every selected plate and posts
  3106. that same list with each plate's item, so the API is what has to keep only the
  3107. slots the plate prints -- a ``force_color_match`` entry blocks dispatch until
  3108. the printer has that exact colour loaded.
  3109. """
  3110. THREE_PLATES = """<?xml version="1.0" encoding="UTF-8"?>
  3111. <config>
  3112. <plate>
  3113. <metadata key="index" value="1"/>
  3114. <filament id="1" used_g="50.0" type="PLA" color="#0B2C7A"/>
  3115. </plate>
  3116. <plate>
  3117. <metadata key="index" value="2"/>
  3118. <filament id="2" used_g="40.0" type="PLA" color="#9B9EA0"/>
  3119. </plate>
  3120. <plate>
  3121. <metadata key="index" value="3"/>
  3122. <filament id="3" used_g="30.0" type="PLA" color="#F4EE2A"/>
  3123. </plate>
  3124. </config>
  3125. """
  3126. # What the dialog posts for every plate: the union of all three plates'
  3127. # filaments, each one force-matched.
  3128. ALL_THREE_COLORS = [
  3129. {"slot_id": 1, "type": "PLA", "color": "#0B2C7A", "color_name": "Army Blue", "force_color_match": True},
  3130. {"slot_id": 2, "type": "PLA", "color": "#9B9EA0", "color_name": "Ash Grey", "force_color_match": True},
  3131. {"slot_id": 3, "type": "PLA", "color": "#F4EE2A", "color_name": "Sunshine Yellow", "force_color_match": True},
  3132. ]
  3133. @pytest.fixture
  3134. async def multi_plate_archive(self, db_session, tmp_path):
  3135. """An archive whose 3MF really exists on disk, one colour per plate."""
  3136. import zipfile
  3137. from backend.app.models.archive import PrintArchive
  3138. file_path = tmp_path / "three_plates.gcode.3mf"
  3139. with zipfile.ZipFile(file_path, "w") as zf:
  3140. zf.writestr("Metadata/slice_info.config", self.THREE_PLATES)
  3141. archive = PrintArchive(
  3142. filename="three_plates.gcode.3mf",
  3143. print_name="Three Plates",
  3144. file_path=str(file_path),
  3145. file_size=file_path.stat().st_size,
  3146. content_hash="platehash0001",
  3147. status="completed",
  3148. )
  3149. db_session.add(archive)
  3150. await db_session.commit()
  3151. await db_session.refresh(archive)
  3152. return archive
  3153. @pytest.fixture
  3154. async def x1c(self, db_session):
  3155. from backend.app.models.printer import Printer
  3156. printer = Printer(
  3157. name="Force Color X1C",
  3158. ip_address="192.168.1.210",
  3159. serial_number="FORCECOLOR01",
  3160. access_code="12345678",
  3161. model="X1C",
  3162. )
  3163. db_session.add(printer)
  3164. await db_session.commit()
  3165. await db_session.refresh(printer)
  3166. return printer
  3167. @pytest.mark.asyncio
  3168. @pytest.mark.integration
  3169. async def test_each_plate_keeps_only_the_colour_it_prints(
  3170. self, async_client: AsyncClient, multi_plate_archive, x1c
  3171. ):
  3172. """The bug: plate 1 prints Army Blue only, but was stored demanding all three."""
  3173. stored = {}
  3174. for plate_id in (1, 2, 3):
  3175. response = await async_client.post(
  3176. "/api/v1/queue/",
  3177. json={
  3178. "target_model": "X1C",
  3179. "archive_id": multi_plate_archive.id,
  3180. "plate_id": plate_id,
  3181. "filament_overrides": self.ALL_THREE_COLORS,
  3182. },
  3183. )
  3184. assert response.status_code == 200
  3185. stored[plate_id] = response.json()["filament_overrides"]
  3186. assert [o["color_name"] for o in stored[1]] == ["Army Blue"]
  3187. assert [o["color_name"] for o in stored[2]] == ["Ash Grey"]
  3188. assert [o["color_name"] for o in stored[3]] == ["Sunshine Yellow"]
  3189. # The slot each entry maps to has to survive narrowing untouched, or the
  3190. # dispatch-time AMS mapping would key the override onto the wrong slot.
  3191. assert [o["slot_id"] for o in stored[2]] == [2]
  3192. @pytest.mark.asyncio
  3193. @pytest.mark.integration
  3194. async def test_whole_file_queue_keeps_every_colour(self, async_client: AsyncClient, multi_plate_archive, x1c):
  3195. """No plate_id means the job prints the whole file, so every colour is needed."""
  3196. response = await async_client.post(
  3197. "/api/v1/queue/",
  3198. json={
  3199. "target_model": "X1C",
  3200. "archive_id": multi_plate_archive.id,
  3201. "filament_overrides": self.ALL_THREE_COLORS,
  3202. },
  3203. )
  3204. assert response.status_code == 200
  3205. assert len(response.json()["filament_overrides"]) == 3
  3206. @pytest.mark.asyncio
  3207. @pytest.mark.integration
  3208. async def test_unreadable_3mf_keeps_every_colour(self, async_client: AsyncClient, db_session, tmp_path, x1c):
  3209. """When the plate's slots can't be read, keep the overrides rather than drop them.
  3210. An item waiting on a colour it doesn't need is visible and fixable; one that
  3211. silently lost its forced colour would dispatch in the wrong filament.
  3212. """
  3213. from backend.app.models.archive import PrintArchive
  3214. file_path = tmp_path / "not_a_zip.gcode.3mf"
  3215. file_path.write_text("this is not a 3mf")
  3216. archive = PrintArchive(
  3217. filename="not_a_zip.gcode.3mf",
  3218. print_name="Corrupt",
  3219. file_path=str(file_path),
  3220. file_size=file_path.stat().st_size,
  3221. content_hash="platehash0002",
  3222. status="completed",
  3223. )
  3224. db_session.add(archive)
  3225. await db_session.commit()
  3226. await db_session.refresh(archive)
  3227. response = await async_client.post(
  3228. "/api/v1/queue/",
  3229. json={
  3230. "target_model": "X1C",
  3231. "archive_id": archive.id,
  3232. "plate_id": 1,
  3233. "filament_overrides": self.ALL_THREE_COLORS,
  3234. },
  3235. )
  3236. assert response.status_code == 200
  3237. assert len(response.json()["filament_overrides"]) == 3
  3238. @pytest.mark.asyncio
  3239. @pytest.mark.integration
  3240. async def test_required_types_stay_scoped_to_the_plate(self, async_client: AsyncClient, db_session, tmp_path, x1c):
  3241. """Override types are merged into required_filament_types, so a shared list
  3242. also widened the type gate -- a PLA-only plate demanded PETG as well."""
  3243. import zipfile
  3244. from backend.app.models.archive import PrintArchive
  3245. xml = """<?xml version="1.0" encoding="UTF-8"?>
  3246. <config>
  3247. <plate>
  3248. <metadata key="index" value="1"/>
  3249. <filament id="1" used_g="50.0" type="PLA" color="#0B2C7A"/>
  3250. </plate>
  3251. <plate>
  3252. <metadata key="index" value="2"/>
  3253. <filament id="2" used_g="40.0" type="PETG" color="#9B9EA0"/>
  3254. </plate>
  3255. </config>
  3256. """
  3257. file_path = tmp_path / "mixed_types.gcode.3mf"
  3258. with zipfile.ZipFile(file_path, "w") as zf:
  3259. zf.writestr("Metadata/slice_info.config", xml)
  3260. archive = PrintArchive(
  3261. filename="mixed_types.gcode.3mf",
  3262. print_name="Mixed",
  3263. file_path=str(file_path),
  3264. file_size=file_path.stat().st_size,
  3265. content_hash="platehash0003",
  3266. status="completed",
  3267. )
  3268. db_session.add(archive)
  3269. await db_session.commit()
  3270. await db_session.refresh(archive)
  3271. response = await async_client.post(
  3272. "/api/v1/queue/",
  3273. json={
  3274. "target_model": "X1C",
  3275. "archive_id": archive.id,
  3276. "plate_id": 1,
  3277. "filament_overrides": [
  3278. {"slot_id": 1, "type": "PLA", "color": "#0B2C7A", "force_color_match": True},
  3279. {"slot_id": 2, "type": "PETG", "color": "#9B9EA0", "force_color_match": True},
  3280. ],
  3281. },
  3282. )
  3283. assert response.status_code == 200
  3284. assert response.json()["required_filament_types"] == ["PLA"]
  3285. @pytest.mark.asyncio
  3286. @pytest.mark.integration
  3287. async def test_editing_an_item_narrows_the_overrides_too(
  3288. self, async_client: AsyncClient, db_session, multi_plate_archive, x1c
  3289. ):
  3290. """The edit dialog posts the same shared list, so PATCH narrows it as well."""
  3291. from backend.app.models.print_queue import PrintQueueItem
  3292. item = PrintQueueItem(
  3293. target_model="X1C",
  3294. archive_id=multi_plate_archive.id,
  3295. plate_id=2,
  3296. status="pending",
  3297. position=1,
  3298. )
  3299. db_session.add(item)
  3300. await db_session.commit()
  3301. await db_session.refresh(item)
  3302. response = await async_client.patch(
  3303. f"/api/v1/queue/{item.id}",
  3304. json={"filament_overrides": self.ALL_THREE_COLORS},
  3305. )
  3306. assert response.status_code == 200
  3307. assert [o["color_name"] for o in response.json()["filament_overrides"]] == ["Ash Grey"]
  3308. @pytest.mark.asyncio
  3309. @pytest.mark.integration
  3310. async def test_editing_the_plate_renarrows_against_the_new_plate(
  3311. self, async_client: AsyncClient, db_session, multi_plate_archive, x1c
  3312. ):
  3313. """Moving an item to another plate must re-scope its colours to that plate."""
  3314. from backend.app.models.print_queue import PrintQueueItem
  3315. item = PrintQueueItem(
  3316. target_model="X1C",
  3317. archive_id=multi_plate_archive.id,
  3318. plate_id=1,
  3319. status="pending",
  3320. position=1,
  3321. )
  3322. db_session.add(item)
  3323. await db_session.commit()
  3324. await db_session.refresh(item)
  3325. response = await async_client.patch(
  3326. f"/api/v1/queue/{item.id}",
  3327. json={"plate_id": 3, "filament_overrides": self.ALL_THREE_COLORS},
  3328. )
  3329. assert response.status_code == 200
  3330. assert [o["color_name"] for o in response.json()["filament_overrides"]] == ["Sunshine Yellow"]
  3331. @pytest.mark.asyncio
  3332. async def test_stop_offline_reconciles_linked_archive_status_2603(
  3333. async_client: AsyncClient, printer_factory, archive_factory, db_session
  3334. ):
  3335. """Stopping a printing item while the printer is offline must also close out its
  3336. archive (#2603).
  3337. When the stop command reaches the printer, the later MQTT completion event flips
  3338. the archive to cancelled. When the printer is offline no such event ever arrives,
  3339. so without this the archive stays "printing" forever while the queue row is
  3340. already cancelled — the reporter's archive 436. The offline branch reconciles the
  3341. archive directly.
  3342. """
  3343. from unittest.mock import MagicMock, patch
  3344. from backend.app.models.print_queue import PrintQueueItem
  3345. printer = await printer_factory(name="Offline printer")
  3346. archive = await archive_factory(
  3347. printer.id, status="printing", plate_id=22, filename="heart 3.gcode.3mf", with_run=False
  3348. )
  3349. item = PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing")
  3350. db_session.add(item)
  3351. await db_session.commit()
  3352. await db_session.refresh(item)
  3353. # stop_print returns False => printer offline / not connected.
  3354. with patch(
  3355. "backend.app.services.printer_manager.printer_manager.stop_print",
  3356. MagicMock(return_value=False),
  3357. ):
  3358. resp = await async_client.post(f"/api/v1/queue/{item.id}/stop")
  3359. assert resp.status_code == 200
  3360. await db_session.refresh(item)
  3361. await db_session.refresh(archive)
  3362. assert item.status == "cancelled"
  3363. assert archive.status == "cancelled", "an offline stop must reconcile the archive, not leave it 'printing'"
  3364. assert archive.completed_at is not None
  3365. assert archive.failure_reason == "Stopped by user (printer was offline)"
  3366. @pytest.mark.asyncio
  3367. async def test_stop_online_leaves_archive_for_mqtt_to_reconcile_2603(
  3368. async_client: AsyncClient, printer_factory, archive_factory, db_session
  3369. ):
  3370. """When the stop command reaches the printer, the archive is left to the MQTT
  3371. completion path — the offline reconcile must NOT fire and pre-empt it."""
  3372. from unittest.mock import MagicMock, patch
  3373. from backend.app.models.print_queue import PrintQueueItem
  3374. printer = await printer_factory(name="Online printer")
  3375. archive = await archive_factory(printer.id, status="printing", filename="heart 3.gcode.3mf", with_run=False)
  3376. item = PrintQueueItem(printer_id=printer.id, archive_id=archive.id, status="printing")
  3377. db_session.add(item)
  3378. await db_session.commit()
  3379. await db_session.refresh(item)
  3380. with patch(
  3381. "backend.app.services.printer_manager.printer_manager.stop_print",
  3382. MagicMock(return_value=True),
  3383. ):
  3384. resp = await async_client.post(f"/api/v1/queue/{item.id}/stop")
  3385. assert resp.status_code == 200
  3386. await db_session.refresh(item)
  3387. await db_session.refresh(archive)
  3388. assert item.status == "cancelled"
  3389. assert archive.status == "printing", "an online stop must leave the archive for the MQTT completion path"