test_virtual_printer.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. """Unit tests for Virtual Printer services.
  2. Tests the virtual printer manager, FTP server, and SSDP server components.
  3. """
  4. import asyncio
  5. from pathlib import Path
  6. from unittest.mock import AsyncMock, MagicMock, patch
  7. import pytest
  8. class TestVirtualPrinterManager:
  9. """Tests for VirtualPrinterManager class."""
  10. @pytest.fixture
  11. def manager(self):
  12. """Create a VirtualPrinterManager instance."""
  13. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  14. return VirtualPrinterManager()
  15. # ========================================================================
  16. # Tests for configuration
  17. # ========================================================================
  18. @pytest.mark.asyncio
  19. async def test_configure_sets_parameters(self, manager):
  20. """Verify configure stores parameters correctly."""
  21. # Mock the start/stop methods to avoid actually starting services
  22. manager._start = AsyncMock()
  23. await manager.configure(
  24. enabled=True,
  25. access_code="12345678",
  26. mode="immediate",
  27. )
  28. assert manager._enabled is True
  29. assert manager._access_code == "12345678"
  30. assert manager._mode == "immediate"
  31. @pytest.mark.asyncio
  32. async def test_configure_disabled_stops_services(self, manager):
  33. """Verify disabling stops all services."""
  34. # First simulate enabled state
  35. manager._enabled = True
  36. manager._tasks = [MagicMock(done=MagicMock(return_value=False))]
  37. manager._stop = AsyncMock()
  38. await manager.configure(enabled=False, access_code="12345678")
  39. assert manager._enabled is False
  40. manager._stop.assert_called_once()
  41. @pytest.mark.asyncio
  42. async def test_configure_requires_access_code_when_enabling(self, manager):
  43. """Verify access code is required when enabling."""
  44. with pytest.raises(ValueError, match="Access code is required"):
  45. await manager.configure(enabled=True)
  46. @pytest.mark.asyncio
  47. async def test_configure_sets_model(self, manager):
  48. """Verify configure stores model correctly."""
  49. manager._start = AsyncMock()
  50. await manager.configure(
  51. enabled=True,
  52. access_code="12345678",
  53. mode="immediate",
  54. model="C11", # P1S model code
  55. )
  56. assert manager._model == "C11"
  57. @pytest.mark.asyncio
  58. async def test_configure_ignores_invalid_model(self, manager):
  59. """Verify configure ignores invalid model codes."""
  60. manager._start = AsyncMock()
  61. await manager.configure(
  62. enabled=True,
  63. access_code="12345678",
  64. model="INVALID",
  65. )
  66. # Should keep default model (3DPrinter-X1-Carbon = X1C)
  67. assert manager._model == "3DPrinter-X1-Carbon"
  68. @pytest.mark.asyncio
  69. async def test_configure_restarts_on_model_change(self, manager):
  70. """Verify model change restarts services when running."""
  71. # Simulate running state
  72. manager._enabled = True
  73. manager._model = "3DPrinter-X1-Carbon"
  74. manager._tasks = [MagicMock(done=MagicMock(return_value=False))]
  75. manager._stop = AsyncMock()
  76. manager._start = AsyncMock()
  77. await manager.configure(
  78. enabled=True,
  79. access_code="12345678",
  80. model="C11", # P1P
  81. )
  82. # Should have stopped and started
  83. manager._stop.assert_called_once()
  84. manager._start.assert_called_once()
  85. # ========================================================================
  86. # Tests for status
  87. # ========================================================================
  88. def test_get_status_returns_correct_format(self, manager):
  89. """Verify get_status returns expected fields."""
  90. manager._enabled = True
  91. manager._mode = "immediate"
  92. manager._model = "C11" # P1P
  93. manager._pending_files = {"file1.3mf": Path("/tmp/file1.3mf")}
  94. # Simulate running tasks
  95. manager._tasks = [MagicMock(done=MagicMock(return_value=False))]
  96. status = manager.get_status()
  97. assert status["enabled"] is True
  98. assert status["running"] is True
  99. assert status["mode"] == "immediate"
  100. assert status["name"] == "Bambuddy"
  101. assert status["serial"] == "01S00A391800001" # C11 (P1P) serial prefix
  102. assert status["model"] == "C11"
  103. assert status["model_name"] == "P1P"
  104. assert status["pending_files"] == 1
  105. def test_get_status_when_stopped(self, manager):
  106. """Verify get_status when not running."""
  107. manager._enabled = False
  108. manager._tasks = []
  109. status = manager.get_status()
  110. assert status["enabled"] is False
  111. assert status["running"] is False
  112. def test_is_running_with_active_tasks(self, manager):
  113. """Verify is_running is True when tasks are active."""
  114. mock_task = MagicMock()
  115. mock_task.done.return_value = False
  116. manager._tasks = [mock_task]
  117. assert manager.is_running is True
  118. def test_is_running_with_no_tasks(self, manager):
  119. """Verify is_running is False when no tasks."""
  120. manager._tasks = []
  121. assert manager.is_running is False
  122. # ========================================================================
  123. # Tests for file handling
  124. # ========================================================================
  125. @pytest.mark.asyncio
  126. async def test_on_file_received_adds_to_pending(self, manager):
  127. """Verify received file is added to pending list."""
  128. manager._mode = "queue"
  129. manager._session_factory = None # Disable actual archiving
  130. file_path = Path("/tmp/test.3mf")
  131. with patch.object(manager, "_queue_file", new_callable=AsyncMock) as mock_queue:
  132. await manager._on_file_received(file_path, "192.168.1.100")
  133. assert "test.3mf" in manager._pending_files
  134. mock_queue.assert_called_once()
  135. @pytest.mark.asyncio
  136. async def test_on_file_received_archives_immediately(self, manager):
  137. """Verify file is archived in immediate mode."""
  138. manager._mode = "immediate"
  139. manager._session_factory = None # Will prevent actual archiving
  140. file_path = Path("/tmp/test.3mf")
  141. with patch.object(manager, "_archive_file", new_callable=AsyncMock) as mock_archive:
  142. await manager._on_file_received(file_path, "192.168.1.100")
  143. mock_archive.assert_called_once_with(file_path, "192.168.1.100")
  144. @pytest.mark.asyncio
  145. async def test_archive_file_skips_non_3mf(self, manager):
  146. """Verify non-3MF files are skipped and cleaned up."""
  147. manager._session_factory = MagicMock()
  148. manager._pending_files["verify_job"] = Path("/tmp/verify_job")
  149. with patch("pathlib.Path.unlink"):
  150. await manager._archive_file(Path("/tmp/verify_job"), "192.168.1.100")
  151. # Should be removed from pending
  152. assert "verify_job" not in manager._pending_files
  153. class TestFTPSession:
  154. """Tests for FTP session handling."""
  155. @pytest.fixture
  156. def mock_reader(self):
  157. """Create a mock StreamReader."""
  158. reader = AsyncMock()
  159. return reader
  160. @pytest.fixture
  161. def mock_writer(self):
  162. """Create a mock StreamWriter."""
  163. writer = MagicMock()
  164. writer.get_extra_info = MagicMock(return_value=("192.168.1.100", 12345))
  165. writer.write = MagicMock()
  166. writer.drain = AsyncMock()
  167. writer.close = MagicMock()
  168. writer.wait_closed = AsyncMock()
  169. writer.is_closing = MagicMock(return_value=False)
  170. return writer
  171. @pytest.fixture
  172. def ssl_context(self):
  173. """Create a mock SSL context."""
  174. return MagicMock()
  175. @pytest.fixture
  176. def session(self, mock_reader, mock_writer, ssl_context, tmp_path):
  177. """Create an FTPSession instance."""
  178. from backend.app.services.virtual_printer.ftp_server import FTPSession
  179. return FTPSession(
  180. reader=mock_reader,
  181. writer=mock_writer,
  182. upload_dir=tmp_path,
  183. access_code="12345678",
  184. ssl_context=ssl_context,
  185. on_file_received=None,
  186. )
  187. # ========================================================================
  188. # Tests for authentication
  189. # ========================================================================
  190. @pytest.mark.asyncio
  191. async def test_user_command_accepts_bblp(self, session):
  192. """Verify USER command accepts bblp user."""
  193. await session.cmd_USER("bblp")
  194. assert session.username == "bblp"
  195. @pytest.mark.asyncio
  196. async def test_pass_command_authenticates(self, session):
  197. """Verify PASS command authenticates with correct code."""
  198. session.username = "bblp"
  199. await session.cmd_PASS("12345678")
  200. assert session.authenticated is True
  201. @pytest.mark.asyncio
  202. async def test_pass_command_rejects_wrong_code(self, session):
  203. """Verify PASS command rejects wrong access code."""
  204. session.username = "bblp"
  205. await session.cmd_PASS("wrongcode")
  206. assert session.authenticated is False
  207. # ========================================================================
  208. # Tests for FTP commands
  209. # ========================================================================
  210. @pytest.mark.asyncio
  211. async def test_syst_command(self, session):
  212. """Verify SYST returns UNIX type."""
  213. await session.cmd_SYST("")
  214. session.writer.write.assert_called()
  215. call_args = session.writer.write.call_args[0][0].decode()
  216. assert "215" in call_args
  217. assert "UNIX" in call_args
  218. @pytest.mark.asyncio
  219. async def test_pwd_command_requires_auth(self, session):
  220. """Verify PWD requires authentication."""
  221. session.authenticated = False
  222. await session.cmd_PWD("")
  223. call_args = session.writer.write.call_args[0][0].decode()
  224. assert "530" in call_args
  225. @pytest.mark.asyncio
  226. async def test_pwd_command_when_authenticated(self, session):
  227. """Verify PWD returns root directory when authenticated."""
  228. session.authenticated = True
  229. await session.cmd_PWD("")
  230. call_args = session.writer.write.call_args[0][0].decode()
  231. assert "257" in call_args
  232. @pytest.mark.asyncio
  233. async def test_type_command_sets_binary(self, session):
  234. """Verify TYPE I sets binary mode."""
  235. session.authenticated = True
  236. await session.cmd_TYPE("I")
  237. assert session.transfer_type == "I"
  238. @pytest.mark.asyncio
  239. async def test_pbsz_command(self, session):
  240. """Verify PBSZ returns success."""
  241. await session.cmd_PBSZ("0")
  242. call_args = session.writer.write.call_args[0][0].decode()
  243. assert "200" in call_args
  244. @pytest.mark.asyncio
  245. async def test_prot_command_accepts_p(self, session):
  246. """Verify PROT P is accepted."""
  247. await session.cmd_PROT("P")
  248. call_args = session.writer.write.call_args[0][0].decode()
  249. assert "200" in call_args
  250. @pytest.mark.asyncio
  251. async def test_quit_command(self, session):
  252. """Verify QUIT sends goodbye and raises CancelledError."""
  253. with pytest.raises(asyncio.CancelledError):
  254. await session.cmd_QUIT("")
  255. class TestSSDPServer:
  256. """Tests for Virtual Printer SSDP server."""
  257. @pytest.fixture
  258. def ssdp_server(self):
  259. """Create a VirtualPrinterSSDPServer instance."""
  260. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  261. return VirtualPrinterSSDPServer(
  262. serial="TEST123",
  263. name="TestPrinter",
  264. model="BL-P001",
  265. )
  266. # ========================================================================
  267. # Tests for SSDP response
  268. # ========================================================================
  269. def test_build_notify_message(self, ssdp_server):
  270. """Verify NOTIFY packet contains required headers."""
  271. # Set a known IP for testing
  272. ssdp_server._local_ip = "192.168.1.100"
  273. message = ssdp_server._build_notify_message()
  274. assert b"NOTIFY" in message
  275. assert b"DevName.bambu.com: TestPrinter" in message
  276. assert b"USN: TEST123" in message
  277. def test_build_response_message(self, ssdp_server):
  278. """Verify response packet contains required headers."""
  279. # Set a known IP for testing
  280. ssdp_server._local_ip = "192.168.1.100"
  281. message = ssdp_server._build_response_message()
  282. assert b"HTTP/1.1 200 OK" in message
  283. assert b"DevName.bambu.com: TestPrinter" in message
  284. assert b"USN: TEST123" in message
  285. def test_ssdp_server_uses_correct_model(self, ssdp_server):
  286. """Verify SSDP server uses the provided model."""
  287. ssdp_server._local_ip = "192.168.1.100"
  288. message = ssdp_server._build_notify_message()
  289. assert b"DevModel.bambu.com: BL-P001" in message
  290. class TestCertificateService:
  291. """Tests for TLS certificate generation."""
  292. @pytest.fixture
  293. def cert_service(self, tmp_path):
  294. """Create a CertificateService instance."""
  295. from backend.app.services.virtual_printer.certificate import CertificateService
  296. return CertificateService(cert_dir=tmp_path, serial="TEST123")
  297. def test_generate_certificates(self, cert_service, tmp_path):
  298. """Verify certificates are generated correctly."""
  299. cert_path, key_path = cert_service.generate_certificates()
  300. assert cert_path.exists()
  301. assert key_path.exists()
  302. # Verify certificate content
  303. cert_content = cert_path.read_text()
  304. assert "BEGIN CERTIFICATE" in cert_content
  305. key_content = key_path.read_text()
  306. assert "BEGIN" in key_content and "KEY" in key_content
  307. def test_certificates_reused_if_exist(self, cert_service):
  308. """Verify existing certificates are reused."""
  309. # First generation
  310. cert_path1, key_path1 = cert_service.generate_certificates()
  311. mtime1 = cert_path1.stat().st_mtime
  312. # Second call should reuse (via ensure_certificates)
  313. cert_path2, key_path2 = cert_service.ensure_certificates()
  314. mtime2 = cert_path2.stat().st_mtime
  315. assert mtime1 == mtime2 # File wasn't regenerated
  316. def test_delete_certificates(self, cert_service):
  317. """Verify certificates can be deleted."""
  318. cert_service.generate_certificates()
  319. assert cert_service.cert_path.exists()
  320. assert cert_service.key_path.exists()
  321. cert_service.delete_certificates()
  322. assert not cert_service.cert_path.exists()
  323. assert not cert_service.key_path.exists()
  324. def test_ensure_creates_if_not_exist(self, cert_service):
  325. """Verify ensure_certificates generates if not existing."""
  326. assert not cert_service.cert_path.exists()
  327. cert_path, key_path = cert_service.ensure_certificates()
  328. assert cert_path.exists()
  329. assert key_path.exists()
  330. class TestSlicerProxyManager:
  331. """Tests for SlicerProxyManager (proxy mode)."""
  332. @pytest.fixture
  333. def proxy_manager(self, tmp_path):
  334. """Create a SlicerProxyManager instance."""
  335. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  336. # Create dummy cert files
  337. cert_path = tmp_path / "cert.pem"
  338. key_path = tmp_path / "key.pem"
  339. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  340. # Split string to avoid pre-commit hook false positive on test data
  341. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  342. return SlicerProxyManager(
  343. target_host="192.168.1.100",
  344. cert_path=cert_path,
  345. key_path=key_path,
  346. )
  347. def test_proxy_manager_initializes_ports(self, proxy_manager):
  348. """Verify proxy manager has correct port constants."""
  349. # FTP proxy uses privileged port 990 to match what Bambu Studio expects
  350. assert proxy_manager.LOCAL_FTP_PORT == 990
  351. assert proxy_manager.LOCAL_MQTT_PORT == 8883
  352. assert proxy_manager.PRINTER_FTP_PORT == 990
  353. assert proxy_manager.PRINTER_MQTT_PORT == 8883
  354. def test_proxy_manager_stores_target_host(self, proxy_manager):
  355. """Verify proxy manager stores target host."""
  356. assert proxy_manager.target_host == "192.168.1.100"
  357. def test_get_status_before_start(self, proxy_manager):
  358. """Verify get_status returns zeros before start."""
  359. status = proxy_manager.get_status()
  360. assert status["running"] is False
  361. assert status["ftp_connections"] == 0
  362. assert status["mqtt_connections"] == 0
  363. class TestSSDPProxy:
  364. """Tests for SSDPProxy (cross-network SSDP relay)."""
  365. @pytest.fixture
  366. def ssdp_proxy(self):
  367. """Create an SSDPProxy instance."""
  368. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  369. return SSDPProxy(
  370. local_interface_ip="192.168.1.100",
  371. remote_interface_ip="10.0.0.100",
  372. target_printer_ip="192.168.1.50",
  373. )
  374. def test_ssdp_proxy_stores_interface_ips(self, ssdp_proxy):
  375. """Verify SSDPProxy stores interface IPs correctly."""
  376. assert ssdp_proxy.local_interface_ip == "192.168.1.100"
  377. assert ssdp_proxy.remote_interface_ip == "10.0.0.100"
  378. assert ssdp_proxy.target_printer_ip == "192.168.1.50"
  379. def test_rewrite_ssdp_location(self, ssdp_proxy):
  380. """Verify SSDP Location header is rewritten to remote interface IP."""
  381. original_packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: TestPrinter\r\n\r\n"
  382. rewritten = ssdp_proxy._rewrite_ssdp_location(original_packet)
  383. # Location should be changed to remote interface IP
  384. assert b"Location: 10.0.0.100" in rewritten
  385. assert b"Location: 192.168.1.50" not in rewritten
  386. # Other headers should be preserved
  387. assert b"DevName.bambu.com: TestPrinter" in rewritten
  388. def test_rewrite_ssdp_location_case_insensitive(self, ssdp_proxy):
  389. """Verify SSDP Location rewrite is case insensitive."""
  390. original_packet = b"NOTIFY * HTTP/1.1\r\nlocation: 192.168.1.50\r\n\r\n"
  391. rewritten = ssdp_proxy._rewrite_ssdp_location(original_packet)
  392. assert b"10.0.0.100" in rewritten
  393. def test_rewrite_ssdp_location_no_match(self, ssdp_proxy):
  394. """Verify packet without Location header is returned unchanged."""
  395. original_packet = b"NOTIFY * HTTP/1.1\r\nDevName.bambu.com: Test\r\n\r\n"
  396. rewritten = ssdp_proxy._rewrite_ssdp_location(original_packet)
  397. # Should be unchanged (no Location header to rewrite)
  398. assert rewritten == original_packet
  399. def test_parse_ssdp_message(self, ssdp_proxy):
  400. """Verify SSDP message parsing extracts headers."""
  401. packet = (
  402. b"NOTIFY * HTTP/1.1\r\n"
  403. b"Location: 192.168.1.50\r\n"
  404. b"DevName.bambu.com: TestPrinter\r\n"
  405. b"DevModel.bambu.com: BL-P001\r\n"
  406. b"\r\n"
  407. )
  408. headers = ssdp_proxy._parse_ssdp_message(packet)
  409. assert headers["location"] == "192.168.1.50"
  410. assert headers["devname.bambu.com"] == "TestPrinter"
  411. assert headers["devmodel.bambu.com"] == "BL-P001"
  412. class TestVirtualPrinterManagerDirectories:
  413. """Tests for VirtualPrinterManager directory management."""
  414. def test_ensure_directories_creates_subdirs(self, tmp_path):
  415. """Verify _ensure_directories creates all required subdirectories."""
  416. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  417. # Create a manager and manually call _ensure_directories with our tmp path
  418. manager = VirtualPrinterManager()
  419. # Override the paths
  420. manager._base_dir = tmp_path / "virtual_printer"
  421. manager._upload_dir = manager._base_dir / "uploads"
  422. manager._cert_dir = manager._base_dir / "certs"
  423. # Call the method
  424. manager._ensure_directories()
  425. # All directories should be created
  426. assert (tmp_path / "virtual_printer").exists()
  427. assert (tmp_path / "virtual_printer" / "uploads").exists()
  428. assert (tmp_path / "virtual_printer" / "uploads" / "cache").exists()
  429. assert (tmp_path / "virtual_printer" / "certs").exists()
  430. def test_ensure_directories_handles_permission_error(self, tmp_path, caplog):
  431. """Verify _ensure_directories logs error on permission failure."""
  432. import logging
  433. from unittest.mock import patch
  434. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  435. # Create manager and override paths
  436. manager = VirtualPrinterManager()
  437. vp_dir = tmp_path / "virtual_printer"
  438. manager._base_dir = vp_dir
  439. manager._upload_dir = vp_dir / "uploads"
  440. manager._cert_dir = vp_dir / "certs"
  441. # Mock mkdir to raise PermissionError (chmod doesn't work as root in Docker)
  442. original_mkdir = type(vp_dir).mkdir
  443. def mock_mkdir(self, *args, **kwargs):
  444. if "virtual_printer" in str(self):
  445. raise PermissionError("Permission denied")
  446. return original_mkdir(self, *args, **kwargs)
  447. with caplog.at_level(logging.ERROR), patch.object(type(vp_dir), "mkdir", mock_mkdir):
  448. # This should log errors but not raise
  449. manager._ensure_directories()
  450. # Check that error was logged
  451. assert "Permission denied" in caplog.text
  452. class TestVirtualPrinterManagerProxyMode:
  453. """Tests for VirtualPrinterManager proxy mode."""
  454. @pytest.fixture
  455. def manager(self):
  456. """Create a VirtualPrinterManager instance."""
  457. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  458. return VirtualPrinterManager()
  459. @pytest.mark.asyncio
  460. async def test_configure_proxy_mode_requires_target_ip(self, manager):
  461. """Verify proxy mode requires target_printer_ip."""
  462. with pytest.raises(ValueError, match="Target printer IP is required"):
  463. await manager.configure(
  464. enabled=True,
  465. mode="proxy",
  466. target_printer_ip="", # Empty target IP
  467. )
  468. @pytest.mark.asyncio
  469. async def test_configure_proxy_mode_does_not_require_access_code(self, manager):
  470. """Verify proxy mode does not require access code (uses real printer's)."""
  471. manager._start = AsyncMock()
  472. # Should not raise - proxy mode doesn't need access code
  473. await manager.configure(
  474. enabled=True,
  475. mode="proxy",
  476. target_printer_ip="192.168.1.100",
  477. )
  478. assert manager._mode == "proxy"
  479. assert manager._target_printer_ip == "192.168.1.100"
  480. def test_get_status_proxy_mode_includes_proxy_fields(self, manager):
  481. """Verify get_status includes proxy-specific fields in proxy mode."""
  482. manager._enabled = True
  483. manager._mode = "proxy"
  484. manager._target_printer_ip = "192.168.1.100"
  485. manager._tasks = [MagicMock(done=MagicMock(return_value=False))]
  486. # Create a mock proxy with get_status
  487. mock_proxy = MagicMock()
  488. mock_proxy.get_status.return_value = {
  489. "running": True,
  490. "ftp_port": 990, # Privileged port for Bambu Studio compatibility
  491. "mqtt_port": 8883,
  492. "ftp_connections": 1,
  493. "mqtt_connections": 2,
  494. "target_host": "192.168.1.100",
  495. }
  496. manager._proxy = mock_proxy
  497. status = manager.get_status()
  498. assert status["mode"] == "proxy"
  499. assert status["target_printer_ip"] == "192.168.1.100"
  500. assert "proxy" in status
  501. assert status["proxy"]["ftp_port"] == 990 # Privileged port for Bambu Studio compatibility
  502. assert status["proxy"]["mqtt_port"] == 8883
  503. assert status["proxy"]["ftp_connections"] == 1
  504. assert status["proxy"]["mqtt_connections"] == 2
  505. @pytest.mark.asyncio
  506. async def test_configure_proxy_mode_with_remote_interface(self, manager):
  507. """Verify proxy mode accepts remote_interface_ip for SSDP proxy."""
  508. manager._start = AsyncMock()
  509. await manager.configure(
  510. enabled=True,
  511. mode="proxy",
  512. target_printer_ip="192.168.1.100",
  513. remote_interface_ip="10.0.0.50",
  514. )
  515. assert manager._mode == "proxy"
  516. assert manager._target_printer_ip == "192.168.1.100"
  517. assert manager._remote_interface_ip == "10.0.0.50"
  518. @pytest.mark.asyncio
  519. async def test_configure_proxy_mode_restarts_on_remote_interface_change(self, manager):
  520. """Verify changing remote_interface_ip restarts services."""
  521. # Simulate running state
  522. manager._enabled = True
  523. manager._mode = "proxy"
  524. manager._target_printer_ip = "192.168.1.100"
  525. manager._remote_interface_ip = "10.0.0.50"
  526. manager._tasks = [MagicMock(done=MagicMock(return_value=False))]
  527. manager._stop = AsyncMock()
  528. manager._start = AsyncMock()
  529. await manager.configure(
  530. enabled=True,
  531. mode="proxy",
  532. target_printer_ip="192.168.1.100",
  533. remote_interface_ip="10.0.0.99", # Changed
  534. )
  535. # Should have stopped and started
  536. manager._stop.assert_called_once()
  537. manager._start.assert_called_once()