test_virtual_printer.py 158 KB

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