test_support_helpers.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. """Unit tests for support module helper functions.
  2. Tests _anonymize_mqtt_broker, _check_port, _get_container_memory_limit,
  3. _format_bytes, and _collect_support_info diagnostic sections.
  4. """
  5. import asyncio
  6. import tempfile
  7. from pathlib import Path
  8. from unittest.mock import AsyncMock, MagicMock, patch
  9. import pytest
  10. class TestApplyLogLevel:
  11. """Tests for _apply_log_level() debug noise suppression."""
  12. def test_debug_mode_suppresses_sqlalchemy_to_warning(self):
  13. """Verify sqlalchemy.engine is set to WARNING (not INFO) in debug mode."""
  14. import logging
  15. from backend.app.api.routes.support import _apply_log_level
  16. _apply_log_level(True)
  17. assert logging.getLogger("sqlalchemy.engine").level == logging.WARNING
  18. def test_debug_mode_suppresses_aiosqlite(self):
  19. """Verify aiosqlite is set to WARNING in debug mode to prevent cursor noise."""
  20. import logging
  21. from backend.app.api.routes.support import _apply_log_level
  22. _apply_log_level(True)
  23. assert logging.getLogger("aiosqlite").level == logging.WARNING
  24. def test_debug_mode_enables_httpcore_debug(self):
  25. """Verify httpcore stays at DEBUG in debug mode."""
  26. import logging
  27. from backend.app.api.routes.support import _apply_log_level
  28. _apply_log_level(True)
  29. assert logging.getLogger("httpcore").level == logging.DEBUG
  30. def test_non_debug_mode_suppresses_all_noisy_loggers(self):
  31. """Verify all noisy loggers are set to WARNING in non-debug mode."""
  32. import logging
  33. from backend.app.api.routes.support import _apply_log_level
  34. _apply_log_level(False)
  35. assert logging.getLogger("sqlalchemy.engine").level == logging.WARNING
  36. assert logging.getLogger("httpcore").level == logging.WARNING
  37. assert logging.getLogger("httpx").level == logging.WARNING
  38. assert logging.getLogger("paho.mqtt").level == logging.WARNING
  39. class TestAnonymizeMqttBroker:
  40. """Tests for _anonymize_mqtt_broker()."""
  41. def test_empty_string(self):
  42. from backend.app.api.routes.support import _anonymize_mqtt_broker
  43. assert _anonymize_mqtt_broker("") == ""
  44. def test_ipv4_address(self):
  45. from backend.app.api.routes.support import _anonymize_mqtt_broker
  46. assert _anonymize_mqtt_broker("192.168.1.100") == "[IP]"
  47. def test_ipv6_address(self):
  48. from backend.app.api.routes.support import _anonymize_mqtt_broker
  49. assert _anonymize_mqtt_broker("::1") == "[IP]"
  50. def test_hostname_with_domain(self):
  51. from backend.app.api.routes.support import _anonymize_mqtt_broker
  52. assert _anonymize_mqtt_broker("mqtt.example.com") == "*.example.com"
  53. def test_hostname_with_subdomain(self):
  54. from backend.app.api.routes.support import _anonymize_mqtt_broker
  55. assert _anonymize_mqtt_broker("broker.mqtt.example.com") == "*.example.com"
  56. def test_single_part_hostname(self):
  57. from backend.app.api.routes.support import _anonymize_mqtt_broker
  58. assert _anonymize_mqtt_broker("localhost") == "localhost"
  59. class TestCheckPort:
  60. """Tests for _check_port()."""
  61. @pytest.mark.asyncio
  62. @pytest.mark.unit
  63. async def test_reachable_port(self):
  64. from backend.app.api.routes.support import _check_port
  65. # Mock a successful connection
  66. mock_writer = AsyncMock()
  67. mock_writer.close = MagicMock()
  68. mock_writer.wait_closed = AsyncMock()
  69. with patch("backend.app.api.routes.support.asyncio.open_connection", return_value=(AsyncMock(), mock_writer)):
  70. result = await _check_port("192.168.1.1", 8883, timeout=1.0)
  71. assert result is True
  72. @pytest.mark.asyncio
  73. @pytest.mark.unit
  74. async def test_unreachable_port(self):
  75. from backend.app.api.routes.support import _check_port
  76. with (
  77. patch(
  78. "backend.app.api.routes.support.asyncio.open_connection",
  79. side_effect=ConnectionRefusedError,
  80. ),
  81. patch(
  82. "backend.app.api.routes.support.asyncio.wait_for",
  83. side_effect=ConnectionRefusedError,
  84. ),
  85. ):
  86. result = await _check_port("192.168.1.1", 8883, timeout=1.0)
  87. assert result is False
  88. @pytest.mark.asyncio
  89. @pytest.mark.unit
  90. async def test_timeout(self):
  91. from backend.app.api.routes.support import _check_port
  92. with patch(
  93. "backend.app.api.routes.support.asyncio.wait_for",
  94. side_effect=asyncio.TimeoutError,
  95. ):
  96. result = await _check_port("192.168.1.1", 8883, timeout=0.1)
  97. assert result is False
  98. class TestGetContainerMemoryLimit:
  99. """Tests for _get_container_memory_limit()."""
  100. def test_cgroup_v2_with_limit(self):
  101. from backend.app.api.routes.support import _get_container_memory_limit
  102. with tempfile.TemporaryDirectory() as tmpdir:
  103. v2_path = Path(tmpdir) / "memory.max"
  104. v2_path.write_text("1073741824\n")
  105. with patch("backend.app.api.routes.support.Path") as mock_path:
  106. # v2 path exists with value
  107. v2_mock = MagicMock()
  108. v2_mock.exists.return_value = True
  109. v2_mock.read_text.return_value = "1073741824\n"
  110. v1_mock = MagicMock()
  111. v1_mock.exists.return_value = False
  112. mock_path.side_effect = lambda p: v2_mock if "memory.max" in p else v1_mock
  113. result = _get_container_memory_limit()
  114. assert result == 1073741824
  115. def test_cgroup_v2_unlimited(self):
  116. from backend.app.api.routes.support import _get_container_memory_limit
  117. with patch("backend.app.api.routes.support.Path") as mock_path:
  118. v2_mock = MagicMock()
  119. v2_mock.exists.return_value = True
  120. v2_mock.read_text.return_value = "max\n"
  121. v1_mock = MagicMock()
  122. v1_mock.exists.return_value = False
  123. mock_path.side_effect = lambda p: v2_mock if "memory.max" in p else v1_mock
  124. result = _get_container_memory_limit()
  125. assert result is None
  126. def test_no_cgroup_files(self):
  127. from backend.app.api.routes.support import _get_container_memory_limit
  128. with patch("backend.app.api.routes.support.Path") as mock_path:
  129. mock_instance = MagicMock()
  130. mock_instance.exists.return_value = False
  131. mock_path.return_value = mock_instance
  132. result = _get_container_memory_limit()
  133. assert result is None
  134. class TestFormatBytes:
  135. """Tests for _format_bytes()."""
  136. def test_bytes(self):
  137. from backend.app.api.routes.support import _format_bytes
  138. assert _format_bytes(500) == "500 B"
  139. def test_kilobytes(self):
  140. from backend.app.api.routes.support import _format_bytes
  141. assert _format_bytes(2048) == "2.0 KB"
  142. def test_megabytes(self):
  143. from backend.app.api.routes.support import _format_bytes
  144. assert _format_bytes(10 * 1024 * 1024) == "10.0 MB"
  145. def test_gigabytes(self):
  146. from backend.app.api.routes.support import _format_bytes
  147. assert _format_bytes(2 * 1024 * 1024 * 1024) == "2.00 GB"
  148. def test_zero(self):
  149. from backend.app.api.routes.support import _format_bytes
  150. assert _format_bytes(0) == "0 B"
  151. class TestSanitizeLogContent:
  152. """Tests for _sanitize_log_content() redaction."""
  153. def test_ipv4_addresses_redacted(self):
  154. """IPv4 addresses in log lines are replaced with [IP]."""
  155. from backend.app.api.routes.support import _sanitize_log_content
  156. content = "2024-01-15 Connected to printer at 192.168.1.100 on port 8883"
  157. result = _sanitize_log_content(content)
  158. assert "192.168.1.100" not in result
  159. assert "[IP]" in result
  160. assert "on port 8883" in result
  161. def test_multiple_ipv4_addresses_redacted(self):
  162. """Multiple different IPs in the same line are all redacted."""
  163. from backend.app.api.routes.support import _sanitize_log_content
  164. content = "Proxy 10.0.0.1 -> 192.168.1.50"
  165. result = _sanitize_log_content(content)
  166. assert result == "Proxy [IP] -> [IP]"
  167. def test_firmware_versions_with_leading_zeros_preserved(self):
  168. """Firmware versions like 01.09.01.00 have leading zeros and should NOT be redacted."""
  169. from backend.app.api.routes.support import _sanitize_log_content
  170. content = "Firmware version: 01.09.01.00"
  171. result = _sanitize_log_content(content)
  172. assert "01.09.01.00" in result
  173. def test_firmware_version_mixed_with_ip(self):
  174. """Firmware versions preserved while real IPs are redacted in the same line."""
  175. from backend.app.api.routes.support import _sanitize_log_content
  176. content = "Printer at 192.168.1.5 running firmware 01.07.02.00"
  177. result = _sanitize_log_content(content)
  178. assert "192.168.1.5" not in result
  179. assert "01.07.02.00" in result
  180. assert "[IP] running firmware 01.07.02.00" in result
  181. def test_printer_ip_from_sensitive_strings(self):
  182. """Printer IPs in sensitive_strings are replaced before regex pass."""
  183. from backend.app.api.routes.support import _sanitize_log_content
  184. content = "Connecting to 192.168.1.100"
  185. result = _sanitize_log_content(content, sensitive_strings={"192.168.1.100": "[IP]"})
  186. assert result == "Connecting to [IP]"
  187. def test_edge_case_zero_ip(self):
  188. """0.0.0.0 is a valid IP and should be redacted."""
  189. from backend.app.api.routes.support import _sanitize_log_content
  190. content = "Binding to 0.0.0.0"
  191. result = _sanitize_log_content(content)
  192. assert result == "Binding to [IP]"
  193. def test_edge_case_broadcast_ip(self):
  194. """255.255.255.255 is a valid IP and should be redacted."""
  195. from backend.app.api.routes.support import _sanitize_log_content
  196. content = "Broadcast to 255.255.255.255"
  197. result = _sanitize_log_content(content)
  198. assert result == "Broadcast to [IP]"
  199. def test_invalid_octet_not_redacted(self):
  200. """Octets >255 are not valid IPs and should not be redacted."""
  201. from backend.app.api.routes.support import _sanitize_log_content
  202. content = "Value 999.999.999.999"
  203. result = _sanitize_log_content(content)
  204. assert "999.999.999.999" in result
  205. def test_existing_serial_redaction_still_works(self):
  206. """Serial number redaction still functions alongside IP redaction."""
  207. from backend.app.api.routes.support import _sanitize_log_content
  208. content = "Printer 01SABCDEF1234 at 10.0.0.5"
  209. result = _sanitize_log_content(content)
  210. assert "[SERIAL]" in result
  211. assert "[IP]" in result
  212. assert "01SABCDEF1234" not in result
  213. assert "10.0.0.5" not in result
  214. def test_existing_email_redaction_still_works(self):
  215. """Email redaction still functions alongside IP redaction."""
  216. from backend.app.api.routes.support import _sanitize_log_content
  217. content = "User user@example.com from 172.16.0.1"
  218. result = _sanitize_log_content(content)
  219. assert "[EMAIL]" in result
  220. assert "[IP]" in result
  221. def test_existing_path_redaction_still_works(self):
  222. """Path redaction still functions alongside IP redaction."""
  223. from backend.app.api.routes.support import _sanitize_log_content
  224. content = "Config at /home/john/config.yaml from 192.168.0.1"
  225. result = _sanitize_log_content(content)
  226. assert "/home/[user]/" in result
  227. assert "[IP]" in result
  228. class TestCollectSupportInfo:
  229. """Tests for _collect_support_info() new diagnostic sections."""
  230. @pytest.mark.asyncio
  231. @pytest.mark.unit
  232. async def test_environment_has_timezone(self):
  233. """Verify environment section includes timezone."""
  234. from backend.app.api.routes.support import _collect_support_info
  235. with (
  236. patch("backend.app.api.routes.support.is_running_in_docker", return_value=False),
  237. patch("backend.app.api.routes.support.async_session") as mock_session_ctx,
  238. patch("backend.app.api.routes.support.printer_manager") as mock_pm,
  239. patch("backend.app.api.routes.support.get_network_interfaces", return_value=[]),
  240. patch("backend.app.api.routes.support.ws_manager") as mock_ws,
  241. patch.dict("os.environ", {"TZ": "America/New_York"}),
  242. ):
  243. mock_pm.get_all_statuses.return_value = {}
  244. mock_ws.active_connections = []
  245. mock_db = AsyncMock()
  246. mock_result = MagicMock()
  247. mock_result.scalar.return_value = 0
  248. mock_result.scalar_one_or_none.return_value = None
  249. mock_result.scalars.return_value.all.return_value = []
  250. mock_db.execute = AsyncMock(return_value=mock_result)
  251. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  252. mock_session_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
  253. info = await _collect_support_info()
  254. assert info["environment"]["timezone"] == "America/New_York"
  255. assert info["environment"]["docker"] is False
  256. @pytest.mark.asyncio
  257. @pytest.mark.unit
  258. async def test_docker_section_present_when_in_docker(self):
  259. """Verify docker section is added when running in Docker."""
  260. from backend.app.api.routes.support import _collect_support_info
  261. with (
  262. patch("backend.app.api.routes.support.is_running_in_docker", return_value=True),
  263. patch("backend.app.api.routes.support._get_container_memory_limit", return_value=1073741824),
  264. patch("backend.app.api.routes.support.async_session") as mock_session_ctx,
  265. patch("backend.app.api.routes.support.printer_manager") as mock_pm,
  266. patch(
  267. "backend.app.api.routes.support.get_network_interfaces",
  268. return_value=[{"name": "eth0", "subnet": "172.17.0.0/16"}],
  269. ),
  270. patch("backend.app.api.routes.support.ws_manager") as mock_ws,
  271. ):
  272. mock_pm.get_all_statuses.return_value = {}
  273. mock_ws.active_connections = []
  274. mock_db = AsyncMock()
  275. mock_result = MagicMock()
  276. mock_result.scalar.return_value = 0
  277. mock_result.scalar_one_or_none.return_value = None
  278. mock_result.scalars.return_value.all.return_value = []
  279. mock_db.execute = AsyncMock(return_value=mock_result)
  280. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  281. mock_session_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
  282. info = await _collect_support_info()
  283. assert "docker" in info
  284. assert info["docker"]["container_memory_limit_bytes"] == 1073741824
  285. assert info["docker"]["container_memory_limit_formatted"] == "1.00 GB"
  286. assert info["docker"]["network_mode_hint"] == "bridge"
  287. @pytest.mark.asyncio
  288. @pytest.mark.unit
  289. async def test_docker_section_absent_when_not_docker(self):
  290. """Verify docker section is absent when not in Docker."""
  291. from backend.app.api.routes.support import _collect_support_info
  292. with (
  293. patch("backend.app.api.routes.support.is_running_in_docker", return_value=False),
  294. patch("backend.app.api.routes.support.async_session") as mock_session_ctx,
  295. patch("backend.app.api.routes.support.printer_manager") as mock_pm,
  296. patch("backend.app.api.routes.support.get_network_interfaces", return_value=[]),
  297. patch("backend.app.api.routes.support.ws_manager") as mock_ws,
  298. ):
  299. mock_pm.get_all_statuses.return_value = {}
  300. mock_ws.active_connections = []
  301. mock_db = AsyncMock()
  302. mock_result = MagicMock()
  303. mock_result.scalar.return_value = 0
  304. mock_result.scalar_one_or_none.return_value = None
  305. mock_result.scalars.return_value.all.return_value = []
  306. mock_db.execute = AsyncMock(return_value=mock_result)
  307. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  308. mock_session_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
  309. info = await _collect_support_info()
  310. assert "docker" not in info
  311. @pytest.mark.asyncio
  312. @pytest.mark.unit
  313. async def test_dependencies_section(self):
  314. """Verify dependencies section lists package versions."""
  315. from backend.app.api.routes.support import _collect_support_info
  316. with (
  317. patch("backend.app.api.routes.support.is_running_in_docker", return_value=False),
  318. patch("backend.app.api.routes.support.async_session") as mock_session_ctx,
  319. patch("backend.app.api.routes.support.printer_manager") as mock_pm,
  320. patch("backend.app.api.routes.support.get_network_interfaces", return_value=[]),
  321. patch("backend.app.api.routes.support.ws_manager") as mock_ws,
  322. ):
  323. mock_pm.get_all_statuses.return_value = {}
  324. mock_ws.active_connections = []
  325. mock_db = AsyncMock()
  326. mock_result = MagicMock()
  327. mock_result.scalar.return_value = 0
  328. mock_result.scalar_one_or_none.return_value = None
  329. mock_result.scalars.return_value.all.return_value = []
  330. mock_db.execute = AsyncMock(return_value=mock_result)
  331. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  332. mock_session_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
  333. info = await _collect_support_info()
  334. assert "dependencies" in info
  335. # fastapi should be installed in test environment
  336. assert "fastapi" in info["dependencies"]
  337. assert info["dependencies"]["fastapi"] is not None
  338. @pytest.mark.asyncio
  339. @pytest.mark.unit
  340. async def test_websockets_section(self):
  341. """Verify websockets section shows connection count."""
  342. from backend.app.api.routes.support import _collect_support_info
  343. with (
  344. patch("backend.app.api.routes.support.is_running_in_docker", return_value=False),
  345. patch("backend.app.api.routes.support.async_session") as mock_session_ctx,
  346. patch("backend.app.api.routes.support.printer_manager") as mock_pm,
  347. patch("backend.app.api.routes.support.get_network_interfaces", return_value=[]),
  348. patch("backend.app.api.routes.support.ws_manager") as mock_ws,
  349. ):
  350. mock_pm.get_all_statuses.return_value = {}
  351. mock_ws.active_connections = ["conn1", "conn2"]
  352. mock_db = AsyncMock()
  353. mock_result = MagicMock()
  354. mock_result.scalar.return_value = 0
  355. mock_result.scalar_one_or_none.return_value = None
  356. mock_result.scalars.return_value.all.return_value = []
  357. mock_db.execute = AsyncMock(return_value=mock_result)
  358. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  359. mock_session_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
  360. info = await _collect_support_info()
  361. assert info["websockets"]["active_connections"] == 2
  362. @pytest.mark.asyncio
  363. @pytest.mark.unit
  364. async def test_network_section(self):
  365. """Verify network section shows interface subnets."""
  366. from backend.app.api.routes.support import _collect_support_info
  367. mock_interfaces = [
  368. {"name": "eth0", "ip": "192.168.1.100", "netmask": "255.255.255.0", "subnet": "192.168.1.0/24"},
  369. {"name": "wlan0", "ip": "10.0.0.50", "netmask": "255.255.255.0", "subnet": "10.0.0.0/24"},
  370. ]
  371. with (
  372. patch("backend.app.api.routes.support.is_running_in_docker", return_value=False),
  373. patch("backend.app.api.routes.support.async_session") as mock_session_ctx,
  374. patch("backend.app.api.routes.support.printer_manager") as mock_pm,
  375. patch("backend.app.api.routes.support.get_network_interfaces", return_value=mock_interfaces),
  376. patch("backend.app.api.routes.support.ws_manager") as mock_ws,
  377. ):
  378. mock_pm.get_all_statuses.return_value = {}
  379. mock_ws.active_connections = []
  380. mock_db = AsyncMock()
  381. mock_result = MagicMock()
  382. mock_result.scalar.return_value = 0
  383. mock_result.scalar_one_or_none.return_value = None
  384. mock_result.scalars.return_value.all.return_value = []
  385. mock_db.execute = AsyncMock(return_value=mock_result)
  386. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  387. mock_session_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
  388. info = await _collect_support_info()
  389. assert info["network"]["interface_count"] == 2
  390. assert info["network"]["interfaces"][0]["name"] == "eth0"
  391. assert info["network"]["interfaces"][0]["subnet"] == "192.168.1.0/24"
  392. # Verify IP addresses are NOT included
  393. for iface in info["network"]["interfaces"]:
  394. assert "ip" not in iface
  395. @pytest.mark.asyncio
  396. @pytest.mark.unit
  397. async def test_log_file_section(self):
  398. """Verify log file section shows size info."""
  399. from backend.app.api.routes.support import _collect_support_info
  400. with tempfile.TemporaryDirectory() as tmpdir:
  401. log_dir = Path(tmpdir)
  402. log_file = log_dir / "bambuddy.log"
  403. log_file.write_text("some log content\n" * 100)
  404. with (
  405. patch("backend.app.api.routes.support.is_running_in_docker", return_value=False),
  406. patch("backend.app.api.routes.support.async_session") as mock_session_ctx,
  407. patch("backend.app.api.routes.support.printer_manager") as mock_pm,
  408. patch("backend.app.api.routes.support.get_network_interfaces", return_value=[]),
  409. patch("backend.app.api.routes.support.ws_manager") as mock_ws,
  410. patch("backend.app.api.routes.support.settings") as mock_settings,
  411. ):
  412. mock_settings.base_dir = Path(tmpdir)
  413. mock_settings.log_dir = log_dir
  414. mock_settings.debug = False
  415. mock_pm.get_all_statuses.return_value = {}
  416. mock_ws.active_connections = []
  417. mock_db = AsyncMock()
  418. mock_result = MagicMock()
  419. mock_result.scalar.return_value = 0
  420. mock_result.scalar_one_or_none.return_value = None
  421. mock_result.scalars.return_value.all.return_value = []
  422. mock_db.execute = AsyncMock(return_value=mock_result)
  423. mock_session_ctx.return_value.__aenter__ = AsyncMock(return_value=mock_db)
  424. mock_session_ctx.return_value.__aexit__ = AsyncMock(return_value=False)
  425. info = await _collect_support_info()
  426. assert "log_file" in info
  427. assert info["log_file"]["size_bytes"] > 0
  428. assert "B" in info["log_file"]["size_formatted"] or "KB" in info["log_file"]["size_formatted"]