test_print_queue_api.py 153 KB

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