test_virtual_printer.py 203 KB

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