test_virtual_printer.py 197 KB

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