test_virtual_printer.py 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003
  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_uses_workflow_defaults_from_settings(self, tmp_path):
  480. """#1235: VP queue-mode constructed PrintQueueItem without specifying
  481. bed_levelling / flow_cali / vibration_cali / layer_inspect / timelapse,
  482. so SQLAlchemy applied the column-level defaults and ignored the user's
  483. workflow preferences entirely. Every print sent from the slicer to the
  484. VP came through with the OPPOSITE of what the workflow page said,
  485. forcing the user to edit each queue item by hand.
  486. """
  487. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  488. added_items = []
  489. mock_db = AsyncMock()
  490. mock_db.add = MagicMock(side_effect=added_items.append)
  491. mock_db.commit = AsyncMock()
  492. mock_session_factory = MagicMock()
  493. mock_session_ctx = AsyncMock()
  494. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  495. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  496. mock_session_factory.return_value = mock_session_ctx
  497. inst = VirtualPrinterInstance(
  498. vp_id=22,
  499. name="DefaultsTest",
  500. mode="queue",
  501. model="C12",
  502. access_code="12345678",
  503. serial_suffix="391800022",
  504. auto_dispatch=True,
  505. base_dir=tmp_path,
  506. session_factory=mock_session_factory,
  507. )
  508. file_path = tmp_path / "test.3mf"
  509. file_path.write_bytes(b"fake3mf")
  510. # The reporter set every workflow default to the OPPOSITE of the model's
  511. # column default. Pre-fix the column defaults won; with the fix the
  512. # settings values must flow through to the queue item exactly as stored.
  513. settings_map = {
  514. "virtual_printer_archive_name_source": None,
  515. "default_bed_levelling": "false", # model default: True
  516. "default_flow_cali": "true", # model default: False
  517. "default_vibration_cali": "false", # model default: True
  518. "default_layer_inspect": "true", # model default: False
  519. "default_timelapse": "true", # model default: False
  520. }
  521. async def fake_get_setting(_db, key):
  522. return settings_map.get(key)
  523. mock_archive = MagicMock()
  524. mock_archive.id = 1
  525. mock_archive.print_name = "test"
  526. with (
  527. patch(
  528. "backend.app.api.routes.settings.get_setting",
  529. new=fake_get_setting,
  530. ),
  531. patch(
  532. "backend.app.services.archive.ArchiveService.archive_print",
  533. new_callable=AsyncMock,
  534. return_value=mock_archive,
  535. ),
  536. ):
  537. await inst._add_to_print_queue(file_path, "192.168.1.100")
  538. assert len(added_items) == 1
  539. queue_item = added_items[0]
  540. assert queue_item.bed_levelling is False, "default_bed_levelling=false must flow through"
  541. assert queue_item.flow_cali is True, "default_flow_cali=true must flow through"
  542. assert queue_item.vibration_cali is False, "default_vibration_cali=false must flow through"
  543. assert queue_item.layer_inspect is True, "default_layer_inspect=true must flow through"
  544. assert queue_item.timelapse is True, "default_timelapse=true must flow through"
  545. @pytest.mark.asyncio
  546. async def test_add_to_print_queue_falls_back_to_schema_defaults_when_unset(self, tmp_path):
  547. """#1235 fallback: when no workflow setting is in the DB, the queue
  548. item should use the AppSettings (Pydantic) defaults — same values
  549. the user sees in the workflow page on a fresh install.
  550. """
  551. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  552. added_items = []
  553. mock_db = AsyncMock()
  554. mock_db.add = MagicMock(side_effect=added_items.append)
  555. mock_db.commit = AsyncMock()
  556. mock_session_factory = MagicMock()
  557. mock_session_ctx = AsyncMock()
  558. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  559. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  560. mock_session_factory.return_value = mock_session_ctx
  561. inst = VirtualPrinterInstance(
  562. vp_id=23,
  563. name="FreshInstallDefaults",
  564. mode="queue",
  565. model="C12",
  566. access_code="12345678",
  567. serial_suffix="391800023",
  568. auto_dispatch=True,
  569. base_dir=tmp_path,
  570. session_factory=mock_session_factory,
  571. )
  572. file_path = tmp_path / "test.3mf"
  573. file_path.write_bytes(b"fake3mf")
  574. mock_archive = MagicMock()
  575. mock_archive.id = 1
  576. mock_archive.print_name = "test"
  577. with (
  578. patch(
  579. "backend.app.api.routes.settings.get_setting",
  580. new_callable=AsyncMock,
  581. return_value=None, # No settings → fall back to schema defaults
  582. ),
  583. patch(
  584. "backend.app.services.archive.ArchiveService.archive_print",
  585. new_callable=AsyncMock,
  586. return_value=mock_archive,
  587. ),
  588. ):
  589. await inst._add_to_print_queue(file_path, "192.168.1.100")
  590. assert len(added_items) == 1
  591. queue_item = added_items[0]
  592. # These must match the AppSettings (Pydantic) defaults in schemas/settings.py
  593. assert queue_item.bed_levelling is True
  594. assert queue_item.flow_cali is False
  595. assert queue_item.vibration_cali is True
  596. assert queue_item.layer_inspect is False
  597. assert queue_item.timelapse is False
  598. @pytest.mark.asyncio
  599. async def test_add_to_print_queue_inherits_slicer_print_options(self, tmp_path):
  600. """#1403: VP-queue items used to fall back to `default_timelapse` even
  601. though the slicer's MQTT `project_file` command carries the user's
  602. actual choice. Capture-via-`on_print_command` flow lets the user's
  603. slicer toggle reach the queue item.
  604. Settings here have timelapse OFF; the slicer's MQTT capture has it ON.
  605. After the fix the queue item must reflect the slicer's choice.
  606. """
  607. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  608. added_items = []
  609. mock_db = AsyncMock()
  610. mock_db.add = MagicMock(side_effect=added_items.append)
  611. mock_db.commit = AsyncMock()
  612. mock_session_factory = MagicMock()
  613. mock_session_ctx = AsyncMock()
  614. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  615. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  616. mock_session_factory.return_value = mock_session_ctx
  617. inst = VirtualPrinterInstance(
  618. vp_id=24,
  619. name="SlicerInherits",
  620. mode="queue",
  621. model="C12",
  622. access_code="12345678",
  623. serial_suffix="391800024",
  624. auto_dispatch=True,
  625. base_dir=tmp_path,
  626. session_factory=mock_session_factory,
  627. )
  628. file_path = tmp_path / "test.3mf"
  629. file_path.write_bytes(b"fake3mf")
  630. # Pre-populate the capture as if MQTT `project_file` arrived already.
  631. # Settings (below) deliberately have timelapse OFF — only the slicer
  632. # capture should drive the resulting queue item.
  633. await inst.on_print_command(
  634. file_path.name,
  635. {
  636. "command": "project_file",
  637. "timelapse": True,
  638. "bed_leveling": False, # Note: MQTT field is single-L `bed_leveling`
  639. "flow_cali": True,
  640. "vibration_cali": False,
  641. "layer_inspect": True,
  642. },
  643. )
  644. settings_map = {
  645. "virtual_printer_archive_name_source": None,
  646. "default_bed_levelling": "true",
  647. "default_flow_cali": "false",
  648. "default_vibration_cali": "true",
  649. "default_layer_inspect": "false",
  650. "default_timelapse": "false",
  651. }
  652. async def fake_get_setting(_db, key):
  653. return settings_map.get(key)
  654. mock_archive = MagicMock()
  655. mock_archive.id = 1
  656. mock_archive.print_name = "test"
  657. with (
  658. patch(
  659. "backend.app.api.routes.settings.get_setting",
  660. new=fake_get_setting,
  661. ),
  662. patch(
  663. "backend.app.services.archive.ArchiveService.archive_print",
  664. new_callable=AsyncMock,
  665. return_value=mock_archive,
  666. ),
  667. ):
  668. await inst._add_to_print_queue(file_path, "192.168.1.100")
  669. assert len(added_items) == 1
  670. queue_item = added_items[0]
  671. assert queue_item.timelapse is True, "Slicer's timelapse=True must override settings.default_timelapse=False"
  672. assert queue_item.bed_levelling is False, "Slicer's bed_leveling=False must override default_bed_levelling=True"
  673. assert queue_item.flow_cali is True
  674. assert queue_item.vibration_cali is False
  675. assert queue_item.layer_inspect is True
  676. # Capture is consumed — no lingering state for the next print of the same name.
  677. assert file_path.name not in inst._slicer_print_options
  678. @pytest.mark.asyncio
  679. async def test_add_to_print_queue_coerces_slicer_integer_zero_one(self, tmp_path):
  680. """#1403: H-family firmwares carry calibration flags as integers
  681. (0/1) rather than booleans. The capture must coerce both shapes so
  682. H-family-sliced jobs through the VP queue work the same as P1/X1.
  683. """
  684. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  685. added_items = []
  686. mock_db = AsyncMock()
  687. mock_db.add = MagicMock(side_effect=added_items.append)
  688. mock_db.commit = AsyncMock()
  689. mock_session_factory = MagicMock()
  690. mock_session_ctx = AsyncMock()
  691. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  692. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  693. mock_session_factory.return_value = mock_session_ctx
  694. inst = VirtualPrinterInstance(
  695. vp_id=25,
  696. name="SlicerIntegers",
  697. mode="queue",
  698. model="C12",
  699. access_code="12345678",
  700. serial_suffix="391800025",
  701. auto_dispatch=True,
  702. base_dir=tmp_path,
  703. session_factory=mock_session_factory,
  704. )
  705. file_path = tmp_path / "test.3mf"
  706. file_path.write_bytes(b"fake3mf")
  707. await inst.on_print_command(
  708. file_path.name,
  709. {"command": "project_file", "timelapse": 1, "bed_leveling": 0, "flow_cali": 1},
  710. )
  711. mock_archive = MagicMock()
  712. mock_archive.id = 1
  713. mock_archive.print_name = "test"
  714. with (
  715. patch(
  716. "backend.app.api.routes.settings.get_setting",
  717. new_callable=AsyncMock,
  718. return_value=None,
  719. ),
  720. patch(
  721. "backend.app.services.archive.ArchiveService.archive_print",
  722. new_callable=AsyncMock,
  723. return_value=mock_archive,
  724. ),
  725. ):
  726. await inst._add_to_print_queue(file_path, "192.168.1.100")
  727. assert len(added_items) == 1
  728. queue_item = added_items[0]
  729. assert queue_item.timelapse is True, "integer 1 must coerce to True"
  730. assert queue_item.bed_levelling is False, "integer 0 must coerce to False"
  731. assert queue_item.flow_cali is True
  732. @pytest.mark.asyncio
  733. async def test_add_to_print_queue_populates_required_filament_types(self, tmp_path):
  734. """#1188: VP queue-mode used to create PrintQueueItems with no
  735. filament fields, so the scheduler fell through to model-only matching
  736. and dispatched onto whatever printer was free regardless of loaded
  737. colour. ``required_filament_types`` is populated unconditionally
  738. (cheap, helps the scheduler validate type even without
  739. ``force_color_match``) — pin that contract here."""
  740. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  741. added_items = []
  742. mock_db = AsyncMock()
  743. mock_db.add = MagicMock(side_effect=added_items.append)
  744. mock_db.commit = AsyncMock()
  745. mock_session_factory = MagicMock()
  746. mock_session_ctx = AsyncMock()
  747. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  748. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  749. mock_session_factory.return_value = mock_session_ctx
  750. inst = VirtualPrinterInstance(
  751. vp_id=21,
  752. name="Reqs",
  753. mode="queue",
  754. model="C12",
  755. access_code="12345678",
  756. serial_suffix="391800021",
  757. auto_dispatch=True,
  758. queue_force_color_match=False, # off → only required_filament_types
  759. base_dir=tmp_path,
  760. session_factory=mock_session_factory,
  761. )
  762. file_path = tmp_path / "multi.3mf"
  763. _write_3mf_with_filaments(
  764. file_path,
  765. [
  766. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "12.3"},
  767. {"id": "2", "type": "PETG", "color": "#000000", "used_g": "4.5"},
  768. # used_g=0 → not actually consumed by this plate, must be ignored
  769. {"id": "3", "type": "ABS", "color": "#FF0000", "used_g": "0"},
  770. ],
  771. plate_index=1,
  772. )
  773. mock_archive = MagicMock()
  774. mock_archive.id = 1
  775. mock_archive.print_name = "multi"
  776. with (
  777. patch(
  778. "backend.app.api.routes.settings.get_setting",
  779. new_callable=AsyncMock,
  780. return_value=None,
  781. ),
  782. patch(
  783. "backend.app.services.archive.ArchiveService.archive_print",
  784. new_callable=AsyncMock,
  785. return_value=mock_archive,
  786. ),
  787. ):
  788. await inst._add_to_print_queue(file_path, "192.168.1.100")
  789. assert len(added_items) == 1
  790. queue_item = added_items[0]
  791. # Type-only fallback always populated. Sorted, deduped, no zero-use ABS.
  792. assert queue_item.required_filament_types is not None
  793. assert json.loads(queue_item.required_filament_types) == ["PETG", "PLA"]
  794. # Setting off → no force_color_match overrides leaked.
  795. assert queue_item.filament_overrides is None
  796. @pytest.mark.asyncio
  797. async def test_add_to_print_queue_force_color_match_writes_overrides(self, tmp_path):
  798. """#1188 core fix: when the per-VP ``queue_force_color_match`` toggle
  799. is on, every consumed slot lands as a ``filament_overrides`` entry
  800. with ``force_color_match: true``. This is the field the scheduler
  801. keys on (``print_scheduler.py:512``) — without it, slot-by-slot
  802. type+color matching never runs."""
  803. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  804. added_items = []
  805. mock_db = AsyncMock()
  806. mock_db.add = MagicMock(side_effect=added_items.append)
  807. mock_db.commit = AsyncMock()
  808. mock_session_factory = MagicMock()
  809. mock_session_ctx = AsyncMock()
  810. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  811. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  812. mock_session_factory.return_value = mock_session_ctx
  813. inst = VirtualPrinterInstance(
  814. vp_id=22,
  815. name="ForceColor",
  816. mode="queue",
  817. model="C12",
  818. access_code="12345678",
  819. serial_suffix="391800022",
  820. auto_dispatch=True,
  821. queue_force_color_match=True, # on
  822. base_dir=tmp_path,
  823. session_factory=mock_session_factory,
  824. )
  825. file_path = tmp_path / "forced.3mf"
  826. _write_3mf_with_filaments(
  827. file_path,
  828. [
  829. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "10.0"},
  830. {"id": "2", "type": "PLA", "color": "#FF00FF", "used_g": "5.0"},
  831. ],
  832. plate_index=1,
  833. )
  834. mock_archive = MagicMock()
  835. mock_archive.id = 1
  836. mock_archive.print_name = "forced"
  837. with (
  838. patch(
  839. "backend.app.api.routes.settings.get_setting",
  840. new_callable=AsyncMock,
  841. return_value=None,
  842. ),
  843. patch(
  844. "backend.app.services.archive.ArchiveService.archive_print",
  845. new_callable=AsyncMock,
  846. return_value=mock_archive,
  847. ),
  848. ):
  849. await inst._add_to_print_queue(file_path, "192.168.1.100")
  850. assert len(added_items) == 1
  851. queue_item = added_items[0]
  852. assert queue_item.filament_overrides is not None
  853. overrides = json.loads(queue_item.filament_overrides)
  854. assert overrides == [
  855. {"slot_id": 1, "type": "PLA", "color": "#FFFFFF", "force_color_match": True},
  856. {"slot_id": 2, "type": "PLA", "color": "#FF00FF", "force_color_match": True},
  857. ]
  858. # required_filament_types still populated alongside overrides.
  859. assert json.loads(queue_item.required_filament_types) == ["PLA"]
  860. @pytest.mark.asyncio
  861. async def test_add_to_print_queue_force_color_match_skips_when_3mf_unparseable(self, tmp_path):
  862. """A malformed or fake-bytes 3MF must not crash the upload path —
  863. we just write the queue item with no filament fields and let the
  864. scheduler fall back to model-only matching (the pre-#1188 default).
  865. Regression guard for the existing fake-bytes happy-path tests."""
  866. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  867. added_items = []
  868. mock_db = AsyncMock()
  869. mock_db.add = MagicMock(side_effect=added_items.append)
  870. mock_db.commit = AsyncMock()
  871. mock_session_factory = MagicMock()
  872. mock_session_ctx = AsyncMock()
  873. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  874. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  875. mock_session_factory.return_value = mock_session_ctx
  876. inst = VirtualPrinterInstance(
  877. vp_id=23,
  878. name="Unparseable",
  879. mode="queue",
  880. model="C12",
  881. access_code="12345678",
  882. serial_suffix="391800023",
  883. auto_dispatch=True,
  884. queue_force_color_match=True,
  885. base_dir=tmp_path,
  886. session_factory=mock_session_factory,
  887. )
  888. file_path = tmp_path / "bad.3mf"
  889. file_path.write_bytes(b"not a real 3mf zip")
  890. mock_archive = MagicMock()
  891. mock_archive.id = 1
  892. mock_archive.print_name = "bad"
  893. with (
  894. patch(
  895. "backend.app.api.routes.settings.get_setting",
  896. new_callable=AsyncMock,
  897. return_value=None,
  898. ),
  899. patch(
  900. "backend.app.services.archive.ArchiveService.archive_print",
  901. new_callable=AsyncMock,
  902. return_value=mock_archive,
  903. ),
  904. ):
  905. await inst._add_to_print_queue(file_path, "192.168.1.100")
  906. assert len(added_items) == 1
  907. queue_item = added_items[0]
  908. # No filament data extractable → both fields stay None (graceful
  909. # fallback to model-only scheduling).
  910. assert queue_item.required_filament_types is None
  911. assert queue_item.filament_overrides is None
  912. # ========================================================================
  913. # Tests for archive_name_source setting (#1152)
  914. # ========================================================================
  915. @pytest.mark.asyncio
  916. @pytest.mark.parametrize(
  917. ("setting_value", "expected_prefer_filename"),
  918. [
  919. ("filename", True),
  920. ("metadata", False),
  921. (None, False), # Default when setting unset
  922. ("", False), # Defensive: empty string is not "filename"
  923. ],
  924. )
  925. async def test_archive_file_passes_prefer_filename_per_setting(
  926. self, tmp_path, setting_value, expected_prefer_filename
  927. ):
  928. """_archive_file reads `virtual_printer_archive_name_source` and forwards
  929. prefer_filename_for_name=True only when it equals 'filename' (#1152)."""
  930. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  931. mock_db = AsyncMock()
  932. mock_session_factory = MagicMock()
  933. mock_session_ctx = AsyncMock()
  934. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  935. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  936. mock_session_factory.return_value = mock_session_ctx
  937. inst = VirtualPrinterInstance(
  938. vp_id=20,
  939. name="NameSource",
  940. mode="archive",
  941. model="C11",
  942. access_code="12345678",
  943. serial_suffix="391800020",
  944. base_dir=tmp_path,
  945. session_factory=mock_session_factory,
  946. )
  947. file_path = tmp_path / "user-renamed-job.3mf"
  948. file_path.write_bytes(b"fake3mf")
  949. mock_archive = MagicMock()
  950. mock_archive.id = 1
  951. mock_archive.print_name = "user-renamed-job"
  952. archive_print_mock = AsyncMock(return_value=mock_archive)
  953. with (
  954. patch(
  955. "backend.app.api.routes.settings.get_setting",
  956. new_callable=AsyncMock,
  957. return_value=setting_value,
  958. ),
  959. patch(
  960. "backend.app.services.archive.ArchiveService.archive_print",
  961. archive_print_mock,
  962. ),
  963. ):
  964. await inst._archive_file(file_path, "192.168.1.100")
  965. assert archive_print_mock.await_count == 1
  966. kwargs = archive_print_mock.await_args.kwargs
  967. assert kwargs.get("prefer_filename_for_name") is expected_prefer_filename
  968. # ========================================================================
  969. # Tests for failure-path cleanup (#audit-R2-1)
  970. # ========================================================================
  971. #
  972. # All three file handlers (_archive_file, _queue_file, _add_to_print_queue)
  973. # previously only popped _pending_files and unlinked the temp file on the
  974. # success branch. Failure paths leaked the marker (blocking same-name
  975. # retries via the FTP layer) and the temp file on disk. The cleanup must
  976. # ALWAYS run, even when archival / queue insert raises.
  977. @pytest.mark.asyncio
  978. async def test_archive_file_failure_path_pops_pending_and_unlinks(self, tmp_path):
  979. """When the archive layer raises, `_pending_files[filename]` must still
  980. be popped and the temp file must be unlinked. Otherwise the FTP layer's
  981. same-name retry guard would silently reject the slicer's next attempt
  982. and the upload_dir would accumulate ghost files."""
  983. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  984. mock_db = AsyncMock()
  985. mock_session_factory = MagicMock()
  986. mock_session_ctx = AsyncMock()
  987. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  988. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  989. mock_session_factory.return_value = mock_session_ctx
  990. inst = VirtualPrinterInstance(
  991. vp_id=40,
  992. name="ArchiveFailCleanup",
  993. mode="archive",
  994. model="C12",
  995. access_code="12345678",
  996. serial_suffix="391800040",
  997. base_dir=tmp_path,
  998. session_factory=mock_session_factory,
  999. )
  1000. file_path = tmp_path / "cleanup-archive.3mf"
  1001. file_path.write_bytes(b"fake3mf")
  1002. inst._pending_files[file_path.name] = file_path
  1003. with (
  1004. patch(
  1005. "backend.app.api.routes.settings.get_setting",
  1006. new_callable=AsyncMock,
  1007. return_value=None,
  1008. ),
  1009. patch(
  1010. "backend.app.services.archive.ArchiveService.archive_print",
  1011. new_callable=AsyncMock,
  1012. side_effect=RuntimeError("archive blew up"),
  1013. ),
  1014. ):
  1015. await inst._archive_file(file_path, "192.168.1.100")
  1016. assert file_path.name not in inst._pending_files
  1017. assert not file_path.exists()
  1018. @pytest.mark.asyncio
  1019. async def test_queue_file_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1020. """Same invariant for _queue_file: a DB error during PendingUpload
  1021. insert must not leak the in-flight marker or the temp file."""
  1022. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1023. mock_db = AsyncMock()
  1024. # Commit raises — emulating a DB connectivity error.
  1025. mock_db.add = MagicMock()
  1026. mock_db.commit = AsyncMock(side_effect=RuntimeError("db unreachable"))
  1027. mock_session_factory = MagicMock()
  1028. mock_session_ctx = AsyncMock()
  1029. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1030. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1031. mock_session_factory.return_value = mock_session_ctx
  1032. inst = VirtualPrinterInstance(
  1033. vp_id=41,
  1034. name="QueueFailCleanup",
  1035. mode="review",
  1036. model="C12",
  1037. access_code="12345678",
  1038. serial_suffix="391800041",
  1039. base_dir=tmp_path,
  1040. session_factory=mock_session_factory,
  1041. )
  1042. file_path = tmp_path / "cleanup-queue.3mf"
  1043. file_path.write_bytes(b"fake3mf")
  1044. inst._pending_files[file_path.name] = file_path
  1045. await inst._queue_file(file_path, "192.168.1.100")
  1046. assert file_path.name not in inst._pending_files
  1047. assert not file_path.exists()
  1048. @pytest.mark.asyncio
  1049. async def test_add_to_print_queue_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1050. """Same invariant for _add_to_print_queue: a DB error or archive
  1051. failure must not leak the in-flight marker or the temp file."""
  1052. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1053. mock_db = AsyncMock()
  1054. mock_db.add = MagicMock()
  1055. mock_db.commit = AsyncMock()
  1056. mock_db.execute = AsyncMock(side_effect=RuntimeError("queue insert blew up"))
  1057. mock_session_factory = MagicMock()
  1058. mock_session_ctx = AsyncMock()
  1059. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1060. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1061. mock_session_factory.return_value = mock_session_ctx
  1062. inst = VirtualPrinterInstance(
  1063. vp_id=42,
  1064. name="DispatchFailCleanup",
  1065. mode="queue",
  1066. model="C12",
  1067. access_code="12345678",
  1068. serial_suffix="391800042",
  1069. auto_dispatch=True,
  1070. base_dir=tmp_path,
  1071. session_factory=mock_session_factory,
  1072. )
  1073. file_path = tmp_path / "cleanup-dispatch.3mf"
  1074. file_path.write_bytes(b"fake3mf")
  1075. inst._pending_files[file_path.name] = file_path
  1076. with patch(
  1077. "backend.app.api.routes.settings.get_setting",
  1078. new_callable=AsyncMock,
  1079. return_value=None,
  1080. ):
  1081. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1082. assert file_path.name not in inst._pending_files
  1083. assert not file_path.exists()
  1084. # ========================================================================
  1085. # Test for position=MAX+1 (audit-R2)
  1086. # ========================================================================
  1087. @pytest.mark.asyncio
  1088. async def test_add_to_print_queue_position_picks_max_plus_one(self, tmp_path):
  1089. """VP-queue items previously got hardcoded `position=1`, colliding
  1090. with existing items at position 1 and producing non-deterministic
  1091. execution order. Now the position is chosen by `MAX(position)+1`
  1092. against the target queue, matching the canonical `POST /print-queue/`
  1093. path."""
  1094. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1095. # Capture the inserted PrintQueueItem so we can assert on .position.
  1096. added_items: list = []
  1097. class _RecordingDb:
  1098. def __init__(self):
  1099. self.add = lambda item: added_items.append(item)
  1100. self.commit = AsyncMock()
  1101. async def execute(self, query): # noqa: ARG002
  1102. """Return a stub result whose `.scalar()` reports the existing
  1103. MAX(position) for the target. Returning 7 means the new item
  1104. should land at 8."""
  1105. result = MagicMock()
  1106. result.scalar = MagicMock(return_value=7)
  1107. return result
  1108. mock_db = _RecordingDb()
  1109. mock_session_factory = MagicMock()
  1110. mock_session_ctx = AsyncMock()
  1111. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1112. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1113. mock_session_factory.return_value = mock_session_ctx
  1114. inst = VirtualPrinterInstance(
  1115. vp_id=43,
  1116. name="PositionMaxPlusOne",
  1117. mode="queue",
  1118. model="C12",
  1119. access_code="12345678",
  1120. serial_suffix="391800043",
  1121. target_printer_id=99,
  1122. auto_dispatch=True,
  1123. base_dir=tmp_path,
  1124. session_factory=mock_session_factory,
  1125. )
  1126. file_path = tmp_path / "next-position.3mf"
  1127. file_path.write_bytes(b"fake3mf")
  1128. mock_archive = MagicMock()
  1129. mock_archive.id = 555
  1130. mock_archive.printer_id = None
  1131. mock_archive.filename = "next-position.3mf"
  1132. mock_archive.print_name = "next-position"
  1133. mock_archive.status = "archived"
  1134. with (
  1135. patch(
  1136. "backend.app.api.routes.settings.get_setting",
  1137. new_callable=AsyncMock,
  1138. return_value=None,
  1139. ),
  1140. patch(
  1141. "backend.app.services.archive.ArchiveService.archive_print",
  1142. new_callable=AsyncMock,
  1143. return_value=mock_archive,
  1144. ),
  1145. patch(
  1146. "backend.app.core.websocket.ws_manager.send_archive_created",
  1147. new_callable=AsyncMock,
  1148. ),
  1149. ):
  1150. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1151. # One queue item was added.
  1152. assert len(added_items) == 1
  1153. queue_item = added_items[0]
  1154. # Position = max(7) + 1 = 8 — NOT the legacy hardcoded 1.
  1155. assert queue_item.position == 8
  1156. class TestVirtualPrinterManager:
  1157. """Tests for VirtualPrinterManager orchestrator."""
  1158. @pytest.fixture
  1159. def manager(self):
  1160. """Create a VirtualPrinterManager instance."""
  1161. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  1162. return VirtualPrinterManager()
  1163. def test_manager_starts_empty(self, manager):
  1164. """Verify manager starts with no instances."""
  1165. assert len(manager._instances) == 0
  1166. assert manager.is_enabled is False
  1167. def test_manager_get_status_empty(self, manager):
  1168. """Verify get_status returns disabled state when no instances."""
  1169. status = manager.get_status()
  1170. assert status["enabled"] is False
  1171. assert status["running"] is False
  1172. assert status["mode"] == "archive"
  1173. def test_manager_is_enabled_with_instance(self, manager, tmp_path):
  1174. """Verify is_enabled is True when instances exist."""
  1175. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1176. inst = VirtualPrinterInstance(
  1177. vp_id=1,
  1178. name="Test",
  1179. mode="archive",
  1180. model="C11",
  1181. access_code="12345678",
  1182. serial_suffix="391800001",
  1183. base_dir=tmp_path,
  1184. )
  1185. manager._instances[1] = inst
  1186. assert manager.is_enabled is True
  1187. @pytest.mark.asyncio
  1188. async def test_manager_remove_instance_server(self, manager, tmp_path):
  1189. """Verify remove_instance stops and removes a server-mode instance."""
  1190. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1191. inst = VirtualPrinterInstance(
  1192. vp_id=1,
  1193. name="Test",
  1194. mode="archive",
  1195. model="C11",
  1196. access_code="12345678",
  1197. serial_suffix="391800001",
  1198. base_dir=tmp_path,
  1199. )
  1200. inst.stop_server = AsyncMock()
  1201. manager._instances[1] = inst
  1202. await manager.remove_instance(1)
  1203. assert 1 not in manager._instances
  1204. inst.stop_server.assert_called_once()
  1205. @pytest.mark.asyncio
  1206. async def test_manager_remove_instance_proxy(self, manager, tmp_path):
  1207. """Verify remove_instance stops proxy-mode instance."""
  1208. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1209. inst = VirtualPrinterInstance(
  1210. vp_id=2,
  1211. name="Proxy",
  1212. mode="proxy",
  1213. model="C11",
  1214. access_code="",
  1215. serial_suffix="391800002",
  1216. target_printer_ip="192.168.1.100",
  1217. base_dir=tmp_path,
  1218. )
  1219. inst.stop_proxy = AsyncMock()
  1220. manager._instances[2] = inst
  1221. await manager.remove_instance(2)
  1222. assert 2 not in manager._instances
  1223. inst.stop_proxy.assert_called_once()
  1224. def test_manager_get_status_with_instance(self, manager, tmp_path):
  1225. """Verify legacy get_status returns first instance data."""
  1226. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1227. inst = VirtualPrinterInstance(
  1228. vp_id=1,
  1229. name="Bambuddy",
  1230. mode="archive",
  1231. model="C11",
  1232. access_code="12345678",
  1233. serial_suffix="391800001",
  1234. base_dir=tmp_path,
  1235. )
  1236. mock_task = MagicMock(done=MagicMock(return_value=False))
  1237. inst._tasks = [mock_task]
  1238. inst._pending_files = {"file1.3mf": Path("/tmp/file1.3mf")} # nosec B108
  1239. manager._instances[1] = inst
  1240. status = manager.get_status()
  1241. assert status["enabled"] is True
  1242. assert status["running"] is True
  1243. assert status["mode"] == "archive"
  1244. assert status["name"] == "Bambuddy"
  1245. assert status["serial"] == "01S00A391800001"
  1246. assert status["model"] == "C11"
  1247. assert status["model_name"] == "P1P"
  1248. assert status["pending_files"] == 1
  1249. def test_manager_get_all_status(self, manager, tmp_path):
  1250. """Verify get_all_status returns status for all instances."""
  1251. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1252. for i in range(1, 3):
  1253. inst = VirtualPrinterInstance(
  1254. vp_id=i,
  1255. name=f"VP{i}",
  1256. mode="archive",
  1257. model="C11",
  1258. access_code="12345678",
  1259. serial_suffix=f"39180000{i}",
  1260. base_dir=tmp_path,
  1261. )
  1262. manager._instances[i] = inst
  1263. statuses = manager.get_all_status()
  1264. assert len(statuses) == 2
  1265. assert statuses[0]["name"] == "VP1"
  1266. assert statuses[1]["name"] == "VP2"
  1267. @pytest.mark.asyncio
  1268. async def test_manager_stop_all(self, manager, tmp_path):
  1269. """Verify stop_all removes all instances."""
  1270. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1271. for i in range(1, 3):
  1272. inst = VirtualPrinterInstance(
  1273. vp_id=i,
  1274. name=f"VP{i}",
  1275. mode="archive",
  1276. model="C11",
  1277. access_code="12345678",
  1278. serial_suffix=f"39180000{i}",
  1279. base_dir=tmp_path,
  1280. )
  1281. inst.stop_server = AsyncMock()
  1282. manager._instances[i] = inst
  1283. await manager.stop_all()
  1284. assert len(manager._instances) == 0
  1285. # ========================================================================
  1286. # Tests for sync_from_db config change detection
  1287. # ========================================================================
  1288. def _make_db_vp(self, **overrides):
  1289. """Create a mock VirtualPrinter DB object."""
  1290. defaults = {
  1291. "id": 1,
  1292. "name": "TestVP",
  1293. "enabled": True,
  1294. "mode": "archive",
  1295. "model": "C11",
  1296. "access_code": "12345678",
  1297. "serial_suffix": "391800001",
  1298. "bind_ip": "",
  1299. "remote_interface_ip": "",
  1300. "target_printer_id": None,
  1301. "auto_dispatch": True,
  1302. "tailscale_disabled": True, # Opt-in default (#1070 UX fix)
  1303. "queue_force_color_match": False, # default — must be explicit so MagicMock truthiness doesn't trip the change detector
  1304. "position": 0,
  1305. }
  1306. defaults.update(overrides)
  1307. vp = MagicMock()
  1308. for k, v in defaults.items():
  1309. setattr(vp, k, v)
  1310. return vp
  1311. def _setup_sync_mocks(self, manager, enabled_vps, tmp_path):
  1312. """Wire up session_factory mock for sync_from_db."""
  1313. mock_result = MagicMock()
  1314. mock_result.scalars.return_value.all.return_value = enabled_vps
  1315. mock_db = AsyncMock()
  1316. mock_db.execute = AsyncMock(return_value=mock_result)
  1317. mock_db.__aenter__ = AsyncMock(return_value=mock_db)
  1318. mock_db.__aexit__ = AsyncMock(return_value=False)
  1319. manager._session_factory = MagicMock(return_value=mock_db)
  1320. manager._base_dir = tmp_path
  1321. @pytest.mark.asyncio
  1322. async def test_sync_from_db_restarts_on_mode_change(self, manager, tmp_path):
  1323. """Verify sync_from_db restarts VP when mode changes."""
  1324. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1325. inst = VirtualPrinterInstance(
  1326. vp_id=1,
  1327. name="TestVP",
  1328. mode="archive",
  1329. model="C11",
  1330. access_code="12345678",
  1331. serial_suffix="391800001",
  1332. base_dir=tmp_path,
  1333. )
  1334. inst.stop_server = AsyncMock()
  1335. manager._instances[1] = inst
  1336. # DB says mode changed to "review"
  1337. db_vp = self._make_db_vp(mode="review")
  1338. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1339. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1340. # Patch VirtualPrinterInstance to prevent actual start
  1341. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1342. mock_new = MagicMock()
  1343. mock_new.start_server = AsyncMock()
  1344. MockInst.return_value = mock_new
  1345. await manager.sync_from_db()
  1346. mock_remove.assert_called_once_with(1)
  1347. @pytest.mark.asyncio
  1348. async def test_sync_from_db_restarts_on_access_code_change(self, manager, tmp_path):
  1349. """Verify sync_from_db restarts VP when access_code changes."""
  1350. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1351. inst = VirtualPrinterInstance(
  1352. vp_id=1,
  1353. name="TestVP",
  1354. mode="archive",
  1355. model="C11",
  1356. access_code="12345678",
  1357. serial_suffix="391800001",
  1358. base_dir=tmp_path,
  1359. )
  1360. inst.stop_server = AsyncMock()
  1361. manager._instances[1] = inst
  1362. db_vp = self._make_db_vp(access_code="newcode99")
  1363. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1364. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1365. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1366. mock_new = MagicMock()
  1367. mock_new.start_server = AsyncMock()
  1368. MockInst.return_value = mock_new
  1369. await manager.sync_from_db()
  1370. mock_remove.assert_called_once_with(1)
  1371. @pytest.mark.asyncio
  1372. async def test_sync_from_db_skips_unchanged_instance(self, manager, tmp_path):
  1373. """Verify sync_from_db does NOT restart when config is identical."""
  1374. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1375. inst = VirtualPrinterInstance(
  1376. vp_id=1,
  1377. name="TestVP",
  1378. mode="archive",
  1379. model="C11",
  1380. access_code="12345678",
  1381. serial_suffix="391800001",
  1382. base_dir=tmp_path,
  1383. )
  1384. manager._instances[1] = inst
  1385. # DB matches running config exactly
  1386. db_vp = self._make_db_vp()
  1387. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1388. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1389. await manager.sync_from_db()
  1390. mock_remove.assert_not_called()
  1391. @pytest.mark.asyncio
  1392. async def test_sync_from_db_restarts_on_bind_ip_change(self, manager, tmp_path):
  1393. """Verify sync_from_db restarts VP when bind_ip changes."""
  1394. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1395. inst = VirtualPrinterInstance(
  1396. vp_id=1,
  1397. name="TestVP",
  1398. mode="archive",
  1399. model="C11",
  1400. access_code="12345678",
  1401. serial_suffix="391800001",
  1402. bind_ip="192.168.1.10",
  1403. base_dir=tmp_path,
  1404. )
  1405. inst.stop_server = AsyncMock()
  1406. manager._instances[1] = inst
  1407. db_vp = self._make_db_vp(bind_ip="192.168.1.20")
  1408. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1409. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1410. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1411. mock_new = MagicMock()
  1412. mock_new.start_server = AsyncMock()
  1413. MockInst.return_value = mock_new
  1414. await manager.sync_from_db()
  1415. mock_remove.assert_called_once_with(1)
  1416. @pytest.mark.asyncio
  1417. async def test_sync_from_db_restarts_on_model_change(self, manager, tmp_path):
  1418. """Verify sync_from_db restarts VP when model changes."""
  1419. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1420. inst = VirtualPrinterInstance(
  1421. vp_id=1,
  1422. name="TestVP",
  1423. mode="archive",
  1424. model="C11",
  1425. access_code="12345678",
  1426. serial_suffix="391800001",
  1427. base_dir=tmp_path,
  1428. )
  1429. inst.stop_server = AsyncMock()
  1430. manager._instances[1] = inst
  1431. db_vp = self._make_db_vp(model="C12")
  1432. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1433. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1434. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1435. mock_new = MagicMock()
  1436. mock_new.start_server = AsyncMock()
  1437. MockInst.return_value = mock_new
  1438. await manager.sync_from_db()
  1439. mock_remove.assert_called_once_with(1)
  1440. @pytest.mark.asyncio
  1441. async def test_sync_from_db_does_not_restart_on_tailscale_toggle(self, manager, tmp_path):
  1442. """Flipping tailscale_disabled is purely informational — must NOT trigger a restart.
  1443. Cert provisioning was removed; the toggle only governs whether the VP card surfaces
  1444. the host's Tailscale IP/FQDN to the user. No service needs to reload, so changing
  1445. it through sync_from_db should leave any running instance untouched.
  1446. """
  1447. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1448. inst = VirtualPrinterInstance(
  1449. vp_id=1,
  1450. name="TestVP",
  1451. mode="archive",
  1452. model="C11",
  1453. access_code="12345678",
  1454. serial_suffix="391800001",
  1455. tailscale_disabled=False,
  1456. base_dir=tmp_path,
  1457. )
  1458. inst.stop_server = AsyncMock()
  1459. manager._instances[1] = inst
  1460. db_vp = self._make_db_vp(tailscale_disabled=True)
  1461. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1462. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1463. await manager.sync_from_db()
  1464. mock_remove.assert_not_called()
  1465. class TestFTPSession:
  1466. """Tests for FTP session handling."""
  1467. @pytest.fixture
  1468. def mock_reader(self):
  1469. """Create a mock StreamReader."""
  1470. reader = AsyncMock()
  1471. return reader
  1472. @pytest.fixture
  1473. def mock_writer(self):
  1474. """Create a mock StreamWriter."""
  1475. writer = MagicMock()
  1476. writer.get_extra_info = MagicMock(return_value=("192.168.1.100", 12345))
  1477. writer.write = MagicMock()
  1478. writer.drain = AsyncMock()
  1479. writer.close = MagicMock()
  1480. writer.wait_closed = AsyncMock()
  1481. writer.is_closing = MagicMock(return_value=False)
  1482. return writer
  1483. @pytest.fixture
  1484. def ssl_context(self):
  1485. """Create a mock SSL context."""
  1486. return MagicMock()
  1487. @pytest.fixture
  1488. def session(self, mock_reader, mock_writer, ssl_context, tmp_path):
  1489. """Create an FTPSession instance."""
  1490. from backend.app.services.virtual_printer.ftp_server import FTPSession
  1491. return FTPSession(
  1492. reader=mock_reader,
  1493. writer=mock_writer,
  1494. upload_dir=tmp_path,
  1495. access_code="12345678",
  1496. ssl_context=ssl_context,
  1497. on_file_received=None,
  1498. )
  1499. # ========================================================================
  1500. # Tests for authentication
  1501. # ========================================================================
  1502. @pytest.mark.asyncio
  1503. async def test_user_command_accepts_bblp(self, session):
  1504. """Verify USER command accepts bblp user."""
  1505. await session.cmd_USER("bblp")
  1506. assert session.username == "bblp"
  1507. @pytest.mark.asyncio
  1508. async def test_pass_command_authenticates(self, session):
  1509. """Verify PASS command authenticates with correct code."""
  1510. session.username = "bblp"
  1511. await session.cmd_PASS("12345678")
  1512. assert session.authenticated is True
  1513. @pytest.mark.asyncio
  1514. async def test_pass_command_rejects_wrong_code(self, session):
  1515. """Verify PASS command rejects wrong access code."""
  1516. session.username = "bblp"
  1517. await session.cmd_PASS("wrongcode")
  1518. assert session.authenticated is False
  1519. # ========================================================================
  1520. # Tests for FTP commands
  1521. # ========================================================================
  1522. @pytest.mark.asyncio
  1523. async def test_syst_command(self, session):
  1524. """Verify SYST returns UNIX type."""
  1525. await session.cmd_SYST("")
  1526. session.writer.write.assert_called()
  1527. call_args = session.writer.write.call_args[0][0].decode()
  1528. assert "215" in call_args
  1529. assert "UNIX" in call_args
  1530. @pytest.mark.asyncio
  1531. async def test_pwd_command_requires_auth(self, session):
  1532. """Verify PWD requires authentication."""
  1533. session.authenticated = False
  1534. await session.cmd_PWD("")
  1535. call_args = session.writer.write.call_args[0][0].decode()
  1536. assert "530" in call_args
  1537. @pytest.mark.asyncio
  1538. async def test_pwd_command_when_authenticated(self, session):
  1539. """Verify PWD returns root directory when authenticated."""
  1540. session.authenticated = True
  1541. await session.cmd_PWD("")
  1542. call_args = session.writer.write.call_args[0][0].decode()
  1543. assert "257" in call_args
  1544. @pytest.mark.asyncio
  1545. async def test_type_command_sets_binary(self, session):
  1546. """Verify TYPE I sets binary mode."""
  1547. session.authenticated = True
  1548. await session.cmd_TYPE("I")
  1549. assert session.transfer_type == "I"
  1550. @pytest.mark.asyncio
  1551. async def test_pbsz_command(self, session):
  1552. """Verify PBSZ returns success."""
  1553. await session.cmd_PBSZ("0")
  1554. call_args = session.writer.write.call_args[0][0].decode()
  1555. assert "200" in call_args
  1556. @pytest.mark.asyncio
  1557. async def test_prot_command_accepts_p(self, session):
  1558. """Verify PROT P is accepted."""
  1559. await session.cmd_PROT("P")
  1560. call_args = session.writer.write.call_args[0][0].decode()
  1561. assert "200" in call_args
  1562. @pytest.mark.asyncio
  1563. async def test_quit_command(self, session):
  1564. """Verify QUIT sends goodbye and raises CancelledError."""
  1565. with pytest.raises(asyncio.CancelledError):
  1566. await session.cmd_QUIT("")
  1567. class TestSSDPServer:
  1568. """Tests for Virtual Printer SSDP server."""
  1569. @pytest.fixture
  1570. def ssdp_server(self):
  1571. """Create a VirtualPrinterSSDPServer instance."""
  1572. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1573. return VirtualPrinterSSDPServer(
  1574. serial="TEST123",
  1575. name="TestPrinter",
  1576. model="BL-P001",
  1577. )
  1578. # ========================================================================
  1579. # Tests for SSDP response
  1580. # ========================================================================
  1581. def test_build_notify_message(self, ssdp_server):
  1582. """Verify NOTIFY packet contains required headers."""
  1583. # Set a known IP for testing
  1584. ssdp_server._local_ip = "192.168.1.100"
  1585. message = ssdp_server._build_notify_message()
  1586. assert b"NOTIFY" in message
  1587. assert b"DevName.bambu.com: TestPrinter" in message
  1588. assert b"USN: TEST123" in message
  1589. def test_build_response_message(self, ssdp_server):
  1590. """Verify response packet contains required headers."""
  1591. # Set a known IP for testing
  1592. ssdp_server._local_ip = "192.168.1.100"
  1593. message = ssdp_server._build_response_message()
  1594. assert b"HTTP/1.1 200 OK" in message
  1595. assert b"DevName.bambu.com: TestPrinter" in message
  1596. assert b"USN: TEST123" in message
  1597. def test_ssdp_server_uses_correct_model(self, ssdp_server):
  1598. """Verify SSDP server uses the provided model."""
  1599. ssdp_server._local_ip = "192.168.1.100"
  1600. message = ssdp_server._build_notify_message()
  1601. assert b"DevModel.bambu.com: BL-P001" in message
  1602. # ========================================================================
  1603. # Tests for advertise_ip parameter
  1604. # ========================================================================
  1605. def test_advertise_ip_sets_local_ip(self):
  1606. """Verify advertise_ip overrides auto-detection."""
  1607. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1608. server = VirtualPrinterSSDPServer(
  1609. serial="TEST123",
  1610. name="TestPrinter",
  1611. model="BL-P001",
  1612. advertise_ip="10.0.0.50",
  1613. )
  1614. assert server._local_ip == "10.0.0.50"
  1615. def test_advertise_ip_empty_string_uses_auto_detect(self):
  1616. """Verify empty advertise_ip falls back to auto-detection."""
  1617. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1618. server = VirtualPrinterSSDPServer(
  1619. serial="TEST123",
  1620. name="TestPrinter",
  1621. model="BL-P001",
  1622. advertise_ip="",
  1623. )
  1624. assert server._local_ip is None
  1625. def test_advertise_ip_in_notify_message(self):
  1626. """Verify NOTIFY message uses the advertise_ip."""
  1627. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1628. server = VirtualPrinterSSDPServer(
  1629. serial="TEST123",
  1630. name="TestPrinter",
  1631. model="BL-P001",
  1632. advertise_ip="10.0.0.50",
  1633. )
  1634. message = server._build_notify_message()
  1635. assert b"Location: 10.0.0.50" in message
  1636. def test_advertise_ip_in_response_message(self):
  1637. """Verify M-SEARCH response uses the advertise_ip."""
  1638. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1639. server = VirtualPrinterSSDPServer(
  1640. serial="TEST123",
  1641. name="TestPrinter",
  1642. model="BL-P001",
  1643. advertise_ip="10.0.0.50",
  1644. )
  1645. message = server._build_response_message()
  1646. assert b"Location: 10.0.0.50" in message
  1647. def test_default_no_advertise_ip(self):
  1648. """Verify default constructor has None local_ip (auto-detect)."""
  1649. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1650. server = VirtualPrinterSSDPServer()
  1651. assert server._local_ip is None
  1652. class TestCertificateService:
  1653. """Tests for TLS certificate generation."""
  1654. @pytest.fixture
  1655. def cert_service(self, tmp_path):
  1656. """Create a CertificateService instance."""
  1657. from backend.app.services.virtual_printer.certificate import CertificateService
  1658. return CertificateService(cert_dir=tmp_path, serial="TEST123")
  1659. def test_generate_certificates(self, cert_service, tmp_path):
  1660. """Verify certificates are generated correctly."""
  1661. cert_path, key_path = cert_service.generate_certificates()
  1662. assert cert_path.exists()
  1663. assert key_path.exists()
  1664. # Verify certificate content
  1665. cert_content = cert_path.read_text()
  1666. assert "BEGIN CERTIFICATE" in cert_content
  1667. key_content = key_path.read_text()
  1668. assert "BEGIN" in key_content and "KEY" in key_content
  1669. def test_certificates_reused_if_exist(self, cert_service):
  1670. """Verify existing certificates are reused."""
  1671. # First generation
  1672. cert_path1, key_path1 = cert_service.generate_certificates()
  1673. mtime1 = cert_path1.stat().st_mtime
  1674. # Second call should reuse (via ensure_certificates)
  1675. cert_path2, key_path2 = cert_service.ensure_certificates()
  1676. mtime2 = cert_path2.stat().st_mtime
  1677. assert mtime1 == mtime2 # File wasn't regenerated
  1678. def test_delete_certificates(self, cert_service):
  1679. """Verify certificates can be deleted."""
  1680. cert_service.generate_certificates()
  1681. assert cert_service.cert_path.exists()
  1682. assert cert_service.key_path.exists()
  1683. cert_service.delete_certificates()
  1684. assert not cert_service.cert_path.exists()
  1685. assert not cert_service.key_path.exists()
  1686. def test_ensure_creates_if_not_exist(self, cert_service):
  1687. """Verify ensure_certificates generates if not existing."""
  1688. assert not cert_service.cert_path.exists()
  1689. cert_path, key_path = cert_service.ensure_certificates()
  1690. assert cert_path.exists()
  1691. assert key_path.exists()
  1692. class TestBindServer:
  1693. """Tests for BindServer (port 3002 bind/detect protocol)."""
  1694. @pytest.fixture
  1695. def bind_server(self):
  1696. """Create a BindServer instance."""
  1697. from backend.app.services.virtual_printer.bind_server import BindServer
  1698. return BindServer(
  1699. serial="09400A391800001",
  1700. model="O1D",
  1701. name="Bambuddy",
  1702. )
  1703. def test_build_frame(self, bind_server):
  1704. """Verify frame building produces correct format."""
  1705. payload = {"login": {"command": "detect"}}
  1706. frame = bind_server._build_frame(payload)
  1707. # Header: 0xA5A5
  1708. assert frame[:2] == b"\xa5\xa5"
  1709. # Trailer: 0xA7A7
  1710. assert frame[-2:] == b"\xa7\xa7"
  1711. # Length field is total message size (LE uint16)
  1712. import struct
  1713. total_len = struct.unpack_from("<H", frame, 2)[0]
  1714. assert total_len == len(frame)
  1715. # JSON payload is between header and trailer
  1716. import json
  1717. json_bytes = frame[4:-2]
  1718. parsed = json.loads(json_bytes)
  1719. assert parsed == payload
  1720. def test_parse_frame_valid(self, bind_server):
  1721. """Verify valid frame parsing extracts JSON correctly."""
  1722. import json
  1723. import struct
  1724. payload = {"login": {"command": "detect", "sequence_id": "20000"}}
  1725. json_bytes = json.dumps(payload, separators=(",", ":")).encode()
  1726. total_len = 4 + len(json_bytes) + 2
  1727. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + json_bytes + b"\xa7\xa7"
  1728. result = bind_server._parse_frame(frame)
  1729. assert result is not None
  1730. assert result["login"]["command"] == "detect"
  1731. assert result["login"]["sequence_id"] == "20000"
  1732. def test_parse_frame_invalid_header(self, bind_server):
  1733. """Verify invalid header returns None."""
  1734. result = bind_server._parse_frame(b"\xbb\xbb\x06\x00{}\xa7\xa7")
  1735. assert result is None
  1736. def test_parse_frame_invalid_trailer(self, bind_server):
  1737. """Verify invalid trailer returns None."""
  1738. result = bind_server._parse_frame(b"\xa5\xa5\x06\x00{}\xbb\xbb")
  1739. assert result is None
  1740. def test_parse_frame_too_short(self, bind_server):
  1741. """Verify short data returns None."""
  1742. result = bind_server._parse_frame(b"\xa5\xa5\x00")
  1743. assert result is None
  1744. def test_parse_frame_invalid_json(self, bind_server):
  1745. """Verify invalid JSON returns None."""
  1746. import struct
  1747. bad_json = b"not json"
  1748. total_len = 4 + len(bad_json) + 2
  1749. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  1750. result = bind_server._parse_frame(frame)
  1751. assert result is None
  1752. def test_build_frame_roundtrip(self, bind_server):
  1753. """Verify build_frame output can be parsed back."""
  1754. payload = {
  1755. "login": {
  1756. "bind": "free",
  1757. "command": "detect",
  1758. "connect": "lan",
  1759. "dev_cap": 1,
  1760. "id": "09400A391800001",
  1761. "model": "O1D",
  1762. "name": "Bambuddy",
  1763. "sequence_id": 3021,
  1764. "version": "01.00.00.00",
  1765. }
  1766. }
  1767. frame = bind_server._build_frame(payload)
  1768. parsed = bind_server._parse_frame(frame)
  1769. assert parsed is not None
  1770. assert parsed["login"]["id"] == "09400A391800001"
  1771. assert parsed["login"]["model"] == "O1D"
  1772. assert parsed["login"]["name"] == "Bambuddy"
  1773. assert parsed["login"]["bind"] == "free"
  1774. def test_bind_server_stores_config(self, bind_server):
  1775. """Verify bind server stores serial, model, name."""
  1776. assert bind_server.serial == "09400A391800001"
  1777. assert bind_server.model == "O1D"
  1778. assert bind_server.name == "Bambuddy"
  1779. assert bind_server.version == "01.00.00.00"
  1780. def test_bind_server_custom_version(self):
  1781. """Verify custom firmware version is stored."""
  1782. from backend.app.services.virtual_printer.bind_server import BindServer
  1783. server = BindServer(
  1784. serial="TEST123",
  1785. model="C13",
  1786. name="Test",
  1787. version="02.03.04.05",
  1788. )
  1789. assert server.version == "02.03.04.05"
  1790. def test_bind_ports_constant(self):
  1791. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  1792. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  1793. assert 3000 in BIND_PORTS
  1794. assert 3002 in BIND_PORTS
  1795. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  1796. """Verify bind server starts with empty servers list."""
  1797. assert bind_server._servers == []
  1798. assert bind_server._running is False
  1799. class TestSlicerProxyManager:
  1800. """Tests for SlicerProxyManager (proxy mode)."""
  1801. @pytest.fixture
  1802. def proxy_manager(self, tmp_path):
  1803. """Create a SlicerProxyManager instance."""
  1804. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  1805. # Create dummy cert files
  1806. cert_path = tmp_path / "cert.pem"
  1807. key_path = tmp_path / "key.pem"
  1808. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  1809. # Split string to avoid pre-commit hook false positive on test data
  1810. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  1811. return SlicerProxyManager(
  1812. target_host="192.168.1.100",
  1813. cert_path=cert_path,
  1814. key_path=key_path,
  1815. )
  1816. def test_proxy_manager_initializes_ports(self, proxy_manager):
  1817. """Verify proxy manager has correct port constants."""
  1818. # FTP proxy uses privileged port 990 to match what Bambu Studio expects
  1819. assert proxy_manager.LOCAL_FTP_PORT == 990
  1820. assert proxy_manager.LOCAL_MQTT_PORT == 8883
  1821. assert proxy_manager.PRINTER_FTP_PORT == 990
  1822. assert proxy_manager.PRINTER_MQTT_PORT == 8883
  1823. assert proxy_manager.PRINTER_FILE_TRANSFER_PORT == 6000
  1824. assert proxy_manager.PRINTER_RTSP_PORT == 322
  1825. # Auxiliary ports: undocumented proprietary ports for A1/P1S etc.
  1826. assert proxy_manager.PRINTER_AUX_PORTS == [2024, 2025, 2026]
  1827. # Bind ports: both 3000 and 3002 for slicer compatibility
  1828. assert proxy_manager.PRINTER_BIND_PORTS == [3000, 3002]
  1829. # FTP data port range for transparent EPSV proxying
  1830. assert proxy_manager.FTP_DATA_PORT_MIN == 50000
  1831. assert proxy_manager.FTP_DATA_PORT_MAX == 50100
  1832. def test_proxy_manager_stores_target_host(self, proxy_manager):
  1833. """Verify proxy manager stores target host."""
  1834. assert proxy_manager.target_host == "192.168.1.100"
  1835. def test_get_status_before_start(self, proxy_manager):
  1836. """Verify get_status returns zeros before start."""
  1837. status = proxy_manager.get_status()
  1838. assert status["running"] is False
  1839. assert status["ftp_connections"] == 0
  1840. assert status["mqtt_connections"] == 0
  1841. @pytest.mark.asyncio
  1842. async def test_proxy_start_creates_transparent_proxies(self, tmp_path):
  1843. """Verify start() uses TCPProxy for FTP/FileTransfer/RTSP and TLSProxy only for MQTT.
  1844. The transparent proxy architecture preserves end-to-end TLS between
  1845. slicer and printer for all protocols except MQTT, which must be
  1846. TLS-terminated to rewrite the printer's IP in MQTT payloads.
  1847. """
  1848. from unittest.mock import AsyncMock, patch
  1849. from backend.app.services.virtual_printer.tcp_proxy import (
  1850. SlicerProxyManager,
  1851. TCPProxy,
  1852. TLSProxy,
  1853. )
  1854. cert_path = tmp_path / "cert.pem"
  1855. key_path = tmp_path / "key.pem"
  1856. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  1857. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  1858. mgr = SlicerProxyManager(
  1859. target_host="192.168.1.100",
  1860. cert_path=cert_path,
  1861. key_path=key_path,
  1862. bind_address="10.0.0.1",
  1863. )
  1864. # Mock asyncio.create_task and asyncio.gather to prevent actual server start
  1865. with (
  1866. patch("asyncio.create_task") as mock_create_task,
  1867. patch("asyncio.gather", new_callable=AsyncMock),
  1868. patch.object(SlicerProxyManager, "_log_activity"),
  1869. ):
  1870. mock_create_task.return_value = MagicMock()
  1871. # start() will create proxies then try to gather tasks — we just
  1872. # need to verify the proxy types after creation.
  1873. # Trigger start but let gather return immediately.
  1874. await mgr.start()
  1875. # FTP, FileTransfer, RTSP should be TCPProxy (transparent)
  1876. assert isinstance(mgr._ftp_proxy, TCPProxy), "FTP should be TCPProxy (transparent)"
  1877. assert isinstance(mgr._file_transfer_proxy, TCPProxy), "FileTransfer should be TCPProxy"
  1878. assert isinstance(mgr._rtsp_proxy, TCPProxy), "RTSP should be TCPProxy"
  1879. # MQTT should be TLSProxy (TLS-terminated for IP rewriting)
  1880. assert isinstance(mgr._mqtt_proxy, TLSProxy), "MQTT should be TLSProxy (TLS-terminated)"
  1881. # Auxiliary ports (2024-2026) should be TCPProxy (transparent)
  1882. assert len(mgr._aux_proxies) == 3, "Should have 3 aux port proxies"
  1883. for ap in mgr._aux_proxies:
  1884. assert isinstance(ap, TCPProxy), "Aux proxies should be TCPProxy"
  1885. assert mgr._aux_proxies[0].listen_port == 2024
  1886. assert mgr._aux_proxies[0].target_port == 2024
  1887. assert mgr._aux_proxies[2].listen_port == 2026
  1888. # FTP data ports should be pre-created as TCPProxy instances
  1889. assert len(mgr._ftp_data_proxies) == 101 # 50000-50100 inclusive
  1890. for dp in mgr._ftp_data_proxies:
  1891. assert isinstance(dp, TCPProxy), "FTP data proxies should be TCPProxy"
  1892. # Verify FTP data proxies target the same port on the printer
  1893. first_dp = mgr._ftp_data_proxies[0]
  1894. assert first_dp.listen_port == 50000
  1895. assert first_dp.target_port == 50000
  1896. assert first_dp.target_host == "192.168.1.100"
  1897. last_dp = mgr._ftp_data_proxies[-1]
  1898. assert last_dp.listen_port == 50100
  1899. assert last_dp.target_port == 50100
  1900. def test_proxy_manager_mqtt_has_ip_rewriting(self, tmp_path):
  1901. """Verify MQTT proxy is configured with IP rewriting when bind_address is set."""
  1902. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  1903. cert_path = tmp_path / "cert.pem"
  1904. key_path = tmp_path / "key.pem"
  1905. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  1906. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  1907. mgr = SlicerProxyManager(
  1908. target_host="192.168.1.100",
  1909. cert_path=cert_path,
  1910. key_path=key_path,
  1911. bind_address="10.0.0.1",
  1912. )
  1913. # Before start, proxies are None — verify constructor stores rewrite config
  1914. assert mgr.bind_address == "10.0.0.1"
  1915. assert mgr.target_host == "192.168.1.100"
  1916. class TestSSDPProxy:
  1917. """Tests for SSDPProxy (cross-network SSDP relay)."""
  1918. @pytest.fixture
  1919. def ssdp_proxy(self):
  1920. """Create an SSDPProxy instance."""
  1921. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  1922. return SSDPProxy(
  1923. local_interface_ip="192.168.1.100",
  1924. remote_interface_ip="10.0.0.100",
  1925. target_printer_ip="192.168.1.50",
  1926. )
  1927. def test_ssdp_proxy_stores_interface_ips(self, ssdp_proxy):
  1928. """Verify SSDPProxy stores interface IPs correctly."""
  1929. assert ssdp_proxy.local_interface_ip == "192.168.1.100"
  1930. assert ssdp_proxy.remote_interface_ip == "10.0.0.100"
  1931. assert ssdp_proxy.target_printer_ip == "192.168.1.50"
  1932. def test_rewrite_ssdp_location(self, ssdp_proxy):
  1933. """Verify SSDP Location header is rewritten to remote interface IP."""
  1934. original_packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: TestPrinter\r\n\r\n"
  1935. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  1936. # Location should be changed to remote interface IP
  1937. assert b"Location: 10.0.0.100" in rewritten
  1938. assert b"Location: 192.168.1.50" not in rewritten
  1939. # Other headers should be preserved
  1940. assert b"DevName.bambu.com: TestPrinter" in rewritten
  1941. def test_rewrite_ssdp_location_case_insensitive(self, ssdp_proxy):
  1942. """Verify SSDP Location rewrite is case insensitive."""
  1943. original_packet = b"NOTIFY * HTTP/1.1\r\nlocation: 192.168.1.50\r\n\r\n"
  1944. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  1945. assert b"10.0.0.100" in rewritten
  1946. def test_rewrite_ssdp_location_no_match(self, ssdp_proxy):
  1947. """Verify packet without Location header is returned unchanged."""
  1948. original_packet = b"NOTIFY * HTTP/1.1\r\nDevName.bambu.com: Test\r\n\r\n"
  1949. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  1950. # No Location header, but _rewrite_ssdp logs a warning and returns as-is
  1951. assert b"DevName.bambu.com: Test" in rewritten
  1952. def test_parse_ssdp_message(self, ssdp_proxy):
  1953. """Verify SSDP message parsing extracts headers."""
  1954. packet = (
  1955. b"NOTIFY * HTTP/1.1\r\n"
  1956. b"Location: 192.168.1.50\r\n"
  1957. b"DevName.bambu.com: TestPrinter\r\n"
  1958. b"DevModel.bambu.com: BL-P001\r\n"
  1959. b"\r\n"
  1960. )
  1961. headers = ssdp_proxy._parse_ssdp_message(packet)
  1962. assert headers["location"] == "192.168.1.50"
  1963. assert headers["devname.bambu.com"] == "TestPrinter"
  1964. assert headers["devmodel.bambu.com"] == "BL-P001"
  1965. class TestVirtualPrinterManagerDirectories:
  1966. """Tests for VirtualPrinterManager directory management."""
  1967. def test_ensure_base_directories_creates_subdirs(self, tmp_path):
  1968. """Verify _ensure_base_directories creates required base directories."""
  1969. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  1970. manager = VirtualPrinterManager()
  1971. manager._base_dir = tmp_path / "virtual_printer"
  1972. manager._ensure_base_directories()
  1973. assert (tmp_path / "virtual_printer").exists()
  1974. assert (tmp_path / "virtual_printer" / "uploads").exists()
  1975. assert (tmp_path / "virtual_printer" / "certs").exists()
  1976. def test_ensure_base_directories_handles_permission_error(self, tmp_path, caplog):
  1977. """Verify _ensure_base_directories logs error on permission failure."""
  1978. import logging
  1979. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  1980. manager = VirtualPrinterManager()
  1981. vp_dir = tmp_path / "virtual_printer"
  1982. manager._base_dir = vp_dir
  1983. original_mkdir = type(vp_dir).mkdir
  1984. def mock_mkdir(self, *args, **kwargs):
  1985. if "virtual_printer" in str(self):
  1986. raise PermissionError("Permission denied")
  1987. return original_mkdir(self, *args, **kwargs)
  1988. with caplog.at_level(logging.ERROR), patch.object(type(vp_dir), "mkdir", mock_mkdir):
  1989. manager._ensure_base_directories()
  1990. assert "Permission denied" in caplog.text
  1991. def test_instance_creates_per_vp_directories(self, tmp_path):
  1992. """Verify VirtualPrinterInstance creates per-VP upload and cert dirs."""
  1993. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1994. VirtualPrinterInstance(
  1995. vp_id=42,
  1996. name="Test",
  1997. mode="archive",
  1998. model="C11",
  1999. access_code="12345678",
  2000. serial_suffix="391800042",
  2001. base_dir=tmp_path,
  2002. )
  2003. assert (tmp_path / "uploads" / "42").exists()
  2004. assert (tmp_path / "uploads" / "42" / "cache").exists()
  2005. assert (tmp_path / "certs" / "42").exists()
  2006. class TestVirtualPrinterInstanceProxyMode:
  2007. """Tests for VirtualPrinterInstance proxy mode."""
  2008. @pytest.fixture
  2009. def proxy_instance(self, tmp_path):
  2010. """Create a proxy-mode VirtualPrinterInstance."""
  2011. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2012. return VirtualPrinterInstance(
  2013. vp_id=10,
  2014. name="ProxyTest",
  2015. mode="proxy",
  2016. model="C11",
  2017. access_code="",
  2018. serial_suffix="391800010",
  2019. target_printer_ip="192.168.1.100",
  2020. target_printer_serial="01P00A000000001",
  2021. base_dir=tmp_path,
  2022. )
  2023. def test_proxy_instance_properties(self, proxy_instance):
  2024. """Verify proxy instance stores config correctly."""
  2025. assert proxy_instance.is_proxy is True
  2026. assert proxy_instance.mode == "proxy"
  2027. assert proxy_instance.target_printer_ip == "192.168.1.100"
  2028. assert proxy_instance.target_printer_serial == "01P00A000000001"
  2029. def test_proxy_instance_does_not_require_access_code(self, proxy_instance):
  2030. """Verify proxy mode can have empty access code."""
  2031. assert proxy_instance.access_code == ""
  2032. def test_get_status_proxy_includes_proxy_fields(self, proxy_instance):
  2033. """Verify get_status includes proxy fields when proxy is active."""
  2034. mock_proxy = MagicMock()
  2035. mock_proxy.get_status.return_value = {
  2036. "running": True,
  2037. "ftp_port": 990,
  2038. "mqtt_port": 8883,
  2039. "ftp_connections": 1,
  2040. "mqtt_connections": 2,
  2041. "target_host": "192.168.1.100",
  2042. }
  2043. proxy_instance._proxy = mock_proxy
  2044. status = proxy_instance.get_status()
  2045. assert "proxy" in status
  2046. assert status["proxy"]["ftp_port"] == 990
  2047. assert status["proxy"]["mqtt_connections"] == 2
  2048. def test_proxy_instance_stores_remote_interface(self, tmp_path):
  2049. """Verify proxy instance stores remote_interface_ip."""
  2050. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2051. inst = VirtualPrinterInstance(
  2052. vp_id=11,
  2053. name="Proxy2",
  2054. mode="proxy",
  2055. model="C11",
  2056. access_code="",
  2057. serial_suffix="391800011",
  2058. target_printer_ip="192.168.1.100",
  2059. remote_interface_ip="10.0.0.50",
  2060. base_dir=tmp_path,
  2061. )
  2062. assert inst.remote_interface_ip == "10.0.0.50"
  2063. class TestVirtualPrinterInstanceIPOverride:
  2064. """Tests for remote_interface_ip and bind_ip on VirtualPrinterInstance."""
  2065. @pytest.fixture
  2066. def instance_with_remote_ip(self, tmp_path):
  2067. """Create an instance with remote_interface_ip set."""
  2068. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2069. return VirtualPrinterInstance(
  2070. vp_id=20,
  2071. name="IPTest",
  2072. mode="archive",
  2073. model="BL-P001",
  2074. access_code="12345678",
  2075. serial_suffix="391800020",
  2076. bind_ip="192.168.1.50",
  2077. remote_interface_ip="10.0.0.50",
  2078. base_dir=tmp_path,
  2079. )
  2080. def test_instance_stores_bind_ip(self, instance_with_remote_ip):
  2081. """Verify bind_ip is stored."""
  2082. assert instance_with_remote_ip.bind_ip == "192.168.1.50"
  2083. def test_instance_stores_remote_interface_ip(self, instance_with_remote_ip):
  2084. """Verify remote_interface_ip is stored."""
  2085. assert instance_with_remote_ip.remote_interface_ip == "10.0.0.50"
  2086. def test_generate_certificates_includes_remote_and_bind_ip(self, instance_with_remote_ip):
  2087. """Verify generate_certificates passes remote_interface_ip and bind_ip as SANs."""
  2088. with (
  2089. patch.object(instance_with_remote_ip._cert_service, "delete_printer_certificate"),
  2090. patch.object(
  2091. instance_with_remote_ip._cert_service,
  2092. "generate_certificates",
  2093. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2094. ) as mock_gen,
  2095. ):
  2096. instance_with_remote_ip.generate_certificates()
  2097. mock_gen.assert_called_once_with(additional_ips=["10.0.0.50", "192.168.1.50"])
  2098. def test_generate_certificates_no_remote_ip(self, tmp_path):
  2099. """Verify generate_certificates passes only bind_ip when no remote_interface_ip."""
  2100. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2101. inst = VirtualPrinterInstance(
  2102. vp_id=21,
  2103. name="NoRemote",
  2104. mode="archive",
  2105. model="BL-P001",
  2106. access_code="12345678",
  2107. serial_suffix="391800021",
  2108. bind_ip="192.168.1.50",
  2109. base_dir=tmp_path,
  2110. )
  2111. with (
  2112. patch.object(inst._cert_service, "delete_printer_certificate"),
  2113. patch.object(
  2114. inst._cert_service,
  2115. "generate_certificates",
  2116. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2117. ) as mock_gen,
  2118. ):
  2119. inst.generate_certificates()
  2120. mock_gen.assert_called_once_with(additional_ips=["192.168.1.50"])
  2121. def test_generate_certificates_no_ips(self, tmp_path):
  2122. """Verify generate_certificates passes None when no IPs configured."""
  2123. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2124. inst = VirtualPrinterInstance(
  2125. vp_id=22,
  2126. name="NoIPs",
  2127. mode="archive",
  2128. model="BL-P001",
  2129. access_code="12345678",
  2130. serial_suffix="391800022",
  2131. base_dir=tmp_path,
  2132. )
  2133. with (
  2134. patch.object(inst._cert_service, "delete_printer_certificate"),
  2135. patch.object(
  2136. inst._cert_service,
  2137. "generate_certificates",
  2138. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2139. ) as mock_gen,
  2140. ):
  2141. inst.generate_certificates()
  2142. mock_gen.assert_called_once_with(additional_ips=None)
  2143. class TestBindServer:
  2144. """Tests for the BindServer (port 3002 bind/detect protocol)."""
  2145. @pytest.fixture
  2146. def bind_server(self):
  2147. """Create a BindServer instance."""
  2148. from backend.app.services.virtual_printer.bind_server import BindServer
  2149. return BindServer(
  2150. serial="01S00C000000001",
  2151. model="BL-P001",
  2152. name="Bambuddy",
  2153. )
  2154. def test_build_frame(self, bind_server):
  2155. """Verify frame format: 0xA5A5 + len(u16le) + JSON + 0xA7A7."""
  2156. payload = {"login": {"command": "detect"}}
  2157. frame = bind_server._build_frame(payload)
  2158. assert frame[:2] == b"\xa5\xa5"
  2159. assert frame[-2:] == b"\xa7\xa7"
  2160. # Length field is total message size
  2161. import struct
  2162. total_len = struct.unpack_from("<H", frame, 2)[0]
  2163. assert total_len == len(frame)
  2164. # JSON payload is between header and trailer
  2165. import json
  2166. json_bytes = frame[4:-2]
  2167. parsed = json.loads(json_bytes)
  2168. assert parsed == payload
  2169. def test_parse_frame_valid(self, bind_server):
  2170. """Verify valid frame parsing."""
  2171. frame = bind_server._build_frame({"login": {"command": "detect", "sequence_id": "20000"}})
  2172. result = bind_server._parse_frame(frame)
  2173. assert result is not None
  2174. assert result["login"]["command"] == "detect"
  2175. assert result["login"]["sequence_id"] == "20000"
  2176. def test_parse_frame_invalid_header(self, bind_server):
  2177. """Verify invalid header returns None."""
  2178. frame = b"\xb5\xb5\x10\x00" + b'{"login":{}}' + b"\xa7\xa7"
  2179. assert bind_server._parse_frame(frame) is None
  2180. def test_parse_frame_invalid_trailer(self, bind_server):
  2181. """Verify invalid trailer returns None."""
  2182. frame = b"\xa5\xa5\x10\x00" + b'{"login":{}}' + b"\xb7\xb7"
  2183. assert bind_server._parse_frame(frame) is None
  2184. def test_parse_frame_too_short(self, bind_server):
  2185. """Verify short data returns None."""
  2186. assert bind_server._parse_frame(b"\xa5\xa5\x00") is None
  2187. assert bind_server._parse_frame(b"") is None
  2188. def test_parse_frame_invalid_json(self, bind_server):
  2189. """Verify invalid JSON returns None."""
  2190. import struct
  2191. bad_json = b"not json"
  2192. total_len = 4 + len(bad_json) + 2
  2193. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  2194. assert bind_server._parse_frame(frame) is None
  2195. def test_build_frame_roundtrip(self, bind_server):
  2196. """Verify build then parse roundtrip."""
  2197. original = {"login": {"bind": "free", "command": "detect", "id": "01S00C000000001"}}
  2198. frame = bind_server._build_frame(original)
  2199. parsed = bind_server._parse_frame(frame)
  2200. assert parsed == original
  2201. def test_bind_server_stores_config(self, bind_server):
  2202. """Verify config is stored correctly."""
  2203. assert bind_server.serial == "01S00C000000001"
  2204. assert bind_server.model == "BL-P001"
  2205. assert bind_server.name == "Bambuddy"
  2206. assert bind_server.version == "01.00.00.00"
  2207. def test_bind_server_custom_version(self):
  2208. """Verify custom firmware version is stored."""
  2209. from backend.app.services.virtual_printer.bind_server import BindServer
  2210. server = BindServer(
  2211. serial="01S00C000000001",
  2212. model="BL-P001",
  2213. name="Bambuddy",
  2214. version="01.09.00.10",
  2215. )
  2216. assert server.version == "01.09.00.10"
  2217. def test_bind_ports_includes_both(self):
  2218. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  2219. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  2220. assert 3000 in BIND_PORTS
  2221. assert 3002 in BIND_PORTS
  2222. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  2223. """Verify bind server starts with empty servers list."""
  2224. assert bind_server._servers == []
  2225. assert bind_server._running is False
  2226. @pytest.mark.asyncio
  2227. async def test_start_server_creates_bind_server(self, tmp_path):
  2228. """Verify start_server creates BindServer with correct params."""
  2229. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2230. inst = VirtualPrinterInstance(
  2231. vp_id=99,
  2232. name="Bambuddy",
  2233. mode="archive",
  2234. model="BL-P001",
  2235. access_code="12345678",
  2236. serial_suffix="391800099",
  2237. bind_ip="192.168.1.50",
  2238. base_dir=tmp_path,
  2239. )
  2240. # Each mocked child service exposes a real asyncio.Event for the
  2241. # readiness barrier added in start_server (set on instantiation so
  2242. # the barrier returns immediately in tests).
  2243. ready_event = asyncio.Event()
  2244. ready_event.set()
  2245. def with_ready(*_args, **_kwargs):
  2246. child = MagicMock()
  2247. child.ready = ready_event
  2248. return child
  2249. with (
  2250. patch(
  2251. "backend.app.services.virtual_printer.manager.VirtualPrinterSSDPServer",
  2252. side_effect=with_ready,
  2253. ),
  2254. patch(
  2255. "backend.app.services.virtual_printer.manager.VirtualPrinterFTPServer",
  2256. side_effect=with_ready,
  2257. ),
  2258. patch(
  2259. "backend.app.services.virtual_printer.manager.SimpleMQTTServer",
  2260. side_effect=with_ready,
  2261. ),
  2262. patch(
  2263. "backend.app.services.virtual_printer.manager.BindServer",
  2264. side_effect=with_ready,
  2265. ) as mock_bind_cls,
  2266. patch.object(inst._cert_service, "delete_printer_certificate"),
  2267. patch.object(
  2268. inst._cert_service,
  2269. "generate_certificates",
  2270. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2271. ),
  2272. ):
  2273. await inst.start_server()
  2274. mock_bind_cls.assert_called_once_with(
  2275. serial=inst.serial,
  2276. model="BL-P001",
  2277. name="Bambuddy",
  2278. bind_address="192.168.1.50",
  2279. cert_path=Path("/tmp/cert.pem"), # nosec B108
  2280. key_path=Path("/tmp/key.pem"), # nosec B108
  2281. )
  2282. class TestResolveModelCodes:
  2283. """Tests for model code resolution (display name → SSDP code)."""
  2284. def test_display_name_to_model_code_maps_all_models(self):
  2285. """Verify reverse mapping covers all VIRTUAL_PRINTER_MODELS entries."""
  2286. from backend.app.services.virtual_printer.manager import DISPLAY_NAME_TO_MODEL_CODE, VIRTUAL_PRINTER_MODELS
  2287. for _code, display_name in VIRTUAL_PRINTER_MODELS.items():
  2288. assert display_name in DISPLAY_NAME_TO_MODEL_CODE
  2289. # For non-duplicate display names, should map back to a valid code
  2290. assert DISPLAY_NAME_TO_MODEL_CODE[display_name] in VIRTUAL_PRINTER_MODELS
  2291. def test_resolve_printer_model_with_ssdp_code(self):
  2292. """SSDP codes pass through unchanged."""
  2293. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  2294. assert _resolve_printer_model("BL-P001") == "BL-P001"
  2295. assert _resolve_printer_model("O1D") == "O1D"
  2296. assert _resolve_printer_model("N2S") == "N2S"
  2297. def test_resolve_printer_model_with_display_name(self):
  2298. """Display names resolve to SSDP codes."""
  2299. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  2300. assert _resolve_printer_model("X1C") == "BL-P001"
  2301. assert _resolve_printer_model("H2D") == "O1D"
  2302. assert _resolve_printer_model("A1") == "N2S"
  2303. assert _resolve_printer_model("P1S") == "C12"
  2304. def test_resolve_printer_model_with_none_or_unknown(self):
  2305. """None and unknown values return None."""
  2306. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  2307. assert _resolve_printer_model(None) is None
  2308. assert _resolve_printer_model("UnknownModel") is None
  2309. class TestMqttIpRewrite:
  2310. """Tests for TLSProxy._rewrite_mqtt_ip() MQTT packet IP rewriting."""
  2311. @staticmethod
  2312. def _build_mqtt_publish(topic: str, payload: bytes) -> bytes:
  2313. """Build a minimal MQTT PUBLISH packet."""
  2314. # PUBLISH fixed header: type 3, no flags
  2315. topic_bytes = topic.encode("utf-8")
  2316. # Variable header: topic length (2 bytes) + topic
  2317. var_header = len(topic_bytes).to_bytes(2, "big") + topic_bytes
  2318. body = var_header + payload
  2319. # Encode remaining length
  2320. remaining = len(body)
  2321. header = bytearray([0x30]) # PUBLISH, QoS 0
  2322. while True:
  2323. encoded_byte = remaining % 128
  2324. remaining //= 128
  2325. if remaining > 0:
  2326. encoded_byte |= 0x80
  2327. header.append(encoded_byte)
  2328. if remaining == 0:
  2329. break
  2330. return bytes(header) + body
  2331. @staticmethod
  2332. def _build_mqtt_pingreq() -> bytes:
  2333. """Build an MQTT PINGREQ packet (2 bytes, no payload)."""
  2334. return b"\xc0\x00"
  2335. def test_rewrite_ip_in_publish(self):
  2336. """IP string in PUBLISH payload is rewritten."""
  2337. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2338. payload = b'{"rtsp_url":"rtsps://192.168.1.100:322/live"}'
  2339. packet = self._build_mqtt_publish("device/status", payload)
  2340. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  2341. assert b"10.0.0.1" in result
  2342. assert b"192.168.1.100" not in result
  2343. def test_no_rewrite_when_ip_absent(self):
  2344. """Packets without the target IP are passed through unchanged."""
  2345. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2346. payload = b'{"status":"idle"}'
  2347. packet = self._build_mqtt_publish("device/status", payload)
  2348. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  2349. assert result == packet
  2350. def test_non_publish_packets_unchanged(self):
  2351. """Non-PUBLISH packets (e.g. PINGREQ) are never rewritten."""
  2352. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2353. pingreq = self._build_mqtt_pingreq()
  2354. result, buf = TLSProxy._rewrite_mqtt_ip(pingreq, b"192.168.1.100", b"10.0.0.1", bytearray())
  2355. assert result == pingreq
  2356. def test_rewrite_preserves_packet_framing(self):
  2357. """Rewritten packet has valid MQTT remaining length."""
  2358. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2359. # Use IPs of different lengths to test length re-encoding
  2360. old_ip = b"192.168.255.133" # 15 bytes
  2361. new_ip = b"10.0.0.1" # 8 bytes
  2362. payload = b'{"ip":"192.168.255.133"}'
  2363. packet = self._build_mqtt_publish("device/status", payload)
  2364. result, buf = TLSProxy._rewrite_mqtt_ip(packet, old_ip, new_ip, bytearray())
  2365. # Parse the result to verify framing
  2366. assert result[0] == 0x30 # PUBLISH header byte
  2367. # Decode remaining length
  2368. pos = 1
  2369. remaining = 0
  2370. multiplier = 1
  2371. while True:
  2372. b = result[pos]
  2373. pos += 1
  2374. remaining += (b & 0x7F) * multiplier
  2375. multiplier *= 128
  2376. if (b & 0x80) == 0:
  2377. break
  2378. # Remaining length should match actual data
  2379. assert pos + remaining == len(result)
  2380. assert new_ip in result
  2381. def test_incomplete_packet_buffered(self):
  2382. """Incomplete packet at end of chunk is buffered for next call."""
  2383. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2384. payload = b'{"ip":"192.168.1.100"}'
  2385. packet = self._build_mqtt_publish("device/status", payload)
  2386. # Split packet in the middle
  2387. half = len(packet) // 2
  2388. chunk1 = packet[:half]
  2389. chunk2 = packet[half:]
  2390. result1, buf = TLSProxy._rewrite_mqtt_ip(chunk1, b"192.168.1.100", b"10.0.0.1", bytearray())
  2391. # First chunk should be buffered (incomplete packet)
  2392. assert len(buf) > 0
  2393. result2, buf = TLSProxy._rewrite_mqtt_ip(chunk2, b"192.168.1.100", b"10.0.0.1", buf)
  2394. # Second chunk completes the packet, IP should be rewritten
  2395. combined = result1 + result2
  2396. assert b"10.0.0.1" in combined
  2397. assert b"192.168.1.100" not in combined
  2398. def test_multiple_packets_in_one_chunk(self):
  2399. """Multiple MQTT packets in a single chunk are all processed."""
  2400. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2401. payload1 = b'{"ip":"192.168.1.100"}'
  2402. payload2 = b'{"other":"data"}'
  2403. packet1 = self._build_mqtt_publish("topic1", payload1)
  2404. packet2 = self._build_mqtt_publish("topic2", payload2)
  2405. combined = packet1 + packet2
  2406. result, buf = TLSProxy._rewrite_mqtt_ip(combined, b"192.168.1.100", b"10.0.0.1", bytearray())
  2407. assert b"10.0.0.1" in result
  2408. assert b"192.168.1.100" not in result
  2409. # Second packet should still be present
  2410. assert b"other" in result
  2411. def test_extra_replacements(self):
  2412. """Extra replacement pairs (e.g. integer IP) are also applied."""
  2413. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2414. payload = b'{"net":{"info":[{"ip":2248124608}]}}'
  2415. packet = self._build_mqtt_publish("device/status", payload)
  2416. result, buf = TLSProxy._rewrite_mqtt_ip(
  2417. packet,
  2418. b"NOMATCH",
  2419. b"NOREPLACE",
  2420. bytearray(),
  2421. extra_replacements=[(b"2248124608", b"285190336")],
  2422. )
  2423. assert b"285190336" in result
  2424. assert b"2248124608" not in result
  2425. class TestIpToLeIntBytes:
  2426. """Tests for TLSProxy._ip_to_le_int_bytes() integer IP conversion."""
  2427. def test_converts_ip_to_le_int(self):
  2428. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2429. assert TLSProxy._ip_to_le_int_bytes("192.168.255.133") == b"2248124608"
  2430. assert TLSProxy._ip_to_le_int_bytes("192.168.255.16") == b"285190336"
  2431. assert TLSProxy._ip_to_le_int_bytes("10.0.0.1") == b"16777226"
  2432. def test_roundtrip(self):
  2433. """Verify the integer converts back to the correct IP."""
  2434. import struct
  2435. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2436. for ip in ["192.168.1.1", "10.0.0.1", "172.16.0.100", "192.168.255.133"]:
  2437. le_int = int(TLSProxy._ip_to_le_int_bytes(ip))
  2438. parts = ip.split(".")
  2439. expected = struct.unpack("<I", bytes(int(p) for p in parts))[0]
  2440. assert le_int == expected
  2441. class TestSSDPProxyName:
  2442. """Tests for SSDPProxy VP name rewriting."""
  2443. @pytest.fixture
  2444. def ssdp_proxy_with_name(self):
  2445. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2446. return SSDPProxy(
  2447. local_interface_ip="192.168.1.100",
  2448. remote_interface_ip="10.0.0.100",
  2449. target_printer_ip="192.168.1.50",
  2450. name="H2D-1 Proxy",
  2451. )
  2452. @pytest.fixture
  2453. def ssdp_proxy_without_name(self):
  2454. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2455. return SSDPProxy(
  2456. local_interface_ip="192.168.1.100",
  2457. remote_interface_ip="10.0.0.100",
  2458. target_printer_ip="192.168.1.50",
  2459. )
  2460. def test_rewrite_uses_configured_name(self, ssdp_proxy_with_name):
  2461. """When name is set, DevName is replaced entirely."""
  2462. 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"
  2463. rewritten = ssdp_proxy_with_name._rewrite_ssdp(packet)
  2464. assert b"DevName.bambu.com: H2D-1 Proxy" in rewritten
  2465. assert b"RealPrinter" not in rewritten
  2466. def test_rewrite_appends_proxy_without_name(self, ssdp_proxy_without_name):
  2467. """When no name is set, ' - Proxy' is appended to the real name."""
  2468. 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"
  2469. rewritten = ssdp_proxy_without_name._rewrite_ssdp(packet)
  2470. assert b"DevName.bambu.com: RealPrinter - Proxy" in rewritten