test_virtual_printer.py 203 KB

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