test_virtual_printer.py 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514
  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="immediate",
  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 == "immediate"
  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="immediate",
  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 = "immediate"
  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 = "immediate"
  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_archive_file_skips_non_3mf(self, instance):
  171. """Verify non-3MF files are skipped and cleaned up."""
  172. instance._session_factory = MagicMock()
  173. instance._pending_files["verify_job"] = Path("/tmp/verify_job") # nosec B108
  174. with patch("pathlib.Path.unlink"):
  175. await instance._archive_file(Path("/tmp/verify_job"), "192.168.1.100") # nosec B108
  176. assert "verify_job" not in instance._pending_files
  177. @pytest.mark.asyncio
  178. async def test_archive_file_broadcasts_archive_created(self, tmp_path):
  179. """#1282: VP immediate-mode archives must broadcast archive_created so
  180. the Archives page refreshes without a tab switch. Real-printer prints
  181. get this via main.py's MQTT print_start handler; the VP path used to
  182. skip the broadcast entirely."""
  183. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  184. mock_db = AsyncMock()
  185. mock_db.commit = AsyncMock()
  186. mock_session_factory = MagicMock()
  187. mock_session_ctx = AsyncMock()
  188. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  189. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  190. mock_session_factory.return_value = mock_session_ctx
  191. inst = VirtualPrinterInstance(
  192. vp_id=30,
  193. name="ImmediateBroadcast",
  194. mode="immediate",
  195. model="C12",
  196. access_code="12345678",
  197. serial_suffix="391800030",
  198. base_dir=tmp_path,
  199. session_factory=mock_session_factory,
  200. )
  201. file_path = tmp_path / "test.3mf"
  202. file_path.write_bytes(b"fake3mf")
  203. mock_archive = MagicMock()
  204. mock_archive.id = 99
  205. mock_archive.printer_id = None
  206. mock_archive.filename = "test.3mf"
  207. mock_archive.print_name = "test"
  208. mock_archive.status = "archived"
  209. with (
  210. patch(
  211. "backend.app.api.routes.settings.get_setting",
  212. new_callable=AsyncMock,
  213. return_value=None,
  214. ),
  215. patch(
  216. "backend.app.services.archive.ArchiveService.archive_print",
  217. new_callable=AsyncMock,
  218. return_value=mock_archive,
  219. ),
  220. patch(
  221. "backend.app.core.websocket.ws_manager.send_archive_created",
  222. new_callable=AsyncMock,
  223. ) as mock_broadcast,
  224. ):
  225. await inst._archive_file(file_path, "192.168.1.100")
  226. mock_broadcast.assert_awaited_once()
  227. payload = mock_broadcast.await_args.args[0]
  228. assert payload["id"] == 99
  229. assert payload["filename"] == "test.3mf"
  230. assert payload["status"] == "archived"
  231. # ========================================================================
  232. # Tests for auto_dispatch
  233. # ========================================================================
  234. def test_auto_dispatch_defaults_to_true(self, tmp_path):
  235. """Verify auto_dispatch defaults to True when not specified."""
  236. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  237. inst = VirtualPrinterInstance(
  238. vp_id=10,
  239. name="DefaultDispatch",
  240. mode="print_queue",
  241. model="C11",
  242. access_code="12345678",
  243. serial_suffix="391800010",
  244. base_dir=tmp_path,
  245. )
  246. assert inst.auto_dispatch is True
  247. @pytest.mark.asyncio
  248. async def test_add_to_print_queue_with_auto_dispatch_on(self, tmp_path):
  249. """Verify queue items have manual_start=False when auto_dispatch=True."""
  250. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  251. mock_db = AsyncMock()
  252. added_items = []
  253. def capture_add(item):
  254. added_items.append(item)
  255. mock_db.add = MagicMock(side_effect=capture_add)
  256. mock_db.commit = AsyncMock()
  257. mock_session_factory = MagicMock()
  258. mock_session_ctx = AsyncMock()
  259. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  260. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  261. mock_session_factory.return_value = mock_session_ctx
  262. inst = VirtualPrinterInstance(
  263. vp_id=11,
  264. name="AutoDispatchOn",
  265. mode="print_queue",
  266. model="C11",
  267. access_code="12345678",
  268. serial_suffix="391800011",
  269. auto_dispatch=True,
  270. base_dir=tmp_path,
  271. session_factory=mock_session_factory,
  272. )
  273. # Create a temp 3mf file
  274. file_path = tmp_path / "test.3mf"
  275. file_path.write_bytes(b"fake3mf")
  276. mock_archive = MagicMock()
  277. mock_archive.id = 1
  278. mock_archive.print_name = "test"
  279. with (
  280. patch(
  281. "backend.app.api.routes.settings.get_setting",
  282. new_callable=AsyncMock,
  283. return_value=None,
  284. ),
  285. patch(
  286. "backend.app.services.archive.ArchiveService.archive_print",
  287. new_callable=AsyncMock,
  288. return_value=mock_archive,
  289. ),
  290. ):
  291. await inst._add_to_print_queue(file_path, "192.168.1.100")
  292. assert len(added_items) == 1
  293. queue_item = added_items[0]
  294. assert queue_item.manual_start is False
  295. @pytest.mark.asyncio
  296. async def test_add_to_print_queue_broadcasts_archive_created(self, tmp_path):
  297. """#1282: VP queue-mode uploads must broadcast archive_created so the
  298. Archives page picks up the new entry live. Pre-fix the page only
  299. refreshed when the user manually switched tabs."""
  300. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  301. mock_db = AsyncMock()
  302. mock_db.add = MagicMock()
  303. mock_db.commit = AsyncMock()
  304. mock_session_factory = MagicMock()
  305. mock_session_ctx = AsyncMock()
  306. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  307. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  308. mock_session_factory.return_value = mock_session_ctx
  309. inst = VirtualPrinterInstance(
  310. vp_id=31,
  311. name="QueueBroadcast",
  312. mode="print_queue",
  313. model="C12",
  314. access_code="12345678",
  315. serial_suffix="391800031",
  316. auto_dispatch=True,
  317. base_dir=tmp_path,
  318. session_factory=mock_session_factory,
  319. )
  320. file_path = tmp_path / "test.3mf"
  321. file_path.write_bytes(b"fake3mf")
  322. mock_archive = MagicMock()
  323. mock_archive.id = 77
  324. mock_archive.printer_id = None
  325. mock_archive.filename = "test.3mf"
  326. mock_archive.print_name = "test"
  327. mock_archive.status = "archived"
  328. with (
  329. patch(
  330. "backend.app.api.routes.settings.get_setting",
  331. new_callable=AsyncMock,
  332. return_value=None,
  333. ),
  334. patch(
  335. "backend.app.services.archive.ArchiveService.archive_print",
  336. new_callable=AsyncMock,
  337. return_value=mock_archive,
  338. ),
  339. patch(
  340. "backend.app.core.websocket.ws_manager.send_archive_created",
  341. new_callable=AsyncMock,
  342. ) as mock_broadcast,
  343. ):
  344. await inst._add_to_print_queue(file_path, "192.168.1.100")
  345. mock_broadcast.assert_awaited_once()
  346. payload = mock_broadcast.await_args.args[0]
  347. assert payload["id"] == 77
  348. assert payload["print_name"] == "test"
  349. assert payload["status"] == "archived"
  350. @pytest.mark.asyncio
  351. async def test_add_to_print_queue_with_auto_dispatch_off(self, tmp_path):
  352. """Verify queue items have manual_start=True when auto_dispatch=False."""
  353. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  354. mock_db = AsyncMock()
  355. added_items = []
  356. def capture_add(item):
  357. added_items.append(item)
  358. mock_db.add = MagicMock(side_effect=capture_add)
  359. mock_db.commit = AsyncMock()
  360. mock_session_factory = MagicMock()
  361. mock_session_ctx = AsyncMock()
  362. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  363. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  364. mock_session_factory.return_value = mock_session_ctx
  365. inst = VirtualPrinterInstance(
  366. vp_id=12,
  367. name="AutoDispatchOff",
  368. mode="print_queue",
  369. model="C11",
  370. access_code="12345678",
  371. serial_suffix="391800012",
  372. auto_dispatch=False,
  373. base_dir=tmp_path,
  374. session_factory=mock_session_factory,
  375. )
  376. # Create a temp 3mf file
  377. file_path = tmp_path / "test.3mf"
  378. file_path.write_bytes(b"fake3mf")
  379. mock_archive = MagicMock()
  380. mock_archive.id = 1
  381. mock_archive.print_name = "test"
  382. with (
  383. patch(
  384. "backend.app.api.routes.settings.get_setting",
  385. new_callable=AsyncMock,
  386. return_value=None,
  387. ),
  388. patch(
  389. "backend.app.services.archive.ArchiveService.archive_print",
  390. new_callable=AsyncMock,
  391. return_value=mock_archive,
  392. ),
  393. ):
  394. await inst._add_to_print_queue(file_path, "192.168.1.100")
  395. assert len(added_items) == 1
  396. queue_item = added_items[0]
  397. assert queue_item.manual_start is True
  398. @pytest.mark.asyncio
  399. async def test_add_to_print_queue_uses_workflow_defaults_from_settings(self, tmp_path):
  400. """#1235: VP queue-mode constructed PrintQueueItem without specifying
  401. bed_levelling / flow_cali / vibration_cali / layer_inspect / timelapse,
  402. so SQLAlchemy applied the column-level defaults and ignored the user's
  403. workflow preferences entirely. Every print sent from the slicer to the
  404. VP came through with the OPPOSITE of what the workflow page said,
  405. forcing the user to edit each queue item by hand.
  406. """
  407. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  408. added_items = []
  409. mock_db = AsyncMock()
  410. mock_db.add = MagicMock(side_effect=added_items.append)
  411. mock_db.commit = AsyncMock()
  412. mock_session_factory = MagicMock()
  413. mock_session_ctx = AsyncMock()
  414. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  415. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  416. mock_session_factory.return_value = mock_session_ctx
  417. inst = VirtualPrinterInstance(
  418. vp_id=22,
  419. name="DefaultsTest",
  420. mode="print_queue",
  421. model="C12",
  422. access_code="12345678",
  423. serial_suffix="391800022",
  424. auto_dispatch=True,
  425. base_dir=tmp_path,
  426. session_factory=mock_session_factory,
  427. )
  428. file_path = tmp_path / "test.3mf"
  429. file_path.write_bytes(b"fake3mf")
  430. # The reporter set every workflow default to the OPPOSITE of the model's
  431. # column default. Pre-fix the column defaults won; with the fix the
  432. # settings values must flow through to the queue item exactly as stored.
  433. settings_map = {
  434. "virtual_printer_archive_name_source": None,
  435. "default_bed_levelling": "false", # model default: True
  436. "default_flow_cali": "true", # model default: False
  437. "default_vibration_cali": "false", # model default: True
  438. "default_layer_inspect": "true", # model default: False
  439. "default_timelapse": "true", # model default: False
  440. }
  441. async def fake_get_setting(_db, key):
  442. return settings_map.get(key)
  443. mock_archive = MagicMock()
  444. mock_archive.id = 1
  445. mock_archive.print_name = "test"
  446. with (
  447. patch(
  448. "backend.app.api.routes.settings.get_setting",
  449. new=fake_get_setting,
  450. ),
  451. patch(
  452. "backend.app.services.archive.ArchiveService.archive_print",
  453. new_callable=AsyncMock,
  454. return_value=mock_archive,
  455. ),
  456. ):
  457. await inst._add_to_print_queue(file_path, "192.168.1.100")
  458. assert len(added_items) == 1
  459. queue_item = added_items[0]
  460. assert queue_item.bed_levelling is False, "default_bed_levelling=false must flow through"
  461. assert queue_item.flow_cali is True, "default_flow_cali=true must flow through"
  462. assert queue_item.vibration_cali is False, "default_vibration_cali=false must flow through"
  463. assert queue_item.layer_inspect is True, "default_layer_inspect=true must flow through"
  464. assert queue_item.timelapse is True, "default_timelapse=true must flow through"
  465. @pytest.mark.asyncio
  466. async def test_add_to_print_queue_falls_back_to_schema_defaults_when_unset(self, tmp_path):
  467. """#1235 fallback: when no workflow setting is in the DB, the queue
  468. item should use the AppSettings (Pydantic) defaults — same values
  469. the user sees in the workflow page on a fresh install.
  470. """
  471. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  472. added_items = []
  473. mock_db = AsyncMock()
  474. mock_db.add = MagicMock(side_effect=added_items.append)
  475. mock_db.commit = AsyncMock()
  476. mock_session_factory = MagicMock()
  477. mock_session_ctx = AsyncMock()
  478. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  479. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  480. mock_session_factory.return_value = mock_session_ctx
  481. inst = VirtualPrinterInstance(
  482. vp_id=23,
  483. name="FreshInstallDefaults",
  484. mode="print_queue",
  485. model="C12",
  486. access_code="12345678",
  487. serial_suffix="391800023",
  488. auto_dispatch=True,
  489. base_dir=tmp_path,
  490. session_factory=mock_session_factory,
  491. )
  492. file_path = tmp_path / "test.3mf"
  493. file_path.write_bytes(b"fake3mf")
  494. mock_archive = MagicMock()
  495. mock_archive.id = 1
  496. mock_archive.print_name = "test"
  497. with (
  498. patch(
  499. "backend.app.api.routes.settings.get_setting",
  500. new_callable=AsyncMock,
  501. return_value=None, # No settings → fall back to schema defaults
  502. ),
  503. patch(
  504. "backend.app.services.archive.ArchiveService.archive_print",
  505. new_callable=AsyncMock,
  506. return_value=mock_archive,
  507. ),
  508. ):
  509. await inst._add_to_print_queue(file_path, "192.168.1.100")
  510. assert len(added_items) == 1
  511. queue_item = added_items[0]
  512. # These must match the AppSettings (Pydantic) defaults in schemas/settings.py
  513. assert queue_item.bed_levelling is True
  514. assert queue_item.flow_cali is False
  515. assert queue_item.vibration_cali is True
  516. assert queue_item.layer_inspect is False
  517. assert queue_item.timelapse is False
  518. @pytest.mark.asyncio
  519. async def test_add_to_print_queue_populates_required_filament_types(self, tmp_path):
  520. """#1188: VP queue-mode used to create PrintQueueItems with no
  521. filament fields, so the scheduler fell through to model-only matching
  522. and dispatched onto whatever printer was free regardless of loaded
  523. colour. ``required_filament_types`` is populated unconditionally
  524. (cheap, helps the scheduler validate type even without
  525. ``force_color_match``) — pin that contract here."""
  526. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  527. added_items = []
  528. mock_db = AsyncMock()
  529. mock_db.add = MagicMock(side_effect=added_items.append)
  530. mock_db.commit = AsyncMock()
  531. mock_session_factory = MagicMock()
  532. mock_session_ctx = AsyncMock()
  533. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  534. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  535. mock_session_factory.return_value = mock_session_ctx
  536. inst = VirtualPrinterInstance(
  537. vp_id=21,
  538. name="Reqs",
  539. mode="print_queue",
  540. model="C12",
  541. access_code="12345678",
  542. serial_suffix="391800021",
  543. auto_dispatch=True,
  544. queue_force_color_match=False, # off → only required_filament_types
  545. base_dir=tmp_path,
  546. session_factory=mock_session_factory,
  547. )
  548. file_path = tmp_path / "multi.3mf"
  549. _write_3mf_with_filaments(
  550. file_path,
  551. [
  552. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "12.3"},
  553. {"id": "2", "type": "PETG", "color": "#000000", "used_g": "4.5"},
  554. # used_g=0 → not actually consumed by this plate, must be ignored
  555. {"id": "3", "type": "ABS", "color": "#FF0000", "used_g": "0"},
  556. ],
  557. plate_index=1,
  558. )
  559. mock_archive = MagicMock()
  560. mock_archive.id = 1
  561. mock_archive.print_name = "multi"
  562. with (
  563. patch(
  564. "backend.app.api.routes.settings.get_setting",
  565. new_callable=AsyncMock,
  566. return_value=None,
  567. ),
  568. patch(
  569. "backend.app.services.archive.ArchiveService.archive_print",
  570. new_callable=AsyncMock,
  571. return_value=mock_archive,
  572. ),
  573. ):
  574. await inst._add_to_print_queue(file_path, "192.168.1.100")
  575. assert len(added_items) == 1
  576. queue_item = added_items[0]
  577. # Type-only fallback always populated. Sorted, deduped, no zero-use ABS.
  578. assert queue_item.required_filament_types is not None
  579. assert json.loads(queue_item.required_filament_types) == ["PETG", "PLA"]
  580. # Setting off → no force_color_match overrides leaked.
  581. assert queue_item.filament_overrides is None
  582. @pytest.mark.asyncio
  583. async def test_add_to_print_queue_force_color_match_writes_overrides(self, tmp_path):
  584. """#1188 core fix: when the per-VP ``queue_force_color_match`` toggle
  585. is on, every consumed slot lands as a ``filament_overrides`` entry
  586. with ``force_color_match: true``. This is the field the scheduler
  587. keys on (``print_scheduler.py:512``) — without it, slot-by-slot
  588. type+color matching never runs."""
  589. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  590. added_items = []
  591. mock_db = AsyncMock()
  592. mock_db.add = MagicMock(side_effect=added_items.append)
  593. mock_db.commit = AsyncMock()
  594. mock_session_factory = MagicMock()
  595. mock_session_ctx = AsyncMock()
  596. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  597. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  598. mock_session_factory.return_value = mock_session_ctx
  599. inst = VirtualPrinterInstance(
  600. vp_id=22,
  601. name="ForceColor",
  602. mode="print_queue",
  603. model="C12",
  604. access_code="12345678",
  605. serial_suffix="391800022",
  606. auto_dispatch=True,
  607. queue_force_color_match=True, # on
  608. base_dir=tmp_path,
  609. session_factory=mock_session_factory,
  610. )
  611. file_path = tmp_path / "forced.3mf"
  612. _write_3mf_with_filaments(
  613. file_path,
  614. [
  615. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "10.0"},
  616. {"id": "2", "type": "PLA", "color": "#FF00FF", "used_g": "5.0"},
  617. ],
  618. plate_index=1,
  619. )
  620. mock_archive = MagicMock()
  621. mock_archive.id = 1
  622. mock_archive.print_name = "forced"
  623. with (
  624. patch(
  625. "backend.app.api.routes.settings.get_setting",
  626. new_callable=AsyncMock,
  627. return_value=None,
  628. ),
  629. patch(
  630. "backend.app.services.archive.ArchiveService.archive_print",
  631. new_callable=AsyncMock,
  632. return_value=mock_archive,
  633. ),
  634. ):
  635. await inst._add_to_print_queue(file_path, "192.168.1.100")
  636. assert len(added_items) == 1
  637. queue_item = added_items[0]
  638. assert queue_item.filament_overrides is not None
  639. overrides = json.loads(queue_item.filament_overrides)
  640. assert overrides == [
  641. {"slot_id": 1, "type": "PLA", "color": "#FFFFFF", "force_color_match": True},
  642. {"slot_id": 2, "type": "PLA", "color": "#FF00FF", "force_color_match": True},
  643. ]
  644. # required_filament_types still populated alongside overrides.
  645. assert json.loads(queue_item.required_filament_types) == ["PLA"]
  646. @pytest.mark.asyncio
  647. async def test_add_to_print_queue_force_color_match_skips_when_3mf_unparseable(self, tmp_path):
  648. """A malformed or fake-bytes 3MF must not crash the upload path —
  649. we just write the queue item with no filament fields and let the
  650. scheduler fall back to model-only matching (the pre-#1188 default).
  651. Regression guard for the existing fake-bytes happy-path tests."""
  652. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  653. added_items = []
  654. mock_db = AsyncMock()
  655. mock_db.add = MagicMock(side_effect=added_items.append)
  656. mock_db.commit = AsyncMock()
  657. mock_session_factory = MagicMock()
  658. mock_session_ctx = AsyncMock()
  659. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  660. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  661. mock_session_factory.return_value = mock_session_ctx
  662. inst = VirtualPrinterInstance(
  663. vp_id=23,
  664. name="Unparseable",
  665. mode="print_queue",
  666. model="C12",
  667. access_code="12345678",
  668. serial_suffix="391800023",
  669. auto_dispatch=True,
  670. queue_force_color_match=True,
  671. base_dir=tmp_path,
  672. session_factory=mock_session_factory,
  673. )
  674. file_path = tmp_path / "bad.3mf"
  675. file_path.write_bytes(b"not a real 3mf zip")
  676. mock_archive = MagicMock()
  677. mock_archive.id = 1
  678. mock_archive.print_name = "bad"
  679. with (
  680. patch(
  681. "backend.app.api.routes.settings.get_setting",
  682. new_callable=AsyncMock,
  683. return_value=None,
  684. ),
  685. patch(
  686. "backend.app.services.archive.ArchiveService.archive_print",
  687. new_callable=AsyncMock,
  688. return_value=mock_archive,
  689. ),
  690. ):
  691. await inst._add_to_print_queue(file_path, "192.168.1.100")
  692. assert len(added_items) == 1
  693. queue_item = added_items[0]
  694. # No filament data extractable → both fields stay None (graceful
  695. # fallback to model-only scheduling).
  696. assert queue_item.required_filament_types is None
  697. assert queue_item.filament_overrides is None
  698. # ========================================================================
  699. # Tests for archive_name_source setting (#1152)
  700. # ========================================================================
  701. @pytest.mark.asyncio
  702. @pytest.mark.parametrize(
  703. ("setting_value", "expected_prefer_filename"),
  704. [
  705. ("filename", True),
  706. ("metadata", False),
  707. (None, False), # Default when setting unset
  708. ("", False), # Defensive: empty string is not "filename"
  709. ],
  710. )
  711. async def test_archive_file_passes_prefer_filename_per_setting(
  712. self, tmp_path, setting_value, expected_prefer_filename
  713. ):
  714. """_archive_file reads `virtual_printer_archive_name_source` and forwards
  715. prefer_filename_for_name=True only when it equals 'filename' (#1152)."""
  716. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  717. mock_db = AsyncMock()
  718. mock_session_factory = MagicMock()
  719. mock_session_ctx = AsyncMock()
  720. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  721. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  722. mock_session_factory.return_value = mock_session_ctx
  723. inst = VirtualPrinterInstance(
  724. vp_id=20,
  725. name="NameSource",
  726. mode="immediate",
  727. model="C11",
  728. access_code="12345678",
  729. serial_suffix="391800020",
  730. base_dir=tmp_path,
  731. session_factory=mock_session_factory,
  732. )
  733. file_path = tmp_path / "user-renamed-job.3mf"
  734. file_path.write_bytes(b"fake3mf")
  735. mock_archive = MagicMock()
  736. mock_archive.id = 1
  737. mock_archive.print_name = "user-renamed-job"
  738. archive_print_mock = AsyncMock(return_value=mock_archive)
  739. with (
  740. patch(
  741. "backend.app.api.routes.settings.get_setting",
  742. new_callable=AsyncMock,
  743. return_value=setting_value,
  744. ),
  745. patch(
  746. "backend.app.services.archive.ArchiveService.archive_print",
  747. archive_print_mock,
  748. ),
  749. ):
  750. await inst._archive_file(file_path, "192.168.1.100")
  751. assert archive_print_mock.await_count == 1
  752. kwargs = archive_print_mock.await_args.kwargs
  753. assert kwargs.get("prefer_filename_for_name") is expected_prefer_filename
  754. class TestVirtualPrinterManager:
  755. """Tests for VirtualPrinterManager orchestrator."""
  756. @pytest.fixture
  757. def manager(self):
  758. """Create a VirtualPrinterManager instance."""
  759. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  760. return VirtualPrinterManager()
  761. def test_manager_starts_empty(self, manager):
  762. """Verify manager starts with no instances."""
  763. assert len(manager._instances) == 0
  764. assert manager.is_enabled is False
  765. def test_manager_get_status_empty(self, manager):
  766. """Verify get_status returns disabled state when no instances."""
  767. status = manager.get_status()
  768. assert status["enabled"] is False
  769. assert status["running"] is False
  770. assert status["mode"] == "immediate"
  771. def test_manager_is_enabled_with_instance(self, manager, tmp_path):
  772. """Verify is_enabled is True when instances exist."""
  773. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  774. inst = VirtualPrinterInstance(
  775. vp_id=1,
  776. name="Test",
  777. mode="immediate",
  778. model="C11",
  779. access_code="12345678",
  780. serial_suffix="391800001",
  781. base_dir=tmp_path,
  782. )
  783. manager._instances[1] = inst
  784. assert manager.is_enabled is True
  785. @pytest.mark.asyncio
  786. async def test_manager_remove_instance_server(self, manager, tmp_path):
  787. """Verify remove_instance stops and removes a server-mode instance."""
  788. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  789. inst = VirtualPrinterInstance(
  790. vp_id=1,
  791. name="Test",
  792. mode="immediate",
  793. model="C11",
  794. access_code="12345678",
  795. serial_suffix="391800001",
  796. base_dir=tmp_path,
  797. )
  798. inst.stop_server = AsyncMock()
  799. manager._instances[1] = inst
  800. await manager.remove_instance(1)
  801. assert 1 not in manager._instances
  802. inst.stop_server.assert_called_once()
  803. @pytest.mark.asyncio
  804. async def test_manager_remove_instance_proxy(self, manager, tmp_path):
  805. """Verify remove_instance stops proxy-mode instance."""
  806. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  807. inst = VirtualPrinterInstance(
  808. vp_id=2,
  809. name="Proxy",
  810. mode="proxy",
  811. model="C11",
  812. access_code="",
  813. serial_suffix="391800002",
  814. target_printer_ip="192.168.1.100",
  815. base_dir=tmp_path,
  816. )
  817. inst.stop_proxy = AsyncMock()
  818. manager._instances[2] = inst
  819. await manager.remove_instance(2)
  820. assert 2 not in manager._instances
  821. inst.stop_proxy.assert_called_once()
  822. def test_manager_get_status_with_instance(self, manager, tmp_path):
  823. """Verify legacy get_status returns first instance data."""
  824. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  825. inst = VirtualPrinterInstance(
  826. vp_id=1,
  827. name="Bambuddy",
  828. mode="immediate",
  829. model="C11",
  830. access_code="12345678",
  831. serial_suffix="391800001",
  832. base_dir=tmp_path,
  833. )
  834. mock_task = MagicMock(done=MagicMock(return_value=False))
  835. inst._tasks = [mock_task]
  836. inst._pending_files = {"file1.3mf": Path("/tmp/file1.3mf")} # nosec B108
  837. manager._instances[1] = inst
  838. status = manager.get_status()
  839. assert status["enabled"] is True
  840. assert status["running"] is True
  841. assert status["mode"] == "immediate"
  842. assert status["name"] == "Bambuddy"
  843. assert status["serial"] == "01S00A391800001"
  844. assert status["model"] == "C11"
  845. assert status["model_name"] == "P1P"
  846. assert status["pending_files"] == 1
  847. def test_manager_get_all_status(self, manager, tmp_path):
  848. """Verify get_all_status returns status for all instances."""
  849. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  850. for i in range(1, 3):
  851. inst = VirtualPrinterInstance(
  852. vp_id=i,
  853. name=f"VP{i}",
  854. mode="immediate",
  855. model="C11",
  856. access_code="12345678",
  857. serial_suffix=f"39180000{i}",
  858. base_dir=tmp_path,
  859. )
  860. manager._instances[i] = inst
  861. statuses = manager.get_all_status()
  862. assert len(statuses) == 2
  863. assert statuses[0]["name"] == "VP1"
  864. assert statuses[1]["name"] == "VP2"
  865. @pytest.mark.asyncio
  866. async def test_manager_stop_all(self, manager, tmp_path):
  867. """Verify stop_all removes all instances."""
  868. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  869. for i in range(1, 3):
  870. inst = VirtualPrinterInstance(
  871. vp_id=i,
  872. name=f"VP{i}",
  873. mode="immediate",
  874. model="C11",
  875. access_code="12345678",
  876. serial_suffix=f"39180000{i}",
  877. base_dir=tmp_path,
  878. )
  879. inst.stop_server = AsyncMock()
  880. manager._instances[i] = inst
  881. await manager.stop_all()
  882. assert len(manager._instances) == 0
  883. # ========================================================================
  884. # Tests for sync_from_db config change detection
  885. # ========================================================================
  886. def _make_db_vp(self, **overrides):
  887. """Create a mock VirtualPrinter DB object."""
  888. defaults = {
  889. "id": 1,
  890. "name": "TestVP",
  891. "enabled": True,
  892. "mode": "immediate",
  893. "model": "C11",
  894. "access_code": "12345678",
  895. "serial_suffix": "391800001",
  896. "bind_ip": "",
  897. "remote_interface_ip": "",
  898. "target_printer_id": None,
  899. "auto_dispatch": True,
  900. "tailscale_disabled": True, # Opt-in default (#1070 UX fix)
  901. "position": 0,
  902. }
  903. defaults.update(overrides)
  904. vp = MagicMock()
  905. for k, v in defaults.items():
  906. setattr(vp, k, v)
  907. return vp
  908. def _setup_sync_mocks(self, manager, enabled_vps, tmp_path):
  909. """Wire up session_factory mock for sync_from_db."""
  910. mock_result = MagicMock()
  911. mock_result.scalars.return_value.all.return_value = enabled_vps
  912. mock_db = AsyncMock()
  913. mock_db.execute = AsyncMock(return_value=mock_result)
  914. mock_db.__aenter__ = AsyncMock(return_value=mock_db)
  915. mock_db.__aexit__ = AsyncMock(return_value=False)
  916. manager._session_factory = MagicMock(return_value=mock_db)
  917. manager._base_dir = tmp_path
  918. @pytest.mark.asyncio
  919. async def test_sync_from_db_restarts_on_mode_change(self, manager, tmp_path):
  920. """Verify sync_from_db restarts VP when mode changes."""
  921. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  922. inst = VirtualPrinterInstance(
  923. vp_id=1,
  924. name="TestVP",
  925. mode="immediate",
  926. model="C11",
  927. access_code="12345678",
  928. serial_suffix="391800001",
  929. base_dir=tmp_path,
  930. )
  931. inst.stop_server = AsyncMock()
  932. manager._instances[1] = inst
  933. # DB says mode changed to "archive"
  934. db_vp = self._make_db_vp(mode="archive")
  935. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  936. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  937. # Patch VirtualPrinterInstance to prevent actual start
  938. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  939. mock_new = MagicMock()
  940. mock_new.start_server = AsyncMock()
  941. MockInst.return_value = mock_new
  942. await manager.sync_from_db()
  943. mock_remove.assert_called_once_with(1)
  944. @pytest.mark.asyncio
  945. async def test_sync_from_db_restarts_on_access_code_change(self, manager, tmp_path):
  946. """Verify sync_from_db restarts VP when access_code changes."""
  947. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  948. inst = VirtualPrinterInstance(
  949. vp_id=1,
  950. name="TestVP",
  951. mode="immediate",
  952. model="C11",
  953. access_code="12345678",
  954. serial_suffix="391800001",
  955. base_dir=tmp_path,
  956. )
  957. inst.stop_server = AsyncMock()
  958. manager._instances[1] = inst
  959. db_vp = self._make_db_vp(access_code="newcode99")
  960. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  961. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  962. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  963. mock_new = MagicMock()
  964. mock_new.start_server = AsyncMock()
  965. MockInst.return_value = mock_new
  966. await manager.sync_from_db()
  967. mock_remove.assert_called_once_with(1)
  968. @pytest.mark.asyncio
  969. async def test_sync_from_db_skips_unchanged_instance(self, manager, tmp_path):
  970. """Verify sync_from_db does NOT restart when config is identical."""
  971. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  972. inst = VirtualPrinterInstance(
  973. vp_id=1,
  974. name="TestVP",
  975. mode="immediate",
  976. model="C11",
  977. access_code="12345678",
  978. serial_suffix="391800001",
  979. base_dir=tmp_path,
  980. )
  981. manager._instances[1] = inst
  982. # DB matches running config exactly
  983. db_vp = self._make_db_vp()
  984. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  985. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  986. await manager.sync_from_db()
  987. mock_remove.assert_not_called()
  988. @pytest.mark.asyncio
  989. async def test_sync_from_db_restarts_on_bind_ip_change(self, manager, tmp_path):
  990. """Verify sync_from_db restarts VP when bind_ip changes."""
  991. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  992. inst = VirtualPrinterInstance(
  993. vp_id=1,
  994. name="TestVP",
  995. mode="immediate",
  996. model="C11",
  997. access_code="12345678",
  998. serial_suffix="391800001",
  999. bind_ip="192.168.1.10",
  1000. base_dir=tmp_path,
  1001. )
  1002. inst.stop_server = AsyncMock()
  1003. manager._instances[1] = inst
  1004. db_vp = self._make_db_vp(bind_ip="192.168.1.20")
  1005. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1006. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1007. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1008. mock_new = MagicMock()
  1009. mock_new.start_server = AsyncMock()
  1010. MockInst.return_value = mock_new
  1011. await manager.sync_from_db()
  1012. mock_remove.assert_called_once_with(1)
  1013. @pytest.mark.asyncio
  1014. async def test_sync_from_db_restarts_on_model_change(self, manager, tmp_path):
  1015. """Verify sync_from_db restarts VP when model changes."""
  1016. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1017. inst = VirtualPrinterInstance(
  1018. vp_id=1,
  1019. name="TestVP",
  1020. mode="immediate",
  1021. model="C11",
  1022. access_code="12345678",
  1023. serial_suffix="391800001",
  1024. base_dir=tmp_path,
  1025. )
  1026. inst.stop_server = AsyncMock()
  1027. manager._instances[1] = inst
  1028. db_vp = self._make_db_vp(model="C12")
  1029. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1030. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1031. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1032. mock_new = MagicMock()
  1033. mock_new.start_server = AsyncMock()
  1034. MockInst.return_value = mock_new
  1035. await manager.sync_from_db()
  1036. mock_remove.assert_called_once_with(1)
  1037. @pytest.mark.asyncio
  1038. async def test_sync_from_db_does_not_restart_on_tailscale_toggle(self, manager, tmp_path):
  1039. """Flipping tailscale_disabled is purely informational — must NOT trigger a restart.
  1040. Cert provisioning was removed; the toggle only governs whether the VP card surfaces
  1041. the host's Tailscale IP/FQDN to the user. No service needs to reload, so changing
  1042. it through sync_from_db should leave any running instance untouched.
  1043. """
  1044. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1045. inst = VirtualPrinterInstance(
  1046. vp_id=1,
  1047. name="TestVP",
  1048. mode="immediate",
  1049. model="C11",
  1050. access_code="12345678",
  1051. serial_suffix="391800001",
  1052. tailscale_disabled=False,
  1053. base_dir=tmp_path,
  1054. )
  1055. inst.stop_server = AsyncMock()
  1056. manager._instances[1] = inst
  1057. db_vp = self._make_db_vp(tailscale_disabled=True)
  1058. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1059. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1060. await manager.sync_from_db()
  1061. mock_remove.assert_not_called()
  1062. class TestFTPSession:
  1063. """Tests for FTP session handling."""
  1064. @pytest.fixture
  1065. def mock_reader(self):
  1066. """Create a mock StreamReader."""
  1067. reader = AsyncMock()
  1068. return reader
  1069. @pytest.fixture
  1070. def mock_writer(self):
  1071. """Create a mock StreamWriter."""
  1072. writer = MagicMock()
  1073. writer.get_extra_info = MagicMock(return_value=("192.168.1.100", 12345))
  1074. writer.write = MagicMock()
  1075. writer.drain = AsyncMock()
  1076. writer.close = MagicMock()
  1077. writer.wait_closed = AsyncMock()
  1078. writer.is_closing = MagicMock(return_value=False)
  1079. return writer
  1080. @pytest.fixture
  1081. def ssl_context(self):
  1082. """Create a mock SSL context."""
  1083. return MagicMock()
  1084. @pytest.fixture
  1085. def session(self, mock_reader, mock_writer, ssl_context, tmp_path):
  1086. """Create an FTPSession instance."""
  1087. from backend.app.services.virtual_printer.ftp_server import FTPSession
  1088. return FTPSession(
  1089. reader=mock_reader,
  1090. writer=mock_writer,
  1091. upload_dir=tmp_path,
  1092. access_code="12345678",
  1093. ssl_context=ssl_context,
  1094. on_file_received=None,
  1095. )
  1096. # ========================================================================
  1097. # Tests for authentication
  1098. # ========================================================================
  1099. @pytest.mark.asyncio
  1100. async def test_user_command_accepts_bblp(self, session):
  1101. """Verify USER command accepts bblp user."""
  1102. await session.cmd_USER("bblp")
  1103. assert session.username == "bblp"
  1104. @pytest.mark.asyncio
  1105. async def test_pass_command_authenticates(self, session):
  1106. """Verify PASS command authenticates with correct code."""
  1107. session.username = "bblp"
  1108. await session.cmd_PASS("12345678")
  1109. assert session.authenticated is True
  1110. @pytest.mark.asyncio
  1111. async def test_pass_command_rejects_wrong_code(self, session):
  1112. """Verify PASS command rejects wrong access code."""
  1113. session.username = "bblp"
  1114. await session.cmd_PASS("wrongcode")
  1115. assert session.authenticated is False
  1116. # ========================================================================
  1117. # Tests for FTP commands
  1118. # ========================================================================
  1119. @pytest.mark.asyncio
  1120. async def test_syst_command(self, session):
  1121. """Verify SYST returns UNIX type."""
  1122. await session.cmd_SYST("")
  1123. session.writer.write.assert_called()
  1124. call_args = session.writer.write.call_args[0][0].decode()
  1125. assert "215" in call_args
  1126. assert "UNIX" in call_args
  1127. @pytest.mark.asyncio
  1128. async def test_pwd_command_requires_auth(self, session):
  1129. """Verify PWD requires authentication."""
  1130. session.authenticated = False
  1131. await session.cmd_PWD("")
  1132. call_args = session.writer.write.call_args[0][0].decode()
  1133. assert "530" in call_args
  1134. @pytest.mark.asyncio
  1135. async def test_pwd_command_when_authenticated(self, session):
  1136. """Verify PWD returns root directory when authenticated."""
  1137. session.authenticated = True
  1138. await session.cmd_PWD("")
  1139. call_args = session.writer.write.call_args[0][0].decode()
  1140. assert "257" in call_args
  1141. @pytest.mark.asyncio
  1142. async def test_type_command_sets_binary(self, session):
  1143. """Verify TYPE I sets binary mode."""
  1144. session.authenticated = True
  1145. await session.cmd_TYPE("I")
  1146. assert session.transfer_type == "I"
  1147. @pytest.mark.asyncio
  1148. async def test_pbsz_command(self, session):
  1149. """Verify PBSZ returns success."""
  1150. await session.cmd_PBSZ("0")
  1151. call_args = session.writer.write.call_args[0][0].decode()
  1152. assert "200" in call_args
  1153. @pytest.mark.asyncio
  1154. async def test_prot_command_accepts_p(self, session):
  1155. """Verify PROT P is accepted."""
  1156. await session.cmd_PROT("P")
  1157. call_args = session.writer.write.call_args[0][0].decode()
  1158. assert "200" in call_args
  1159. @pytest.mark.asyncio
  1160. async def test_quit_command(self, session):
  1161. """Verify QUIT sends goodbye and raises CancelledError."""
  1162. with pytest.raises(asyncio.CancelledError):
  1163. await session.cmd_QUIT("")
  1164. class TestSSDPServer:
  1165. """Tests for Virtual Printer SSDP server."""
  1166. @pytest.fixture
  1167. def ssdp_server(self):
  1168. """Create a VirtualPrinterSSDPServer instance."""
  1169. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1170. return VirtualPrinterSSDPServer(
  1171. serial="TEST123",
  1172. name="TestPrinter",
  1173. model="BL-P001",
  1174. )
  1175. # ========================================================================
  1176. # Tests for SSDP response
  1177. # ========================================================================
  1178. def test_build_notify_message(self, ssdp_server):
  1179. """Verify NOTIFY packet contains required headers."""
  1180. # Set a known IP for testing
  1181. ssdp_server._local_ip = "192.168.1.100"
  1182. message = ssdp_server._build_notify_message()
  1183. assert b"NOTIFY" in message
  1184. assert b"DevName.bambu.com: TestPrinter" in message
  1185. assert b"USN: TEST123" in message
  1186. def test_build_response_message(self, ssdp_server):
  1187. """Verify response packet contains required headers."""
  1188. # Set a known IP for testing
  1189. ssdp_server._local_ip = "192.168.1.100"
  1190. message = ssdp_server._build_response_message()
  1191. assert b"HTTP/1.1 200 OK" in message
  1192. assert b"DevName.bambu.com: TestPrinter" in message
  1193. assert b"USN: TEST123" in message
  1194. def test_ssdp_server_uses_correct_model(self, ssdp_server):
  1195. """Verify SSDP server uses the provided model."""
  1196. ssdp_server._local_ip = "192.168.1.100"
  1197. message = ssdp_server._build_notify_message()
  1198. assert b"DevModel.bambu.com: BL-P001" in message
  1199. # ========================================================================
  1200. # Tests for advertise_ip parameter
  1201. # ========================================================================
  1202. def test_advertise_ip_sets_local_ip(self):
  1203. """Verify advertise_ip overrides auto-detection."""
  1204. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1205. server = VirtualPrinterSSDPServer(
  1206. serial="TEST123",
  1207. name="TestPrinter",
  1208. model="BL-P001",
  1209. advertise_ip="10.0.0.50",
  1210. )
  1211. assert server._local_ip == "10.0.0.50"
  1212. def test_advertise_ip_empty_string_uses_auto_detect(self):
  1213. """Verify empty advertise_ip falls back to auto-detection."""
  1214. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1215. server = VirtualPrinterSSDPServer(
  1216. serial="TEST123",
  1217. name="TestPrinter",
  1218. model="BL-P001",
  1219. advertise_ip="",
  1220. )
  1221. assert server._local_ip is None
  1222. def test_advertise_ip_in_notify_message(self):
  1223. """Verify NOTIFY message uses the advertise_ip."""
  1224. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1225. server = VirtualPrinterSSDPServer(
  1226. serial="TEST123",
  1227. name="TestPrinter",
  1228. model="BL-P001",
  1229. advertise_ip="10.0.0.50",
  1230. )
  1231. message = server._build_notify_message()
  1232. assert b"Location: 10.0.0.50" in message
  1233. def test_advertise_ip_in_response_message(self):
  1234. """Verify M-SEARCH response uses the advertise_ip."""
  1235. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1236. server = VirtualPrinterSSDPServer(
  1237. serial="TEST123",
  1238. name="TestPrinter",
  1239. model="BL-P001",
  1240. advertise_ip="10.0.0.50",
  1241. )
  1242. message = server._build_response_message()
  1243. assert b"Location: 10.0.0.50" in message
  1244. def test_default_no_advertise_ip(self):
  1245. """Verify default constructor has None local_ip (auto-detect)."""
  1246. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1247. server = VirtualPrinterSSDPServer()
  1248. assert server._local_ip is None
  1249. class TestCertificateService:
  1250. """Tests for TLS certificate generation."""
  1251. @pytest.fixture
  1252. def cert_service(self, tmp_path):
  1253. """Create a CertificateService instance."""
  1254. from backend.app.services.virtual_printer.certificate import CertificateService
  1255. return CertificateService(cert_dir=tmp_path, serial="TEST123")
  1256. def test_generate_certificates(self, cert_service, tmp_path):
  1257. """Verify certificates are generated correctly."""
  1258. cert_path, key_path = cert_service.generate_certificates()
  1259. assert cert_path.exists()
  1260. assert key_path.exists()
  1261. # Verify certificate content
  1262. cert_content = cert_path.read_text()
  1263. assert "BEGIN CERTIFICATE" in cert_content
  1264. key_content = key_path.read_text()
  1265. assert "BEGIN" in key_content and "KEY" in key_content
  1266. def test_certificates_reused_if_exist(self, cert_service):
  1267. """Verify existing certificates are reused."""
  1268. # First generation
  1269. cert_path1, key_path1 = cert_service.generate_certificates()
  1270. mtime1 = cert_path1.stat().st_mtime
  1271. # Second call should reuse (via ensure_certificates)
  1272. cert_path2, key_path2 = cert_service.ensure_certificates()
  1273. mtime2 = cert_path2.stat().st_mtime
  1274. assert mtime1 == mtime2 # File wasn't regenerated
  1275. def test_delete_certificates(self, cert_service):
  1276. """Verify certificates can be deleted."""
  1277. cert_service.generate_certificates()
  1278. assert cert_service.cert_path.exists()
  1279. assert cert_service.key_path.exists()
  1280. cert_service.delete_certificates()
  1281. assert not cert_service.cert_path.exists()
  1282. assert not cert_service.key_path.exists()
  1283. def test_ensure_creates_if_not_exist(self, cert_service):
  1284. """Verify ensure_certificates generates if not existing."""
  1285. assert not cert_service.cert_path.exists()
  1286. cert_path, key_path = cert_service.ensure_certificates()
  1287. assert cert_path.exists()
  1288. assert key_path.exists()
  1289. class TestBindServer:
  1290. """Tests for BindServer (port 3002 bind/detect protocol)."""
  1291. @pytest.fixture
  1292. def bind_server(self):
  1293. """Create a BindServer instance."""
  1294. from backend.app.services.virtual_printer.bind_server import BindServer
  1295. return BindServer(
  1296. serial="09400A391800001",
  1297. model="O1D",
  1298. name="Bambuddy",
  1299. )
  1300. def test_build_frame(self, bind_server):
  1301. """Verify frame building produces correct format."""
  1302. payload = {"login": {"command": "detect"}}
  1303. frame = bind_server._build_frame(payload)
  1304. # Header: 0xA5A5
  1305. assert frame[:2] == b"\xa5\xa5"
  1306. # Trailer: 0xA7A7
  1307. assert frame[-2:] == b"\xa7\xa7"
  1308. # Length field is total message size (LE uint16)
  1309. import struct
  1310. total_len = struct.unpack_from("<H", frame, 2)[0]
  1311. assert total_len == len(frame)
  1312. # JSON payload is between header and trailer
  1313. import json
  1314. json_bytes = frame[4:-2]
  1315. parsed = json.loads(json_bytes)
  1316. assert parsed == payload
  1317. def test_parse_frame_valid(self, bind_server):
  1318. """Verify valid frame parsing extracts JSON correctly."""
  1319. import json
  1320. import struct
  1321. payload = {"login": {"command": "detect", "sequence_id": "20000"}}
  1322. json_bytes = json.dumps(payload, separators=(",", ":")).encode()
  1323. total_len = 4 + len(json_bytes) + 2
  1324. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + json_bytes + b"\xa7\xa7"
  1325. result = bind_server._parse_frame(frame)
  1326. assert result is not None
  1327. assert result["login"]["command"] == "detect"
  1328. assert result["login"]["sequence_id"] == "20000"
  1329. def test_parse_frame_invalid_header(self, bind_server):
  1330. """Verify invalid header returns None."""
  1331. result = bind_server._parse_frame(b"\xbb\xbb\x06\x00{}\xa7\xa7")
  1332. assert result is None
  1333. def test_parse_frame_invalid_trailer(self, bind_server):
  1334. """Verify invalid trailer returns None."""
  1335. result = bind_server._parse_frame(b"\xa5\xa5\x06\x00{}\xbb\xbb")
  1336. assert result is None
  1337. def test_parse_frame_too_short(self, bind_server):
  1338. """Verify short data returns None."""
  1339. result = bind_server._parse_frame(b"\xa5\xa5\x00")
  1340. assert result is None
  1341. def test_parse_frame_invalid_json(self, bind_server):
  1342. """Verify invalid JSON returns None."""
  1343. import struct
  1344. bad_json = b"not json"
  1345. total_len = 4 + len(bad_json) + 2
  1346. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  1347. result = bind_server._parse_frame(frame)
  1348. assert result is None
  1349. def test_build_frame_roundtrip(self, bind_server):
  1350. """Verify build_frame output can be parsed back."""
  1351. payload = {
  1352. "login": {
  1353. "bind": "free",
  1354. "command": "detect",
  1355. "connect": "lan",
  1356. "dev_cap": 1,
  1357. "id": "09400A391800001",
  1358. "model": "O1D",
  1359. "name": "Bambuddy",
  1360. "sequence_id": 3021,
  1361. "version": "01.00.00.00",
  1362. }
  1363. }
  1364. frame = bind_server._build_frame(payload)
  1365. parsed = bind_server._parse_frame(frame)
  1366. assert parsed is not None
  1367. assert parsed["login"]["id"] == "09400A391800001"
  1368. assert parsed["login"]["model"] == "O1D"
  1369. assert parsed["login"]["name"] == "Bambuddy"
  1370. assert parsed["login"]["bind"] == "free"
  1371. def test_bind_server_stores_config(self, bind_server):
  1372. """Verify bind server stores serial, model, name."""
  1373. assert bind_server.serial == "09400A391800001"
  1374. assert bind_server.model == "O1D"
  1375. assert bind_server.name == "Bambuddy"
  1376. assert bind_server.version == "01.00.00.00"
  1377. def test_bind_server_custom_version(self):
  1378. """Verify custom firmware version is stored."""
  1379. from backend.app.services.virtual_printer.bind_server import BindServer
  1380. server = BindServer(
  1381. serial="TEST123",
  1382. model="C13",
  1383. name="Test",
  1384. version="02.03.04.05",
  1385. )
  1386. assert server.version == "02.03.04.05"
  1387. def test_bind_ports_constant(self):
  1388. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  1389. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  1390. assert 3000 in BIND_PORTS
  1391. assert 3002 in BIND_PORTS
  1392. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  1393. """Verify bind server starts with empty servers list."""
  1394. assert bind_server._servers == []
  1395. assert bind_server._running is False
  1396. class TestSlicerProxyManager:
  1397. """Tests for SlicerProxyManager (proxy mode)."""
  1398. @pytest.fixture
  1399. def proxy_manager(self, tmp_path):
  1400. """Create a SlicerProxyManager instance."""
  1401. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  1402. # Create dummy cert files
  1403. cert_path = tmp_path / "cert.pem"
  1404. key_path = tmp_path / "key.pem"
  1405. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  1406. # Split string to avoid pre-commit hook false positive on test data
  1407. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  1408. return SlicerProxyManager(
  1409. target_host="192.168.1.100",
  1410. cert_path=cert_path,
  1411. key_path=key_path,
  1412. )
  1413. def test_proxy_manager_initializes_ports(self, proxy_manager):
  1414. """Verify proxy manager has correct port constants."""
  1415. # FTP proxy uses privileged port 990 to match what Bambu Studio expects
  1416. assert proxy_manager.LOCAL_FTP_PORT == 990
  1417. assert proxy_manager.LOCAL_MQTT_PORT == 8883
  1418. assert proxy_manager.PRINTER_FTP_PORT == 990
  1419. assert proxy_manager.PRINTER_MQTT_PORT == 8883
  1420. assert proxy_manager.PRINTER_FILE_TRANSFER_PORT == 6000
  1421. assert proxy_manager.PRINTER_RTSP_PORT == 322
  1422. # Auxiliary ports: undocumented proprietary ports for A1/P1S etc.
  1423. assert proxy_manager.PRINTER_AUX_PORTS == [2024, 2025, 2026]
  1424. # Bind ports: both 3000 and 3002 for slicer compatibility
  1425. assert proxy_manager.PRINTER_BIND_PORTS == [3000, 3002]
  1426. # FTP data port range for transparent EPSV proxying
  1427. assert proxy_manager.FTP_DATA_PORT_MIN == 50000
  1428. assert proxy_manager.FTP_DATA_PORT_MAX == 50100
  1429. def test_proxy_manager_stores_target_host(self, proxy_manager):
  1430. """Verify proxy manager stores target host."""
  1431. assert proxy_manager.target_host == "192.168.1.100"
  1432. def test_get_status_before_start(self, proxy_manager):
  1433. """Verify get_status returns zeros before start."""
  1434. status = proxy_manager.get_status()
  1435. assert status["running"] is False
  1436. assert status["ftp_connections"] == 0
  1437. assert status["mqtt_connections"] == 0
  1438. @pytest.mark.asyncio
  1439. async def test_proxy_start_creates_transparent_proxies(self, tmp_path):
  1440. """Verify start() uses TCPProxy for FTP/FileTransfer/RTSP and TLSProxy only for MQTT.
  1441. The transparent proxy architecture preserves end-to-end TLS between
  1442. slicer and printer for all protocols except MQTT, which must be
  1443. TLS-terminated to rewrite the printer's IP in MQTT payloads.
  1444. """
  1445. from unittest.mock import AsyncMock, patch
  1446. from backend.app.services.virtual_printer.tcp_proxy import (
  1447. SlicerProxyManager,
  1448. TCPProxy,
  1449. TLSProxy,
  1450. )
  1451. cert_path = tmp_path / "cert.pem"
  1452. key_path = tmp_path / "key.pem"
  1453. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  1454. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  1455. mgr = SlicerProxyManager(
  1456. target_host="192.168.1.100",
  1457. cert_path=cert_path,
  1458. key_path=key_path,
  1459. bind_address="10.0.0.1",
  1460. )
  1461. # Mock asyncio.create_task and asyncio.gather to prevent actual server start
  1462. with (
  1463. patch("asyncio.create_task") as mock_create_task,
  1464. patch("asyncio.gather", new_callable=AsyncMock),
  1465. patch.object(SlicerProxyManager, "_log_activity"),
  1466. ):
  1467. mock_create_task.return_value = MagicMock()
  1468. # start() will create proxies then try to gather tasks — we just
  1469. # need to verify the proxy types after creation.
  1470. # Trigger start but let gather return immediately.
  1471. await mgr.start()
  1472. # FTP, FileTransfer, RTSP should be TCPProxy (transparent)
  1473. assert isinstance(mgr._ftp_proxy, TCPProxy), "FTP should be TCPProxy (transparent)"
  1474. assert isinstance(mgr._file_transfer_proxy, TCPProxy), "FileTransfer should be TCPProxy"
  1475. assert isinstance(mgr._rtsp_proxy, TCPProxy), "RTSP should be TCPProxy"
  1476. # MQTT should be TLSProxy (TLS-terminated for IP rewriting)
  1477. assert isinstance(mgr._mqtt_proxy, TLSProxy), "MQTT should be TLSProxy (TLS-terminated)"
  1478. # Auxiliary ports (2024-2026) should be TCPProxy (transparent)
  1479. assert len(mgr._aux_proxies) == 3, "Should have 3 aux port proxies"
  1480. for ap in mgr._aux_proxies:
  1481. assert isinstance(ap, TCPProxy), "Aux proxies should be TCPProxy"
  1482. assert mgr._aux_proxies[0].listen_port == 2024
  1483. assert mgr._aux_proxies[0].target_port == 2024
  1484. assert mgr._aux_proxies[2].listen_port == 2026
  1485. # FTP data ports should be pre-created as TCPProxy instances
  1486. assert len(mgr._ftp_data_proxies) == 101 # 50000-50100 inclusive
  1487. for dp in mgr._ftp_data_proxies:
  1488. assert isinstance(dp, TCPProxy), "FTP data proxies should be TCPProxy"
  1489. # Verify FTP data proxies target the same port on the printer
  1490. first_dp = mgr._ftp_data_proxies[0]
  1491. assert first_dp.listen_port == 50000
  1492. assert first_dp.target_port == 50000
  1493. assert first_dp.target_host == "192.168.1.100"
  1494. last_dp = mgr._ftp_data_proxies[-1]
  1495. assert last_dp.listen_port == 50100
  1496. assert last_dp.target_port == 50100
  1497. def test_proxy_manager_mqtt_has_ip_rewriting(self, tmp_path):
  1498. """Verify MQTT proxy is configured with IP rewriting when bind_address is set."""
  1499. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  1500. cert_path = tmp_path / "cert.pem"
  1501. key_path = tmp_path / "key.pem"
  1502. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  1503. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  1504. mgr = SlicerProxyManager(
  1505. target_host="192.168.1.100",
  1506. cert_path=cert_path,
  1507. key_path=key_path,
  1508. bind_address="10.0.0.1",
  1509. )
  1510. # Before start, proxies are None — verify constructor stores rewrite config
  1511. assert mgr.bind_address == "10.0.0.1"
  1512. assert mgr.target_host == "192.168.1.100"
  1513. class TestSSDPProxy:
  1514. """Tests for SSDPProxy (cross-network SSDP relay)."""
  1515. @pytest.fixture
  1516. def ssdp_proxy(self):
  1517. """Create an SSDPProxy instance."""
  1518. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  1519. return SSDPProxy(
  1520. local_interface_ip="192.168.1.100",
  1521. remote_interface_ip="10.0.0.100",
  1522. target_printer_ip="192.168.1.50",
  1523. )
  1524. def test_ssdp_proxy_stores_interface_ips(self, ssdp_proxy):
  1525. """Verify SSDPProxy stores interface IPs correctly."""
  1526. assert ssdp_proxy.local_interface_ip == "192.168.1.100"
  1527. assert ssdp_proxy.remote_interface_ip == "10.0.0.100"
  1528. assert ssdp_proxy.target_printer_ip == "192.168.1.50"
  1529. def test_rewrite_ssdp_location(self, ssdp_proxy):
  1530. """Verify SSDP Location header is rewritten to remote interface IP."""
  1531. original_packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: TestPrinter\r\n\r\n"
  1532. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  1533. # Location should be changed to remote interface IP
  1534. assert b"Location: 10.0.0.100" in rewritten
  1535. assert b"Location: 192.168.1.50" not in rewritten
  1536. # Other headers should be preserved
  1537. assert b"DevName.bambu.com: TestPrinter" in rewritten
  1538. def test_rewrite_ssdp_location_case_insensitive(self, ssdp_proxy):
  1539. """Verify SSDP Location rewrite is case insensitive."""
  1540. original_packet = b"NOTIFY * HTTP/1.1\r\nlocation: 192.168.1.50\r\n\r\n"
  1541. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  1542. assert b"10.0.0.100" in rewritten
  1543. def test_rewrite_ssdp_location_no_match(self, ssdp_proxy):
  1544. """Verify packet without Location header is returned unchanged."""
  1545. original_packet = b"NOTIFY * HTTP/1.1\r\nDevName.bambu.com: Test\r\n\r\n"
  1546. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  1547. # No Location header, but _rewrite_ssdp logs a warning and returns as-is
  1548. assert b"DevName.bambu.com: Test" in rewritten
  1549. def test_parse_ssdp_message(self, ssdp_proxy):
  1550. """Verify SSDP message parsing extracts headers."""
  1551. packet = (
  1552. b"NOTIFY * HTTP/1.1\r\n"
  1553. b"Location: 192.168.1.50\r\n"
  1554. b"DevName.bambu.com: TestPrinter\r\n"
  1555. b"DevModel.bambu.com: BL-P001\r\n"
  1556. b"\r\n"
  1557. )
  1558. headers = ssdp_proxy._parse_ssdp_message(packet)
  1559. assert headers["location"] == "192.168.1.50"
  1560. assert headers["devname.bambu.com"] == "TestPrinter"
  1561. assert headers["devmodel.bambu.com"] == "BL-P001"
  1562. class TestVirtualPrinterManagerDirectories:
  1563. """Tests for VirtualPrinterManager directory management."""
  1564. def test_ensure_base_directories_creates_subdirs(self, tmp_path):
  1565. """Verify _ensure_base_directories creates required base directories."""
  1566. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  1567. manager = VirtualPrinterManager()
  1568. manager._base_dir = tmp_path / "virtual_printer"
  1569. manager._ensure_base_directories()
  1570. assert (tmp_path / "virtual_printer").exists()
  1571. assert (tmp_path / "virtual_printer" / "uploads").exists()
  1572. assert (tmp_path / "virtual_printer" / "certs").exists()
  1573. def test_ensure_base_directories_handles_permission_error(self, tmp_path, caplog):
  1574. """Verify _ensure_base_directories logs error on permission failure."""
  1575. import logging
  1576. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  1577. manager = VirtualPrinterManager()
  1578. vp_dir = tmp_path / "virtual_printer"
  1579. manager._base_dir = vp_dir
  1580. original_mkdir = type(vp_dir).mkdir
  1581. def mock_mkdir(self, *args, **kwargs):
  1582. if "virtual_printer" in str(self):
  1583. raise PermissionError("Permission denied")
  1584. return original_mkdir(self, *args, **kwargs)
  1585. with caplog.at_level(logging.ERROR), patch.object(type(vp_dir), "mkdir", mock_mkdir):
  1586. manager._ensure_base_directories()
  1587. assert "Permission denied" in caplog.text
  1588. def test_instance_creates_per_vp_directories(self, tmp_path):
  1589. """Verify VirtualPrinterInstance creates per-VP upload and cert dirs."""
  1590. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1591. VirtualPrinterInstance(
  1592. vp_id=42,
  1593. name="Test",
  1594. mode="immediate",
  1595. model="C11",
  1596. access_code="12345678",
  1597. serial_suffix="391800042",
  1598. base_dir=tmp_path,
  1599. )
  1600. assert (tmp_path / "uploads" / "42").exists()
  1601. assert (tmp_path / "uploads" / "42" / "cache").exists()
  1602. assert (tmp_path / "certs" / "42").exists()
  1603. class TestVirtualPrinterInstanceProxyMode:
  1604. """Tests for VirtualPrinterInstance proxy mode."""
  1605. @pytest.fixture
  1606. def proxy_instance(self, tmp_path):
  1607. """Create a proxy-mode VirtualPrinterInstance."""
  1608. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1609. return VirtualPrinterInstance(
  1610. vp_id=10,
  1611. name="ProxyTest",
  1612. mode="proxy",
  1613. model="C11",
  1614. access_code="",
  1615. serial_suffix="391800010",
  1616. target_printer_ip="192.168.1.100",
  1617. target_printer_serial="01P00A000000001",
  1618. base_dir=tmp_path,
  1619. )
  1620. def test_proxy_instance_properties(self, proxy_instance):
  1621. """Verify proxy instance stores config correctly."""
  1622. assert proxy_instance.is_proxy is True
  1623. assert proxy_instance.mode == "proxy"
  1624. assert proxy_instance.target_printer_ip == "192.168.1.100"
  1625. assert proxy_instance.target_printer_serial == "01P00A000000001"
  1626. def test_proxy_instance_does_not_require_access_code(self, proxy_instance):
  1627. """Verify proxy mode can have empty access code."""
  1628. assert proxy_instance.access_code == ""
  1629. def test_get_status_proxy_includes_proxy_fields(self, proxy_instance):
  1630. """Verify get_status includes proxy fields when proxy is active."""
  1631. mock_proxy = MagicMock()
  1632. mock_proxy.get_status.return_value = {
  1633. "running": True,
  1634. "ftp_port": 990,
  1635. "mqtt_port": 8883,
  1636. "ftp_connections": 1,
  1637. "mqtt_connections": 2,
  1638. "target_host": "192.168.1.100",
  1639. }
  1640. proxy_instance._proxy = mock_proxy
  1641. status = proxy_instance.get_status()
  1642. assert "proxy" in status
  1643. assert status["proxy"]["ftp_port"] == 990
  1644. assert status["proxy"]["mqtt_connections"] == 2
  1645. def test_proxy_instance_stores_remote_interface(self, tmp_path):
  1646. """Verify proxy instance stores remote_interface_ip."""
  1647. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1648. inst = VirtualPrinterInstance(
  1649. vp_id=11,
  1650. name="Proxy2",
  1651. mode="proxy",
  1652. model="C11",
  1653. access_code="",
  1654. serial_suffix="391800011",
  1655. target_printer_ip="192.168.1.100",
  1656. remote_interface_ip="10.0.0.50",
  1657. base_dir=tmp_path,
  1658. )
  1659. assert inst.remote_interface_ip == "10.0.0.50"
  1660. class TestVirtualPrinterInstanceIPOverride:
  1661. """Tests for remote_interface_ip and bind_ip on VirtualPrinterInstance."""
  1662. @pytest.fixture
  1663. def instance_with_remote_ip(self, tmp_path):
  1664. """Create an instance with remote_interface_ip set."""
  1665. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1666. return VirtualPrinterInstance(
  1667. vp_id=20,
  1668. name="IPTest",
  1669. mode="immediate",
  1670. model="BL-P001",
  1671. access_code="12345678",
  1672. serial_suffix="391800020",
  1673. bind_ip="192.168.1.50",
  1674. remote_interface_ip="10.0.0.50",
  1675. base_dir=tmp_path,
  1676. )
  1677. def test_instance_stores_bind_ip(self, instance_with_remote_ip):
  1678. """Verify bind_ip is stored."""
  1679. assert instance_with_remote_ip.bind_ip == "192.168.1.50"
  1680. def test_instance_stores_remote_interface_ip(self, instance_with_remote_ip):
  1681. """Verify remote_interface_ip is stored."""
  1682. assert instance_with_remote_ip.remote_interface_ip == "10.0.0.50"
  1683. def test_generate_certificates_includes_remote_and_bind_ip(self, instance_with_remote_ip):
  1684. """Verify generate_certificates passes remote_interface_ip and bind_ip as SANs."""
  1685. with (
  1686. patch.object(instance_with_remote_ip._cert_service, "delete_printer_certificate"),
  1687. patch.object(
  1688. instance_with_remote_ip._cert_service,
  1689. "generate_certificates",
  1690. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  1691. ) as mock_gen,
  1692. ):
  1693. instance_with_remote_ip.generate_certificates()
  1694. mock_gen.assert_called_once_with(additional_ips=["10.0.0.50", "192.168.1.50"])
  1695. def test_generate_certificates_no_remote_ip(self, tmp_path):
  1696. """Verify generate_certificates passes only bind_ip when no remote_interface_ip."""
  1697. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1698. inst = VirtualPrinterInstance(
  1699. vp_id=21,
  1700. name="NoRemote",
  1701. mode="immediate",
  1702. model="BL-P001",
  1703. access_code="12345678",
  1704. serial_suffix="391800021",
  1705. bind_ip="192.168.1.50",
  1706. base_dir=tmp_path,
  1707. )
  1708. with (
  1709. patch.object(inst._cert_service, "delete_printer_certificate"),
  1710. patch.object(
  1711. inst._cert_service,
  1712. "generate_certificates",
  1713. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  1714. ) as mock_gen,
  1715. ):
  1716. inst.generate_certificates()
  1717. mock_gen.assert_called_once_with(additional_ips=["192.168.1.50"])
  1718. def test_generate_certificates_no_ips(self, tmp_path):
  1719. """Verify generate_certificates passes None when no IPs configured."""
  1720. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1721. inst = VirtualPrinterInstance(
  1722. vp_id=22,
  1723. name="NoIPs",
  1724. mode="immediate",
  1725. model="BL-P001",
  1726. access_code="12345678",
  1727. serial_suffix="391800022",
  1728. base_dir=tmp_path,
  1729. )
  1730. with (
  1731. patch.object(inst._cert_service, "delete_printer_certificate"),
  1732. patch.object(
  1733. inst._cert_service,
  1734. "generate_certificates",
  1735. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  1736. ) as mock_gen,
  1737. ):
  1738. inst.generate_certificates()
  1739. mock_gen.assert_called_once_with(additional_ips=None)
  1740. class TestBindServer:
  1741. """Tests for the BindServer (port 3002 bind/detect protocol)."""
  1742. @pytest.fixture
  1743. def bind_server(self):
  1744. """Create a BindServer instance."""
  1745. from backend.app.services.virtual_printer.bind_server import BindServer
  1746. return BindServer(
  1747. serial="01S00C000000001",
  1748. model="BL-P001",
  1749. name="Bambuddy",
  1750. )
  1751. def test_build_frame(self, bind_server):
  1752. """Verify frame format: 0xA5A5 + len(u16le) + JSON + 0xA7A7."""
  1753. payload = {"login": {"command": "detect"}}
  1754. frame = bind_server._build_frame(payload)
  1755. assert frame[:2] == b"\xa5\xa5"
  1756. assert frame[-2:] == b"\xa7\xa7"
  1757. # Length field is total message size
  1758. import struct
  1759. total_len = struct.unpack_from("<H", frame, 2)[0]
  1760. assert total_len == len(frame)
  1761. # JSON payload is between header and trailer
  1762. import json
  1763. json_bytes = frame[4:-2]
  1764. parsed = json.loads(json_bytes)
  1765. assert parsed == payload
  1766. def test_parse_frame_valid(self, bind_server):
  1767. """Verify valid frame parsing."""
  1768. frame = bind_server._build_frame({"login": {"command": "detect", "sequence_id": "20000"}})
  1769. result = bind_server._parse_frame(frame)
  1770. assert result is not None
  1771. assert result["login"]["command"] == "detect"
  1772. assert result["login"]["sequence_id"] == "20000"
  1773. def test_parse_frame_invalid_header(self, bind_server):
  1774. """Verify invalid header returns None."""
  1775. frame = b"\xb5\xb5\x10\x00" + b'{"login":{}}' + b"\xa7\xa7"
  1776. assert bind_server._parse_frame(frame) is None
  1777. def test_parse_frame_invalid_trailer(self, bind_server):
  1778. """Verify invalid trailer returns None."""
  1779. frame = b"\xa5\xa5\x10\x00" + b'{"login":{}}' + b"\xb7\xb7"
  1780. assert bind_server._parse_frame(frame) is None
  1781. def test_parse_frame_too_short(self, bind_server):
  1782. """Verify short data returns None."""
  1783. assert bind_server._parse_frame(b"\xa5\xa5\x00") is None
  1784. assert bind_server._parse_frame(b"") is None
  1785. def test_parse_frame_invalid_json(self, bind_server):
  1786. """Verify invalid JSON returns None."""
  1787. import struct
  1788. bad_json = b"not json"
  1789. total_len = 4 + len(bad_json) + 2
  1790. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  1791. assert bind_server._parse_frame(frame) is None
  1792. def test_build_frame_roundtrip(self, bind_server):
  1793. """Verify build then parse roundtrip."""
  1794. original = {"login": {"bind": "free", "command": "detect", "id": "01S00C000000001"}}
  1795. frame = bind_server._build_frame(original)
  1796. parsed = bind_server._parse_frame(frame)
  1797. assert parsed == original
  1798. def test_bind_server_stores_config(self, bind_server):
  1799. """Verify config is stored correctly."""
  1800. assert bind_server.serial == "01S00C000000001"
  1801. assert bind_server.model == "BL-P001"
  1802. assert bind_server.name == "Bambuddy"
  1803. assert bind_server.version == "01.00.00.00"
  1804. def test_bind_server_custom_version(self):
  1805. """Verify custom firmware version is stored."""
  1806. from backend.app.services.virtual_printer.bind_server import BindServer
  1807. server = BindServer(
  1808. serial="01S00C000000001",
  1809. model="BL-P001",
  1810. name="Bambuddy",
  1811. version="01.09.00.10",
  1812. )
  1813. assert server.version == "01.09.00.10"
  1814. def test_bind_ports_includes_both(self):
  1815. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  1816. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  1817. assert 3000 in BIND_PORTS
  1818. assert 3002 in BIND_PORTS
  1819. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  1820. """Verify bind server starts with empty servers list."""
  1821. assert bind_server._servers == []
  1822. assert bind_server._running is False
  1823. @pytest.mark.asyncio
  1824. async def test_start_server_creates_bind_server(self, tmp_path):
  1825. """Verify start_server creates BindServer with correct params."""
  1826. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1827. inst = VirtualPrinterInstance(
  1828. vp_id=99,
  1829. name="Bambuddy",
  1830. mode="immediate",
  1831. model="BL-P001",
  1832. access_code="12345678",
  1833. serial_suffix="391800099",
  1834. bind_ip="192.168.1.50",
  1835. base_dir=tmp_path,
  1836. )
  1837. with (
  1838. patch("backend.app.services.virtual_printer.manager.VirtualPrinterSSDPServer"),
  1839. patch("backend.app.services.virtual_printer.manager.VirtualPrinterFTPServer"),
  1840. patch("backend.app.services.virtual_printer.manager.SimpleMQTTServer"),
  1841. patch("backend.app.services.virtual_printer.manager.BindServer") as mock_bind_cls,
  1842. patch.object(inst._cert_service, "delete_printer_certificate"),
  1843. patch.object(
  1844. inst._cert_service,
  1845. "generate_certificates",
  1846. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  1847. ),
  1848. ):
  1849. await inst.start_server()
  1850. mock_bind_cls.assert_called_once_with(
  1851. serial=inst.serial,
  1852. model="BL-P001",
  1853. name="Bambuddy",
  1854. bind_address="192.168.1.50",
  1855. cert_path=Path("/tmp/cert.pem"), # nosec B108
  1856. key_path=Path("/tmp/key.pem"), # nosec B108
  1857. )
  1858. class TestResolveModelCodes:
  1859. """Tests for model code resolution (display name → SSDP code)."""
  1860. def test_display_name_to_model_code_maps_all_models(self):
  1861. """Verify reverse mapping covers all VIRTUAL_PRINTER_MODELS entries."""
  1862. from backend.app.services.virtual_printer.manager import DISPLAY_NAME_TO_MODEL_CODE, VIRTUAL_PRINTER_MODELS
  1863. for _code, display_name in VIRTUAL_PRINTER_MODELS.items():
  1864. assert display_name in DISPLAY_NAME_TO_MODEL_CODE
  1865. # For non-duplicate display names, should map back to a valid code
  1866. assert DISPLAY_NAME_TO_MODEL_CODE[display_name] in VIRTUAL_PRINTER_MODELS
  1867. def test_resolve_printer_model_with_ssdp_code(self):
  1868. """SSDP codes pass through unchanged."""
  1869. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  1870. assert _resolve_printer_model("BL-P001") == "BL-P001"
  1871. assert _resolve_printer_model("O1D") == "O1D"
  1872. assert _resolve_printer_model("N2S") == "N2S"
  1873. def test_resolve_printer_model_with_display_name(self):
  1874. """Display names resolve to SSDP codes."""
  1875. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  1876. assert _resolve_printer_model("X1C") == "BL-P001"
  1877. assert _resolve_printer_model("H2D") == "O1D"
  1878. assert _resolve_printer_model("A1") == "N2S"
  1879. assert _resolve_printer_model("P1S") == "C12"
  1880. def test_resolve_printer_model_with_none_or_unknown(self):
  1881. """None and unknown values return None."""
  1882. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  1883. assert _resolve_printer_model(None) is None
  1884. assert _resolve_printer_model("UnknownModel") is None
  1885. class TestMqttIpRewrite:
  1886. """Tests for TLSProxy._rewrite_mqtt_ip() MQTT packet IP rewriting."""
  1887. @staticmethod
  1888. def _build_mqtt_publish(topic: str, payload: bytes) -> bytes:
  1889. """Build a minimal MQTT PUBLISH packet."""
  1890. # PUBLISH fixed header: type 3, no flags
  1891. topic_bytes = topic.encode("utf-8")
  1892. # Variable header: topic length (2 bytes) + topic
  1893. var_header = len(topic_bytes).to_bytes(2, "big") + topic_bytes
  1894. body = var_header + payload
  1895. # Encode remaining length
  1896. remaining = len(body)
  1897. header = bytearray([0x30]) # PUBLISH, QoS 0
  1898. while True:
  1899. encoded_byte = remaining % 128
  1900. remaining //= 128
  1901. if remaining > 0:
  1902. encoded_byte |= 0x80
  1903. header.append(encoded_byte)
  1904. if remaining == 0:
  1905. break
  1906. return bytes(header) + body
  1907. @staticmethod
  1908. def _build_mqtt_pingreq() -> bytes:
  1909. """Build an MQTT PINGREQ packet (2 bytes, no payload)."""
  1910. return b"\xc0\x00"
  1911. def test_rewrite_ip_in_publish(self):
  1912. """IP string in PUBLISH payload is rewritten."""
  1913. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  1914. payload = b'{"rtsp_url":"rtsps://192.168.1.100:322/live"}'
  1915. packet = self._build_mqtt_publish("device/status", payload)
  1916. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  1917. assert b"10.0.0.1" in result
  1918. assert b"192.168.1.100" not in result
  1919. def test_no_rewrite_when_ip_absent(self):
  1920. """Packets without the target IP are passed through unchanged."""
  1921. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  1922. payload = b'{"status":"idle"}'
  1923. packet = self._build_mqtt_publish("device/status", payload)
  1924. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  1925. assert result == packet
  1926. def test_non_publish_packets_unchanged(self):
  1927. """Non-PUBLISH packets (e.g. PINGREQ) are never rewritten."""
  1928. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  1929. pingreq = self._build_mqtt_pingreq()
  1930. result, buf = TLSProxy._rewrite_mqtt_ip(pingreq, b"192.168.1.100", b"10.0.0.1", bytearray())
  1931. assert result == pingreq
  1932. def test_rewrite_preserves_packet_framing(self):
  1933. """Rewritten packet has valid MQTT remaining length."""
  1934. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  1935. # Use IPs of different lengths to test length re-encoding
  1936. old_ip = b"192.168.255.133" # 15 bytes
  1937. new_ip = b"10.0.0.1" # 8 bytes
  1938. payload = b'{"ip":"192.168.255.133"}'
  1939. packet = self._build_mqtt_publish("device/status", payload)
  1940. result, buf = TLSProxy._rewrite_mqtt_ip(packet, old_ip, new_ip, bytearray())
  1941. # Parse the result to verify framing
  1942. assert result[0] == 0x30 # PUBLISH header byte
  1943. # Decode remaining length
  1944. pos = 1
  1945. remaining = 0
  1946. multiplier = 1
  1947. while True:
  1948. b = result[pos]
  1949. pos += 1
  1950. remaining += (b & 0x7F) * multiplier
  1951. multiplier *= 128
  1952. if (b & 0x80) == 0:
  1953. break
  1954. # Remaining length should match actual data
  1955. assert pos + remaining == len(result)
  1956. assert new_ip in result
  1957. def test_incomplete_packet_buffered(self):
  1958. """Incomplete packet at end of chunk is buffered for next call."""
  1959. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  1960. payload = b'{"ip":"192.168.1.100"}'
  1961. packet = self._build_mqtt_publish("device/status", payload)
  1962. # Split packet in the middle
  1963. half = len(packet) // 2
  1964. chunk1 = packet[:half]
  1965. chunk2 = packet[half:]
  1966. result1, buf = TLSProxy._rewrite_mqtt_ip(chunk1, b"192.168.1.100", b"10.0.0.1", bytearray())
  1967. # First chunk should be buffered (incomplete packet)
  1968. assert len(buf) > 0
  1969. result2, buf = TLSProxy._rewrite_mqtt_ip(chunk2, b"192.168.1.100", b"10.0.0.1", buf)
  1970. # Second chunk completes the packet, IP should be rewritten
  1971. combined = result1 + result2
  1972. assert b"10.0.0.1" in combined
  1973. assert b"192.168.1.100" not in combined
  1974. def test_multiple_packets_in_one_chunk(self):
  1975. """Multiple MQTT packets in a single chunk are all processed."""
  1976. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  1977. payload1 = b'{"ip":"192.168.1.100"}'
  1978. payload2 = b'{"other":"data"}'
  1979. packet1 = self._build_mqtt_publish("topic1", payload1)
  1980. packet2 = self._build_mqtt_publish("topic2", payload2)
  1981. combined = packet1 + packet2
  1982. result, buf = TLSProxy._rewrite_mqtt_ip(combined, b"192.168.1.100", b"10.0.0.1", bytearray())
  1983. assert b"10.0.0.1" in result
  1984. assert b"192.168.1.100" not in result
  1985. # Second packet should still be present
  1986. assert b"other" in result
  1987. def test_extra_replacements(self):
  1988. """Extra replacement pairs (e.g. integer IP) are also applied."""
  1989. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  1990. payload = b'{"net":{"info":[{"ip":2248124608}]}}'
  1991. packet = self._build_mqtt_publish("device/status", payload)
  1992. result, buf = TLSProxy._rewrite_mqtt_ip(
  1993. packet,
  1994. b"NOMATCH",
  1995. b"NOREPLACE",
  1996. bytearray(),
  1997. extra_replacements=[(b"2248124608", b"285190336")],
  1998. )
  1999. assert b"285190336" in result
  2000. assert b"2248124608" not in result
  2001. class TestIpToLeIntBytes:
  2002. """Tests for TLSProxy._ip_to_le_int_bytes() integer IP conversion."""
  2003. def test_converts_ip_to_le_int(self):
  2004. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2005. assert TLSProxy._ip_to_le_int_bytes("192.168.255.133") == b"2248124608"
  2006. assert TLSProxy._ip_to_le_int_bytes("192.168.255.16") == b"285190336"
  2007. assert TLSProxy._ip_to_le_int_bytes("10.0.0.1") == b"16777226"
  2008. def test_roundtrip(self):
  2009. """Verify the integer converts back to the correct IP."""
  2010. import struct
  2011. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2012. for ip in ["192.168.1.1", "10.0.0.1", "172.16.0.100", "192.168.255.133"]:
  2013. le_int = int(TLSProxy._ip_to_le_int_bytes(ip))
  2014. parts = ip.split(".")
  2015. expected = struct.unpack("<I", bytes(int(p) for p in parts))[0]
  2016. assert le_int == expected
  2017. class TestSSDPProxyName:
  2018. """Tests for SSDPProxy VP name rewriting."""
  2019. @pytest.fixture
  2020. def ssdp_proxy_with_name(self):
  2021. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2022. return SSDPProxy(
  2023. local_interface_ip="192.168.1.100",
  2024. remote_interface_ip="10.0.0.100",
  2025. target_printer_ip="192.168.1.50",
  2026. name="H2D-1 Proxy",
  2027. )
  2028. @pytest.fixture
  2029. def ssdp_proxy_without_name(self):
  2030. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2031. return SSDPProxy(
  2032. local_interface_ip="192.168.1.100",
  2033. remote_interface_ip="10.0.0.100",
  2034. target_printer_ip="192.168.1.50",
  2035. )
  2036. def test_rewrite_uses_configured_name(self, ssdp_proxy_with_name):
  2037. """When name is set, DevName is replaced entirely."""
  2038. 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"
  2039. rewritten = ssdp_proxy_with_name._rewrite_ssdp(packet)
  2040. assert b"DevName.bambu.com: H2D-1 Proxy" in rewritten
  2041. assert b"RealPrinter" not in rewritten
  2042. def test_rewrite_appends_proxy_without_name(self, ssdp_proxy_without_name):
  2043. """When no name is set, ' - Proxy' is appended to the real name."""
  2044. 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"
  2045. rewritten = ssdp_proxy_without_name._rewrite_ssdp(packet)
  2046. assert b"DevName.bambu.com: RealPrinter - Proxy" in rewritten