test_virtual_printer.py 202 KB

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