test_virtual_printer.py 194 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973
  1. """Unit tests for Virtual Printer services.
  2. Tests the virtual printer manager, FTP server, and SSDP server components.
  3. """
  4. import asyncio
  5. import json
  6. import shutil
  7. import zipfile
  8. from pathlib import Path
  9. from types import SimpleNamespace
  10. from unittest.mock import AsyncMock, MagicMock, patch
  11. import pytest
  12. @pytest.fixture(autouse=True)
  13. def _fake_file_manager_store():
  14. """Uploads go to the File Manager (library_store); its own tests cover it.
  15. Here it stands in with file id 1 and the default folder settings, so these
  16. tests see what the virtual printer does around it.
  17. """
  18. stored = MagicMock(id=1, filename="upload.3mf", folder_id=None)
  19. with (
  20. patch(
  21. "backend.app.services.virtual_printer.library_store.store_upload",
  22. AsyncMock(return_value=(stored, False)),
  23. ) as store,
  24. patch(
  25. "backend.app.services.virtual_printer.library_store.upload_settings",
  26. AsyncMock(return_value=(None, False)),
  27. ),
  28. ):
  29. yield store
  30. def _write_3mf_with_filaments(file_path: Path, filaments: list[dict], plate_index: int = 1) -> None:
  31. """Build a minimal 3MF zip with `Metadata/slice_info.config` carrying the
  32. given per-slot filament entries. Each `filaments` dict needs `id`, `type`,
  33. `color`, `used_g`. Used by the #1188 VP queue-mode tests below."""
  34. filament_xml = "".join(
  35. f'<filament id="{f["id"]}" type="{f["type"]}" color="{f["color"]}" '
  36. f'used_g="{f["used_g"]}" tray_info_idx="{f.get("tray_info_idx", "")}"/>'
  37. for f in filaments
  38. )
  39. config = (
  40. '<?xml version="1.0" encoding="utf-8"?>'
  41. "<config>"
  42. f'<plate><metadata key="index" value="{plate_index}"/>'
  43. f"{filament_xml}"
  44. "</plate>"
  45. "</config>"
  46. )
  47. with zipfile.ZipFile(file_path, "w") as zf:
  48. zf.writestr("Metadata/slice_info.config", config)
  49. # Plate gcode is referenced for plate-id detection in the VP path —
  50. # presence is enough; contents don't matter.
  51. zf.writestr(f"Metadata/plate_{plate_index}.gcode", "; gcode\n")
  52. class TestVirtualPrinterInstance:
  53. """Tests for VirtualPrinterInstance class."""
  54. @pytest.fixture(autouse=True)
  55. def _no_queue_announcement(self):
  56. """Its own query would take a result the session mocks hold for the test."""
  57. with patch("backend.app.services.queue_announcements.announce_queue_jobs_added", AsyncMock()):
  58. yield
  59. @pytest.fixture
  60. def instance(self, tmp_path):
  61. """Create a VirtualPrinterInstance with test defaults."""
  62. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  63. return VirtualPrinterInstance(
  64. vp_id=1,
  65. name="TestPrinter",
  66. mode="library",
  67. model="C11",
  68. access_code="12345678",
  69. serial_suffix="391800001",
  70. base_dir=tmp_path,
  71. )
  72. # ========================================================================
  73. # Tests for instance properties
  74. # ========================================================================
  75. def test_instance_stores_parameters(self, instance):
  76. """Verify constructor stores parameters correctly."""
  77. assert instance.id == 1
  78. assert instance.name == "TestPrinter"
  79. assert instance.mode == "library"
  80. assert instance.model == "C11"
  81. assert instance.access_code == "12345678"
  82. assert instance.serial_suffix == "391800001"
  83. def test_instance_serial_property(self, instance):
  84. """Verify serial is generated from model prefix + suffix."""
  85. # C11 = P1P, prefix = 01S00A
  86. assert instance.serial == "01S00A391800001"
  87. def test_instance_serial_x1c(self, tmp_path):
  88. """Verify X1C serial uses correct prefix."""
  89. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  90. inst = VirtualPrinterInstance(
  91. vp_id=2,
  92. name="X1C",
  93. mode="library",
  94. model="BL-P001",
  95. access_code="12345678",
  96. serial_suffix="391800002",
  97. base_dir=tmp_path,
  98. )
  99. assert inst.serial == "00M00A391800002"
  100. def test_instance_is_proxy_false(self, instance):
  101. """Verify is_proxy is False for non-proxy mode."""
  102. assert instance.is_proxy is False
  103. def test_instance_is_proxy_true(self, tmp_path):
  104. """Verify is_proxy is True for proxy mode."""
  105. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  106. inst = VirtualPrinterInstance(
  107. vp_id=3,
  108. name="Proxy",
  109. mode="proxy",
  110. model="C11",
  111. access_code="",
  112. serial_suffix="391800003",
  113. target_printer_ip="192.168.1.100",
  114. base_dir=tmp_path,
  115. )
  116. assert inst.is_proxy is True
  117. def test_instance_is_running_with_active_tasks(self, instance):
  118. """Verify is_running is True when tasks are active."""
  119. mock_task = MagicMock()
  120. mock_task.done.return_value = False
  121. instance._tasks = [mock_task]
  122. assert instance.is_running is True
  123. def test_instance_is_running_with_no_tasks(self, instance):
  124. """Verify is_running is False when no tasks."""
  125. assert instance.is_running is False
  126. def test_instance_creates_directories(self, instance, tmp_path):
  127. """Verify instance creates upload and cert directories."""
  128. assert (tmp_path / "uploads" / "1").exists()
  129. assert (tmp_path / "uploads" / "1" / "cache").exists()
  130. assert (tmp_path / "certs" / "1").exists()
  131. # ========================================================================
  132. # Tests for status
  133. # ========================================================================
  134. def test_get_status_returns_correct_format(self, instance):
  135. """Verify get_status returns expected fields."""
  136. instance._pending_files = {"file1.3mf": Path("/tmp/file1.3mf")} # nosec B108
  137. mock_task = MagicMock(done=MagicMock(return_value=False))
  138. instance._tasks = [mock_task]
  139. status = instance.get_status()
  140. assert status["running"] is True
  141. assert status["pending_files"] == 1
  142. def test_get_status_not_running(self, instance):
  143. """Verify get_status when no tasks."""
  144. status = instance.get_status()
  145. assert status["running"] is False
  146. assert status["pending_files"] == 0
  147. @pytest.mark.asyncio
  148. @pytest.mark.parametrize("handler", ["_store_in_library", "_queue_file", "_add_to_print_queue"])
  149. async def test_a_file_that_cannot_be_handled_leaves_the_pending_count(self, instance, handler):
  150. """Without a database the file is dropped, and the status stops counting it."""
  151. file_path = Path("/tmp/test.3mf") # nosec B108
  152. instance._session_factory = None
  153. instance._pending_files = {file_path.name: file_path}
  154. await getattr(instance, handler)(file_path, "192.168.1.100")
  155. assert instance.get_status()["pending_files"] == 0
  156. # ========================================================================
  157. # Tests for file handling
  158. # ========================================================================
  159. @pytest.mark.asyncio
  160. async def test_on_file_received_adds_to_pending(self, instance):
  161. """Verify received file is added to pending list in review mode."""
  162. instance.mode = "review"
  163. file_path = Path("/tmp/test.3mf") # nosec B108
  164. with patch.object(instance, "_queue_file", new_callable=AsyncMock) as mock_queue:
  165. await instance.on_file_received(file_path, "192.168.1.100")
  166. assert "test.3mf" in instance._pending_files
  167. mock_queue.assert_called_once()
  168. @pytest.mark.asyncio
  169. async def test_on_file_received_archives_immediately(self, instance):
  170. """Verify file is archived in immediate mode."""
  171. file_path = Path("/tmp/test.3mf") # nosec B108
  172. with patch.object(instance, "_store_in_library", new_callable=AsyncMock) as mock_archive:
  173. await instance.on_file_received(file_path, "192.168.1.100")
  174. mock_archive.assert_called_once_with(file_path, "192.168.1.100")
  175. @pytest.mark.asyncio
  176. async def test_on_file_received_signals_FINISH_to_slicer(self, instance):
  177. """Regression #1280: when a slicer's Print flow uploads to a non-proxy VP,
  178. the VP must transition gcode_state PREPARE → FINISH so the slicer's
  179. in-flight-job lock releases. Going PREPARE → IDLE wedges Orca at
  180. "Downloading...(0%)" and blocks the next dispatch with "busy with
  181. another print job".
  182. Send-flow slicers don't watch the post-upload state, so this is a
  183. no-op behavior change for them.
  184. """
  185. instance.mode = "library"
  186. instance._mqtt = MagicMock()
  187. instance._mqtt.set_gcode_state = MagicMock()
  188. file_path = Path("/tmp/test.3mf") # nosec B108
  189. with patch.object(instance, "_store_in_library", new_callable=AsyncMock):
  190. await instance.on_file_received(file_path, "192.168.1.100")
  191. instance._mqtt.set_gcode_state.assert_called_once_with("FINISH", filename="test.3mf", prepare_percent="100")
  192. @pytest.mark.asyncio
  193. async def test_on_file_received_non_3mf_does_not_touch_state(self, instance):
  194. """Non-3MF uploads (e.g., a job's auxiliary files) must not transition
  195. the visible state — the slicer is only tracking the .3mf upload."""
  196. instance.mode = "library"
  197. instance._mqtt = MagicMock()
  198. instance._mqtt.set_gcode_state = MagicMock()
  199. file_path = Path("/tmp/test.gcode") # nosec B108
  200. with patch.object(instance, "_store_in_library", new_callable=AsyncMock):
  201. await instance.on_file_received(file_path, "192.168.1.100")
  202. instance._mqtt.set_gcode_state.assert_not_called()
  203. @pytest.mark.asyncio
  204. async def test_on_print_command_schedules_finish_release_non_proxy(self, instance):
  205. """#1658: Bambu Studio 2.7.x flipped the slicer's Send flow to
  206. FTP → FTP → MQTT project_file. Under that order the synthetic
  207. project_file ack overwrites the FINISH set by #1280 in
  208. ``on_file_received`` back to PREPARE, leaving the slicer's
  209. "Downloading" modal stuck forever. Re-firing FINISH a moment after
  210. the ack releases the modal.
  211. """
  212. instance.mode = "library"
  213. instance._mqtt = MagicMock()
  214. instance._mqtt.set_gcode_state = MagicMock()
  215. with patch.object(instance, "_delayed_finish_release", new_callable=AsyncMock) as mock_delayed:
  216. await instance.on_print_command("test.3mf", {"command": "project_file"})
  217. mock_delayed.assert_called_once()
  218. # First positional arg should be the filename; second is the delay seconds.
  219. args = mock_delayed.call_args.args
  220. assert args[0] == "test.3mf"
  221. assert isinstance(args[1], int | float)
  222. @pytest.mark.asyncio
  223. async def test_on_print_command_proxy_mode_does_not_reschedule_finish(self, instance):
  224. """Proxy mode hands push_status straight from the real printer through
  225. the bridge. Re-firing a synthetic FINISH would clobber a real
  226. PREPARE / RUNNING transition coming back from the printer, so the
  227. scheduler is exempt for proxy mode."""
  228. instance.mode = "proxy"
  229. instance._mqtt = MagicMock()
  230. with patch.object(instance, "_delayed_finish_release", new_callable=AsyncMock) as mock_delayed:
  231. await instance.on_print_command("test.3mf", {"command": "project_file"})
  232. mock_delayed.assert_not_called()
  233. @pytest.mark.asyncio
  234. async def test_on_print_command_no_mqtt_does_not_schedule(self, instance):
  235. """If the MQTT server isn't running yet (transient race during boot),
  236. the scheduler must skip silently — no AttributeError, no orphan task."""
  237. instance.mode = "queue"
  238. instance._mqtt = None
  239. # Should not raise.
  240. await instance.on_print_command("test.3mf", {"command": "project_file"})
  241. assert instance._finish_release_task is None
  242. @pytest.mark.asyncio
  243. async def test_schedule_finish_release_cancels_previous_timer(self, instance):
  244. """A slicer that fires project_file twice (e.g. retry after a transient
  245. FTP hiccup) must only result in one FINISH transition — the earlier
  246. in-flight timer is cancelled when the next one is scheduled."""
  247. instance.mode = "queue"
  248. instance._mqtt = MagicMock()
  249. instance._schedule_finish_release("first.3mf", delay=10.0)
  250. first_task = instance._finish_release_task
  251. assert first_task is not None
  252. instance._schedule_finish_release("second.3mf", delay=10.0)
  253. second_task = instance._finish_release_task
  254. assert second_task is not first_task
  255. # Give the loop one tick so the cancelled task settles.
  256. await asyncio.sleep(0)
  257. assert first_task.cancelled() or first_task.done()
  258. # Clean up the still-pending second task so the test doesn't leak it.
  259. second_task.cancel()
  260. try:
  261. await second_task
  262. except asyncio.CancelledError:
  263. pass
  264. @pytest.mark.asyncio
  265. async def test_delayed_finish_release_sets_finish_state(self, instance):
  266. """End-to-end: after the delay elapses, set_gcode_state is called with
  267. FINISH and prepare_percent=100, matching the wire-format the slicer's
  268. Print flow consumes to release "Downloading"."""
  269. instance._mqtt = MagicMock()
  270. instance._mqtt.set_gcode_state = MagicMock()
  271. await instance._delayed_finish_release("queued.3mf", delay=0.0)
  272. instance._mqtt.set_gcode_state.assert_called_once_with("FINISH", filename="queued.3mf", prepare_percent="100")
  273. @pytest.mark.asyncio
  274. async def test_on_print_command_no_filename_does_not_schedule(self, instance):
  275. """A project_file command without a subtask_name (defensive — real
  276. slicers always send one) must not schedule a no-op FINISH that would
  277. carry an empty filename on the next 1 Hz push."""
  278. instance.mode = "queue"
  279. instance._mqtt = MagicMock()
  280. with patch.object(instance, "_delayed_finish_release", new_callable=AsyncMock) as mock_delayed:
  281. await instance.on_print_command("", {"command": "project_file"})
  282. mock_delayed.assert_not_called()
  283. @pytest.mark.asyncio
  284. async def test_store_in_library_skips_non_3mf(self, instance, _fake_file_manager_store):
  285. """Verify non-3MF files are skipped and cleaned up."""
  286. instance._session_factory = MagicMock()
  287. instance._pending_files["verify_job"] = Path("/tmp/verify_job") # nosec B108
  288. with patch("pathlib.Path.unlink"):
  289. await instance._store_in_library(Path("/tmp/verify_job"), "192.168.1.100") # nosec B108
  290. assert "verify_job" not in instance._pending_files
  291. _fake_file_manager_store.assert_not_awaited()
  292. @pytest.mark.asyncio
  293. async def test_store_in_library_stores_in_the_vp_folder_and_broadcasts(self, tmp_path, _fake_file_manager_store):
  294. """Library mode: the upload goes to the File Manager folder the VP is
  295. set to, open File Manager pages are told, and the temp file goes."""
  296. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  297. mock_session_factory = MagicMock()
  298. mock_session_ctx = AsyncMock()
  299. mock_session_ctx.__aenter__ = AsyncMock(return_value=AsyncMock())
  300. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  301. mock_session_factory.return_value = mock_session_ctx
  302. inst = VirtualPrinterInstance(
  303. vp_id=30,
  304. name="LibraryMode",
  305. mode="library",
  306. model="C12",
  307. access_code="12345678",
  308. serial_suffix="391800030",
  309. base_dir=tmp_path,
  310. session_factory=mock_session_factory,
  311. )
  312. file_path = tmp_path / "test.3mf"
  313. file_path.write_bytes(b"fake3mf")
  314. inst._pending_files[file_path.name] = file_path
  315. with (
  316. patch(
  317. "backend.app.services.virtual_printer.library_store.upload_settings",
  318. AsyncMock(return_value=(7, False)),
  319. ),
  320. patch(
  321. "backend.app.core.websocket.ws_manager.send_library_files_changed",
  322. new_callable=AsyncMock,
  323. ) as mock_broadcast,
  324. ):
  325. await inst._store_in_library(file_path, "192.168.1.100")
  326. _fake_file_manager_store.assert_awaited_once()
  327. kwargs = _fake_file_manager_store.await_args.kwargs
  328. assert kwargs["source_path"] == file_path
  329. assert kwargs["filename"] == "test.3mf"
  330. assert kwargs["folder_id"] == 7
  331. mock_broadcast.assert_awaited_once()
  332. assert file_path.name not in inst._pending_files
  333. assert not file_path.exists()
  334. # ========================================================================
  335. # Tests for auto_dispatch
  336. # ========================================================================
  337. def test_auto_dispatch_defaults_to_true(self, tmp_path):
  338. """Verify auto_dispatch defaults to True when not specified."""
  339. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  340. inst = VirtualPrinterInstance(
  341. vp_id=10,
  342. name="DefaultDispatch",
  343. mode="queue",
  344. model="C11",
  345. access_code="12345678",
  346. serial_suffix="391800010",
  347. base_dir=tmp_path,
  348. )
  349. assert inst.auto_dispatch is True
  350. @pytest.mark.asyncio
  351. async def test_add_to_print_queue_with_auto_dispatch_on(self, tmp_path):
  352. """Verify queue items have manual_start=False when auto_dispatch=True."""
  353. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  354. mock_db = AsyncMock()
  355. added_items = []
  356. def capture_add(item):
  357. added_items.append(item)
  358. mock_db.add = MagicMock(side_effect=capture_add)
  359. mock_db.commit = AsyncMock()
  360. mock_session_factory = MagicMock()
  361. mock_session_ctx = AsyncMock()
  362. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  363. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  364. mock_session_factory.return_value = mock_session_ctx
  365. inst = VirtualPrinterInstance(
  366. vp_id=11,
  367. name="AutoDispatchOn",
  368. mode="queue",
  369. model="C11",
  370. access_code="12345678",
  371. serial_suffix="391800011",
  372. auto_dispatch=True,
  373. base_dir=tmp_path,
  374. session_factory=mock_session_factory,
  375. )
  376. # Create a temp 3mf file
  377. file_path = tmp_path / "test.3mf"
  378. file_path.write_bytes(b"fake3mf")
  379. with (
  380. patch(
  381. "backend.app.api.routes.settings.get_setting",
  382. new_callable=AsyncMock,
  383. return_value=None,
  384. ),
  385. ):
  386. await inst._add_to_print_queue(file_path, "192.168.1.100")
  387. assert len(added_items) == 1
  388. queue_item = added_items[0]
  389. assert queue_item.manual_start is False
  390. @pytest.mark.asyncio
  391. @pytest.mark.parametrize("remove_after_print", [False, True])
  392. async def test_add_to_print_queue_prints_the_file_manager_file(
  393. self, tmp_path, _fake_file_manager_store, remove_after_print
  394. ):
  395. """Queue mode: the upload goes to the VP's File Manager folder and the
  396. queue item prints that file; the archive is made when it prints.
  397. "Remove from File Manager once it prints" rides on the item."""
  398. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  399. added_items = []
  400. mock_db = AsyncMock()
  401. mock_db.add = MagicMock(side_effect=added_items.append)
  402. mock_session_ctx = AsyncMock()
  403. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  404. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  405. inst = VirtualPrinterInstance(
  406. vp_id=12,
  407. name="QueueToLibrary",
  408. mode="queue",
  409. model="C11",
  410. access_code="12345678",
  411. serial_suffix="391800012",
  412. base_dir=tmp_path,
  413. session_factory=MagicMock(return_value=mock_session_ctx),
  414. )
  415. file_path = tmp_path / "test.3mf"
  416. file_path.write_bytes(b"fake3mf")
  417. with (
  418. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=None),
  419. patch(
  420. "backend.app.services.virtual_printer.library_store.upload_settings",
  421. AsyncMock(return_value=(7, remove_after_print)),
  422. ),
  423. ):
  424. await inst._add_to_print_queue(file_path, "192.168.1.100")
  425. assert _fake_file_manager_store.await_args.kwargs["folder_id"] == 7
  426. assert len(added_items) == 1
  427. assert added_items[0].library_file_id == 1
  428. assert added_items[0].archive_id is None
  429. assert added_items[0].cleanup_library_after_dispatch is remove_after_print
  430. assert not file_path.exists()
  431. @pytest.mark.asyncio
  432. async def test_add_to_print_queue_broadcasts_library_files_changed(self, tmp_path):
  433. """#1282: VP queue-mode uploads must tell open pages so the new file
  434. shows up live. The upload is a File Manager file now, not an archive."""
  435. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  436. mock_db = AsyncMock()
  437. mock_db.add = MagicMock()
  438. mock_db.commit = AsyncMock()
  439. mock_session_factory = MagicMock()
  440. mock_session_ctx = AsyncMock()
  441. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  442. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  443. mock_session_factory.return_value = mock_session_ctx
  444. inst = VirtualPrinterInstance(
  445. vp_id=31,
  446. name="QueueBroadcast",
  447. mode="queue",
  448. model="C12",
  449. access_code="12345678",
  450. serial_suffix="391800031",
  451. auto_dispatch=True,
  452. base_dir=tmp_path,
  453. session_factory=mock_session_factory,
  454. )
  455. file_path = tmp_path / "test.3mf"
  456. file_path.write_bytes(b"fake3mf")
  457. with (
  458. patch(
  459. "backend.app.api.routes.settings.get_setting",
  460. new_callable=AsyncMock,
  461. return_value=None,
  462. ),
  463. patch(
  464. "backend.app.core.websocket.ws_manager.send_library_files_changed",
  465. new_callable=AsyncMock,
  466. ) as mock_broadcast,
  467. ):
  468. await inst._add_to_print_queue(file_path, "192.168.1.100")
  469. mock_broadcast.assert_awaited_once()
  470. @pytest.mark.asyncio
  471. async def test_add_to_print_queue_with_auto_dispatch_off(self, tmp_path):
  472. """Verify queue items have manual_start=True when auto_dispatch=False."""
  473. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  474. mock_db = AsyncMock()
  475. added_items = []
  476. def capture_add(item):
  477. added_items.append(item)
  478. mock_db.add = MagicMock(side_effect=capture_add)
  479. mock_db.commit = AsyncMock()
  480. mock_session_factory = MagicMock()
  481. mock_session_ctx = AsyncMock()
  482. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  483. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  484. mock_session_factory.return_value = mock_session_ctx
  485. inst = VirtualPrinterInstance(
  486. vp_id=12,
  487. name="AutoDispatchOff",
  488. mode="queue",
  489. model="C11",
  490. access_code="12345678",
  491. serial_suffix="391800012",
  492. auto_dispatch=False,
  493. base_dir=tmp_path,
  494. session_factory=mock_session_factory,
  495. )
  496. # Create a temp 3mf file
  497. file_path = tmp_path / "test.3mf"
  498. file_path.write_bytes(b"fake3mf")
  499. with (
  500. patch(
  501. "backend.app.api.routes.settings.get_setting",
  502. new_callable=AsyncMock,
  503. return_value=None,
  504. ),
  505. ):
  506. await inst._add_to_print_queue(file_path, "192.168.1.100")
  507. assert len(added_items) == 1
  508. queue_item = added_items[0]
  509. assert queue_item.manual_start is True
  510. @pytest.mark.asyncio
  511. async def test_add_to_print_queue_gcode_injection_on(self, tmp_path):
  512. """#1516: queue items opt into injection when the VP has gcode_injection=True."""
  513. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  514. mock_db = AsyncMock()
  515. added_items = []
  516. mock_db.add = MagicMock(side_effect=added_items.append)
  517. mock_db.commit = AsyncMock()
  518. mock_session_factory = MagicMock()
  519. mock_session_ctx = AsyncMock()
  520. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  521. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  522. mock_session_factory.return_value = mock_session_ctx
  523. inst = VirtualPrinterInstance(
  524. vp_id=13,
  525. name="InjectOn",
  526. mode="queue",
  527. model="C11",
  528. access_code="12345678",
  529. serial_suffix="391800013",
  530. gcode_injection=True,
  531. base_dir=tmp_path,
  532. session_factory=mock_session_factory,
  533. )
  534. file_path = tmp_path / "test.3mf"
  535. file_path.write_bytes(b"fake3mf")
  536. with (
  537. patch(
  538. "backend.app.api.routes.settings.get_setting",
  539. new_callable=AsyncMock,
  540. return_value=None,
  541. ),
  542. ):
  543. await inst._add_to_print_queue(file_path, "192.168.1.100")
  544. assert len(added_items) == 1
  545. assert added_items[0].gcode_injection is True
  546. @pytest.mark.asyncio
  547. async def test_add_to_print_queue_gcode_injection_off_by_default(self, tmp_path):
  548. """#1516: queue items do NOT inject when the VP leaves gcode_injection at its default."""
  549. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  550. mock_db = AsyncMock()
  551. added_items = []
  552. mock_db.add = MagicMock(side_effect=added_items.append)
  553. mock_db.commit = AsyncMock()
  554. mock_session_factory = MagicMock()
  555. mock_session_ctx = AsyncMock()
  556. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  557. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  558. mock_session_factory.return_value = mock_session_ctx
  559. inst = VirtualPrinterInstance(
  560. vp_id=14,
  561. name="InjectOff",
  562. mode="queue",
  563. model="C11",
  564. access_code="12345678",
  565. serial_suffix="391800014",
  566. base_dir=tmp_path,
  567. session_factory=mock_session_factory,
  568. )
  569. file_path = tmp_path / "test.3mf"
  570. file_path.write_bytes(b"fake3mf")
  571. with (
  572. patch(
  573. "backend.app.api.routes.settings.get_setting",
  574. new_callable=AsyncMock,
  575. return_value=None,
  576. ),
  577. ):
  578. await inst._add_to_print_queue(file_path, "192.168.1.100")
  579. assert len(added_items) == 1
  580. assert added_items[0].gcode_injection is False
  581. @pytest.mark.asyncio
  582. async def test_add_to_print_queue_uses_workflow_defaults_from_settings(self, tmp_path):
  583. """#1235: VP queue-mode constructed PrintQueueItem without specifying
  584. bed_levelling / flow_cali / vibration_cali / layer_inspect / timelapse,
  585. so SQLAlchemy applied the column-level defaults and ignored the user's
  586. workflow preferences entirely. Every print sent from the slicer to the
  587. VP came through with the OPPOSITE of what the workflow page said,
  588. forcing the user to edit each queue item by hand.
  589. """
  590. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  591. added_items = []
  592. mock_db = AsyncMock()
  593. mock_db.add = MagicMock(side_effect=added_items.append)
  594. mock_db.commit = AsyncMock()
  595. mock_session_factory = MagicMock()
  596. mock_session_ctx = AsyncMock()
  597. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  598. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  599. mock_session_factory.return_value = mock_session_ctx
  600. inst = VirtualPrinterInstance(
  601. vp_id=22,
  602. name="DefaultsTest",
  603. mode="queue",
  604. model="C12",
  605. access_code="12345678",
  606. serial_suffix="391800022",
  607. auto_dispatch=True,
  608. base_dir=tmp_path,
  609. session_factory=mock_session_factory,
  610. )
  611. file_path = tmp_path / "test.3mf"
  612. file_path.write_bytes(b"fake3mf")
  613. # The reporter set every workflow default to the OPPOSITE of the model's
  614. # column default. Pre-fix the column defaults won; with the fix the
  615. # settings values must flow through to the queue item exactly as stored.
  616. settings_map = {
  617. "virtual_printer_archive_name_source": None,
  618. # Legacy boolean-string rows still coerce (false->off, true->on).
  619. "default_bed_levelling": "false", # tri-state default: auto
  620. "default_flow_cali": "true", # tri-state default: auto
  621. "default_vibration_cali": "false", # model default: True
  622. "default_layer_inspect": "true", # model default: False
  623. "default_timelapse": "true", # model default: False
  624. }
  625. async def fake_get_setting(_db, key):
  626. return settings_map.get(key)
  627. with (
  628. patch(
  629. "backend.app.api.routes.settings.get_setting",
  630. new=fake_get_setting,
  631. ),
  632. ):
  633. await inst._add_to_print_queue(file_path, "192.168.1.100")
  634. assert len(added_items) == 1
  635. queue_item = added_items[0]
  636. assert queue_item.bed_levelling == "off", "default_bed_levelling=false must flow through"
  637. assert queue_item.flow_cali == "on", "default_flow_cali=true must flow through"
  638. assert queue_item.vibration_cali is False, "default_vibration_cali=false must flow through"
  639. assert queue_item.layer_inspect is True, "default_layer_inspect=true must flow through"
  640. assert queue_item.timelapse is True, "default_timelapse=true must flow through"
  641. @pytest.mark.asyncio
  642. async def test_add_to_print_queue_falls_back_to_schema_defaults_when_unset(self, tmp_path):
  643. """#1235 fallback: when no workflow setting is in the DB, the queue
  644. item should use the AppSettings (Pydantic) defaults — same values
  645. the user sees in the workflow page on a fresh install.
  646. """
  647. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  648. added_items = []
  649. mock_db = AsyncMock()
  650. mock_db.add = MagicMock(side_effect=added_items.append)
  651. mock_db.commit = AsyncMock()
  652. mock_session_factory = MagicMock()
  653. mock_session_ctx = AsyncMock()
  654. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  655. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  656. mock_session_factory.return_value = mock_session_ctx
  657. inst = VirtualPrinterInstance(
  658. vp_id=23,
  659. name="FreshInstallDefaults",
  660. mode="queue",
  661. model="C12",
  662. access_code="12345678",
  663. serial_suffix="391800023",
  664. auto_dispatch=True,
  665. base_dir=tmp_path,
  666. session_factory=mock_session_factory,
  667. )
  668. file_path = tmp_path / "test.3mf"
  669. file_path.write_bytes(b"fake3mf")
  670. with (
  671. patch(
  672. "backend.app.api.routes.settings.get_setting",
  673. new_callable=AsyncMock,
  674. return_value=None, # No settings → fall back to schema defaults
  675. ),
  676. ):
  677. await inst._add_to_print_queue(file_path, "192.168.1.100")
  678. assert len(added_items) == 1
  679. queue_item = added_items[0]
  680. # These must match the AppSettings (Pydantic) defaults in schemas/settings.py
  681. assert queue_item.bed_levelling == "auto"
  682. assert queue_item.flow_cali == "auto"
  683. assert queue_item.vibration_cali is True
  684. assert queue_item.layer_inspect is False
  685. assert queue_item.timelapse is False
  686. @pytest.mark.asyncio
  687. async def test_add_to_print_queue_inherits_slicer_print_options(self, tmp_path):
  688. """#1403: VP-queue items used to fall back to `default_timelapse` even
  689. though the slicer's MQTT `project_file` command carries the user's
  690. actual choice. Capture-via-`on_print_command` flow lets the user's
  691. slicer toggle reach the queue item.
  692. Settings here have timelapse OFF; the slicer's MQTT capture has it ON.
  693. After the fix the queue item must reflect the slicer's choice.
  694. """
  695. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  696. added_items = []
  697. mock_db = AsyncMock()
  698. mock_db.add = MagicMock(side_effect=added_items.append)
  699. mock_db.commit = AsyncMock()
  700. mock_session_factory = MagicMock()
  701. mock_session_ctx = AsyncMock()
  702. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  703. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  704. mock_session_factory.return_value = mock_session_ctx
  705. inst = VirtualPrinterInstance(
  706. vp_id=24,
  707. name="SlicerInherits",
  708. mode="queue",
  709. model="C12",
  710. access_code="12345678",
  711. serial_suffix="391800024",
  712. auto_dispatch=True,
  713. base_dir=tmp_path,
  714. session_factory=mock_session_factory,
  715. )
  716. file_path = tmp_path / "test.3mf"
  717. file_path.write_bytes(b"fake3mf")
  718. # Pre-populate the capture as if MQTT `project_file` arrived already.
  719. # Settings (below) deliberately have timelapse OFF — only the slicer
  720. # capture should drive the resulting queue item.
  721. await inst.on_print_command(
  722. file_path.name,
  723. {
  724. "command": "project_file",
  725. "timelapse": True,
  726. "bed_leveling": False, # Note: MQTT field is single-L `bed_leveling`
  727. "flow_cali": True,
  728. "vibration_cali": False,
  729. "layer_inspect": True,
  730. },
  731. )
  732. settings_map = {
  733. "virtual_printer_archive_name_source": None,
  734. "default_bed_levelling": "true",
  735. "default_flow_cali": "false",
  736. "default_vibration_cali": "true",
  737. "default_layer_inspect": "false",
  738. "default_timelapse": "false",
  739. }
  740. async def fake_get_setting(_db, key):
  741. return settings_map.get(key)
  742. with (
  743. patch(
  744. "backend.app.api.routes.settings.get_setting",
  745. new=fake_get_setting,
  746. ),
  747. ):
  748. await inst._add_to_print_queue(file_path, "192.168.1.100")
  749. assert len(added_items) == 1
  750. queue_item = added_items[0]
  751. assert queue_item.timelapse is True, "Slicer's timelapse=True must override settings.default_timelapse=False"
  752. assert queue_item.bed_levelling == "off", "Slicer's bed_leveling=False must override default_bed_levelling"
  753. assert queue_item.flow_cali == "on"
  754. assert queue_item.vibration_cali is False
  755. assert queue_item.layer_inspect is True
  756. # Capture is consumed — no lingering state for the next print of the same name.
  757. assert file_path.name not in inst._slicer_print_options
  758. @pytest.mark.asyncio
  759. async def test_add_to_print_queue_coerces_slicer_integer_zero_one(self, tmp_path):
  760. """#1403: H-family firmwares carry calibration flags as integers
  761. (0/1) rather than booleans. The capture must coerce both shapes so
  762. H-family-sliced jobs through the VP queue work the same as P1/X1.
  763. """
  764. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  765. added_items = []
  766. mock_db = AsyncMock()
  767. mock_db.add = MagicMock(side_effect=added_items.append)
  768. mock_db.commit = AsyncMock()
  769. mock_session_factory = MagicMock()
  770. mock_session_ctx = AsyncMock()
  771. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  772. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  773. mock_session_factory.return_value = mock_session_ctx
  774. inst = VirtualPrinterInstance(
  775. vp_id=25,
  776. name="SlicerIntegers",
  777. mode="queue",
  778. model="C12",
  779. access_code="12345678",
  780. serial_suffix="391800025",
  781. auto_dispatch=True,
  782. base_dir=tmp_path,
  783. session_factory=mock_session_factory,
  784. )
  785. file_path = tmp_path / "test.3mf"
  786. file_path.write_bytes(b"fake3mf")
  787. await inst.on_print_command(
  788. file_path.name,
  789. {"command": "project_file", "timelapse": 1, "bed_leveling": 0, "flow_cali": 1},
  790. )
  791. with (
  792. patch(
  793. "backend.app.api.routes.settings.get_setting",
  794. new_callable=AsyncMock,
  795. return_value=None,
  796. ),
  797. ):
  798. await inst._add_to_print_queue(file_path, "192.168.1.100")
  799. assert len(added_items) == 1
  800. queue_item = added_items[0]
  801. assert queue_item.timelapse is True, "integer 1 must coerce to True"
  802. assert queue_item.bed_levelling == "off", "integer 0 must coerce to off"
  803. assert queue_item.flow_cali == "on"
  804. @pytest.mark.asyncio
  805. async def test_add_to_print_queue_captures_slicer_auto_from_int_companion(self, tmp_path):
  806. """The slicer's tri-state rides on the int companion (auto_bed_leveling /
  807. extrude_cali_flag). When the slicer picks "Auto" it sends bed_leveling
  808. false + auto_bed_leveling 2; the VP must record "auto", not "off".
  809. """
  810. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  811. added_items = []
  812. mock_db = AsyncMock()
  813. mock_db.add = MagicMock(side_effect=added_items.append)
  814. mock_db.commit = AsyncMock()
  815. mock_session_factory = MagicMock()
  816. mock_session_ctx = AsyncMock()
  817. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  818. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  819. mock_session_factory.return_value = mock_session_ctx
  820. inst = VirtualPrinterInstance(
  821. vp_id=26,
  822. name="SlicerAuto",
  823. mode="queue",
  824. model="C12",
  825. access_code="12345678",
  826. serial_suffix="391800026",
  827. auto_dispatch=True,
  828. base_dir=tmp_path,
  829. session_factory=mock_session_factory,
  830. )
  831. file_path = tmp_path / "test.3mf"
  832. file_path.write_bytes(b"fake3mf")
  833. await inst.on_print_command(
  834. file_path.name,
  835. {
  836. "command": "project_file",
  837. "bed_leveling": False,
  838. "auto_bed_leveling": 2,
  839. "flow_cali": False,
  840. "extrude_cali_flag": 2,
  841. },
  842. )
  843. with (
  844. patch(
  845. "backend.app.api.routes.settings.get_setting",
  846. new_callable=AsyncMock,
  847. return_value=None,
  848. ),
  849. ):
  850. await inst._add_to_print_queue(file_path, "192.168.1.100")
  851. assert len(added_items) == 1
  852. queue_item = added_items[0]
  853. assert queue_item.bed_levelling == "auto", "auto_bed_leveling=2 must record 'auto'"
  854. assert queue_item.flow_cali == "auto", "extrude_cali_flag=2 must record 'auto'"
  855. @pytest.mark.asyncio
  856. async def test_add_to_print_queue_populates_required_filament_types(self, tmp_path):
  857. """#1188: VP queue-mode used to create PrintQueueItems with no
  858. filament fields, so the scheduler fell through to model-only matching
  859. and dispatched onto whatever printer was free regardless of loaded
  860. colour. ``required_filament_types`` is populated unconditionally
  861. (cheap, helps the scheduler validate type even without
  862. ``force_color_match``) — pin that contract here."""
  863. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  864. added_items = []
  865. mock_db = AsyncMock()
  866. mock_db.add = MagicMock(side_effect=added_items.append)
  867. mock_db.commit = AsyncMock()
  868. mock_session_factory = MagicMock()
  869. mock_session_ctx = AsyncMock()
  870. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  871. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  872. mock_session_factory.return_value = mock_session_ctx
  873. inst = VirtualPrinterInstance(
  874. vp_id=21,
  875. name="Reqs",
  876. mode="queue",
  877. model="C12",
  878. access_code="12345678",
  879. serial_suffix="391800021",
  880. auto_dispatch=True,
  881. queue_force_color_match=False, # off → only required_filament_types
  882. base_dir=tmp_path,
  883. session_factory=mock_session_factory,
  884. )
  885. file_path = tmp_path / "multi.3mf"
  886. _write_3mf_with_filaments(
  887. file_path,
  888. [
  889. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "12.3"},
  890. {"id": "2", "type": "PETG", "color": "#000000", "used_g": "4.5"},
  891. # used_g=0 → not actually consumed by this plate, must be ignored
  892. {"id": "3", "type": "ABS", "color": "#FF0000", "used_g": "0"},
  893. ],
  894. plate_index=1,
  895. )
  896. with (
  897. patch(
  898. "backend.app.api.routes.settings.get_setting",
  899. new_callable=AsyncMock,
  900. return_value=None,
  901. ),
  902. ):
  903. await inst._add_to_print_queue(file_path, "192.168.1.100")
  904. assert len(added_items) == 1
  905. queue_item = added_items[0]
  906. # Type-only fallback always populated. Sorted, deduped, no zero-use ABS.
  907. assert queue_item.required_filament_types is not None
  908. assert json.loads(queue_item.required_filament_types) == ["PETG", "PLA"]
  909. # Setting off → no force_color_match overrides leaked.
  910. assert queue_item.filament_overrides is None
  911. @pytest.mark.asyncio
  912. async def test_add_to_print_queue_force_color_match_writes_overrides(self, tmp_path):
  913. """#1188 core fix: when the per-VP ``queue_force_color_match`` toggle
  914. is on, every consumed slot lands as a ``filament_overrides`` entry
  915. with ``force_color_match: true``. This is the field the scheduler
  916. keys on (``print_scheduler.py:512``) — without it, slot-by-slot
  917. type+color matching never runs."""
  918. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  919. added_items = []
  920. mock_db = AsyncMock()
  921. mock_db.add = MagicMock(side_effect=added_items.append)
  922. mock_db.commit = AsyncMock()
  923. mock_session_factory = MagicMock()
  924. mock_session_ctx = AsyncMock()
  925. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  926. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  927. mock_session_factory.return_value = mock_session_ctx
  928. inst = VirtualPrinterInstance(
  929. vp_id=22,
  930. name="ForceColor",
  931. mode="queue",
  932. model="C12",
  933. access_code="12345678",
  934. serial_suffix="391800022",
  935. auto_dispatch=True,
  936. queue_force_color_match=True, # on
  937. base_dir=tmp_path,
  938. session_factory=mock_session_factory,
  939. )
  940. file_path = tmp_path / "forced.3mf"
  941. _write_3mf_with_filaments(
  942. file_path,
  943. [
  944. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "10.0"},
  945. {"id": "2", "type": "PLA", "color": "#FF00FF", "used_g": "5.0"},
  946. ],
  947. plate_index=1,
  948. )
  949. with (
  950. patch(
  951. "backend.app.api.routes.settings.get_setting",
  952. new_callable=AsyncMock,
  953. return_value=None,
  954. ),
  955. ):
  956. await inst._add_to_print_queue(file_path, "192.168.1.100")
  957. assert len(added_items) == 1
  958. queue_item = added_items[0]
  959. assert queue_item.filament_overrides is not None
  960. overrides = json.loads(queue_item.filament_overrides)
  961. assert overrides == [
  962. {"slot_id": 1, "type": "PLA", "color": "#FFFFFF", "tray_info_idx": "", "force_color_match": True},
  963. {"slot_id": 2, "type": "PLA", "color": "#FF00FF", "tray_info_idx": "", "force_color_match": True},
  964. ]
  965. # required_filament_types still populated alongside overrides.
  966. assert json.loads(queue_item.required_filament_types) == ["PLA"]
  967. @pytest.mark.asyncio
  968. async def test_add_to_print_queue_force_color_match_carries_tray_info_idx(self, tmp_path):
  969. """#2650: the force override must carry the 3MF's ``tray_info_idx`` so the
  970. scheduler can tell Bambu PLA variants apart (Basic GFA00 / Matte GFA01 /
  971. Silk GFA06) — they all report ``tray_type == "PLA"`` with the same colour,
  972. so type+colour alone dispatches onto the wrong variant."""
  973. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  974. added_items = []
  975. mock_db = AsyncMock()
  976. mock_db.add = MagicMock(side_effect=added_items.append)
  977. mock_db.commit = AsyncMock()
  978. mock_session_factory = MagicMock()
  979. mock_session_ctx = AsyncMock()
  980. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  981. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  982. mock_session_factory.return_value = mock_session_ctx
  983. inst = VirtualPrinterInstance(
  984. vp_id=24,
  985. name="Variant",
  986. mode="queue",
  987. model="C12",
  988. access_code="12345678",
  989. serial_suffix="391800024",
  990. auto_dispatch=True,
  991. queue_force_color_match=True,
  992. base_dir=tmp_path,
  993. session_factory=mock_session_factory,
  994. )
  995. file_path = tmp_path / "variant.3mf"
  996. _write_3mf_with_filaments(
  997. file_path,
  998. [
  999. # White PLA Matte — same colour as Basic/Silk, distinguished only by idx.
  1000. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "10.0", "tray_info_idx": "GFA01"},
  1001. ],
  1002. plate_index=1,
  1003. )
  1004. with (
  1005. patch(
  1006. "backend.app.api.routes.settings.get_setting",
  1007. new_callable=AsyncMock,
  1008. return_value=None,
  1009. ),
  1010. ):
  1011. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1012. assert len(added_items) == 1
  1013. overrides = json.loads(added_items[0].filament_overrides)
  1014. assert overrides == [
  1015. {"slot_id": 1, "type": "PLA", "color": "#FFFFFF", "tray_info_idx": "GFA01", "force_color_match": True},
  1016. ]
  1017. @pytest.mark.asyncio
  1018. async def test_add_to_print_queue_force_color_match_skips_when_3mf_unparseable(self, tmp_path):
  1019. """A malformed or fake-bytes 3MF must not crash the upload path —
  1020. we just write the queue item with no filament fields and let the
  1021. scheduler fall back to model-only matching (the pre-#1188 default).
  1022. Regression guard for the existing fake-bytes happy-path tests."""
  1023. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1024. added_items = []
  1025. mock_db = AsyncMock()
  1026. mock_db.add = MagicMock(side_effect=added_items.append)
  1027. mock_db.commit = AsyncMock()
  1028. mock_session_factory = MagicMock()
  1029. mock_session_ctx = AsyncMock()
  1030. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1031. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1032. mock_session_factory.return_value = mock_session_ctx
  1033. inst = VirtualPrinterInstance(
  1034. vp_id=23,
  1035. name="Unparseable",
  1036. mode="queue",
  1037. model="C12",
  1038. access_code="12345678",
  1039. serial_suffix="391800023",
  1040. auto_dispatch=True,
  1041. queue_force_color_match=True,
  1042. base_dir=tmp_path,
  1043. session_factory=mock_session_factory,
  1044. )
  1045. file_path = tmp_path / "bad.3mf"
  1046. file_path.write_bytes(b"not a real 3mf zip")
  1047. with (
  1048. patch(
  1049. "backend.app.api.routes.settings.get_setting",
  1050. new_callable=AsyncMock,
  1051. return_value=None,
  1052. ),
  1053. ):
  1054. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1055. assert len(added_items) == 1
  1056. queue_item = added_items[0]
  1057. # No filament data extractable → both fields stay None (graceful
  1058. # fallback to model-only scheduling).
  1059. assert queue_item.required_filament_types is None
  1060. assert queue_item.filament_overrides is None
  1061. # ========================================================================
  1062. # Tests for archive_name_source setting (#1152)
  1063. # ========================================================================
  1064. # ========================================================================
  1065. # Tests for failure-path cleanup (#audit-R2-1)
  1066. # ========================================================================
  1067. #
  1068. # All three file handlers (_store_in_library, _queue_file, _add_to_print_queue)
  1069. # previously only popped _pending_files and unlinked the temp file on the
  1070. # success branch. Failure paths leaked the marker (blocking same-name
  1071. # retries via the FTP layer) and the temp file on disk. The cleanup must
  1072. # ALWAYS run, even when archival / queue insert raises.
  1073. @pytest.mark.asyncio
  1074. async def test_store_in_library_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1075. """When storing in the File Manager raises, `_pending_files[filename]` must still
  1076. be popped and the temp file must be unlinked. Otherwise the FTP layer's
  1077. same-name retry guard would silently reject the slicer's next attempt
  1078. and the upload_dir would accumulate ghost files."""
  1079. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1080. mock_db = AsyncMock()
  1081. mock_session_factory = MagicMock()
  1082. mock_session_ctx = AsyncMock()
  1083. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1084. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1085. mock_session_factory.return_value = mock_session_ctx
  1086. inst = VirtualPrinterInstance(
  1087. vp_id=40,
  1088. name="LibraryFailCleanup",
  1089. mode="library",
  1090. model="C12",
  1091. access_code="12345678",
  1092. serial_suffix="391800040",
  1093. base_dir=tmp_path,
  1094. session_factory=mock_session_factory,
  1095. )
  1096. file_path = tmp_path / "cleanup-archive.3mf"
  1097. file_path.write_bytes(b"fake3mf")
  1098. inst._pending_files[file_path.name] = file_path
  1099. with patch(
  1100. "backend.app.services.virtual_printer.library_store.store_upload",
  1101. new_callable=AsyncMock,
  1102. side_effect=RuntimeError("store blew up"),
  1103. ):
  1104. await inst._store_in_library(file_path, "192.168.1.100")
  1105. assert file_path.name not in inst._pending_files
  1106. assert not file_path.exists()
  1107. @pytest.mark.asyncio
  1108. async def test_queue_file_records_the_virtual_printer(self, tmp_path):
  1109. """Review mode: the pending upload names the VP it came in on, so
  1110. approving it stores the file in that VP's File Manager folder."""
  1111. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1112. added = []
  1113. mock_db = AsyncMock()
  1114. mock_db.add = MagicMock(side_effect=added.append)
  1115. mock_session_ctx = AsyncMock()
  1116. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1117. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1118. inst = VirtualPrinterInstance(
  1119. vp_id=42,
  1120. name="Review",
  1121. mode="review",
  1122. model="C12",
  1123. access_code="12345678",
  1124. serial_suffix="391800042",
  1125. base_dir=tmp_path,
  1126. session_factory=MagicMock(return_value=mock_session_ctx),
  1127. )
  1128. file_path = tmp_path / "review.3mf"
  1129. file_path.write_bytes(b"fake3mf")
  1130. await inst._queue_file(file_path, "192.168.1.100")
  1131. assert len(added) == 1
  1132. assert added[0].virtual_printer_id == 42
  1133. assert file_path.exists(), "the file waits for the review"
  1134. @pytest.mark.asyncio
  1135. async def test_queue_file_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1136. """Same invariant for _queue_file: a DB error during PendingUpload
  1137. insert must not leak the in-flight marker or the temp file."""
  1138. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1139. mock_db = AsyncMock()
  1140. # Commit raises — emulating a DB connectivity error.
  1141. mock_db.add = MagicMock()
  1142. mock_db.commit = AsyncMock(side_effect=RuntimeError("db unreachable"))
  1143. mock_session_factory = MagicMock()
  1144. mock_session_ctx = AsyncMock()
  1145. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1146. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1147. mock_session_factory.return_value = mock_session_ctx
  1148. inst = VirtualPrinterInstance(
  1149. vp_id=41,
  1150. name="QueueFailCleanup",
  1151. mode="review",
  1152. model="C12",
  1153. access_code="12345678",
  1154. serial_suffix="391800041",
  1155. base_dir=tmp_path,
  1156. session_factory=mock_session_factory,
  1157. )
  1158. file_path = tmp_path / "cleanup-queue.3mf"
  1159. file_path.write_bytes(b"fake3mf")
  1160. inst._pending_files[file_path.name] = file_path
  1161. await inst._queue_file(file_path, "192.168.1.100")
  1162. assert file_path.name not in inst._pending_files
  1163. assert not file_path.exists()
  1164. @pytest.mark.asyncio
  1165. async def test_add_to_print_queue_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1166. """Same invariant for _add_to_print_queue: a DB error or archive
  1167. failure must not leak the in-flight marker or the temp file."""
  1168. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1169. mock_db = AsyncMock()
  1170. mock_db.add = MagicMock()
  1171. mock_db.commit = AsyncMock()
  1172. mock_db.execute = AsyncMock(side_effect=RuntimeError("queue insert blew up"))
  1173. mock_session_factory = MagicMock()
  1174. mock_session_ctx = AsyncMock()
  1175. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1176. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1177. mock_session_factory.return_value = mock_session_ctx
  1178. inst = VirtualPrinterInstance(
  1179. vp_id=42,
  1180. name="DispatchFailCleanup",
  1181. mode="queue",
  1182. model="C12",
  1183. access_code="12345678",
  1184. serial_suffix="391800042",
  1185. auto_dispatch=True,
  1186. base_dir=tmp_path,
  1187. session_factory=mock_session_factory,
  1188. )
  1189. file_path = tmp_path / "cleanup-dispatch.3mf"
  1190. file_path.write_bytes(b"fake3mf")
  1191. inst._pending_files[file_path.name] = file_path
  1192. with patch(
  1193. "backend.app.api.routes.settings.get_setting",
  1194. new_callable=AsyncMock,
  1195. return_value=None,
  1196. ):
  1197. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1198. assert file_path.name not in inst._pending_files
  1199. assert not file_path.exists()
  1200. # ========================================================================
  1201. # Test for position=MAX+1 (audit-R2)
  1202. # ========================================================================
  1203. @pytest.mark.asyncio
  1204. async def test_add_to_print_queue_position_picks_max_plus_one(self, tmp_path):
  1205. """VP-queue items previously got hardcoded `position=1`, colliding
  1206. with existing items at position 1 and producing non-deterministic
  1207. execution order. Now the position is chosen by `MAX(position)+1`
  1208. against the target queue, matching the canonical `POST /print-queue/`
  1209. path."""
  1210. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1211. # Capture the inserted PrintQueueItem so we can assert on .position.
  1212. added_items: list = []
  1213. class _RecordingDb:
  1214. def __init__(self):
  1215. self.add = lambda item: added_items.append(item)
  1216. self.commit = AsyncMock()
  1217. async def execute(self, query): # noqa: ARG002
  1218. """Return a stub result whose `.scalar()` reports the existing
  1219. MAX(position) for the target. Returning 7 means the new item
  1220. should land at 8."""
  1221. result = MagicMock()
  1222. result.scalar = MagicMock(return_value=7)
  1223. return result
  1224. mock_db = _RecordingDb()
  1225. mock_session_factory = MagicMock()
  1226. mock_session_ctx = AsyncMock()
  1227. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1228. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1229. mock_session_factory.return_value = mock_session_ctx
  1230. inst = VirtualPrinterInstance(
  1231. vp_id=43,
  1232. name="PositionMaxPlusOne",
  1233. mode="queue",
  1234. model="C12",
  1235. access_code="12345678",
  1236. serial_suffix="391800043",
  1237. target_printer_id=99,
  1238. auto_dispatch=True,
  1239. base_dir=tmp_path,
  1240. session_factory=mock_session_factory,
  1241. )
  1242. file_path = tmp_path / "next-position.3mf"
  1243. file_path.write_bytes(b"fake3mf")
  1244. with (
  1245. patch(
  1246. "backend.app.api.routes.settings.get_setting",
  1247. new_callable=AsyncMock,
  1248. return_value=None,
  1249. ),
  1250. patch(
  1251. "backend.app.core.websocket.ws_manager.send_library_files_changed",
  1252. new_callable=AsyncMock,
  1253. ),
  1254. ):
  1255. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1256. # One queue item was added.
  1257. assert len(added_items) == 1
  1258. queue_item = added_items[0]
  1259. # Position = max(7) + 1 = 8 — NOT the legacy hardcoded 1.
  1260. assert queue_item.position == 8
  1261. @pytest.mark.asyncio
  1262. async def test_add_to_print_queue_multi_plate_send_all_enqueues_one_per_plate(self, tmp_path):
  1263. """#1733: BambuStudio / OrcaSlicer "Send All" of a multi-plate project
  1264. uploads ONE 3MF containing every plate. Pre-fix only the first plate
  1265. index was extracted and one queue item was created; plates 2..N were
  1266. silently dropped. Post-fix every `<plate>` block in `slice_info.config`
  1267. produces its own PrintQueueItem with the correct ``plate_id``, sharing
  1268. the same backing archive, with consecutive positions for plate-order
  1269. execution.
  1270. """
  1271. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1272. added_items: list = []
  1273. class _RecordingDb:
  1274. def __init__(self):
  1275. # Capture inserted items as they're added; assign a fake .id
  1276. # on flush so the manager's logger doesn't see None.
  1277. self._next_id = 1000
  1278. def _add(item):
  1279. added_items.append(item)
  1280. self.add = _add
  1281. self.commit = AsyncMock()
  1282. async def execute(self, query): # noqa: ARG002
  1283. """Return MAX(position) = 0 so plate items land at 1, 2, 3."""
  1284. result = MagicMock()
  1285. result.scalar = MagicMock(return_value=0)
  1286. return result
  1287. async def flush(self):
  1288. # Mimic the FK populate so queue_item.id is available after add().
  1289. for item in added_items:
  1290. if getattr(item, "id", None) is None:
  1291. item.id = self._next_id
  1292. self._next_id += 1
  1293. mock_db = _RecordingDb()
  1294. mock_session_factory = MagicMock()
  1295. mock_session_ctx = AsyncMock()
  1296. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1297. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1298. mock_session_factory.return_value = mock_session_ctx
  1299. inst = VirtualPrinterInstance(
  1300. vp_id=44,
  1301. name="MultiPlateSendAll",
  1302. mode="queue",
  1303. model="O1D", # H2D — matches the live VP H2D-1 Proxy in #1733
  1304. access_code="12345678",
  1305. serial_suffix="391800044",
  1306. target_printer_id=1,
  1307. auto_dispatch=False, # manual_start, mirrors the live VP
  1308. base_dir=tmp_path,
  1309. session_factory=mock_session_factory,
  1310. )
  1311. # Build a 3MF with three plates baked into slice_info.config —
  1312. # mirrors what BambuStudio / OrcaSlicer's "Send All" puts on the wire.
  1313. file_path = tmp_path / "Cube.gcode.3mf"
  1314. _write_3mf_with_filaments(
  1315. file_path, [{"id": 1, "type": "PLA", "color": "#000000", "used_g": "15.61"}], plate_index=1
  1316. )
  1317. # Append plate 2 and 3 blocks to slice_info.config to mimic Send All.
  1318. with zipfile.ZipFile(file_path, "r") as zf:
  1319. existing = zf.read("Metadata/slice_info.config").decode()
  1320. # Inject two additional <plate> blocks (indices 2 and 3) inside <config>.
  1321. multi_plate_config = existing.replace(
  1322. "</config>",
  1323. (
  1324. '<plate><metadata key="index" value="2"/>'
  1325. '<filament id="2" type="PETG" color="#FB0207" used_g="14.45"/>'
  1326. "</plate>"
  1327. '<plate><metadata key="index" value="3"/>'
  1328. '<filament id="3" type="PLA" color="#FFFFFF" used_g="12.10"/>'
  1329. "</plate>"
  1330. "</config>"
  1331. ),
  1332. )
  1333. # Repack the zip with the expanded slice_info.config.
  1334. import io as _io
  1335. buf = _io.BytesIO()
  1336. with zipfile.ZipFile(file_path, "r") as src, zipfile.ZipFile(buf, "w") as dst:
  1337. for name in src.namelist():
  1338. if name == "Metadata/slice_info.config":
  1339. dst.writestr(name, multi_plate_config)
  1340. else:
  1341. dst.writestr(name, src.read(name))
  1342. # Plate-2 and plate-3 gcode payloads so `extract_filament_requirements`
  1343. # has something to read for each — contents irrelevant, presence matters.
  1344. dst.writestr("Metadata/plate_2.gcode", "; plate 2 gcode\n")
  1345. dst.writestr("Metadata/plate_3.gcode", "; plate 3 gcode\n")
  1346. file_path.write_bytes(buf.getvalue())
  1347. with (
  1348. patch(
  1349. "backend.app.api.routes.settings.get_setting",
  1350. new_callable=AsyncMock,
  1351. return_value=None,
  1352. ),
  1353. patch(
  1354. "backend.app.core.websocket.ws_manager.send_library_files_changed",
  1355. new_callable=AsyncMock,
  1356. ),
  1357. ):
  1358. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1359. # Three queue items, one per plate, with the correct plate_id and
  1360. # consecutive positions starting at MAX(position)+1 = 1.
  1361. assert len(added_items) == 3, f"Expected 3 queue items for 3-plate Send All, got {len(added_items)}"
  1362. plate_ids = [q.plate_id for q in added_items]
  1363. assert plate_ids == [1, 2, 3], f"plate_ids should preserve slice_info order, got {plate_ids}"
  1364. positions = [q.position for q in added_items]
  1365. assert positions == [1, 2, 3], f"positions should be consecutive, got {positions}"
  1366. library_file_ids = {q.library_file_id for q in added_items}
  1367. assert library_file_ids == {1}, f"All queue items must print the one File Manager file, got {library_file_ids}"
  1368. assert {q.archive_id for q in added_items} == {None}, "the archive is made when a plate prints"
  1369. # auto_dispatch=False on the VP → every item is manual_start.
  1370. assert all(q.manual_start for q in added_items)
  1371. @pytest.mark.asyncio
  1372. async def test_add_to_print_queue_captures_nozzle_mapping(self, tmp_path):
  1373. """#1780: BambuStudio's project_file for H2C rack-swap (O1C2) sends
  1374. per-filament physical nozzle position IDs in `nozzle_mapping`. VP
  1375. intake must store it as a JSON string on the queue item so the
  1376. dispatcher can replay it. Without this the H2C firmware falls back
  1377. to "last matching nozzle" auto-pick and ignores the user's slicer
  1378. choice.
  1379. """
  1380. import json as _json
  1381. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1382. added_items = []
  1383. mock_db = AsyncMock()
  1384. mock_db.add = MagicMock(side_effect=added_items.append)
  1385. mock_db.commit = AsyncMock()
  1386. mock_session_factory = MagicMock()
  1387. mock_session_ctx = AsyncMock()
  1388. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1389. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1390. mock_session_factory.return_value = mock_session_ctx
  1391. inst = VirtualPrinterInstance(
  1392. # The slicer's nozzle positions are kept only for a VP bound to one printer.
  1393. target_printer_id=7,
  1394. vp_id=42,
  1395. name="H2CRack",
  1396. mode="queue",
  1397. model="O1C2",
  1398. access_code="12345678",
  1399. serial_suffix="391800042",
  1400. base_dir=tmp_path,
  1401. session_factory=mock_session_factory,
  1402. )
  1403. file_path = tmp_path / "test.3mf"
  1404. file_path.write_bytes(b"fake3mf")
  1405. # Pre-populate as if BS's project_file arrived. Wire shape matches
  1406. # BambuStudio's PrintJob params: nozzle_mapping = 32-entry array of
  1407. # per-filament physical nozzle position IDs (verified via H2C wire
  1408. # capture). The slicer-side `nozzles_info` field that the original
  1409. # #1780 attempt also looked for was never actually sent — it has
  1410. # been dropped from the capture path entirely.
  1411. await inst.on_print_command(
  1412. file_path.name,
  1413. {
  1414. "command": "project_file",
  1415. "nozzle_mapping": [16, -1, -1, 1, -1, -1, -1, -1],
  1416. },
  1417. )
  1418. with (
  1419. patch(
  1420. "backend.app.api.routes.settings.get_setting",
  1421. new_callable=AsyncMock,
  1422. return_value=None,
  1423. ),
  1424. ):
  1425. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1426. assert len(added_items) == 1
  1427. item = added_items[0]
  1428. assert item.nozzle_mapping is not None
  1429. assert _json.loads(item.nozzle_mapping) == [16, -1, -1, 1, -1, -1, -1, -1]
  1430. @pytest.mark.asyncio
  1431. async def test_add_to_print_queue_no_nozzle_mapping_when_slicer_omits(self, tmp_path):
  1432. """#1780: every model other than O1C2 sends no nozzle_mapping — the
  1433. queue item must carry NULL, not an empty list. NULL is what the
  1434. dispatch layer keys off of to skip the injection entirely on non-
  1435. rack-swap printers.
  1436. """
  1437. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1438. added_items = []
  1439. mock_db = AsyncMock()
  1440. mock_db.add = MagicMock(side_effect=added_items.append)
  1441. mock_db.commit = AsyncMock()
  1442. mock_session_factory = MagicMock()
  1443. mock_session_ctx = AsyncMock()
  1444. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1445. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1446. mock_session_factory.return_value = mock_session_ctx
  1447. inst = VirtualPrinterInstance(
  1448. vp_id=43,
  1449. name="NotH2C",
  1450. mode="queue",
  1451. model="C11",
  1452. access_code="12345678",
  1453. serial_suffix="391800043",
  1454. base_dir=tmp_path,
  1455. session_factory=mock_session_factory,
  1456. )
  1457. file_path = tmp_path / "test.3mf"
  1458. file_path.write_bytes(b"fake3mf")
  1459. # X1C-style slicer command — no nozzle fields.
  1460. await inst.on_print_command(
  1461. file_path.name,
  1462. {"command": "project_file", "timelapse": False, "bed_leveling": True},
  1463. )
  1464. with (
  1465. patch(
  1466. "backend.app.api.routes.settings.get_setting",
  1467. new_callable=AsyncMock,
  1468. return_value=None,
  1469. ),
  1470. ):
  1471. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1472. assert len(added_items) == 1
  1473. item = added_items[0]
  1474. assert item.nozzle_mapping is None
  1475. @pytest.mark.asyncio
  1476. async def test_add_to_print_queue_ignores_ams_mapping_when_toggle_off(self, tmp_path):
  1477. """With the per-VP `save_ams_mapping` toggle off, the slicer's
  1478. AMS-slot pick must be ignored entirely — neither stamped on the queue
  1479. item nor persisted to the archive.
  1480. Taking the slicer's pick makes `_ensure_ams_mapping` return early, so
  1481. `_compute_ams_mapping_for_printer` never runs — and that's where
  1482. `prefer_lowest_filament`, its AMS-filament-backup gate (#1766) and the
  1483. inventory-remain overrides live. Honouring it unconditionally would
  1484. retire all of that for every existing queue-mode VP on upgrade, so it
  1485. is opt-in like every other queue-mode behaviour toggle (#2700 review).
  1486. """
  1487. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1488. added_items = []
  1489. mock_db = AsyncMock()
  1490. mock_db.add = MagicMock(side_effect=added_items.append)
  1491. mock_db.commit = AsyncMock()
  1492. mock_session_factory = MagicMock()
  1493. mock_session_ctx = AsyncMock()
  1494. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1495. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1496. mock_session_factory.return_value = mock_session_ctx
  1497. inst = VirtualPrinterInstance(
  1498. vp_id=44,
  1499. name="AMSMappingOff",
  1500. mode="queue",
  1501. model="X1C",
  1502. access_code="12345678",
  1503. serial_suffix="391800044",
  1504. base_dir=tmp_path,
  1505. session_factory=mock_session_factory,
  1506. save_ams_mapping=False,
  1507. target_printer_id=7,
  1508. )
  1509. file_path = tmp_path / "test.3mf"
  1510. file_path.write_bytes(b"fake3mf")
  1511. await inst.on_print_command(
  1512. file_path.name,
  1513. {"command": "project_file", "ams_mapping": [4, -1, 12, -1]},
  1514. )
  1515. with (
  1516. patch(
  1517. "backend.app.api.routes.settings.get_setting",
  1518. new_callable=AsyncMock,
  1519. return_value=None,
  1520. ),
  1521. ):
  1522. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1523. assert len(added_items) == 1
  1524. assert added_items[0].ams_mapping is None
  1525. assert added_items[0].slicer_ams_mapping is None
  1526. @pytest.mark.asyncio
  1527. async def test_add_to_print_queue_persists_ams_mapping_to_archive_when_toggle_on(self, tmp_path):
  1528. """With the per-VP `save_ams_mapping` toggle on, the slicer's AMS
  1529. pick must also be kept on the queue item, so the archive its print
  1530. creates gets it as `extra_data.slicer_ams_mapping` and a later
  1531. reprint can reuse the exact physical spool.
  1532. """
  1533. import json as _json
  1534. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1535. added_items = []
  1536. mock_db = AsyncMock()
  1537. mock_db.add = MagicMock(side_effect=added_items.append)
  1538. mock_db.commit = AsyncMock()
  1539. mock_session_factory = MagicMock()
  1540. mock_session_ctx = AsyncMock()
  1541. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1542. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1543. mock_session_factory.return_value = mock_session_ctx
  1544. inst = VirtualPrinterInstance(
  1545. vp_id=45,
  1546. name="AMSMappingOn",
  1547. mode="queue",
  1548. model="X1C",
  1549. access_code="12345678",
  1550. serial_suffix="391800045",
  1551. base_dir=tmp_path,
  1552. session_factory=mock_session_factory,
  1553. save_ams_mapping=True,
  1554. target_printer_id=7,
  1555. )
  1556. file_path = tmp_path / "test.3mf"
  1557. file_path.write_bytes(b"fake3mf")
  1558. await inst.on_print_command(
  1559. file_path.name,
  1560. {"command": "project_file", "ams_mapping": [4, -1, 12, -1]},
  1561. )
  1562. with (
  1563. patch(
  1564. "backend.app.api.routes.settings.get_setting",
  1565. new_callable=AsyncMock,
  1566. return_value=None,
  1567. ),
  1568. ):
  1569. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1570. assert len(added_items) == 1
  1571. assert _json.loads(added_items[0].ams_mapping) == [4, -1, 12, -1]
  1572. assert json.loads(added_items[0].slicer_ams_mapping) == {"mapping": [4, -1, 12, -1], "printer_id": 7}
  1573. assert added_items[0].printer_id == 7 # the printer the pick was made against
  1574. @pytest.mark.asyncio
  1575. async def test_add_to_print_queue_ignores_ams_mapping_for_model_based_vp(self, tmp_path):
  1576. """A model-based VP (`target_printer_id=None`, dispatched later by the
  1577. scheduler to whichever printer matches) has no MQTT bridge to a real
  1578. printer, so the slicer has no live AMS layout to resolve tray IDs
  1579. against. Whatever it sends must be ignored on both the queue item and
  1580. the archive — trusting it would dispatch the eventually-chosen
  1581. printer onto a tray resolved against nothing (#2700 review).
  1582. """
  1583. import json as _json
  1584. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1585. added_items = []
  1586. mock_db = AsyncMock()
  1587. mock_db.add = MagicMock(side_effect=added_items.append)
  1588. mock_db.commit = AsyncMock()
  1589. mock_session_factory = MagicMock()
  1590. mock_session_ctx = AsyncMock()
  1591. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1592. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1593. mock_session_factory.return_value = mock_session_ctx
  1594. inst = VirtualPrinterInstance(
  1595. vp_id=451,
  1596. name="AMSMappingModelBased",
  1597. mode="queue",
  1598. model="X1C",
  1599. access_code="12345678",
  1600. serial_suffix="391800451",
  1601. base_dir=tmp_path,
  1602. session_factory=mock_session_factory,
  1603. save_ams_mapping=True,
  1604. target_printer_id=None,
  1605. )
  1606. file_path = tmp_path / "test.3mf"
  1607. file_path.write_bytes(b"fake3mf")
  1608. await inst.on_print_command(
  1609. file_path.name,
  1610. {"command": "project_file", "ams_mapping": [4, -1, 12, -1]},
  1611. )
  1612. with (
  1613. patch(
  1614. "backend.app.api.routes.settings.get_setting",
  1615. new_callable=AsyncMock,
  1616. return_value=None,
  1617. ),
  1618. ):
  1619. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1620. assert len(added_items) == 1
  1621. assert added_items[0].ams_mapping is None
  1622. assert added_items[0].slicer_ams_mapping is None
  1623. @pytest.mark.asyncio
  1624. async def test_add_to_print_queue_ignores_unresolved_ams_mapping_sentinel(self, tmp_path):
  1625. """#2589: an all -1 `ams_mapping` means the slicer's own race lost —
  1626. every slot unresolved. Must be dropped (queue item AND archive),
  1627. never trusted over a fresh scheduler-computed mapping.
  1628. """
  1629. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1630. added_items = []
  1631. mock_db = AsyncMock()
  1632. mock_db.add = MagicMock(side_effect=added_items.append)
  1633. mock_db.commit = AsyncMock()
  1634. mock_session_factory = MagicMock()
  1635. mock_session_ctx = AsyncMock()
  1636. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1637. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1638. mock_session_factory.return_value = mock_session_ctx
  1639. inst = VirtualPrinterInstance(
  1640. vp_id=46,
  1641. name="AMSMappingSentinel",
  1642. mode="queue",
  1643. model="X1C",
  1644. access_code="12345678",
  1645. serial_suffix="391800046",
  1646. base_dir=tmp_path,
  1647. session_factory=mock_session_factory,
  1648. save_ams_mapping=True,
  1649. target_printer_id=7,
  1650. )
  1651. file_path = tmp_path / "test.3mf"
  1652. file_path.write_bytes(b"fake3mf")
  1653. await inst.on_print_command(
  1654. file_path.name,
  1655. {"command": "project_file", "ams_mapping": [-1, -1, -1, -1]},
  1656. )
  1657. with (
  1658. patch(
  1659. "backend.app.api.routes.settings.get_setting",
  1660. new_callable=AsyncMock,
  1661. return_value=None,
  1662. ),
  1663. ):
  1664. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1665. assert len(added_items) == 1
  1666. assert added_items[0].ams_mapping is None
  1667. assert added_items[0].slicer_ams_mapping is None
  1668. @pytest.mark.asyncio
  1669. async def test_add_to_print_queue_force_color_match_keeps_mapping_off_the_queue_item(self, tmp_path):
  1670. """`Force color match` and `Save AMS mapping` both on: the archive
  1671. still gets the slicer's pick (that's what the toggle promises for
  1672. later reprints), but THIS dispatch does not.
  1673. Force color match's only effect on a fixed-printer item is via the
  1674. per-slot `filament_overrides`, which are consumed inside
  1675. `_compute_ams_mapping_for_printer` — the exact function a stored
  1676. mapping makes `_ensure_ams_mapping` skip. Leaving the mapping on the
  1677. item would silently retire the user's explicit strictness (#2700
  1678. review).
  1679. """
  1680. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1681. added_items = []
  1682. mock_db = AsyncMock()
  1683. mock_db.add = MagicMock(side_effect=added_items.append)
  1684. mock_db.flush = AsyncMock()
  1685. mock_db.commit = AsyncMock()
  1686. mock_session_factory = MagicMock()
  1687. mock_session_ctx = AsyncMock()
  1688. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1689. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1690. mock_session_factory.return_value = mock_session_ctx
  1691. inst = VirtualPrinterInstance(
  1692. vp_id=47,
  1693. name="AMSMappingVsForceColor",
  1694. mode="queue",
  1695. model="X1C",
  1696. access_code="12345678",
  1697. serial_suffix="391800047",
  1698. base_dir=tmp_path,
  1699. session_factory=mock_session_factory,
  1700. save_ams_mapping=True,
  1701. queue_force_color_match=True,
  1702. target_printer_id=7,
  1703. )
  1704. file_path = tmp_path / "test.3mf"
  1705. file_path.write_bytes(b"fake3mf")
  1706. await inst.on_print_command(
  1707. file_path.name,
  1708. {"command": "project_file", "ams_mapping": [4, -1, 12, -1]},
  1709. )
  1710. with (
  1711. patch(
  1712. "backend.app.api.routes.settings.get_setting",
  1713. new_callable=AsyncMock,
  1714. return_value=None,
  1715. ),
  1716. ):
  1717. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1718. assert len(added_items) == 1
  1719. assert added_items[0].ams_mapping is None
  1720. assert json.loads(added_items[0].slicer_ams_mapping) == {"mapping": [4, -1, 12, -1], "printer_id": 7}
  1721. assert added_items[0].printer_id == 7 # the printer the pick was made against
  1722. @pytest.mark.asyncio
  1723. async def test_add_to_print_queue_drops_ams_mapping_too_short_for_the_plate(self, tmp_path, monkeypatch):
  1724. """A slicer mapping shorter than the plate's highest slot id can't
  1725. address that plate's own slots, and `_ensure_ams_mapping` would keep it
  1726. anyway (it only rejects an all-unresolved mapping). Drop it for that
  1727. plate so the scheduler computes one from live AMS state instead.
  1728. The mapping is indexed by the 3MF's file-global slot ids, so the plate
  1729. that fits keeps it — only the one that doesn't falls back (#2700
  1730. review).
  1731. """
  1732. import json as _json
  1733. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1734. added_items = []
  1735. mock_db = AsyncMock()
  1736. mock_db.add = MagicMock(side_effect=added_items.append)
  1737. mock_db.flush = AsyncMock()
  1738. mock_db.commit = AsyncMock()
  1739. mock_db.execute = AsyncMock()
  1740. mock_db.execute.return_value.scalar.return_value = None
  1741. mock_session_factory = MagicMock()
  1742. mock_session_ctx = AsyncMock()
  1743. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1744. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1745. mock_session_factory.return_value = mock_session_ctx
  1746. inst = VirtualPrinterInstance(
  1747. vp_id=48,
  1748. name="AMSMappingShort",
  1749. mode="queue",
  1750. model="X1C",
  1751. access_code="12345678",
  1752. serial_suffix="391800048",
  1753. base_dir=tmp_path,
  1754. session_factory=mock_session_factory,
  1755. save_ams_mapping=True,
  1756. target_printer_id=7,
  1757. )
  1758. file_path = tmp_path / "test.3mf"
  1759. file_path.write_bytes(b"fake3mf")
  1760. monkeypatch.setattr(inst, "_extract_plate_ids", lambda _p: [1, 2])
  1761. # Plate 1 prints slots 1-2 (fits the 2-entry mapping); plate 2 also
  1762. # prints slot 4, which the mapping cannot address.
  1763. def fake_reqs(_path, plate_id):
  1764. if plate_id == 1:
  1765. return [
  1766. {"slot_id": 1, "type": "PLA", "color": "#FF0000"},
  1767. {"slot_id": 2, "type": "PLA", "color": "#00FF00"},
  1768. ]
  1769. return [
  1770. {"slot_id": 1, "type": "PLA", "color": "#FF0000"},
  1771. {"slot_id": 4, "type": "PLA", "color": "#0000FF"},
  1772. ]
  1773. monkeypatch.setattr(
  1774. "backend.app.services.filament_requirements.extract_filament_requirements",
  1775. fake_reqs,
  1776. )
  1777. await inst.on_print_command(
  1778. file_path.name,
  1779. {"command": "project_file", "ams_mapping": [4, 12]},
  1780. )
  1781. with (
  1782. patch(
  1783. "backend.app.api.routes.settings.get_setting",
  1784. new_callable=AsyncMock,
  1785. return_value=None,
  1786. ),
  1787. ):
  1788. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1789. assert len(added_items) == 2
  1790. assert _json.loads(added_items[0].ams_mapping) == [4, 12]
  1791. assert added_items[1].ams_mapping is None
  1792. # The archive keeps the mapping either way — it is the file's, not one
  1793. # plate's, and a reprint of the plate that fits still wants it.
  1794. assert json.loads(added_items[0].slicer_ams_mapping)["mapping"] == [4, 12]
  1795. @pytest.mark.asyncio
  1796. async def test_add_to_print_queue_nozzle_pick_replicated_across_plates(self, tmp_path, monkeypatch):
  1797. """#1780 × #1697/#1188: a multi-plate Send All from BS must stamp the
  1798. same nozzle_mapping on every plate's queue item, not only the first.
  1799. Mirrors the per-plate stamping for gcode_injection,
  1800. filament_overrides, etc.
  1801. """
  1802. import json as _json
  1803. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1804. added_items = []
  1805. mock_db = AsyncMock()
  1806. mock_db.add = MagicMock(side_effect=added_items.append)
  1807. mock_db.flush = AsyncMock()
  1808. mock_db.commit = AsyncMock()
  1809. mock_db.execute = AsyncMock()
  1810. mock_db.execute.return_value.scalar.return_value = None
  1811. mock_session_factory = MagicMock()
  1812. mock_session_ctx = AsyncMock()
  1813. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1814. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1815. mock_session_factory.return_value = mock_session_ctx
  1816. inst = VirtualPrinterInstance(
  1817. # The slicer's nozzle positions are kept only for a VP bound to one printer.
  1818. target_printer_id=7,
  1819. vp_id=44,
  1820. name="H2CMultiPlate",
  1821. mode="queue",
  1822. model="O1C2",
  1823. access_code="12345678",
  1824. serial_suffix="391800044",
  1825. base_dir=tmp_path,
  1826. session_factory=mock_session_factory,
  1827. )
  1828. file_path = tmp_path / "test.3mf"
  1829. file_path.write_bytes(b"fake3mf")
  1830. # Force 3 plates so the queue loop runs three times.
  1831. monkeypatch.setattr(inst, "_extract_plate_ids", lambda _p: [1, 2, 3])
  1832. await inst.on_print_command(
  1833. file_path.name,
  1834. {
  1835. "command": "project_file",
  1836. "nozzle_mapping": [16, 0],
  1837. },
  1838. )
  1839. with (
  1840. patch(
  1841. "backend.app.api.routes.settings.get_setting",
  1842. new_callable=AsyncMock,
  1843. return_value=None,
  1844. ),
  1845. ):
  1846. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1847. assert len(added_items) == 3
  1848. for item in added_items:
  1849. assert _json.loads(item.nozzle_mapping) == [16, 0]
  1850. @pytest.mark.asyncio
  1851. async def test_on_print_command_late_mqtt_retroactively_stamps_queue_item(self, tmp_path):
  1852. """#1780 round 3: Bambu Studio's MQTT project_file can arrive AFTER
  1853. `_add_to_print_queue` already gave up waiting (observed at 2.085 s
  1854. on H2C wireless setups). The queue item was committed with settings
  1855. defaults; the slicer's nozzle_mapping + workflow flags must be
  1856. patched onto it when MQTT lands, otherwise the H2C firmware falls
  1857. back to auto-pick.
  1858. """
  1859. import json as _json
  1860. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1861. added_items: list = []
  1862. mock_db = AsyncMock()
  1863. mock_db.add = MagicMock(
  1864. side_effect=lambda item: (added_items.append(item), setattr(item, "id", 100 + len(added_items)))[0]
  1865. )
  1866. async def _flush():
  1867. # added_items[-1].id was set by `add`; nothing else to do.
  1868. return None
  1869. mock_db.flush = AsyncMock(side_effect=_flush)
  1870. mock_db.commit = AsyncMock()
  1871. # First execute() call (the position-max SELECT inside _add_to_print_queue)
  1872. # returns None; second (the eligible-pending SELECT in
  1873. # _restamp_recent_queue_item) returns the committed queue id; third
  1874. # (the UPDATE) is fire-and-forget.
  1875. position_max_result = MagicMock()
  1876. position_max_result.scalar = MagicMock(return_value=None)
  1877. select_pending_result = MagicMock()
  1878. select_pending_result.all = MagicMock(return_value=[(101, None, None)])
  1879. update_result = MagicMock()
  1880. mock_db.execute = AsyncMock(side_effect=[position_max_result, select_pending_result, update_result])
  1881. mock_session_factory = MagicMock()
  1882. mock_session_ctx = AsyncMock()
  1883. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1884. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1885. mock_session_factory.return_value = mock_session_ctx
  1886. inst = VirtualPrinterInstance(
  1887. # The slicer's nozzle positions are kept only for a VP bound to one printer.
  1888. target_printer_id=7,
  1889. vp_id=99,
  1890. name="LateMQTT",
  1891. mode="queue",
  1892. model="O1C2",
  1893. access_code="12345678",
  1894. serial_suffix="391800099",
  1895. base_dir=tmp_path,
  1896. session_factory=mock_session_factory,
  1897. )
  1898. # MQTT server presence enables the wait_for path; we don't actually
  1899. # use any methods on it.
  1900. inst._mqtt = MagicMock()
  1901. file_path = tmp_path / "test.3mf"
  1902. file_path.write_bytes(b"fake3mf")
  1903. # 1. _add_to_print_queue runs WITHOUT a prior on_print_command —
  1904. # the wait_for times out (settings-default fallback) and the
  1905. # queue item is committed.
  1906. with (
  1907. patch(
  1908. "backend.app.api.routes.settings.get_setting",
  1909. new_callable=AsyncMock,
  1910. return_value=None,
  1911. ),
  1912. # Shorten the wait so the test isn't slow.
  1913. patch(
  1914. "backend.app.services.virtual_printer.manager._SLICER_OPTIONS_WAIT_TIMEOUT",
  1915. 0.05,
  1916. ),
  1917. ):
  1918. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1919. assert len(added_items) == 1
  1920. assert added_items[0].nozzle_mapping is None # MQTT was never received
  1921. assert file_path.name in inst._recent_queue_items
  1922. # 2. MQTT project_file arrives AFTER the wait expired — must
  1923. # retroactively patch the queue item.
  1924. await inst.on_print_command(
  1925. file_path.name,
  1926. {
  1927. "command": "project_file",
  1928. "file": file_path.name,
  1929. "nozzle_mapping": [16, -1, -1, 1],
  1930. "timelapse": True,
  1931. "bed_leveling": False,
  1932. },
  1933. )
  1934. # The UPDATE call is the third execute. Inspect its values.
  1935. update_call = mock_db.execute.await_args_list[2]
  1936. update_stmt = update_call.args[0]
  1937. compiled = update_stmt.compile(compile_kwargs={"literal_binds": False})
  1938. params = dict(compiled.params)
  1939. assert _json.loads(params["nozzle_mapping"]) == [16, -1, -1, 1]
  1940. assert params["timelapse"] is True
  1941. assert params["bed_levelling"] == "off" # MQTT bed_leveling → column bed_levelling (tri-state)
  1942. # Recent-queue tracking dict is cleared after the patch.
  1943. assert file_path.name not in inst._recent_queue_items
  1944. @pytest.mark.asyncio
  1945. async def test_on_print_command_late_mqtt_retroactively_stamps_archive_ams_mapping(self, tmp_path):
  1946. """Same #1780-round-3 race as the test above, but for `ams_mapping`
  1947. specifically: the archive was already created (with no
  1948. `slicer_ams_mapping`, since the slicer's pick hadn't arrived yet)
  1949. before this late MQTT lands. With the toggle on and a fixed target
  1950. printer, the archive must be retroactively patched too — otherwise a
  1951. reprint from this archive would never see the badge or the Mapping
  1952. button, even though the queue item itself dispatches correctly.
  1953. """
  1954. import json as _json
  1955. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1956. added_items: list = []
  1957. mock_db = AsyncMock()
  1958. mock_db.add = MagicMock(
  1959. side_effect=lambda item: (added_items.append(item), setattr(item, "id", 100 + len(added_items)))[0]
  1960. )
  1961. mock_db.flush = AsyncMock()
  1962. mock_db.commit = AsyncMock()
  1963. mock_archive_row = MagicMock()
  1964. mock_archive_row.id = 55
  1965. mock_archive_row.extra_data = None
  1966. position_max_result = MagicMock()
  1967. position_max_result.scalar = MagicMock(return_value=None)
  1968. select_pending_result = MagicMock()
  1969. # (queue_item_id, archive_id) — matches the id set by db.add above.
  1970. select_pending_result.all = MagicMock(return_value=[(101, 55, None)])
  1971. update_result = MagicMock()
  1972. select_archives_result = MagicMock()
  1973. select_archives_result.scalars = MagicMock(
  1974. return_value=MagicMock(all=MagicMock(return_value=[mock_archive_row]))
  1975. )
  1976. mock_db.execute = AsyncMock(
  1977. side_effect=[
  1978. position_max_result,
  1979. select_pending_result,
  1980. update_result,
  1981. update_result,
  1982. select_archives_result,
  1983. ]
  1984. )
  1985. mock_session_factory = MagicMock()
  1986. mock_session_ctx = AsyncMock()
  1987. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1988. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1989. mock_session_factory.return_value = mock_session_ctx
  1990. inst = VirtualPrinterInstance(
  1991. vp_id=98,
  1992. name="LateMQTTArchivePatch",
  1993. mode="queue",
  1994. model="X1C",
  1995. access_code="12345678",
  1996. serial_suffix="391800098",
  1997. base_dir=tmp_path,
  1998. session_factory=mock_session_factory,
  1999. save_ams_mapping=True,
  2000. target_printer_id=7,
  2001. )
  2002. inst._mqtt = MagicMock()
  2003. file_path = tmp_path / "test.3mf"
  2004. file_path.write_bytes(b"fake3mf")
  2005. with (
  2006. patch(
  2007. "backend.app.api.routes.settings.get_setting",
  2008. new_callable=AsyncMock,
  2009. return_value=None,
  2010. ),
  2011. patch(
  2012. "backend.app.services.virtual_printer.manager._SLICER_OPTIONS_WAIT_TIMEOUT",
  2013. 0.05,
  2014. ),
  2015. ):
  2016. await inst._add_to_print_queue(file_path, "192.168.1.100")
  2017. assert len(added_items) == 1
  2018. assert added_items[0].ams_mapping is None # MQTT was never received in time
  2019. # MQTT project_file arrives late, carrying the slicer's AMS pick.
  2020. await inst.on_print_command(
  2021. file_path.name,
  2022. {
  2023. "command": "project_file",
  2024. "file": file_path.name,
  2025. "ams_mapping": [4, -1, 12, -1],
  2026. },
  2027. )
  2028. # 3rd execute() is the queue-item UPDATE, 4th keeps the pick on the
  2029. # item for its archive, 5th is the SELECT of archives already made.
  2030. update_call = mock_db.execute.await_args_list[2]
  2031. compiled = update_call.args[0].compile(compile_kwargs={"literal_binds": False})
  2032. assert _json.loads(dict(compiled.params)["ams_mapping"]) == [4, -1, 12, -1]
  2033. kept = mock_db.execute.await_args_list[3].args[0].compile(compile_kwargs={"literal_binds": False})
  2034. assert _json.loads(dict(kept.params)["slicer_ams_mapping"]) == {"mapping": [4, -1, 12, -1], "printer_id": 7}
  2035. assert mock_archive_row.extra_data == {
  2036. "slicer_ams_mapping": {"mapping": [4, -1, 12, -1], "printer_id": 7},
  2037. }
  2038. @pytest.mark.asyncio
  2039. async def test_on_print_command_late_mqtt_skips_archive_patch_for_model_based_vp(self, tmp_path):
  2040. """The archive patch above must not fire for a model-based VP
  2041. (`target_printer_id=None`) either — same rationale as the immediate
  2042. path: no fixed printer means no live AMS layout to have resolved the
  2043. late mapping against.
  2044. """
  2045. import json as _json
  2046. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2047. added_items: list = []
  2048. mock_db = AsyncMock()
  2049. mock_db.add = MagicMock(
  2050. side_effect=lambda item: (added_items.append(item), setattr(item, "id", 200 + len(added_items)))[0]
  2051. )
  2052. mock_db.flush = AsyncMock()
  2053. mock_db.commit = AsyncMock()
  2054. position_max_result = MagicMock()
  2055. position_max_result.scalar = MagicMock(return_value=None)
  2056. select_pending_result = MagicMock()
  2057. select_pending_result.all = MagicMock(return_value=[(201, 65, None)])
  2058. update_result = MagicMock()
  2059. # No 4th execute() expected — the archive patch must be skipped
  2060. # entirely, so only 3 calls should ever happen.
  2061. mock_db.execute = AsyncMock(side_effect=[position_max_result, select_pending_result, update_result])
  2062. mock_session_factory = MagicMock()
  2063. mock_session_ctx = AsyncMock()
  2064. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  2065. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  2066. mock_session_factory.return_value = mock_session_ctx
  2067. inst = VirtualPrinterInstance(
  2068. vp_id=97,
  2069. name="LateMQTTModelBased",
  2070. mode="queue",
  2071. model="X1C",
  2072. access_code="12345678",
  2073. serial_suffix="391800097",
  2074. base_dir=tmp_path,
  2075. session_factory=mock_session_factory,
  2076. save_ams_mapping=True,
  2077. target_printer_id=None,
  2078. )
  2079. inst._mqtt = MagicMock()
  2080. file_path = tmp_path / "test.3mf"
  2081. file_path.write_bytes(b"fake3mf")
  2082. with (
  2083. patch(
  2084. "backend.app.api.routes.settings.get_setting",
  2085. new_callable=AsyncMock,
  2086. return_value=None,
  2087. ),
  2088. patch(
  2089. "backend.app.services.virtual_printer.manager._SLICER_OPTIONS_WAIT_TIMEOUT",
  2090. 0.05,
  2091. ),
  2092. ):
  2093. await inst._add_to_print_queue(file_path, "192.168.1.100")
  2094. await inst.on_print_command(
  2095. file_path.name,
  2096. {
  2097. "command": "project_file",
  2098. "file": file_path.name,
  2099. "ams_mapping": [4, -1, 12, -1],
  2100. # An unrelated field so `patch` isn't empty and the UPDATE
  2101. # actually runs — isolates the assertion to "ams_mapping was
  2102. # excluded" rather than "nothing happened at all".
  2103. "timelapse": True,
  2104. },
  2105. )
  2106. # 3rd execute() is the queue-item UPDATE — ams_mapping must be absent
  2107. # from it. No 4th execute() (the archive SELECT) should follow.
  2108. assert mock_db.execute.await_count == 3
  2109. update_call = mock_db.execute.await_args_list[2]
  2110. compiled = update_call.args[0].compile(compile_kwargs={"literal_binds": False})
  2111. assert "ams_mapping" not in dict(compiled.params)
  2112. assert dict(compiled.params)["timelapse"] is True
  2113. @pytest.mark.asyncio
  2114. async def test_on_print_command_late_mqtt_force_color_match_archives_but_does_not_stamp(self, tmp_path):
  2115. """The late path splits the same way the immediate one does when
  2116. `Force color match` is on: the archive still records the slicer's pick
  2117. for later reprints, but it must not reach the queue item, or the
  2118. overrides the user asked for would never be applied (#2700 review).
  2119. """
  2120. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2121. added_items: list = []
  2122. mock_db = AsyncMock()
  2123. mock_db.add = MagicMock(
  2124. side_effect=lambda item: (added_items.append(item), setattr(item, "id", 300 + len(added_items)))[0]
  2125. )
  2126. mock_db.flush = AsyncMock()
  2127. mock_db.commit = AsyncMock()
  2128. mock_archive_row = MagicMock()
  2129. mock_archive_row.id = 75
  2130. mock_archive_row.extra_data = None
  2131. position_max_result = MagicMock()
  2132. position_max_result.scalar = MagicMock(return_value=None)
  2133. select_pending_result = MagicMock()
  2134. select_pending_result.all = MagicMock(return_value=[(301, 75, None)])
  2135. update_result = MagicMock()
  2136. select_archives_result = MagicMock()
  2137. select_archives_result.scalars = MagicMock(
  2138. return_value=MagicMock(all=MagicMock(return_value=[mock_archive_row]))
  2139. )
  2140. mock_db.execute = AsyncMock(
  2141. side_effect=[
  2142. position_max_result,
  2143. select_pending_result,
  2144. update_result,
  2145. update_result,
  2146. select_archives_result,
  2147. ]
  2148. )
  2149. mock_session_factory = MagicMock()
  2150. mock_session_ctx = AsyncMock()
  2151. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  2152. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  2153. mock_session_factory.return_value = mock_session_ctx
  2154. inst = VirtualPrinterInstance(
  2155. vp_id=96,
  2156. name="LateMQTTForceColor",
  2157. mode="queue",
  2158. model="X1C",
  2159. access_code="12345678",
  2160. serial_suffix="391800096",
  2161. base_dir=tmp_path,
  2162. session_factory=mock_session_factory,
  2163. save_ams_mapping=True,
  2164. queue_force_color_match=True,
  2165. target_printer_id=7,
  2166. )
  2167. inst._mqtt = MagicMock()
  2168. file_path = tmp_path / "test.3mf"
  2169. file_path.write_bytes(b"fake3mf")
  2170. with (
  2171. patch(
  2172. "backend.app.api.routes.settings.get_setting",
  2173. new_callable=AsyncMock,
  2174. return_value=None,
  2175. ),
  2176. patch(
  2177. "backend.app.services.virtual_printer.manager._SLICER_OPTIONS_WAIT_TIMEOUT",
  2178. 0.05,
  2179. ),
  2180. ):
  2181. await inst._add_to_print_queue(file_path, "192.168.1.100")
  2182. await inst.on_print_command(
  2183. file_path.name,
  2184. {
  2185. "command": "project_file",
  2186. "file": file_path.name,
  2187. "ams_mapping": [4, -1, 12, -1],
  2188. # Keeps the UPDATE non-empty so the assertion below is "the
  2189. # mapping was excluded", not "nothing ran".
  2190. "timelapse": True,
  2191. },
  2192. )
  2193. update_call = mock_db.execute.await_args_list[2]
  2194. compiled = update_call.args[0].compile(compile_kwargs={"literal_binds": False})
  2195. assert "ams_mapping" not in dict(compiled.params)
  2196. assert dict(compiled.params)["timelapse"] is True
  2197. # Kept for the archive all the same: Force color match only decides
  2198. # how this print is matched.
  2199. kept = mock_db.execute.await_args_list[3].args[0].compile(compile_kwargs={"literal_binds": False})
  2200. assert json.loads(dict(kept.params)["slicer_ams_mapping"]) == {"mapping": [4, -1, 12, -1], "printer_id": 7}
  2201. assert mock_archive_row.extra_data == {
  2202. "slicer_ams_mapping": {"mapping": [4, -1, 12, -1], "printer_id": 7},
  2203. }
  2204. @pytest.mark.asyncio
  2205. async def test_on_print_command_late_mqtt_ignores_ams_mapping_when_toggle_off(self, tmp_path):
  2206. """Toggle off: the late path must not stamp the queue item either, or
  2207. the opt-in would leak in through the #1780 race window.
  2208. """
  2209. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2210. added_items: list = []
  2211. mock_db = AsyncMock()
  2212. mock_db.add = MagicMock(
  2213. side_effect=lambda item: (added_items.append(item), setattr(item, "id", 400 + len(added_items)))[0]
  2214. )
  2215. mock_db.flush = AsyncMock()
  2216. mock_db.commit = AsyncMock()
  2217. position_max_result = MagicMock()
  2218. position_max_result.scalar = MagicMock(return_value=None)
  2219. select_pending_result = MagicMock()
  2220. select_pending_result.all = MagicMock(return_value=[(401, 85, None)])
  2221. update_result = MagicMock()
  2222. # No 4th execute(): with nothing to save there is no archive SELECT.
  2223. mock_db.execute = AsyncMock(side_effect=[position_max_result, select_pending_result, update_result])
  2224. mock_session_factory = MagicMock()
  2225. mock_session_ctx = AsyncMock()
  2226. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  2227. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  2228. mock_session_factory.return_value = mock_session_ctx
  2229. inst = VirtualPrinterInstance(
  2230. vp_id=95,
  2231. name="LateMQTTToggleOff",
  2232. mode="queue",
  2233. model="X1C",
  2234. access_code="12345678",
  2235. serial_suffix="391800095",
  2236. base_dir=tmp_path,
  2237. session_factory=mock_session_factory,
  2238. save_ams_mapping=False,
  2239. target_printer_id=7,
  2240. )
  2241. inst._mqtt = MagicMock()
  2242. file_path = tmp_path / "test.3mf"
  2243. file_path.write_bytes(b"fake3mf")
  2244. with (
  2245. patch(
  2246. "backend.app.api.routes.settings.get_setting",
  2247. new_callable=AsyncMock,
  2248. return_value=None,
  2249. ),
  2250. patch(
  2251. "backend.app.services.virtual_printer.manager._SLICER_OPTIONS_WAIT_TIMEOUT",
  2252. 0.05,
  2253. ),
  2254. ):
  2255. await inst._add_to_print_queue(file_path, "192.168.1.100")
  2256. await inst.on_print_command(
  2257. file_path.name,
  2258. {
  2259. "command": "project_file",
  2260. "file": file_path.name,
  2261. "ams_mapping": [4, -1, 12, -1],
  2262. "timelapse": True,
  2263. },
  2264. )
  2265. assert mock_db.execute.await_count == 3
  2266. update_call = mock_db.execute.await_args_list[2]
  2267. compiled = update_call.args[0].compile(compile_kwargs={"literal_binds": False})
  2268. assert "ams_mapping" not in dict(compiled.params)
  2269. assert dict(compiled.params)["timelapse"] is True
  2270. @pytest.mark.asyncio
  2271. async def test_add_to_print_queue_catches_mqtt_stashed_post_wait_timeout(self, tmp_path):
  2272. """The actual race-window scenario: wait_for times out, then MQTT
  2273. arrives and stashes options AFTER the wait but BEFORE the
  2274. post-commit re-check. The post-commit pop must catch it.
  2275. """
  2276. import json as _json
  2277. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2278. added_items: list = []
  2279. mock_db = AsyncMock()
  2280. mock_db.add = MagicMock(
  2281. side_effect=lambda item: (added_items.append(item), setattr(item, "id", 300 + len(added_items)))[0]
  2282. )
  2283. mock_db.flush = AsyncMock()
  2284. mock_db.commit = AsyncMock()
  2285. position_max_result = MagicMock()
  2286. position_max_result.scalar = MagicMock(return_value=None)
  2287. select_pending_result = MagicMock()
  2288. select_pending_result.all = MagicMock(return_value=[(301, None, None)])
  2289. update_result = MagicMock()
  2290. mock_db.execute = AsyncMock(side_effect=[position_max_result, select_pending_result, update_result])
  2291. mock_session_factory = MagicMock()
  2292. mock_session_ctx = AsyncMock()
  2293. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  2294. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  2295. mock_session_factory.return_value = mock_session_ctx
  2296. inst = VirtualPrinterInstance(
  2297. # The slicer's nozzle positions are kept only for a VP bound to one printer.
  2298. target_printer_id=7,
  2299. vp_id=96,
  2300. name="RaceCommitYield",
  2301. mode="queue",
  2302. model="O1C2",
  2303. access_code="12345678",
  2304. serial_suffix="391800096",
  2305. base_dir=tmp_path,
  2306. session_factory=mock_session_factory,
  2307. )
  2308. inst._mqtt = MagicMock()
  2309. file_path = tmp_path / "test.3mf"
  2310. file_path.write_bytes(b"fake3mf")
  2311. # Stash MQTT data on the FIRST commit (simulating MQTT arrival
  2312. # during _add_to_print_queue's commit yield); _restamp also calls
  2313. # db.commit later, so we one-shot the side effect.
  2314. commit_calls = {"n": 0}
  2315. async def _delayed_stash(*_args, **_kwargs):
  2316. commit_calls["n"] += 1
  2317. if commit_calls["n"] == 1:
  2318. inst._slicer_print_options[file_path.name] = {
  2319. "command": "project_file",
  2320. "file": file_path.name,
  2321. "nozzle_mapping": [0, 16, -1, -1],
  2322. "timelapse": False,
  2323. }
  2324. return None
  2325. mock_db.commit = AsyncMock(side_effect=_delayed_stash)
  2326. with (
  2327. patch(
  2328. "backend.app.api.routes.settings.get_setting",
  2329. new_callable=AsyncMock,
  2330. return_value=None,
  2331. ),
  2332. patch(
  2333. "backend.app.services.virtual_printer.manager._SLICER_OPTIONS_WAIT_TIMEOUT",
  2334. 0.05,
  2335. ),
  2336. ):
  2337. await inst._add_to_print_queue(file_path, "192.168.1.100")
  2338. # Queue item INSERTed with defaults (wait timed out, no slicer_opts).
  2339. assert len(added_items) == 1
  2340. # But the post-commit pop caught the late stash and applied the
  2341. # slicer nozzle_mapping via _restamp's UPDATE.
  2342. update_call = mock_db.execute.await_args_list[2]
  2343. update_stmt = update_call.args[0]
  2344. compiled = update_stmt.compile(compile_kwargs={"literal_binds": False})
  2345. params = dict(compiled.params)
  2346. assert _json.loads(params["nozzle_mapping"]) == [0, 16, -1, -1]
  2347. assert params["timelapse"] is False
  2348. # _recent_queue_items entry was consumed by the post-commit
  2349. # _restamp call.
  2350. assert file_path.name not in inst._recent_queue_items
  2351. # And the stash is empty.
  2352. assert file_path.name not in inst._slicer_print_options
  2353. @pytest.mark.asyncio
  2354. async def test_on_print_command_late_mqtt_skips_already_dispatched_item(self, tmp_path):
  2355. """Once the scheduler has picked the queue item up (status != pending),
  2356. the retroactive patch is a no-op — racing the dispatcher would be
  2357. unsafe.
  2358. """
  2359. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2360. mock_db = AsyncMock()
  2361. # The eligible-pending SELECT returns nothing — item is no longer pending.
  2362. empty_result = MagicMock()
  2363. empty_result.all = MagicMock(return_value=[])
  2364. mock_db.execute = AsyncMock(return_value=empty_result)
  2365. mock_db.commit = AsyncMock()
  2366. mock_session_factory = MagicMock()
  2367. mock_session_ctx = AsyncMock()
  2368. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  2369. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  2370. mock_session_factory.return_value = mock_session_ctx
  2371. inst = VirtualPrinterInstance(
  2372. # The slicer's nozzle positions are kept only for a VP bound to one printer.
  2373. target_printer_id=7,
  2374. vp_id=98,
  2375. name="LateMQTTDispatched",
  2376. mode="queue",
  2377. model="O1C2",
  2378. access_code="12345678",
  2379. serial_suffix="391800098",
  2380. base_dir=tmp_path,
  2381. session_factory=mock_session_factory,
  2382. )
  2383. inst._mqtt = MagicMock()
  2384. # Pre-seed the recent-queue dict — pretend _add_to_print_queue just
  2385. # committed item id 42.
  2386. inst._recent_queue_items["test.3mf"] = ([42], 1_000_000.0)
  2387. # Drive _restamp via on_print_command on the late-MQTT path.
  2388. with patch("backend.app.services.virtual_printer.manager.time.monotonic", return_value=1_000_001.0):
  2389. await inst.on_print_command(
  2390. "test.3mf",
  2391. {
  2392. "command": "project_file",
  2393. "file": "test.3mf",
  2394. "nozzle_mapping": [16, -1],
  2395. },
  2396. )
  2397. # No UPDATE was issued — only the eligibility SELECT ran.
  2398. assert mock_db.execute.await_count == 1
  2399. mock_db.commit.assert_not_awaited()
  2400. assert "test.3mf" not in inst._recent_queue_items
  2401. class TestExtractSlicerAmsMappingJson:
  2402. """Unit tests for `_extract_slicer_ams_mapping_json`, the pure-function
  2403. parser that pulls the slicer's own live-resolved AMS-slot pick out of a
  2404. captured project_file MQTT payload (see docstring in manager.py)."""
  2405. def _extract(self, data):
  2406. from backend.app.services.virtual_printer.manager import _extract_slicer_ams_mapping_json
  2407. return _extract_slicer_ams_mapping_json(data, "[test]")
  2408. def test_missing_field_returns_none(self):
  2409. assert self._extract({}) is None
  2410. def test_valid_int_list_returns_json(self):
  2411. import json as _json
  2412. result = self._extract({"ams_mapping": [4, -1, 12, -1]})
  2413. assert result is not None
  2414. assert _json.loads(result) == [4, -1, 12, -1]
  2415. def test_stringified_json_is_parsed(self):
  2416. import json as _json
  2417. result = self._extract({"ams_mapping": "[0, 1, 2]"})
  2418. assert result is not None
  2419. assert _json.loads(result) == [0, 1, 2]
  2420. def test_unparseable_string_returns_none(self):
  2421. assert self._extract({"ams_mapping": "not json"}) is None
  2422. def test_non_list_value_returns_none(self):
  2423. assert self._extract({"ams_mapping": 42}) is None
  2424. def test_empty_list_returns_none(self):
  2425. assert self._extract({"ams_mapping": []}) is None
  2426. def test_non_int_entries_return_none(self):
  2427. assert self._extract({"ams_mapping": [1, "two", 3]}) is None
  2428. def test_2589_all_unresolved_sentinel_returns_none(self):
  2429. """#2589: every slot -1 means the slicer's own resolution race
  2430. lost — never trust this over a fresh live computation."""
  2431. assert self._extract({"ams_mapping": [-1, -1, -1, -1]}) is None
  2432. def test_partially_resolved_mapping_is_kept(self):
  2433. import json as _json
  2434. # Only some slots resolved is still meaningful — keep it.
  2435. result = self._extract({"ams_mapping": [-1, 4, -1, -1]})
  2436. assert result is not None
  2437. assert _json.loads(result) == [-1, 4, -1, -1]
  2438. class TestVirtualPrinterManager:
  2439. """Tests for VirtualPrinterManager orchestrator."""
  2440. @pytest.fixture
  2441. def manager(self):
  2442. """Create a VirtualPrinterManager instance."""
  2443. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  2444. return VirtualPrinterManager()
  2445. def test_manager_starts_empty(self, manager):
  2446. """Verify manager starts with no instances."""
  2447. assert len(manager._instances) == 0
  2448. assert manager.is_enabled is False
  2449. def test_manager_get_status_empty(self, manager):
  2450. """Verify get_status returns disabled state when no instances."""
  2451. status = manager.get_status()
  2452. assert status["enabled"] is False
  2453. assert status["running"] is False
  2454. assert status["mode"] == "library"
  2455. def test_manager_is_enabled_with_instance(self, manager, tmp_path):
  2456. """Verify is_enabled is True when instances exist."""
  2457. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2458. inst = VirtualPrinterInstance(
  2459. vp_id=1,
  2460. name="Test",
  2461. mode="library",
  2462. model="C11",
  2463. access_code="12345678",
  2464. serial_suffix="391800001",
  2465. base_dir=tmp_path,
  2466. )
  2467. manager._instances[1] = inst
  2468. assert manager.is_enabled is True
  2469. @pytest.mark.asyncio
  2470. async def test_manager_remove_instance_server(self, manager, tmp_path):
  2471. """Verify remove_instance stops and removes a server-mode instance."""
  2472. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2473. inst = VirtualPrinterInstance(
  2474. vp_id=1,
  2475. name="Test",
  2476. mode="library",
  2477. model="C11",
  2478. access_code="12345678",
  2479. serial_suffix="391800001",
  2480. base_dir=tmp_path,
  2481. )
  2482. inst.stop_server = AsyncMock()
  2483. manager._instances[1] = inst
  2484. await manager.remove_instance(1)
  2485. assert 1 not in manager._instances
  2486. inst.stop_server.assert_called_once()
  2487. @pytest.mark.asyncio
  2488. async def test_manager_remove_instance_proxy(self, manager, tmp_path):
  2489. """Verify remove_instance stops proxy-mode instance."""
  2490. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2491. inst = VirtualPrinterInstance(
  2492. vp_id=2,
  2493. name="Proxy",
  2494. mode="proxy",
  2495. model="C11",
  2496. access_code="",
  2497. serial_suffix="391800002",
  2498. target_printer_ip="192.168.1.100",
  2499. base_dir=tmp_path,
  2500. )
  2501. inst.stop_proxy = AsyncMock()
  2502. manager._instances[2] = inst
  2503. await manager.remove_instance(2)
  2504. assert 2 not in manager._instances
  2505. inst.stop_proxy.assert_called_once()
  2506. def test_manager_get_status_with_instance(self, manager, tmp_path):
  2507. """Verify legacy get_status returns first instance data."""
  2508. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2509. inst = VirtualPrinterInstance(
  2510. vp_id=1,
  2511. name="Bambuddy",
  2512. mode="library",
  2513. model="C11",
  2514. access_code="12345678",
  2515. serial_suffix="391800001",
  2516. base_dir=tmp_path,
  2517. )
  2518. mock_task = MagicMock(done=MagicMock(return_value=False))
  2519. inst._tasks = [mock_task]
  2520. inst._pending_files = {"file1.3mf": Path("/tmp/file1.3mf")} # nosec B108
  2521. manager._instances[1] = inst
  2522. status = manager.get_status()
  2523. assert status["enabled"] is True
  2524. assert status["running"] is True
  2525. assert status["mode"] == "library"
  2526. assert status["name"] == "Bambuddy"
  2527. assert status["serial"] == "01S00A391800001"
  2528. assert status["model"] == "C11"
  2529. assert status["model_name"] == "P1P"
  2530. assert status["pending_files"] == 1
  2531. @pytest.mark.asyncio
  2532. async def test_manager_stop_all(self, manager, tmp_path):
  2533. """Verify stop_all removes all instances."""
  2534. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2535. for i in range(1, 3):
  2536. inst = VirtualPrinterInstance(
  2537. vp_id=i,
  2538. name=f"VP{i}",
  2539. mode="library",
  2540. model="C11",
  2541. access_code="12345678",
  2542. serial_suffix=f"39180000{i}",
  2543. base_dir=tmp_path,
  2544. )
  2545. inst.stop_server = AsyncMock()
  2546. manager._instances[i] = inst
  2547. await manager.stop_all()
  2548. assert len(manager._instances) == 0
  2549. # ========================================================================
  2550. # Tests for sync_from_db config change detection
  2551. # ========================================================================
  2552. def _make_db_vp(self, **overrides):
  2553. """Create a mock VirtualPrinter DB object."""
  2554. defaults = {
  2555. "id": 1,
  2556. "name": "TestVP",
  2557. "enabled": True,
  2558. "mode": "library",
  2559. "model": "C11",
  2560. "access_code": "12345678",
  2561. "serial_suffix": "391800001",
  2562. "bind_ip": "",
  2563. "remote_interface_ip": "",
  2564. "target_printer_id": None,
  2565. "auto_dispatch": True,
  2566. "tailscale_disabled": True, # Opt-in default (#1070 UX fix)
  2567. "queue_force_color_match": False, # default — must be explicit so MagicMock truthiness doesn't trip the change detector
  2568. "save_ams_mapping": False, # same reason as above
  2569. "gcode_injection": False, # same reason as above
  2570. "position": 0,
  2571. }
  2572. defaults.update(overrides)
  2573. vp = MagicMock()
  2574. for k, v in defaults.items():
  2575. setattr(vp, k, v)
  2576. return vp
  2577. def _setup_sync_mocks(self, manager, enabled_vps, tmp_path):
  2578. """Wire up session_factory mock for sync_from_db."""
  2579. mock_result = MagicMock()
  2580. mock_result.scalars.return_value.all.return_value = enabled_vps
  2581. mock_db = AsyncMock()
  2582. mock_db.execute = AsyncMock(return_value=mock_result)
  2583. mock_db.__aenter__ = AsyncMock(return_value=mock_db)
  2584. mock_db.__aexit__ = AsyncMock(return_value=False)
  2585. manager._session_factory = MagicMock(return_value=mock_db)
  2586. manager._base_dir = tmp_path
  2587. @pytest.mark.asyncio
  2588. async def test_sync_from_db_restarts_on_mode_change(self, manager, tmp_path):
  2589. """Verify sync_from_db restarts VP when mode changes."""
  2590. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2591. inst = VirtualPrinterInstance(
  2592. vp_id=1,
  2593. name="TestVP",
  2594. mode="library",
  2595. model="C11",
  2596. access_code="12345678",
  2597. serial_suffix="391800001",
  2598. base_dir=tmp_path,
  2599. )
  2600. inst.stop_server = AsyncMock()
  2601. manager._instances[1] = inst
  2602. # DB says mode changed to "review"
  2603. db_vp = self._make_db_vp(mode="review")
  2604. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  2605. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  2606. # Patch VirtualPrinterInstance to prevent actual start
  2607. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  2608. mock_new = MagicMock()
  2609. mock_new.start_server = AsyncMock()
  2610. MockInst.return_value = mock_new
  2611. await manager.sync_from_db()
  2612. mock_remove.assert_called_once_with(1)
  2613. @pytest.mark.asyncio
  2614. async def test_sync_from_db_restarts_on_access_code_change(self, manager, tmp_path):
  2615. """Verify sync_from_db restarts VP when access_code changes."""
  2616. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2617. inst = VirtualPrinterInstance(
  2618. vp_id=1,
  2619. name="TestVP",
  2620. mode="library",
  2621. model="C11",
  2622. access_code="12345678",
  2623. serial_suffix="391800001",
  2624. base_dir=tmp_path,
  2625. )
  2626. inst.stop_server = AsyncMock()
  2627. manager._instances[1] = inst
  2628. db_vp = self._make_db_vp(access_code="newcode99")
  2629. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  2630. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  2631. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  2632. mock_new = MagicMock()
  2633. mock_new.start_server = AsyncMock()
  2634. MockInst.return_value = mock_new
  2635. await manager.sync_from_db()
  2636. mock_remove.assert_called_once_with(1)
  2637. @pytest.mark.asyncio
  2638. async def test_sync_from_db_skips_unchanged_instance(self, manager, tmp_path):
  2639. """Verify sync_from_db does NOT restart when config is identical."""
  2640. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2641. inst = VirtualPrinterInstance(
  2642. vp_id=1,
  2643. name="TestVP",
  2644. mode="library",
  2645. model="C11",
  2646. access_code="12345678",
  2647. serial_suffix="391800001",
  2648. base_dir=tmp_path,
  2649. )
  2650. manager._instances[1] = inst
  2651. # DB matches running config exactly
  2652. db_vp = self._make_db_vp()
  2653. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  2654. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  2655. await manager.sync_from_db()
  2656. mock_remove.assert_not_called()
  2657. @pytest.mark.asyncio
  2658. async def test_sync_from_db_restarts_on_bind_ip_change(self, manager, tmp_path):
  2659. """Verify sync_from_db restarts VP when bind_ip changes."""
  2660. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2661. inst = VirtualPrinterInstance(
  2662. vp_id=1,
  2663. name="TestVP",
  2664. mode="library",
  2665. model="C11",
  2666. access_code="12345678",
  2667. serial_suffix="391800001",
  2668. bind_ip="192.168.1.10",
  2669. base_dir=tmp_path,
  2670. )
  2671. inst.stop_server = AsyncMock()
  2672. manager._instances[1] = inst
  2673. db_vp = self._make_db_vp(bind_ip="192.168.1.20")
  2674. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  2675. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  2676. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  2677. mock_new = MagicMock()
  2678. mock_new.start_server = AsyncMock()
  2679. MockInst.return_value = mock_new
  2680. await manager.sync_from_db()
  2681. mock_remove.assert_called_once_with(1)
  2682. @pytest.mark.asyncio
  2683. async def test_sync_from_db_restarts_on_model_change(self, manager, tmp_path):
  2684. """Verify sync_from_db restarts VP when model changes."""
  2685. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2686. inst = VirtualPrinterInstance(
  2687. vp_id=1,
  2688. name="TestVP",
  2689. mode="library",
  2690. model="C11",
  2691. access_code="12345678",
  2692. serial_suffix="391800001",
  2693. base_dir=tmp_path,
  2694. )
  2695. inst.stop_server = AsyncMock()
  2696. manager._instances[1] = inst
  2697. db_vp = self._make_db_vp(model="C12")
  2698. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  2699. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  2700. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  2701. mock_new = MagicMock()
  2702. mock_new.start_server = AsyncMock()
  2703. MockInst.return_value = mock_new
  2704. await manager.sync_from_db()
  2705. mock_remove.assert_called_once_with(1)
  2706. @pytest.mark.asyncio
  2707. async def test_sync_from_db_does_not_restart_on_tailscale_toggle(self, manager, tmp_path):
  2708. """Flipping tailscale_disabled is purely informational — must NOT trigger a restart.
  2709. Cert provisioning was removed; the toggle only governs whether the VP card surfaces
  2710. the host's Tailscale IP/FQDN to the user. No service needs to reload, so changing
  2711. it through sync_from_db should leave any running instance untouched.
  2712. """
  2713. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2714. inst = VirtualPrinterInstance(
  2715. vp_id=1,
  2716. name="TestVP",
  2717. mode="library",
  2718. model="C11",
  2719. access_code="12345678",
  2720. serial_suffix="391800001",
  2721. base_dir=tmp_path,
  2722. )
  2723. inst.stop_server = AsyncMock()
  2724. manager._instances[1] = inst
  2725. db_vp = self._make_db_vp(tailscale_disabled=True)
  2726. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  2727. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  2728. await manager.sync_from_db()
  2729. mock_remove.assert_not_called()
  2730. @pytest.mark.asyncio
  2731. async def test_sync_from_db_restarts_on_gcode_injection_toggle(self, manager, tmp_path):
  2732. """Toggling gcode_injection in the DB must restart the running instance.
  2733. Without this, the in-memory ``self.gcode_injection`` keeps its old value
  2734. and ``_add_to_print_queue`` stamps the stale flag on every new queue
  2735. item — so disabling injection in the UI silently has no effect until
  2736. the process restarts.
  2737. """
  2738. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2739. inst = VirtualPrinterInstance(
  2740. vp_id=1,
  2741. name="TestVP",
  2742. mode="library",
  2743. model="C11",
  2744. access_code="12345678",
  2745. serial_suffix="391800001",
  2746. gcode_injection=True,
  2747. base_dir=tmp_path,
  2748. )
  2749. inst.stop_server = AsyncMock()
  2750. manager._instances[1] = inst
  2751. db_vp = self._make_db_vp(gcode_injection=False)
  2752. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  2753. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  2754. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  2755. mock_new = MagicMock()
  2756. mock_new.start_server = AsyncMock()
  2757. MockInst.return_value = mock_new
  2758. await manager.sync_from_db()
  2759. mock_remove.assert_called_once_with(1)
  2760. def _setup_proxy_sync_mocks(
  2761. self, manager, enabled_vps, tmp_path, printer_ip="192.168.1.50", serial="0948AB012345678"
  2762. ):
  2763. """Like _setup_sync_mocks, but the target printer lookup returns a real IP and serial."""
  2764. vps_result = MagicMock()
  2765. vps_result.scalars.return_value.all.return_value = enabled_vps
  2766. printer_result = MagicMock()
  2767. printer_result.scalar_one_or_none.return_value = SimpleNamespace(ip_address=printer_ip, serial_number=serial)
  2768. async def execute(stmt):
  2769. entity = stmt.column_descriptions[0]["entity"]
  2770. return printer_result if entity.__name__ == "Printer" else vps_result
  2771. mock_db = AsyncMock()
  2772. mock_db.execute = AsyncMock(side_effect=execute)
  2773. mock_db.__aenter__ = AsyncMock(return_value=mock_db)
  2774. mock_db.__aexit__ = AsyncMock(return_value=False)
  2775. manager._session_factory = MagicMock(return_value=mock_db)
  2776. manager._base_dir = tmp_path
  2777. @pytest.mark.asyncio
  2778. async def test_sync_from_db_leaves_a_running_proxy_vp_alone(self, manager, tmp_path):
  2779. """A proxy VP that sync started must survive the next sync unchanged.
  2780. The proxy branch built its instance without the row's target printer
  2781. id, so every later sync saw a change and restarted every proxy VP,
  2782. dropping the slicer's connection, whenever any VP or printer was saved.
  2783. The queue-mode toggles are set away from their defaults, as on a VP
  2784. switched from queue mode to proxy, which keeps them in its row.
  2785. """
  2786. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2787. db_vp = self._make_db_vp(
  2788. mode="proxy",
  2789. model="O1D",
  2790. target_printer_id=7,
  2791. bind_ip="10.0.0.5",
  2792. auto_dispatch=False,
  2793. queue_force_color_match=True,
  2794. save_ams_mapping=True,
  2795. gcode_injection=True,
  2796. )
  2797. self._setup_proxy_sync_mocks(manager, [db_vp], tmp_path)
  2798. with (
  2799. patch.object(VirtualPrinterInstance, "start_proxy", new_callable=AsyncMock) as mock_start,
  2800. patch.object(VirtualPrinterInstance, "stop_proxy", new_callable=AsyncMock) as mock_stop,
  2801. ):
  2802. await manager.sync_from_db()
  2803. assert mock_start.await_count == 1
  2804. assert manager._instances[1].target_printer_id == 7
  2805. await manager.sync_from_db()
  2806. assert mock_start.await_count == 1
  2807. mock_stop.assert_not_awaited()
  2808. @pytest.mark.asyncio
  2809. async def test_sync_from_db_restarts_a_proxy_vp_on_target_ip_change(self, manager, tmp_path):
  2810. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2811. db_vp = self._make_db_vp(mode="proxy", model="O1D", target_printer_id=7, bind_ip="10.0.0.5")
  2812. self._setup_proxy_sync_mocks(manager, [db_vp], tmp_path)
  2813. with (
  2814. patch.object(VirtualPrinterInstance, "start_proxy", new_callable=AsyncMock) as mock_start,
  2815. patch.object(VirtualPrinterInstance, "stop_proxy", new_callable=AsyncMock) as mock_stop,
  2816. ):
  2817. await manager.sync_from_db()
  2818. self._setup_proxy_sync_mocks(manager, [db_vp], tmp_path, printer_ip="192.168.1.77")
  2819. await manager.sync_from_db()
  2820. mock_stop.assert_awaited_once()
  2821. assert mock_start.await_count == 2
  2822. assert manager._instances[1].target_printer_ip == "192.168.1.77"
  2823. @pytest.mark.asyncio
  2824. async def test_sync_from_db_restarts_a_proxy_vp_on_rename(self, manager, tmp_path):
  2825. """The name is advertised to the slicer (SSDP, bind), so a rename only
  2826. reaches the slicer through a restart."""
  2827. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2828. db_vp = self._make_db_vp(mode="proxy", model="O1D", target_printer_id=7, bind_ip="10.0.0.5")
  2829. self._setup_proxy_sync_mocks(manager, [db_vp], tmp_path)
  2830. with (
  2831. patch.object(VirtualPrinterInstance, "start_proxy", new_callable=AsyncMock) as mock_start,
  2832. patch.object(VirtualPrinterInstance, "stop_proxy", new_callable=AsyncMock) as mock_stop,
  2833. ):
  2834. await manager.sync_from_db()
  2835. db_vp.name = "Workshop H2D"
  2836. await manager.sync_from_db()
  2837. mock_stop.assert_awaited_once()
  2838. assert mock_start.await_count == 2
  2839. assert manager._instances[1].name == "Workshop H2D"
  2840. @pytest.mark.asyncio
  2841. async def test_sync_from_db_restarts_on_rename(self, manager, tmp_path):
  2842. """Same for a server-mode VP: the running SSDP and bind servers keep
  2843. advertising the old name until the instance restarts."""
  2844. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2845. inst = VirtualPrinterInstance(
  2846. vp_id=1,
  2847. name="TestVP",
  2848. mode="library",
  2849. model="C11",
  2850. access_code="12345678",
  2851. serial_suffix="391800001",
  2852. base_dir=tmp_path,
  2853. )
  2854. manager._instances[1] = inst
  2855. db_vp = self._make_db_vp(name="Renamed VP")
  2856. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  2857. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  2858. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  2859. mock_new = MagicMock()
  2860. mock_new.start_server = AsyncMock()
  2861. MockInst.return_value = mock_new
  2862. await manager.sync_from_db()
  2863. mock_remove.assert_called_once_with(1)
  2864. class TestFTPSession:
  2865. """Tests for FTP session handling."""
  2866. @pytest.fixture
  2867. def mock_reader(self):
  2868. """Create a mock StreamReader."""
  2869. reader = AsyncMock()
  2870. return reader
  2871. @pytest.fixture
  2872. def mock_writer(self):
  2873. """Create a mock StreamWriter."""
  2874. writer = MagicMock()
  2875. writer.get_extra_info = MagicMock(return_value=("192.168.1.100", 12345))
  2876. writer.write = MagicMock()
  2877. writer.drain = AsyncMock()
  2878. writer.close = MagicMock()
  2879. writer.wait_closed = AsyncMock()
  2880. writer.is_closing = MagicMock(return_value=False)
  2881. return writer
  2882. @pytest.fixture
  2883. def ssl_context(self):
  2884. """Create a mock SSL context."""
  2885. return MagicMock()
  2886. @pytest.fixture
  2887. def session(self, mock_reader, mock_writer, ssl_context, tmp_path):
  2888. """Create an FTPSession instance."""
  2889. from backend.app.services.virtual_printer.ftp_server import FTPSession
  2890. return FTPSession(
  2891. reader=mock_reader,
  2892. writer=mock_writer,
  2893. upload_dir=tmp_path,
  2894. access_code="12345678",
  2895. ssl_context=ssl_context,
  2896. on_file_received=None,
  2897. )
  2898. # ========================================================================
  2899. # Tests for authentication
  2900. # ========================================================================
  2901. @pytest.mark.asyncio
  2902. async def test_user_command_accepts_bblp(self, session):
  2903. """Verify USER command accepts bblp user."""
  2904. await session.cmd_USER("bblp")
  2905. assert session.username == "bblp"
  2906. @pytest.mark.asyncio
  2907. async def test_pass_command_authenticates(self, session):
  2908. """Verify PASS command authenticates with correct code."""
  2909. session.username = "bblp"
  2910. await session.cmd_PASS("12345678")
  2911. assert session.authenticated is True
  2912. @pytest.mark.asyncio
  2913. async def test_pass_command_rejects_wrong_code(self, session):
  2914. """Verify PASS command rejects wrong access code."""
  2915. session.username = "bblp"
  2916. await session.cmd_PASS("wrongcode")
  2917. assert session.authenticated is False
  2918. # ========================================================================
  2919. # Tests for FTP commands
  2920. # ========================================================================
  2921. @pytest.mark.asyncio
  2922. async def test_syst_command(self, session):
  2923. """Verify SYST returns UNIX type."""
  2924. await session.cmd_SYST("")
  2925. session.writer.write.assert_called()
  2926. call_args = session.writer.write.call_args[0][0].decode()
  2927. assert "215" in call_args
  2928. assert "UNIX" in call_args
  2929. @pytest.mark.asyncio
  2930. async def test_pwd_command_requires_auth(self, session):
  2931. """Verify PWD requires authentication."""
  2932. session.authenticated = False
  2933. await session.cmd_PWD("")
  2934. call_args = session.writer.write.call_args[0][0].decode()
  2935. assert "530" in call_args
  2936. @pytest.mark.asyncio
  2937. async def test_pwd_command_when_authenticated(self, session):
  2938. """Verify PWD returns root directory when authenticated."""
  2939. session.authenticated = True
  2940. await session.cmd_PWD("")
  2941. call_args = session.writer.write.call_args[0][0].decode()
  2942. assert "257" in call_args
  2943. @pytest.mark.asyncio
  2944. async def test_type_command_sets_binary(self, session):
  2945. """Verify TYPE I sets binary mode."""
  2946. session.authenticated = True
  2947. await session.cmd_TYPE("I")
  2948. assert session.transfer_type == "I"
  2949. @pytest.mark.asyncio
  2950. async def test_pbsz_command(self, session):
  2951. """Verify PBSZ returns success."""
  2952. await session.cmd_PBSZ("0")
  2953. call_args = session.writer.write.call_args[0][0].decode()
  2954. assert "200" in call_args
  2955. @pytest.mark.asyncio
  2956. async def test_prot_command_accepts_p(self, session):
  2957. """Verify PROT P is accepted."""
  2958. await session.cmd_PROT("P")
  2959. call_args = session.writer.write.call_args[0][0].decode()
  2960. assert "200" in call_args
  2961. @pytest.mark.asyncio
  2962. async def test_quit_command(self, session):
  2963. """Verify QUIT sends goodbye and raises CancelledError."""
  2964. with pytest.raises(asyncio.CancelledError):
  2965. await session.cmd_QUIT("")
  2966. class TestSSDPServer:
  2967. """Tests for Virtual Printer SSDP server."""
  2968. @pytest.fixture
  2969. def ssdp_server(self):
  2970. """Create a VirtualPrinterSSDPServer instance."""
  2971. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  2972. return VirtualPrinterSSDPServer(
  2973. serial="TEST123",
  2974. name="TestPrinter",
  2975. model="BL-P001",
  2976. )
  2977. # ========================================================================
  2978. # Tests for SSDP response
  2979. # ========================================================================
  2980. def test_build_notify_message(self, ssdp_server):
  2981. """Verify NOTIFY packet contains required headers."""
  2982. # Set a known IP for testing
  2983. ssdp_server._local_ip = "192.168.1.100"
  2984. message = ssdp_server._build_notify_message()
  2985. assert b"NOTIFY" in message
  2986. assert b"DevName.bambu.com: TestPrinter" in message
  2987. assert b"USN: TEST123" in message
  2988. def test_build_response_message(self, ssdp_server):
  2989. """Verify response packet contains required headers."""
  2990. # Set a known IP for testing
  2991. ssdp_server._local_ip = "192.168.1.100"
  2992. message = ssdp_server._build_response_message()
  2993. assert b"HTTP/1.1 200 OK" in message
  2994. assert b"DevName.bambu.com: TestPrinter" in message
  2995. assert b"USN: TEST123" in message
  2996. def test_ssdp_server_uses_correct_model(self, ssdp_server):
  2997. """Verify SSDP server uses the provided model."""
  2998. ssdp_server._local_ip = "192.168.1.100"
  2999. message = ssdp_server._build_notify_message()
  3000. assert b"DevModel.bambu.com: BL-P001" in message
  3001. # ========================================================================
  3002. # Tests for advertise_ip parameter
  3003. # ========================================================================
  3004. def test_advertise_ip_sets_local_ip(self):
  3005. """Verify advertise_ip overrides auto-detection."""
  3006. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  3007. server = VirtualPrinterSSDPServer(
  3008. serial="TEST123",
  3009. name="TestPrinter",
  3010. model="BL-P001",
  3011. advertise_ip="10.0.0.50",
  3012. )
  3013. assert server._local_ip == "10.0.0.50"
  3014. def test_advertise_ip_empty_string_uses_auto_detect(self):
  3015. """Verify empty advertise_ip falls back to auto-detection."""
  3016. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  3017. server = VirtualPrinterSSDPServer(
  3018. serial="TEST123",
  3019. name="TestPrinter",
  3020. model="BL-P001",
  3021. advertise_ip="",
  3022. )
  3023. assert server._local_ip is None
  3024. def test_advertise_ip_in_notify_message(self):
  3025. """Verify NOTIFY message uses the advertise_ip."""
  3026. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  3027. server = VirtualPrinterSSDPServer(
  3028. serial="TEST123",
  3029. name="TestPrinter",
  3030. model="BL-P001",
  3031. advertise_ip="10.0.0.50",
  3032. )
  3033. message = server._build_notify_message()
  3034. assert b"Location: 10.0.0.50" in message
  3035. def test_advertise_ip_in_response_message(self):
  3036. """Verify M-SEARCH response uses the advertise_ip."""
  3037. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  3038. server = VirtualPrinterSSDPServer(
  3039. serial="TEST123",
  3040. name="TestPrinter",
  3041. model="BL-P001",
  3042. advertise_ip="10.0.0.50",
  3043. )
  3044. message = server._build_response_message()
  3045. assert b"Location: 10.0.0.50" in message
  3046. def test_default_no_advertise_ip(self):
  3047. """Verify default constructor has None local_ip (auto-detect)."""
  3048. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  3049. server = VirtualPrinterSSDPServer()
  3050. assert server._local_ip is None
  3051. class TestCertificateService:
  3052. """Tests for TLS certificate generation."""
  3053. @pytest.fixture
  3054. def cert_service(self, tmp_path):
  3055. """Create a CertificateService instance."""
  3056. from backend.app.services.virtual_printer.certificate import CertificateService
  3057. return CertificateService(cert_dir=tmp_path, serial="TEST123")
  3058. def test_generate_certificates(self, cert_service, tmp_path):
  3059. """Verify certificates are generated correctly."""
  3060. cert_path, key_path = cert_service.generate_certificates()
  3061. assert cert_path.exists()
  3062. assert key_path.exists()
  3063. # Verify certificate content
  3064. cert_content = cert_path.read_text()
  3065. assert "BEGIN CERTIFICATE" in cert_content
  3066. key_content = key_path.read_text()
  3067. assert "BEGIN" in key_content and "KEY" in key_content
  3068. # --- CA identity (#3014) ------------------------------------------------
  3069. #
  3070. # A slicer trust store is a flat list of certificates, and OpenSSL resolves
  3071. # an issuer by Subject DN: the first CA whose DN matches is the only one
  3072. # tried. While every Bambuddy install signed as plain "Virtual Printer CA",
  3073. # importing the CAs of two instances broke whichever landed second in the
  3074. # file — with the same generic connection error an unimported CA produces.
  3075. @staticmethod
  3076. def _install(base, serial):
  3077. """Build a CertificateService laid out the way the manager lays one out."""
  3078. from backend.app.services.virtual_printer.certificate import CertificateService
  3079. return CertificateService(cert_dir=base / "0", serial=serial, shared_ca_dir=base)
  3080. @staticmethod
  3081. def _plant_legacy_ca(ca_dir):
  3082. """Write a pre-#3014 CA: plain common name, no SubjectKeyIdentifier."""
  3083. from datetime import datetime, timedelta, timezone
  3084. from cryptography import x509
  3085. from cryptography.hazmat.primitives import hashes, serialization
  3086. from cryptography.hazmat.primitives.asymmetric import rsa
  3087. from cryptography.x509.oid import NameOID
  3088. key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
  3089. name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Virtual Printer CA")])
  3090. now = datetime.now(timezone.utc)
  3091. cert = (
  3092. x509.CertificateBuilder()
  3093. .subject_name(name)
  3094. .issuer_name(name)
  3095. .public_key(key.public_key())
  3096. .serial_number(x509.random_serial_number())
  3097. .not_valid_before(now)
  3098. .not_valid_after(now + timedelta(days=7300))
  3099. .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
  3100. .sign(key, hashes.SHA256())
  3101. )
  3102. ca_dir.mkdir(parents=True, exist_ok=True)
  3103. (ca_dir / "bbl_ca.key").write_bytes(
  3104. key.private_bytes(
  3105. encoding=serialization.Encoding.PEM,
  3106. format=serialization.PrivateFormat.TraditionalOpenSSL,
  3107. encryption_algorithm=serialization.NoEncryption(),
  3108. )
  3109. )
  3110. (ca_dir / "bbl_ca.crt").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
  3111. return cert
  3112. def test_ca_common_name_is_unique_per_install(self, tmp_path):
  3113. """Two installs must not produce CAs that share a Subject DN."""
  3114. from cryptography import x509
  3115. from backend.app.services.virtual_printer.certificate import CA_COMMON_NAME_PREFIX
  3116. cas = []
  3117. for name in ("a", "b"):
  3118. service = self._install(tmp_path / name, "TEST123")
  3119. service.generate_certificates()
  3120. cas.append(x509.load_pem_x509_certificate(service.ca_cert_path.read_bytes()))
  3121. subjects = [ca.subject.rfc4514_string() for ca in cas]
  3122. assert all(s.startswith(f"CN={CA_COMMON_NAME_PREFIX} ") for s in subjects)
  3123. assert subjects[0] != subjects[1]
  3124. def test_ca_key_identifier_is_carried_into_the_printer_certificate(self, cert_service):
  3125. """The CA advertises a key id and the leaf names it as its authority."""
  3126. from cryptography import x509
  3127. cert_path, _ = cert_service.generate_certificates()
  3128. leaf = x509.load_pem_x509_certificate(cert_path.read_bytes())
  3129. ca = x509.load_pem_x509_certificate(cert_service.ca_cert_path.read_bytes())
  3130. ca_skid = ca.extensions.get_extension_for_class(x509.SubjectKeyIdentifier).value
  3131. leaf_akid = leaf.extensions.get_extension_for_class(x509.AuthorityKeyIdentifier).value
  3132. assert leaf_akid.key_identifier == ca_skid.digest
  3133. def test_existing_ca_is_reused_and_its_certificate_shape_is_unchanged(self, tmp_path):
  3134. """An install that already has a CA keeps it — nothing to re-import.
  3135. Its printer certificate also stays exactly as it was: no authority key
  3136. identifier, because the CA it was signed by advertises none.
  3137. """
  3138. from cryptography import x509
  3139. from cryptography.hazmat.primitives import hashes
  3140. planted = self._plant_legacy_ca(tmp_path)
  3141. service = self._install(tmp_path, "TEST123")
  3142. cert_path, _ = service.generate_certificates()
  3143. ca = x509.load_pem_x509_certificate(service.ca_cert_path.read_bytes())
  3144. assert ca.fingerprint(hashes.SHA256()) == planted.fingerprint(hashes.SHA256())
  3145. assert ca.subject.rfc4514_string() == "CN=Virtual Printer CA"
  3146. leaf = x509.load_pem_x509_certificate(cert_path.read_bytes())
  3147. with pytest.raises(x509.ExtensionNotFound):
  3148. leaf.extensions.get_extension_for_class(x509.AuthorityKeyIdentifier)
  3149. @pytest.mark.skipif(shutil.which("openssl") is None, reason="needs the openssl binary")
  3150. def test_two_installs_verify_from_a_single_trust_store(self, tmp_path):
  3151. """The reported symptom: both CAs imported, both chains must verify."""
  3152. import subprocess
  3153. leaves = []
  3154. bundle = b""
  3155. for name, serial in (("a", "00M09A391800001"), ("b", "01P00A391800002")):
  3156. service = self._install(tmp_path / name, serial)
  3157. cert_path, _ = service.generate_certificates()
  3158. # The per-VP file is a chain (leaf + CA); OpenSSL reads the leaf first.
  3159. leaves.append(cert_path)
  3160. bundle += service.ca_cert_path.read_bytes()
  3161. bundle_path = tmp_path / "trust_store.pem"
  3162. bundle_path.write_bytes(bundle)
  3163. for leaf in leaves:
  3164. result = subprocess.run(
  3165. ["openssl", "verify", "-CAfile", str(bundle_path), str(leaf)],
  3166. capture_output=True,
  3167. text=True,
  3168. )
  3169. assert result.returncode == 0, result.stdout + result.stderr
  3170. class TestBindServer:
  3171. """Tests for BindServer (port 3002 bind/detect protocol)."""
  3172. @pytest.fixture
  3173. def bind_server(self):
  3174. """Create a BindServer instance."""
  3175. from backend.app.services.virtual_printer.bind_server import BindServer
  3176. return BindServer(
  3177. serial="09400A391800001",
  3178. model="O1D",
  3179. name="Bambuddy",
  3180. )
  3181. def test_build_frame(self, bind_server):
  3182. """Verify frame building produces correct format."""
  3183. payload = {"login": {"command": "detect"}}
  3184. frame = bind_server._build_frame(payload)
  3185. # Header: 0xA5A5
  3186. assert frame[:2] == b"\xa5\xa5"
  3187. # Trailer: 0xA7A7
  3188. assert frame[-2:] == b"\xa7\xa7"
  3189. # Length field is total message size (LE uint16)
  3190. import struct
  3191. total_len = struct.unpack_from("<H", frame, 2)[0]
  3192. assert total_len == len(frame)
  3193. # JSON payload is between header and trailer
  3194. import json
  3195. json_bytes = frame[4:-2]
  3196. parsed = json.loads(json_bytes)
  3197. assert parsed == payload
  3198. def test_parse_frame_valid(self, bind_server):
  3199. """Verify valid frame parsing extracts JSON correctly."""
  3200. import json
  3201. import struct
  3202. payload = {"login": {"command": "detect", "sequence_id": "20000"}}
  3203. json_bytes = json.dumps(payload, separators=(",", ":")).encode()
  3204. total_len = 4 + len(json_bytes) + 2
  3205. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + json_bytes + b"\xa7\xa7"
  3206. result = bind_server._parse_frame(frame)
  3207. assert result is not None
  3208. assert result["login"]["command"] == "detect"
  3209. assert result["login"]["sequence_id"] == "20000"
  3210. def test_parse_frame_invalid_header(self, bind_server):
  3211. """Verify invalid header returns None."""
  3212. result = bind_server._parse_frame(b"\xbb\xbb\x06\x00{}\xa7\xa7")
  3213. assert result is None
  3214. def test_parse_frame_invalid_trailer(self, bind_server):
  3215. """Verify invalid trailer returns None."""
  3216. result = bind_server._parse_frame(b"\xa5\xa5\x06\x00{}\xbb\xbb")
  3217. assert result is None
  3218. def test_parse_frame_too_short(self, bind_server):
  3219. """Verify short data returns None."""
  3220. result = bind_server._parse_frame(b"\xa5\xa5\x00")
  3221. assert result is None
  3222. def test_parse_frame_invalid_json(self, bind_server):
  3223. """Verify invalid JSON returns None."""
  3224. import struct
  3225. bad_json = b"not json"
  3226. total_len = 4 + len(bad_json) + 2
  3227. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  3228. result = bind_server._parse_frame(frame)
  3229. assert result is None
  3230. def test_build_frame_roundtrip(self, bind_server):
  3231. """Verify build_frame output can be parsed back."""
  3232. payload = {
  3233. "login": {
  3234. "bind": "free",
  3235. "command": "detect",
  3236. "connect": "lan",
  3237. "dev_cap": 1,
  3238. "id": "09400A391800001",
  3239. "model": "O1D",
  3240. "name": "Bambuddy",
  3241. "sequence_id": 3021,
  3242. "version": "01.00.00.00",
  3243. }
  3244. }
  3245. frame = bind_server._build_frame(payload)
  3246. parsed = bind_server._parse_frame(frame)
  3247. assert parsed is not None
  3248. assert parsed["login"]["id"] == "09400A391800001"
  3249. assert parsed["login"]["model"] == "O1D"
  3250. assert parsed["login"]["name"] == "Bambuddy"
  3251. assert parsed["login"]["bind"] == "free"
  3252. def test_bind_server_stores_config(self, bind_server):
  3253. """Verify bind server stores serial, model, name."""
  3254. assert bind_server.serial == "09400A391800001"
  3255. assert bind_server.model == "O1D"
  3256. assert bind_server.name == "Bambuddy"
  3257. assert bind_server.version == "01.00.00.00"
  3258. def test_bind_server_custom_version(self):
  3259. """Verify custom firmware version is stored."""
  3260. from backend.app.services.virtual_printer.bind_server import BindServer
  3261. server = BindServer(
  3262. serial="TEST123",
  3263. model="C13",
  3264. name="Test",
  3265. version="02.03.04.05",
  3266. )
  3267. assert server.version == "02.03.04.05"
  3268. def test_bind_ports_constant(self):
  3269. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  3270. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  3271. assert 3000 in BIND_PORTS
  3272. assert 3002 in BIND_PORTS
  3273. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  3274. """Verify bind server starts with empty servers list."""
  3275. assert bind_server._servers == []
  3276. assert bind_server._running is False
  3277. class TestSlicerProxyManager:
  3278. """Tests for SlicerProxyManager (proxy mode)."""
  3279. @pytest.fixture
  3280. def proxy_manager(self, tmp_path):
  3281. """Create a SlicerProxyManager instance."""
  3282. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  3283. # Create dummy cert files
  3284. cert_path = tmp_path / "cert.pem"
  3285. key_path = tmp_path / "key.pem"
  3286. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  3287. # Split string to avoid pre-commit hook false positive on test data
  3288. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  3289. return SlicerProxyManager(
  3290. target_host="192.168.1.100",
  3291. cert_path=cert_path,
  3292. key_path=key_path,
  3293. )
  3294. def test_proxy_manager_initializes_ports(self, proxy_manager):
  3295. """Verify proxy manager has correct port constants."""
  3296. # FTP proxy uses privileged port 990 to match what Bambu Studio expects
  3297. assert proxy_manager.LOCAL_FTP_PORT == 990
  3298. assert proxy_manager.LOCAL_MQTT_PORT == 8883
  3299. assert proxy_manager.PRINTER_FTP_PORT == 990
  3300. assert proxy_manager.PRINTER_MQTT_PORT == 8883
  3301. assert proxy_manager.PRINTER_FILE_TRANSFER_PORT == 6000
  3302. assert proxy_manager.PRINTER_RTSP_PORT == 322
  3303. # Auxiliary ports: undocumented proprietary ports for A1/P1S etc.
  3304. assert proxy_manager.PRINTER_AUX_PORTS == [2024, 2025, 2026]
  3305. # Bind ports: both 3000 and 3002 for slicer compatibility
  3306. assert proxy_manager.PRINTER_BIND_PORTS == [3000, 3002]
  3307. # FTP data port range for transparent EPSV proxying
  3308. assert proxy_manager.FTP_DATA_PORT_MIN == 50000
  3309. assert proxy_manager.FTP_DATA_PORT_MAX == 50100
  3310. def test_proxy_manager_stores_target_host(self, proxy_manager):
  3311. """Verify proxy manager stores target host."""
  3312. assert proxy_manager.target_host == "192.168.1.100"
  3313. def test_get_status_before_start(self, proxy_manager):
  3314. """Verify get_status returns zeros before start."""
  3315. status = proxy_manager.get_status()
  3316. assert status["running"] is False
  3317. assert status["ftp_connections"] == 0
  3318. assert status["mqtt_connections"] == 0
  3319. @pytest.mark.asyncio
  3320. async def test_proxy_start_creates_transparent_proxies(self, tmp_path):
  3321. """Verify start() uses TCPProxy for FTP/FileTransfer/RTSP and TLSProxy only for MQTT.
  3322. The transparent proxy architecture preserves end-to-end TLS between
  3323. slicer and printer for all protocols except MQTT, which must be
  3324. TLS-terminated to rewrite the printer's IP in MQTT payloads.
  3325. """
  3326. from unittest.mock import patch
  3327. from backend.app.services.virtual_printer.tcp_proxy import (
  3328. SlicerProxyManager,
  3329. TCPProxy,
  3330. TLSProxy,
  3331. )
  3332. cert_path = tmp_path / "cert.pem"
  3333. key_path = tmp_path / "key.pem"
  3334. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  3335. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  3336. mgr = SlicerProxyManager(
  3337. target_host="192.168.1.100",
  3338. cert_path=cert_path,
  3339. key_path=key_path,
  3340. bind_address="10.0.0.1",
  3341. )
  3342. # Mock asyncio.create_task and asyncio.gather to prevent actual
  3343. # server start. Close every coroutine handed to create_task (gather
  3344. # only sees the stand-in tasks) — otherwise the ~110
  3345. # run_with_logging() coros built inside start() are garbage-collected
  3346. # unfinalized and surface later as PytestUnraisableExceptionWarning at
  3347. # random in other tests.
  3348. def _close_and_stand_in(coro, **_):
  3349. coro.close()
  3350. return MagicMock()
  3351. with (
  3352. patch("asyncio.create_task", side_effect=_close_and_stand_in),
  3353. patch("asyncio.gather", new=AsyncMock()),
  3354. patch.object(SlicerProxyManager, "_log_activity"),
  3355. ):
  3356. await mgr.start()
  3357. # FTP, FileTransfer, RTSP should be TCPProxy (transparent)
  3358. assert isinstance(mgr._ftp_proxy, TCPProxy), "FTP should be TCPProxy (transparent)"
  3359. assert isinstance(mgr._file_transfer_proxy, TCPProxy), "FileTransfer should be TCPProxy"
  3360. assert isinstance(mgr._rtsp_proxy, TCPProxy), "RTSP should be TCPProxy"
  3361. # MQTT should be TLSProxy (TLS-terminated for IP rewriting)
  3362. assert isinstance(mgr._mqtt_proxy, TLSProxy), "MQTT should be TLSProxy (TLS-terminated)"
  3363. # Auxiliary ports (2024-2026) should be TCPProxy (transparent)
  3364. assert len(mgr._aux_proxies) == 3, "Should have 3 aux port proxies"
  3365. for ap in mgr._aux_proxies:
  3366. assert isinstance(ap, TCPProxy), "Aux proxies should be TCPProxy"
  3367. assert mgr._aux_proxies[0].listen_port == 2024
  3368. assert mgr._aux_proxies[0].target_port == 2024
  3369. assert mgr._aux_proxies[2].listen_port == 2026
  3370. # FTP data ports should be pre-created as TCPProxy instances
  3371. assert len(mgr._ftp_data_proxies) == 101 # 50000-50100 inclusive
  3372. for dp in mgr._ftp_data_proxies:
  3373. assert isinstance(dp, TCPProxy), "FTP data proxies should be TCPProxy"
  3374. # Verify FTP data proxies target the same port on the printer
  3375. first_dp = mgr._ftp_data_proxies[0]
  3376. assert first_dp.listen_port == 50000
  3377. assert first_dp.target_port == 50000
  3378. assert first_dp.target_host == "192.168.1.100"
  3379. last_dp = mgr._ftp_data_proxies[-1]
  3380. assert last_dp.listen_port == 50100
  3381. assert last_dp.target_port == 50100
  3382. def test_proxy_manager_mqtt_has_ip_rewriting(self, tmp_path):
  3383. """Verify MQTT proxy is configured with IP rewriting when bind_address is set."""
  3384. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  3385. cert_path = tmp_path / "cert.pem"
  3386. key_path = tmp_path / "key.pem"
  3387. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  3388. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  3389. mgr = SlicerProxyManager(
  3390. target_host="192.168.1.100",
  3391. cert_path=cert_path,
  3392. key_path=key_path,
  3393. bind_address="10.0.0.1",
  3394. )
  3395. # Before start, proxies are None — verify constructor stores rewrite config
  3396. assert mgr.bind_address == "10.0.0.1"
  3397. assert mgr.target_host == "192.168.1.100"
  3398. class TestSSDPProxy:
  3399. """Tests for SSDPProxy (cross-network SSDP relay)."""
  3400. @pytest.fixture
  3401. def ssdp_proxy(self):
  3402. """Create an SSDPProxy instance."""
  3403. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  3404. return SSDPProxy(
  3405. local_interface_ip="192.168.1.100",
  3406. remote_interface_ip="10.0.0.100",
  3407. target_printer_ip="192.168.1.50",
  3408. )
  3409. def test_ssdp_proxy_stores_interface_ips(self, ssdp_proxy):
  3410. """Verify SSDPProxy stores interface IPs correctly."""
  3411. assert ssdp_proxy.local_interface_ip == "192.168.1.100"
  3412. assert ssdp_proxy.remote_interface_ip == "10.0.0.100"
  3413. assert ssdp_proxy.target_printer_ip == "192.168.1.50"
  3414. def test_rewrite_ssdp_location(self, ssdp_proxy):
  3415. """Verify SSDP Location header is rewritten to remote interface IP."""
  3416. original_packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: TestPrinter\r\n\r\n"
  3417. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  3418. # Location should be changed to remote interface IP
  3419. assert b"Location: 10.0.0.100" in rewritten
  3420. assert b"Location: 192.168.1.50" not in rewritten
  3421. # Other headers should be preserved
  3422. assert b"DevName.bambu.com: TestPrinter" in rewritten
  3423. def test_rewrite_ssdp_location_case_insensitive(self, ssdp_proxy):
  3424. """Verify SSDP Location rewrite is case insensitive."""
  3425. original_packet = b"NOTIFY * HTTP/1.1\r\nlocation: 192.168.1.50\r\n\r\n"
  3426. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  3427. assert b"10.0.0.100" in rewritten
  3428. def test_rewrite_ssdp_location_no_match(self, ssdp_proxy):
  3429. """Verify packet without Location header is returned unchanged."""
  3430. original_packet = b"NOTIFY * HTTP/1.1\r\nDevName.bambu.com: Test\r\n\r\n"
  3431. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  3432. # No Location header, but _rewrite_ssdp logs a warning and returns as-is
  3433. assert b"DevName.bambu.com: Test" in rewritten
  3434. def test_parse_ssdp_message(self, ssdp_proxy):
  3435. """Verify SSDP message parsing extracts headers."""
  3436. packet = (
  3437. b"NOTIFY * HTTP/1.1\r\n"
  3438. b"Location: 192.168.1.50\r\n"
  3439. b"DevName.bambu.com: TestPrinter\r\n"
  3440. b"DevModel.bambu.com: BL-P001\r\n"
  3441. b"\r\n"
  3442. )
  3443. headers = ssdp_proxy._parse_ssdp_message(packet)
  3444. assert headers["location"] == "192.168.1.50"
  3445. assert headers["devname.bambu.com"] == "TestPrinter"
  3446. assert headers["devmodel.bambu.com"] == "BL-P001"
  3447. class TestVirtualPrinterManagerDirectories:
  3448. """Tests for VirtualPrinterManager directory management."""
  3449. def test_ensure_base_directories_creates_subdirs(self, tmp_path):
  3450. """Verify _ensure_base_directories creates required base directories."""
  3451. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  3452. manager = VirtualPrinterManager()
  3453. manager._base_dir = tmp_path / "virtual_printer"
  3454. manager._ensure_base_directories()
  3455. assert (tmp_path / "virtual_printer").exists()
  3456. assert (tmp_path / "virtual_printer" / "uploads").exists()
  3457. assert (tmp_path / "virtual_printer" / "certs").exists()
  3458. def test_ensure_base_directories_handles_permission_error(self, tmp_path, caplog):
  3459. """Verify _ensure_base_directories logs error on permission failure."""
  3460. import logging
  3461. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  3462. manager = VirtualPrinterManager()
  3463. vp_dir = tmp_path / "virtual_printer"
  3464. manager._base_dir = vp_dir
  3465. original_mkdir = type(vp_dir).mkdir
  3466. def mock_mkdir(self, *args, **kwargs):
  3467. if "virtual_printer" in str(self):
  3468. raise PermissionError("Permission denied")
  3469. return original_mkdir(self, *args, **kwargs)
  3470. with caplog.at_level(logging.ERROR), patch.object(type(vp_dir), "mkdir", mock_mkdir):
  3471. manager._ensure_base_directories()
  3472. assert "Permission denied" in caplog.text
  3473. def test_instance_creates_per_vp_directories(self, tmp_path):
  3474. """Verify VirtualPrinterInstance creates per-VP upload and cert dirs."""
  3475. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  3476. VirtualPrinterInstance(
  3477. vp_id=42,
  3478. name="Test",
  3479. mode="library",
  3480. model="C11",
  3481. access_code="12345678",
  3482. serial_suffix="391800042",
  3483. base_dir=tmp_path,
  3484. )
  3485. assert (tmp_path / "uploads" / "42").exists()
  3486. assert (tmp_path / "uploads" / "42" / "cache").exists()
  3487. assert (tmp_path / "certs" / "42").exists()
  3488. class TestVirtualPrinterCameraPassthrough:
  3489. """Tests for the non-proxy VP camera pass-through port selection (#1868).
  3490. The camera port must follow the TARGET printer's model, not the VP's
  3491. spoofed model: RTSP models (X1/X2/H2/P2S) use 322, chamber-image models
  3492. (A1/P1) use 6000. Before the fix, the manager hardcoded 322, so P1S /
  3493. A1 targets got a 322 listener with no upstream and BambuStudio /
  3494. OrcaSlicer Liveview failed with error `[2:-10061]` (the reporter's
  3495. symptom in #1868).
  3496. """
  3497. @staticmethod
  3498. def _patch_start_server(monkeypatch):
  3499. """Patch every non-camera constructor start_server touches so the
  3500. test only exercises the camera-port branch. Returns the list that
  3501. ``TCPProxy`` calls get captured into."""
  3502. from backend.app.services.virtual_printer import manager as vp_manager
  3503. tcp_calls: list[dict] = []
  3504. class FakeTCPProxy:
  3505. def __init__(self, **kwargs):
  3506. tcp_calls.append(kwargs)
  3507. self.kwargs = kwargs
  3508. async def start(self):
  3509. return None
  3510. async def stop(self):
  3511. return None
  3512. # Camera pass-through is the only TCPProxy start_server constructs.
  3513. monkeypatch.setattr(vp_manager, "TCPProxy", FakeTCPProxy)
  3514. # No-op every other service constructor + resolve_cert_and_advertise.
  3515. # start_server() awaits `.ready.wait()` on FTP/MQTT/Bind/SSDP after
  3516. # spawning them, so each fake instance must carry an already-set
  3517. # asyncio.Event as `.ready` — a plain MagicMock returns another
  3518. # MagicMock for `.wait()`, which `asyncio.gather` then rejects with
  3519. # `TypeError: An asyncio.Future, a coroutine or an awaitable is
  3520. # required`.
  3521. def _service_factory():
  3522. def make(*args, **kwargs):
  3523. inst = MagicMock()
  3524. inst.start = AsyncMock(return_value=None)
  3525. inst.stop = AsyncMock(return_value=None)
  3526. ready = asyncio.Event()
  3527. ready.set()
  3528. inst.ready = ready
  3529. return inst
  3530. return make
  3531. for name in (
  3532. "VirtualPrinterFTPServer",
  3533. "SimpleMQTTServer",
  3534. "MQTTBridge",
  3535. "BindServer",
  3536. "VirtualPrinterSSDPServer",
  3537. "SSDPProxy",
  3538. ):
  3539. monkeypatch.setattr(vp_manager, name, _service_factory())
  3540. return tcp_calls
  3541. async def _run_start_server(
  3542. self,
  3543. tmp_path,
  3544. monkeypatch,
  3545. *,
  3546. target_model: str,
  3547. target_ip: str = "192.168.1.100",
  3548. ) -> list[dict]:
  3549. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  3550. tcp_calls = self._patch_start_server(monkeypatch)
  3551. instance = VirtualPrinterInstance(
  3552. vp_id=99,
  3553. name="CamTest",
  3554. mode="library",
  3555. model="BL-P001", # VP's spoofed identity — irrelevant here
  3556. access_code="12345678",
  3557. serial_suffix="391800099",
  3558. target_printer_id=7,
  3559. base_dir=tmp_path,
  3560. )
  3561. # printer_manager stub returns a client with the model + ip we want.
  3562. client = MagicMock()
  3563. client.ip_address = target_ip
  3564. client.model = target_model
  3565. printer_manager = MagicMock()
  3566. printer_manager.get_client.return_value = client
  3567. instance._printer_manager = printer_manager
  3568. # Cert / advertise resolution — start_server calls this early. Patch
  3569. # to a fixed tuple so no filesystem I/O is required.
  3570. monkeypatch.setattr(
  3571. instance,
  3572. "_resolve_cert_and_advertise",
  3573. lambda: (Path("/tmp/cert.pem"), Path("/tmp/key.pem"), "192.168.1.1"), # nosec B108
  3574. )
  3575. try:
  3576. await instance.start_server()
  3577. finally:
  3578. for task in instance._tasks:
  3579. task.cancel()
  3580. await asyncio.gather(*instance._tasks, return_exceptions=True)
  3581. return tcp_calls
  3582. @pytest.mark.asyncio
  3583. async def test_rtsp_model_p2s_opens_port_322(self, tmp_path, monkeypatch):
  3584. calls = await self._run_start_server(tmp_path, monkeypatch, target_model="P2S")
  3585. assert any(c["listen_port"] == 322 and c["target_port"] == 322 for c in calls), (
  3586. f"Expected 322 pass-through for RTSP model P2S, got {calls}"
  3587. )
  3588. @pytest.mark.asyncio
  3589. async def test_chamber_image_model_p1s_opens_port_6000(self, tmp_path, monkeypatch):
  3590. """#1868 regression guard: P1S target must expose 6000, not 322."""
  3591. calls = await self._run_start_server(tmp_path, monkeypatch, target_model="P1S")
  3592. assert any(c["listen_port"] == 6000 and c["target_port"] == 6000 for c in calls), (
  3593. f"Expected 6000 pass-through for chamber-image model P1S (#1868), got {calls}"
  3594. )
  3595. assert not any(c["listen_port"] == 322 for c in calls), f"P1S should NOT get a 322 listener, got {calls}"
  3596. @pytest.mark.asyncio
  3597. async def test_chamber_image_model_a1_opens_port_6000(self, tmp_path, monkeypatch):
  3598. calls = await self._run_start_server(tmp_path, monkeypatch, target_model="A1")
  3599. assert any(c["listen_port"] == 6000 and c["target_port"] == 6000 for c in calls)
  3600. @pytest.mark.asyncio
  3601. async def test_rtsp_model_x1c_opens_port_322(self, tmp_path, monkeypatch):
  3602. calls = await self._run_start_server(tmp_path, monkeypatch, target_model="X1C")
  3603. assert any(c["listen_port"] == 322 and c["target_port"] == 322 for c in calls)
  3604. class TestVirtualPrinterInstanceProxyMode:
  3605. """Tests for VirtualPrinterInstance proxy mode."""
  3606. @pytest.fixture
  3607. def proxy_instance(self, tmp_path):
  3608. """Create a proxy-mode VirtualPrinterInstance."""
  3609. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  3610. return VirtualPrinterInstance(
  3611. vp_id=10,
  3612. name="ProxyTest",
  3613. mode="proxy",
  3614. model="C11",
  3615. access_code="",
  3616. serial_suffix="391800010",
  3617. target_printer_ip="192.168.1.100",
  3618. target_printer_serial="01P00A000000001",
  3619. base_dir=tmp_path,
  3620. )
  3621. def test_proxy_instance_properties(self, proxy_instance):
  3622. """Verify proxy instance stores config correctly."""
  3623. assert proxy_instance.is_proxy is True
  3624. assert proxy_instance.mode == "proxy"
  3625. assert proxy_instance.target_printer_ip == "192.168.1.100"
  3626. assert proxy_instance.target_printer_serial == "01P00A000000001"
  3627. def test_proxy_instance_does_not_require_access_code(self, proxy_instance):
  3628. """Verify proxy mode can have empty access code."""
  3629. assert proxy_instance.access_code == ""
  3630. def test_get_status_proxy_includes_proxy_fields(self, proxy_instance):
  3631. """Verify get_status includes proxy fields when proxy is active."""
  3632. mock_proxy = MagicMock()
  3633. mock_proxy.get_status.return_value = {
  3634. "running": True,
  3635. "ftp_port": 990,
  3636. "mqtt_port": 8883,
  3637. "ftp_connections": 1,
  3638. "mqtt_connections": 2,
  3639. "target_host": "192.168.1.100",
  3640. }
  3641. proxy_instance._proxy = mock_proxy
  3642. status = proxy_instance.get_status()
  3643. assert "proxy" in status
  3644. assert status["proxy"]["ftp_port"] == 990
  3645. assert status["proxy"]["mqtt_connections"] == 2
  3646. def test_proxy_instance_stores_remote_interface(self, tmp_path):
  3647. """Verify proxy instance stores remote_interface_ip."""
  3648. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  3649. inst = VirtualPrinterInstance(
  3650. vp_id=11,
  3651. name="Proxy2",
  3652. mode="proxy",
  3653. model="C11",
  3654. access_code="",
  3655. serial_suffix="391800011",
  3656. target_printer_ip="192.168.1.100",
  3657. remote_interface_ip="10.0.0.50",
  3658. base_dir=tmp_path,
  3659. )
  3660. assert inst.remote_interface_ip == "10.0.0.50"
  3661. class TestVirtualPrinterInstanceIPOverride:
  3662. """Tests for remote_interface_ip and bind_ip on VirtualPrinterInstance."""
  3663. @pytest.fixture
  3664. def instance_with_remote_ip(self, tmp_path):
  3665. """Create an instance with remote_interface_ip set."""
  3666. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  3667. return VirtualPrinterInstance(
  3668. vp_id=20,
  3669. name="IPTest",
  3670. mode="library",
  3671. model="BL-P001",
  3672. access_code="12345678",
  3673. serial_suffix="391800020",
  3674. bind_ip="192.168.1.50",
  3675. remote_interface_ip="10.0.0.50",
  3676. base_dir=tmp_path,
  3677. )
  3678. def test_instance_stores_bind_ip(self, instance_with_remote_ip):
  3679. """Verify bind_ip is stored."""
  3680. assert instance_with_remote_ip.bind_ip == "192.168.1.50"
  3681. def test_instance_stores_remote_interface_ip(self, instance_with_remote_ip):
  3682. """Verify remote_interface_ip is stored."""
  3683. assert instance_with_remote_ip.remote_interface_ip == "10.0.0.50"
  3684. def test_generate_certificates_includes_remote_and_bind_ip(self, instance_with_remote_ip):
  3685. """Verify generate_certificates passes remote_interface_ip and bind_ip as SANs."""
  3686. with (
  3687. patch.object(instance_with_remote_ip._cert_service, "delete_printer_certificate"),
  3688. patch.object(
  3689. instance_with_remote_ip._cert_service,
  3690. "generate_certificates",
  3691. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  3692. ) as mock_gen,
  3693. ):
  3694. instance_with_remote_ip.generate_certificates()
  3695. mock_gen.assert_called_once_with(additional_ips=["10.0.0.50", "192.168.1.50"])
  3696. def test_generate_certificates_no_remote_ip(self, tmp_path):
  3697. """Verify generate_certificates passes only bind_ip when no remote_interface_ip."""
  3698. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  3699. inst = VirtualPrinterInstance(
  3700. vp_id=21,
  3701. name="NoRemote",
  3702. mode="library",
  3703. model="BL-P001",
  3704. access_code="12345678",
  3705. serial_suffix="391800021",
  3706. bind_ip="192.168.1.50",
  3707. base_dir=tmp_path,
  3708. )
  3709. with (
  3710. patch.object(inst._cert_service, "delete_printer_certificate"),
  3711. patch.object(
  3712. inst._cert_service,
  3713. "generate_certificates",
  3714. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  3715. ) as mock_gen,
  3716. ):
  3717. inst.generate_certificates()
  3718. mock_gen.assert_called_once_with(additional_ips=["192.168.1.50"])
  3719. def test_generate_certificates_no_ips(self, tmp_path):
  3720. """Verify generate_certificates passes None when no IPs configured."""
  3721. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  3722. inst = VirtualPrinterInstance(
  3723. vp_id=22,
  3724. name="NoIPs",
  3725. mode="library",
  3726. model="BL-P001",
  3727. access_code="12345678",
  3728. serial_suffix="391800022",
  3729. base_dir=tmp_path,
  3730. )
  3731. with (
  3732. patch.object(inst._cert_service, "delete_printer_certificate"),
  3733. patch.object(
  3734. inst._cert_service,
  3735. "generate_certificates",
  3736. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  3737. ) as mock_gen,
  3738. ):
  3739. inst.generate_certificates()
  3740. mock_gen.assert_called_once_with(additional_ips=None)
  3741. class TestBindServer:
  3742. """Tests for the BindServer (port 3002 bind/detect protocol)."""
  3743. @pytest.fixture
  3744. def bind_server(self):
  3745. """Create a BindServer instance."""
  3746. from backend.app.services.virtual_printer.bind_server import BindServer
  3747. return BindServer(
  3748. serial="01S00C000000001",
  3749. model="BL-P001",
  3750. name="Bambuddy",
  3751. )
  3752. def test_build_frame(self, bind_server):
  3753. """Verify frame format: 0xA5A5 + len(u16le) + JSON + 0xA7A7."""
  3754. payload = {"login": {"command": "detect"}}
  3755. frame = bind_server._build_frame(payload)
  3756. assert frame[:2] == b"\xa5\xa5"
  3757. assert frame[-2:] == b"\xa7\xa7"
  3758. # Length field is total message size
  3759. import struct
  3760. total_len = struct.unpack_from("<H", frame, 2)[0]
  3761. assert total_len == len(frame)
  3762. # JSON payload is between header and trailer
  3763. import json
  3764. json_bytes = frame[4:-2]
  3765. parsed = json.loads(json_bytes)
  3766. assert parsed == payload
  3767. def test_parse_frame_valid(self, bind_server):
  3768. """Verify valid frame parsing."""
  3769. frame = bind_server._build_frame({"login": {"command": "detect", "sequence_id": "20000"}})
  3770. result = bind_server._parse_frame(frame)
  3771. assert result is not None
  3772. assert result["login"]["command"] == "detect"
  3773. assert result["login"]["sequence_id"] == "20000"
  3774. def test_parse_frame_invalid_header(self, bind_server):
  3775. """Verify invalid header returns None."""
  3776. frame = b"\xb5\xb5\x10\x00" + b'{"login":{}}' + b"\xa7\xa7"
  3777. assert bind_server._parse_frame(frame) is None
  3778. def test_parse_frame_invalid_trailer(self, bind_server):
  3779. """Verify invalid trailer returns None."""
  3780. frame = b"\xa5\xa5\x10\x00" + b'{"login":{}}' + b"\xb7\xb7"
  3781. assert bind_server._parse_frame(frame) is None
  3782. def test_parse_frame_too_short(self, bind_server):
  3783. """Verify short data returns None."""
  3784. assert bind_server._parse_frame(b"\xa5\xa5\x00") is None
  3785. assert bind_server._parse_frame(b"") is None
  3786. def test_parse_frame_invalid_json(self, bind_server):
  3787. """Verify invalid JSON returns None."""
  3788. import struct
  3789. bad_json = b"not json"
  3790. total_len = 4 + len(bad_json) + 2
  3791. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  3792. assert bind_server._parse_frame(frame) is None
  3793. def test_build_frame_roundtrip(self, bind_server):
  3794. """Verify build then parse roundtrip."""
  3795. original = {"login": {"bind": "free", "command": "detect", "id": "01S00C000000001"}}
  3796. frame = bind_server._build_frame(original)
  3797. parsed = bind_server._parse_frame(frame)
  3798. assert parsed == original
  3799. def test_bind_server_stores_config(self, bind_server):
  3800. """Verify config is stored correctly."""
  3801. assert bind_server.serial == "01S00C000000001"
  3802. assert bind_server.model == "BL-P001"
  3803. assert bind_server.name == "Bambuddy"
  3804. assert bind_server.version == "01.00.00.00"
  3805. def test_bind_server_custom_version(self):
  3806. """Verify custom firmware version is stored."""
  3807. from backend.app.services.virtual_printer.bind_server import BindServer
  3808. server = BindServer(
  3809. serial="01S00C000000001",
  3810. model="BL-P001",
  3811. name="Bambuddy",
  3812. version="01.09.00.10",
  3813. )
  3814. assert server.version == "01.09.00.10"
  3815. def test_bind_ports_includes_both(self):
  3816. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  3817. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  3818. assert 3000 in BIND_PORTS
  3819. assert 3002 in BIND_PORTS
  3820. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  3821. """Verify bind server starts with empty servers list."""
  3822. assert bind_server._servers == []
  3823. assert bind_server._running is False
  3824. @pytest.mark.asyncio
  3825. async def test_start_server_creates_bind_server(self, tmp_path):
  3826. """Verify start_server creates BindServer with correct params."""
  3827. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  3828. inst = VirtualPrinterInstance(
  3829. vp_id=99,
  3830. name="Bambuddy",
  3831. mode="library",
  3832. model="BL-P001",
  3833. access_code="12345678",
  3834. serial_suffix="391800099",
  3835. bind_ip="192.168.1.50",
  3836. base_dir=tmp_path,
  3837. )
  3838. # Each mocked child service exposes a real asyncio.Event for the
  3839. # readiness barrier added in start_server (set on instantiation so
  3840. # the barrier returns immediately in tests).
  3841. ready_event = asyncio.Event()
  3842. ready_event.set()
  3843. def with_ready(*_args, **_kwargs):
  3844. child = MagicMock()
  3845. child.ready = ready_event
  3846. return child
  3847. with (
  3848. patch(
  3849. "backend.app.services.virtual_printer.manager.VirtualPrinterSSDPServer",
  3850. side_effect=with_ready,
  3851. ),
  3852. patch(
  3853. "backend.app.services.virtual_printer.manager.VirtualPrinterFTPServer",
  3854. side_effect=with_ready,
  3855. ),
  3856. patch(
  3857. "backend.app.services.virtual_printer.manager.SimpleMQTTServer",
  3858. side_effect=with_ready,
  3859. ),
  3860. patch(
  3861. "backend.app.services.virtual_printer.manager.BindServer",
  3862. side_effect=with_ready,
  3863. ) as mock_bind_cls,
  3864. patch.object(inst._cert_service, "delete_printer_certificate"),
  3865. patch.object(
  3866. inst._cert_service,
  3867. "generate_certificates",
  3868. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  3869. ),
  3870. ):
  3871. await inst.start_server()
  3872. mock_bind_cls.assert_called_once_with(
  3873. serial=inst.serial,
  3874. model="BL-P001",
  3875. name="Bambuddy",
  3876. bind_address="192.168.1.50",
  3877. cert_path=Path("/tmp/cert.pem"), # nosec B108
  3878. key_path=Path("/tmp/key.pem"), # nosec B108
  3879. )
  3880. class TestResolveModelCodes:
  3881. """Tests for model code resolution (display name → SSDP code)."""
  3882. def test_display_name_to_model_code_maps_all_models(self):
  3883. """Verify reverse mapping covers all VIRTUAL_PRINTER_MODELS entries."""
  3884. from backend.app.services.virtual_printer.manager import DISPLAY_NAME_TO_MODEL_CODE, VIRTUAL_PRINTER_MODELS
  3885. for _code, display_name in VIRTUAL_PRINTER_MODELS.items():
  3886. assert display_name in DISPLAY_NAME_TO_MODEL_CODE
  3887. # For non-duplicate display names, should map back to a valid code
  3888. assert DISPLAY_NAME_TO_MODEL_CODE[display_name] in VIRTUAL_PRINTER_MODELS
  3889. def test_resolve_printer_model_with_ssdp_code(self):
  3890. """SSDP codes pass through unchanged."""
  3891. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  3892. assert _resolve_printer_model("BL-P001") == "BL-P001"
  3893. assert _resolve_printer_model("O1D") == "O1D"
  3894. assert _resolve_printer_model("N2S") == "N2S"
  3895. def test_resolve_printer_model_with_display_name(self):
  3896. """Display names resolve to SSDP codes."""
  3897. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  3898. assert _resolve_printer_model("X1C") == "BL-P001"
  3899. assert _resolve_printer_model("H2D") == "O1D"
  3900. assert _resolve_printer_model("A1") == "N2S"
  3901. assert _resolve_printer_model("P1S") == "C12"
  3902. def test_resolve_printer_model_with_none_or_unknown(self):
  3903. """None and unknown values return None."""
  3904. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  3905. assert _resolve_printer_model(None) is None
  3906. assert _resolve_printer_model("UnknownModel") is None
  3907. class TestMqttIpRewrite:
  3908. """Tests for TLSProxy._rewrite_mqtt_ip() MQTT packet IP rewriting."""
  3909. @staticmethod
  3910. def _build_mqtt_publish(topic: str, payload: bytes) -> bytes:
  3911. """Build a minimal MQTT PUBLISH packet."""
  3912. # PUBLISH fixed header: type 3, no flags
  3913. topic_bytes = topic.encode("utf-8")
  3914. # Variable header: topic length (2 bytes) + topic
  3915. var_header = len(topic_bytes).to_bytes(2, "big") + topic_bytes
  3916. body = var_header + payload
  3917. # Encode remaining length
  3918. remaining = len(body)
  3919. header = bytearray([0x30]) # PUBLISH, QoS 0
  3920. while True:
  3921. encoded_byte = remaining % 128
  3922. remaining //= 128
  3923. if remaining > 0:
  3924. encoded_byte |= 0x80
  3925. header.append(encoded_byte)
  3926. if remaining == 0:
  3927. break
  3928. return bytes(header) + body
  3929. @staticmethod
  3930. def _build_mqtt_pingreq() -> bytes:
  3931. """Build an MQTT PINGREQ packet (2 bytes, no payload)."""
  3932. return b"\xc0\x00"
  3933. def test_rewrite_ip_in_publish(self):
  3934. """IP string in PUBLISH payload is rewritten."""
  3935. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  3936. payload = b'{"rtsp_url":"rtsps://192.168.1.100:322/live"}'
  3937. packet = self._build_mqtt_publish("device/status", payload)
  3938. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  3939. assert b"10.0.0.1" in result
  3940. assert b"192.168.1.100" not in result
  3941. def test_no_rewrite_when_ip_absent(self):
  3942. """Packets without the target IP are passed through unchanged."""
  3943. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  3944. payload = b'{"status":"idle"}'
  3945. packet = self._build_mqtt_publish("device/status", payload)
  3946. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  3947. assert result == packet
  3948. def test_non_publish_packets_unchanged(self):
  3949. """Non-PUBLISH packets (e.g. PINGREQ) are never rewritten."""
  3950. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  3951. pingreq = self._build_mqtt_pingreq()
  3952. result, buf = TLSProxy._rewrite_mqtt_ip(pingreq, b"192.168.1.100", b"10.0.0.1", bytearray())
  3953. assert result == pingreq
  3954. def test_rewrite_preserves_packet_framing(self):
  3955. """Rewritten packet has valid MQTT remaining length."""
  3956. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  3957. # Use IPs of different lengths to test length re-encoding
  3958. old_ip = b"192.168.255.133" # 15 bytes
  3959. new_ip = b"10.0.0.1" # 8 bytes
  3960. payload = b'{"ip":"192.168.255.133"}'
  3961. packet = self._build_mqtt_publish("device/status", payload)
  3962. result, buf = TLSProxy._rewrite_mqtt_ip(packet, old_ip, new_ip, bytearray())
  3963. # Parse the result to verify framing
  3964. assert result[0] == 0x30 # PUBLISH header byte
  3965. # Decode remaining length
  3966. pos = 1
  3967. remaining = 0
  3968. multiplier = 1
  3969. while True:
  3970. b = result[pos]
  3971. pos += 1
  3972. remaining += (b & 0x7F) * multiplier
  3973. multiplier *= 128
  3974. if (b & 0x80) == 0:
  3975. break
  3976. # Remaining length should match actual data
  3977. assert pos + remaining == len(result)
  3978. assert new_ip in result
  3979. def test_incomplete_packet_buffered(self):
  3980. """Incomplete packet at end of chunk is buffered for next call."""
  3981. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  3982. payload = b'{"ip":"192.168.1.100"}'
  3983. packet = self._build_mqtt_publish("device/status", payload)
  3984. # Split packet in the middle
  3985. half = len(packet) // 2
  3986. chunk1 = packet[:half]
  3987. chunk2 = packet[half:]
  3988. result1, buf = TLSProxy._rewrite_mqtt_ip(chunk1, b"192.168.1.100", b"10.0.0.1", bytearray())
  3989. # First chunk should be buffered (incomplete packet)
  3990. assert len(buf) > 0
  3991. result2, buf = TLSProxy._rewrite_mqtt_ip(chunk2, b"192.168.1.100", b"10.0.0.1", buf)
  3992. # Second chunk completes the packet, IP should be rewritten
  3993. combined = result1 + result2
  3994. assert b"10.0.0.1" in combined
  3995. assert b"192.168.1.100" not in combined
  3996. def test_multiple_packets_in_one_chunk(self):
  3997. """Multiple MQTT packets in a single chunk are all processed."""
  3998. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  3999. payload1 = b'{"ip":"192.168.1.100"}'
  4000. payload2 = b'{"other":"data"}'
  4001. packet1 = self._build_mqtt_publish("topic1", payload1)
  4002. packet2 = self._build_mqtt_publish("topic2", payload2)
  4003. combined = packet1 + packet2
  4004. result, buf = TLSProxy._rewrite_mqtt_ip(combined, b"192.168.1.100", b"10.0.0.1", bytearray())
  4005. assert b"10.0.0.1" in result
  4006. assert b"192.168.1.100" not in result
  4007. # Second packet should still be present
  4008. assert b"other" in result
  4009. def test_extra_replacements(self):
  4010. """Extra replacement pairs (e.g. integer IP) are also applied."""
  4011. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  4012. payload = b'{"net":{"info":[{"ip":2248124608}]}}'
  4013. packet = self._build_mqtt_publish("device/status", payload)
  4014. result, buf = TLSProxy._rewrite_mqtt_ip(
  4015. packet,
  4016. b"NOMATCH",
  4017. b"NOREPLACE",
  4018. bytearray(),
  4019. extra_replacements=[(b"2248124608", b"285190336")],
  4020. )
  4021. assert b"285190336" in result
  4022. assert b"2248124608" not in result
  4023. class TestIpToLeIntBytes:
  4024. """Tests for TLSProxy._ip_to_le_int_bytes() integer IP conversion."""
  4025. def test_converts_ip_to_le_int(self):
  4026. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  4027. assert TLSProxy._ip_to_le_int_bytes("192.168.255.133") == b"2248124608"
  4028. assert TLSProxy._ip_to_le_int_bytes("192.168.255.16") == b"285190336"
  4029. assert TLSProxy._ip_to_le_int_bytes("10.0.0.1") == b"16777226"
  4030. def test_roundtrip(self):
  4031. """Verify the integer converts back to the correct IP."""
  4032. import struct
  4033. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  4034. for ip in ["192.168.1.1", "10.0.0.1", "172.16.0.100", "192.168.255.133"]:
  4035. le_int = int(TLSProxy._ip_to_le_int_bytes(ip))
  4036. parts = ip.split(".")
  4037. expected = struct.unpack("<I", bytes(int(p) for p in parts))[0]
  4038. assert le_int == expected
  4039. class TestSSDPProxyName:
  4040. """Tests for SSDPProxy VP name rewriting."""
  4041. @pytest.fixture
  4042. def ssdp_proxy_with_name(self):
  4043. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  4044. return SSDPProxy(
  4045. local_interface_ip="192.168.1.100",
  4046. remote_interface_ip="10.0.0.100",
  4047. target_printer_ip="192.168.1.50",
  4048. name="H2D-1 Proxy",
  4049. )
  4050. @pytest.fixture
  4051. def ssdp_proxy_without_name(self):
  4052. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  4053. return SSDPProxy(
  4054. local_interface_ip="192.168.1.100",
  4055. remote_interface_ip="10.0.0.100",
  4056. target_printer_ip="192.168.1.50",
  4057. )
  4058. def test_rewrite_uses_configured_name(self, ssdp_proxy_with_name):
  4059. """When name is set, DevName is replaced entirely."""
  4060. packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: RealPrinter\r\nDevBind.bambu.com: cloud\r\n\r\n"
  4061. rewritten = ssdp_proxy_with_name._rewrite_ssdp(packet)
  4062. assert b"DevName.bambu.com: H2D-1 Proxy" in rewritten
  4063. assert b"RealPrinter" not in rewritten
  4064. def test_rewrite_appends_proxy_without_name(self, ssdp_proxy_without_name):
  4065. """When no name is set, ' - Proxy' is appended to the real name."""
  4066. packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: RealPrinter\r\nDevBind.bambu.com: cloud\r\n\r\n"
  4067. rewritten = ssdp_proxy_without_name._rewrite_ssdp(packet)
  4068. assert b"DevName.bambu.com: RealPrinter - Proxy" in rewritten
  4069. class TestVPProjectFileStashKey:
  4070. """Regression: `on_print_command` MUST stash slicer options under the
  4071. FTP filename (`data["file"]`, with extension), NOT under `filename`
  4072. (the slicer's `subtask_name`, bare).
  4073. #1780 root cause (real bundle, 2026-06-21): BambuStudio sends
  4074. `subtask_name = "Model_Name"` (bare) and `file = "Model_Name.gcode.3mf"`
  4075. (with extension). `_add_to_print_queue` looks up the stash under
  4076. `file_path.name` from the FTP receive side, which always has the
  4077. extension. If the stash uses `subtask_name`, lookup misses → every
  4078. captured slicer field (bed_leveling, flow_cali, vibration_cali,
  4079. layer_inspect, timelapse, nozzle_mapping) silently falls back to
  4080. settings defaults on every Bambu Studio "Send" upload.
  4081. `filename` (subtask_name) must still flow to `_schedule_finish_release`
  4082. untouched — push_status echoes it back as gcode_file / subtask_name and
  4083. the slicer matches against its own local subtask_name there. So
  4084. `on_print_command` keeps `filename` for state-feedback but derives the
  4085. stash key from `data["file"]`.
  4086. """
  4087. @pytest.fixture
  4088. def instance(self, tmp_path):
  4089. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  4090. return VirtualPrinterInstance(
  4091. vp_id=99,
  4092. name="StashKeyTest",
  4093. mode="queue",
  4094. model="O1C2",
  4095. access_code="12345678",
  4096. serial_suffix="999999999",
  4097. base_dir=tmp_path,
  4098. )
  4099. @pytest.mark.asyncio
  4100. async def test_stash_key_uses_file_field_not_subtask_name(self, instance):
  4101. """BambuStudio's real wire shape: `subtask_name` ≠ `file`.
  4102. on_print_command must stash under `data["file"]` so the FTP-side
  4103. `_add_to_print_queue` lookup matches.
  4104. """
  4105. # mqtt_server.py:_handle_publish hands the bare subtask_name as
  4106. # `filename` and the full print_data body as `data`. The FTP filename
  4107. # lives in `data["file"]`.
  4108. await instance.on_print_command(
  4109. "Filament_Track_Switch_Holder", # subtask_name (bare)
  4110. {
  4111. "command": "project_file",
  4112. "subtask_name": "Filament_Track_Switch_Holder",
  4113. "file": "Filament_Track_Switch_Holder.gcode.3mf",
  4114. "nozzle_mapping": [16, -1, -1, 1],
  4115. },
  4116. )
  4117. # Stash MUST be under the FTP filename, not the bare subtask_name.
  4118. # `_add_to_print_queue` does `_slicer_print_options.pop(file_path.name, None)`
  4119. # where file_path.name == "Filament_Track_Switch_Holder.gcode.3mf".
  4120. assert "Filament_Track_Switch_Holder.gcode.3mf" in instance._slicer_print_options
  4121. assert "Filament_Track_Switch_Holder" not in instance._slicer_print_options
  4122. # Body must carry nozzle_mapping verbatim.
  4123. stashed = instance._slicer_print_options["Filament_Track_Switch_Holder.gcode.3mf"]
  4124. assert stashed["nozzle_mapping"] == [16, -1, -1, 1]
  4125. @pytest.mark.asyncio
  4126. async def test_stash_key_falls_back_to_filename_when_file_absent(self, instance):
  4127. """Defensive fallback: a slicer that omits the `file` field entirely
  4128. (legacy / non-3MF) must fall back to `filename` (subtask_name), not
  4129. leave the stash unkeyed."""
  4130. await instance.on_print_command(
  4131. "BareName",
  4132. {
  4133. "command": "project_file",
  4134. "subtask_name": "BareName",
  4135. # no "file" field
  4136. },
  4137. )
  4138. assert "BareName" in instance._slicer_print_options
  4139. @pytest.mark.asyncio
  4140. async def test_stash_key_signals_event_under_file_key(self, instance):
  4141. """`_add_to_print_queue` registers a wait-event under `file_path.name`
  4142. when the slicer's project_file arrives late. on_print_command must
  4143. signal THAT event (keyed by the FTP filename), not one keyed by
  4144. subtask_name — else the waiter times out even though the stash is
  4145. present and addressable."""
  4146. import asyncio
  4147. ftp_filename = "Filament_Track_Switch_Holder.gcode.3mf"
  4148. event = asyncio.Event()
  4149. instance._slicer_print_options_events[ftp_filename] = event
  4150. await instance.on_print_command(
  4151. "Filament_Track_Switch_Holder", # bare subtask_name
  4152. {
  4153. "command": "project_file",
  4154. "subtask_name": "Filament_Track_Switch_Holder",
  4155. "file": ftp_filename,
  4156. },
  4157. )
  4158. # Event keyed by FTP filename must fire even though on_print_command
  4159. # was called with the bare subtask_name.
  4160. assert event.is_set()