test_printer_diagnostic.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. """Unit tests for the connection diagnostic.
  2. Pins the pass / fail / warn / skip contract of each check. Those statuses
  3. drive the localized fix text the user sees when a printer won't connect,
  4. so a status flip is a user-facing regression — each one is asserted here.
  5. """
  6. import types
  7. from contextlib import ExitStack
  8. from unittest.mock import AsyncMock, MagicMock, patch
  9. from backend.app.services.printer_diagnostic import _same_subnet, run_connection_diagnostic
  10. MOD = "backend.app.services.printer_diagnostic"
  11. def _statuses(result):
  12. """Map of check id -> status for concise assertions."""
  13. return {c.id: c.status for c in result.checks}
  14. def _port_probe(overrides=None):
  15. """Sync side_effect for _check_port. Defaults: every port reachable."""
  16. reachable = {8883: True, 990: True, 322: True}
  17. reachable.update(overrides or {})
  18. def _probe(ip, port, timeout=3.0):
  19. return reachable[port]
  20. return _probe
  21. def _state(*, connected=True, developer_mode=True, store_to_sdcard=True):
  22. return types.SimpleNamespace(
  23. connected=connected,
  24. developer_mode=developer_mode,
  25. store_to_sdcard=store_to_sdcard,
  26. )
  27. class _Env:
  28. """Patches the diagnostic's network/printer helpers for one run."""
  29. def __init__(
  30. self,
  31. *,
  32. ports=None,
  33. in_docker=True,
  34. network_mode="host",
  35. host_ip="192.168.1.5",
  36. state=None,
  37. test_connection_success=True,
  38. report_messages_since_connect: int | None = 5,
  39. ):
  40. self.ports = ports or _port_probe()
  41. self.in_docker = in_docker
  42. self.network_mode = network_mode
  43. self.host_ip = host_ip
  44. self.state = state
  45. self.test_connection_success = test_connection_success
  46. # ``None`` means get_client returns None (e.g. pre-add flow); an int
  47. # means there's a client with that counter value.
  48. self.report_messages_since_connect = report_messages_since_connect
  49. self._stack = ExitStack()
  50. def __enter__(self):
  51. manager = MagicMock()
  52. manager.get_status.return_value = self.state
  53. manager.test_connection = AsyncMock(return_value={"success": self.test_connection_success})
  54. if self.report_messages_since_connect is None:
  55. manager.get_client.return_value = None
  56. else:
  57. client = MagicMock()
  58. client.report_messages_since_connect = self.report_messages_since_connect
  59. manager.get_client.return_value = client
  60. self._stack.enter_context(patch(f"{MOD}._check_port", new_callable=AsyncMock, side_effect=self.ports))
  61. self._stack.enter_context(patch(f"{MOD}.is_running_in_docker", return_value=self.in_docker))
  62. self._stack.enter_context(patch(f"{MOD}._detect_docker_network_mode", return_value=self.network_mode))
  63. self._stack.enter_context(patch(f"{MOD}._get_host_ip", return_value=self.host_ip))
  64. self._stack.enter_context(patch(f"{MOD}.printer_manager", manager))
  65. return self
  66. def __exit__(self, *exc):
  67. self._stack.close()
  68. return False
  69. def _printer(ip="192.168.1.50"):
  70. return types.SimpleNamespace(id=1, ip_address=ip)
  71. class TestSameSubnet:
  72. def test_same_24(self):
  73. assert _same_subnet("192.168.1.10", "192.168.1.200") is True
  74. def test_different_24(self):
  75. assert _same_subnet("192.168.1.10", "192.168.2.10") is False
  76. def test_hostname_undeterminable(self):
  77. assert _same_subnet("printer.local", "192.168.1.10") is None
  78. def test_ipv6_undeterminable(self):
  79. assert _same_subnet("fe80::1", "192.168.1.10") is None
  80. class TestExistingPrinter:
  81. async def test_all_healthy(self):
  82. with _Env(
  83. state=_state(connected=True, developer_mode=True, store_to_sdcard=True),
  84. report_messages_since_connect=42,
  85. ):
  86. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  87. s = _statuses(result)
  88. assert result.overall == "ok"
  89. assert s == {
  90. "port_mqtt": "pass",
  91. "port_ftps": "pass",
  92. "port_rtsps": "pass",
  93. "network_mode": "pass",
  94. "subnet": "pass",
  95. "external_storage": "pass",
  96. "mqtt_auth": "pass",
  97. "developer_mode": "pass",
  98. "printer_publishing": "pass",
  99. }
  100. async def test_mqtt_port_unreachable_is_a_problem(self):
  101. with _Env(ports=_port_probe({8883: False}), state=_state()):
  102. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  103. s = _statuses(result)
  104. assert result.overall == "problems"
  105. assert s["port_mqtt"] == "fail"
  106. # Auth can't be judged when the broker port itself is closed.
  107. assert s["mqtt_auth"] == "skip"
  108. async def test_ftps_and_rtsps_only_warn(self):
  109. with _Env(ports=_port_probe({990: False, 322: False}), state=_state()):
  110. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  111. s = _statuses(result)
  112. # No critical failure -> warnings, not problems.
  113. assert result.overall == "warnings"
  114. assert s["port_ftps"] == "warn"
  115. assert s["port_rtsps"] == "warn"
  116. async def test_developer_mode_off_is_a_problem(self):
  117. with _Env(state=_state(connected=True, developer_mode=False)):
  118. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  119. s = _statuses(result)
  120. assert s["developer_mode"] == "fail"
  121. assert result.overall == "problems"
  122. async def test_developer_mode_skipped_when_disconnected(self):
  123. # No live MQTT connection -> developer_mode can't be read.
  124. with _Env(state=_state(connected=False)):
  125. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  126. s = _statuses(result)
  127. assert s["developer_mode"] == "skip"
  128. # Reachable port but no connection -> credential failure class.
  129. assert s["mqtt_auth"] == "fail"
  130. # Can't observe report messages without a connection.
  131. assert s["printer_publishing"] == "skip"
  132. async def test_bridge_mode_warns_and_skips_subnet(self):
  133. with _Env(network_mode="bridge", state=_state()):
  134. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  135. s = _statuses(result)
  136. assert s["network_mode"] == "warn"
  137. # Container IP isn't the host IP in bridge mode -> subnet check is meaningless.
  138. assert s["subnet"] == "skip"
  139. async def test_network_mode_skipped_outside_docker(self):
  140. with _Env(in_docker=False, state=_state()):
  141. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  142. assert _statuses(result)["network_mode"] == "skip"
  143. async def test_different_subnet_warns(self):
  144. with _Env(host_ip="10.0.0.5", state=_state()):
  145. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  146. assert _statuses(result)["subnet"] == "warn"
  147. async def test_printer_publishing_passes_when_reports_seen(self):
  148. # Counter > 0 means the printer is publishing on the report topic.
  149. with _Env(state=_state(), report_messages_since_connect=1):
  150. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  151. assert _statuses(result)["printer_publishing"] == "pass"
  152. async def test_printer_publishing_fails_when_zero_reports_after_wait(self):
  153. # Counter stays at 0 across the wait window — printer never published.
  154. # Tiny wait_for_publish_seconds keeps the test sub-second.
  155. with _Env(state=_state(), report_messages_since_connect=0):
  156. result = await run_connection_diagnostic(
  157. "192.168.1.50",
  158. printer=_printer(),
  159. wait_for_publish_seconds=0.05,
  160. )
  161. s = _statuses(result)
  162. assert s["printer_publishing"] == "fail"
  163. # Overall escalates because fail is present.
  164. assert result.overall == "problems"
  165. # The check exposes the wait budget so the UI can render a countdown.
  166. params = next(c.params for c in result.checks if c.id == "printer_publishing")
  167. assert params == {"max_wait_seconds": 0.05}
  168. async def test_printer_publishing_skips_when_disconnected(self):
  169. # No live MQTT connection -> can't observe report messages.
  170. with _Env(state=_state(connected=False), report_messages_since_connect=0):
  171. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  172. assert _statuses(result)["printer_publishing"] == "skip"
  173. async def test_printer_publishing_skips_when_no_client(self):
  174. # State says connected but printer_manager has no client object
  175. # (race between client teardown and a fresh diagnostic request).
  176. with _Env(state=_state(), report_messages_since_connect=None):
  177. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  178. assert _statuses(result)["printer_publishing"] == "skip"
  179. async def test_printer_publishing_no_wait_returns_instantly_on_zero(self):
  180. # Default wait is 0 — instant pass/fail without polling. Used by the
  181. # support-package code path so bundling stays fast.
  182. with _Env(state=_state(), report_messages_since_connect=0):
  183. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  184. s = _statuses(result)
  185. assert s["printer_publishing"] == "fail"
  186. params = next(c.params for c in result.checks if c.id == "printer_publishing")
  187. # No wait -> no max_wait_seconds param surfaced to the UI.
  188. assert params == {}
  189. class TestPreAddFlow:
  190. async def test_bad_credentials_fail_mqtt_auth(self):
  191. with _Env(test_connection_success=False):
  192. result = await run_connection_diagnostic("192.168.1.50", serial_number="01P", access_code="wrong")
  193. s = _statuses(result)
  194. assert s["mqtt_auth"] == "fail"
  195. # No saved printer -> developer mode can't be read.
  196. assert s["developer_mode"] == "skip"
  197. async def test_good_credentials_pass_mqtt_auth(self):
  198. with _Env(test_connection_success=True):
  199. result = await run_connection_diagnostic("192.168.1.50", serial_number="01P", access_code="right")
  200. assert _statuses(result)["mqtt_auth"] == "pass"
  201. async def test_no_credentials_skips_mqtt_auth(self):
  202. with _Env():
  203. result = await run_connection_diagnostic("192.168.1.50")
  204. assert _statuses(result)["mqtt_auth"] == "skip"
  205. class TestExternalStorageCheck:
  206. """Install step 4 — "Store sent files on external storage".
  207. Detected via ``state.store_to_sdcard`` (parsed from MQTT push_status
  208. ``home_flag`` bit 11). Only catches the printer-side variant of the
  209. setting on newer firmware (P2S 01.02 / Studio 2.6+) — the older
  210. slicer-side variant is undetectable from outside the slicer and is
  211. covered separately by the no-3MF archive-fallback banner.
  212. """
  213. async def test_passes_when_store_to_sdcard_true(self):
  214. with _Env(state=_state(store_to_sdcard=True)):
  215. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  216. assert _statuses(result)["external_storage"] == "pass"
  217. async def test_fails_when_store_to_sdcard_false(self):
  218. # Bit 11 reported as 0 -> printer-side toggle is off. Overall
  219. # escalates to "problems" because a fail is present.
  220. with _Env(state=_state(store_to_sdcard=False)):
  221. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  222. assert _statuses(result)["external_storage"] == "fail"
  223. assert result.overall == "problems"
  224. async def test_skips_when_disconnected(self):
  225. # State exists (we have a saved printer) but the MQTT connection
  226. # dropped, so the latest store_to_sdcard value can't be trusted.
  227. with _Env(state=_state(connected=False, store_to_sdcard=True)):
  228. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  229. assert _statuses(result)["external_storage"] == "skip"
  230. async def test_skips_pre_add_flow(self):
  231. # No saved printer -> no state -> nothing to read. The check has
  232. # to skip; pre-add can't probe this without a live MQTT session.
  233. with _Env():
  234. result = await run_connection_diagnostic(
  235. "192.168.1.50",
  236. serial_number="01P",
  237. access_code="probe-code",
  238. )
  239. assert _statuses(result)["external_storage"] == "skip"
  240. async def test_skips_when_field_missing(self):
  241. # State exists and is connected but store_to_sdcard was never
  242. # populated (firmware that doesn't push home_flag). Skip rather
  243. # than fabricate a False from a missing field.
  244. bare = types.SimpleNamespace(connected=True, developer_mode=True)
  245. with _Env(state=bare):
  246. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  247. assert _statuses(result)["external_storage"] == "skip"