test_virtual_printer.py 191 KB

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