test_virtual_printer.py 197 KB

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