test_printer_diagnostic.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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, 6000: 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", model=None):
  70. return types.SimpleNamespace(id=1, ip_address=ip, model=model)
  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_a1_mini_uses_chamber_image_camera_port(self):
  117. # A1/P1-family printers use the chamber-image camera protocol on 6000,
  118. # not RTSPS on 322. A closed 322 must not create a false camera warning.
  119. with _Env(ports=_port_probe({322: False, 6000: True}), state=_state()):
  120. result = await run_connection_diagnostic(
  121. "192.168.1.50",
  122. printer=_printer(model="A1 Mini"),
  123. )
  124. assert _statuses(result)["port_rtsps"] == "pass"
  125. camera_check = next(c for c in result.checks if c.id == "port_rtsps")
  126. assert camera_check.params == {"port": 6000, "protocol": "Chamber Image"}
  127. async def test_rtsp_models_still_probe_rtsps_port(self):
  128. with _Env(ports=_port_probe({322: False, 6000: True}), state=_state()):
  129. result = await run_connection_diagnostic(
  130. "192.168.1.50",
  131. printer=_printer(model="X1C"),
  132. )
  133. assert _statuses(result)["port_rtsps"] == "warn"
  134. camera_check = next(c for c in result.checks if c.id == "port_rtsps")
  135. assert camera_check.params == {"port": 322, "protocol": "RTSPS"}
  136. async def test_developer_mode_off_is_a_problem(self):
  137. with _Env(state=_state(connected=True, developer_mode=False)):
  138. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  139. s = _statuses(result)
  140. assert s["developer_mode"] == "fail"
  141. assert result.overall == "problems"
  142. async def test_developer_mode_skipped_when_disconnected(self):
  143. # No live MQTT connection -> developer_mode can't be read.
  144. with _Env(state=_state(connected=False)):
  145. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  146. s = _statuses(result)
  147. assert s["developer_mode"] == "skip"
  148. # Reachable port but no connection -> credential failure class.
  149. assert s["mqtt_auth"] == "fail"
  150. # Can't observe report messages without a connection.
  151. assert s["printer_publishing"] == "skip"
  152. async def test_bridge_mode_warns_and_skips_subnet(self):
  153. with _Env(network_mode="bridge", state=_state()):
  154. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  155. s = _statuses(result)
  156. assert s["network_mode"] == "warn"
  157. # Container IP isn't the host IP in bridge mode -> subnet check is meaningless.
  158. assert s["subnet"] == "skip"
  159. async def test_network_mode_skipped_outside_docker(self):
  160. with _Env(in_docker=False, state=_state()):
  161. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  162. assert _statuses(result)["network_mode"] == "skip"
  163. async def test_different_subnet_warns(self):
  164. with _Env(host_ip="10.0.0.5", state=_state()):
  165. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  166. assert _statuses(result)["subnet"] == "warn"
  167. async def test_printer_publishing_passes_when_reports_seen(self):
  168. # Counter > 0 means the printer is publishing on the report topic.
  169. with _Env(state=_state(), report_messages_since_connect=1):
  170. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  171. assert _statuses(result)["printer_publishing"] == "pass"
  172. async def test_printer_publishing_fails_when_zero_reports_after_wait(self):
  173. # Counter stays at 0 across the wait window — printer never published.
  174. # Tiny wait_for_publish_seconds keeps the test sub-second.
  175. with _Env(state=_state(), report_messages_since_connect=0):
  176. result = await run_connection_diagnostic(
  177. "192.168.1.50",
  178. printer=_printer(),
  179. wait_for_publish_seconds=0.05,
  180. )
  181. s = _statuses(result)
  182. assert s["printer_publishing"] == "fail"
  183. # Overall escalates because fail is present.
  184. assert result.overall == "problems"
  185. # The check exposes the wait budget so the UI can render a countdown.
  186. params = next(c.params for c in result.checks if c.id == "printer_publishing")
  187. assert params == {"max_wait_seconds": 0.05}
  188. async def test_printer_publishing_skips_when_disconnected(self):
  189. # No live MQTT connection -> can't observe report messages.
  190. with _Env(state=_state(connected=False), report_messages_since_connect=0):
  191. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  192. assert _statuses(result)["printer_publishing"] == "skip"
  193. async def test_printer_publishing_skips_when_no_client(self):
  194. # State says connected but printer_manager has no client object
  195. # (race between client teardown and a fresh diagnostic request).
  196. with _Env(state=_state(), report_messages_since_connect=None):
  197. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  198. assert _statuses(result)["printer_publishing"] == "skip"
  199. async def test_printer_publishing_no_wait_returns_instantly_on_zero(self):
  200. # Default wait is 0 — instant pass/fail without polling. Used by the
  201. # support-package code path so bundling stays fast.
  202. with _Env(state=_state(), report_messages_since_connect=0):
  203. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  204. s = _statuses(result)
  205. assert s["printer_publishing"] == "fail"
  206. params = next(c.params for c in result.checks if c.id == "printer_publishing")
  207. # No wait -> no max_wait_seconds param surfaced to the UI.
  208. assert params == {}
  209. class TestPreAddFlow:
  210. async def test_bad_credentials_fail_mqtt_auth(self):
  211. with _Env(test_connection_success=False):
  212. result = await run_connection_diagnostic("192.168.1.50", serial_number="01P", access_code="wrong")
  213. s = _statuses(result)
  214. assert s["mqtt_auth"] == "fail"
  215. # No saved printer -> developer mode can't be read.
  216. assert s["developer_mode"] == "skip"
  217. async def test_good_credentials_pass_mqtt_auth(self):
  218. with _Env(test_connection_success=True):
  219. result = await run_connection_diagnostic("192.168.1.50", serial_number="01P", access_code="right")
  220. assert _statuses(result)["mqtt_auth"] == "pass"
  221. async def test_no_credentials_skips_mqtt_auth(self):
  222. with _Env():
  223. result = await run_connection_diagnostic("192.168.1.50")
  224. assert _statuses(result)["mqtt_auth"] == "skip"
  225. class TestExternalStorageCheck:
  226. """Install step 4 — "Store sent files on external storage".
  227. Detected via ``state.store_to_sdcard`` (parsed from MQTT push_status
  228. ``home_flag`` bit 11). Only catches the printer-side variant of the
  229. setting on newer firmware (P2S 01.02 / Studio 2.6+) — the older
  230. slicer-side variant is undetectable from outside the slicer and is
  231. covered separately by the no-3MF archive-fallback banner.
  232. """
  233. async def test_passes_when_store_to_sdcard_true(self):
  234. with _Env(state=_state(store_to_sdcard=True)):
  235. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  236. assert _statuses(result)["external_storage"] == "pass"
  237. async def test_fails_when_store_to_sdcard_false(self):
  238. # Bit 11 reported as 0 -> printer-side toggle is off. Overall
  239. # escalates to "problems" because a fail is present.
  240. with _Env(state=_state(store_to_sdcard=False)):
  241. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  242. assert _statuses(result)["external_storage"] == "fail"
  243. assert result.overall == "problems"
  244. async def test_skips_when_disconnected(self):
  245. # State exists (we have a saved printer) but the MQTT connection
  246. # dropped, so the latest store_to_sdcard value can't be trusted.
  247. with _Env(state=_state(connected=False, store_to_sdcard=True)):
  248. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  249. assert _statuses(result)["external_storage"] == "skip"
  250. async def test_skips_pre_add_flow(self):
  251. # No saved printer -> no state -> nothing to read. The check has
  252. # to skip; pre-add can't probe this without a live MQTT session.
  253. with _Env():
  254. result = await run_connection_diagnostic(
  255. "192.168.1.50",
  256. serial_number="01P",
  257. access_code="probe-code",
  258. )
  259. assert _statuses(result)["external_storage"] == "skip"
  260. async def test_skips_when_field_missing(self):
  261. # State exists and is connected but store_to_sdcard was never
  262. # populated (firmware that doesn't push home_flag). Skip rather
  263. # than fabricate a False from a missing field.
  264. bare = types.SimpleNamespace(connected=True, developer_mode=True)
  265. with _Env(state=bare):
  266. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  267. assert _statuses(result)["external_storage"] == "skip"
  268. async def test_skips_on_a1_no_external_storage_slot(self):
  269. # Regression for #1703: A1 and A1 Mini ship without a MicroSD slot
  270. # at all, so home_flag bit 11 is never set and a naive read would
  271. # report `fail` for every A1-series user. The model-aware skip
  272. # branch suppresses that — and the overall result must NOT escalate
  273. # to "problems" purely because of this check.
  274. with _Env(state=_state(store_to_sdcard=False)):
  275. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="A1"))
  276. assert _statuses(result)["external_storage"] == "skip"
  277. assert result.overall == "ok"
  278. async def test_skips_on_a1_mini_no_external_storage_slot(self):
  279. with _Env(state=_state(store_to_sdcard=False)):
  280. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="A1 Mini"))
  281. assert _statuses(result)["external_storage"] == "skip"
  282. async def test_still_fails_on_x1c_when_toggle_off(self):
  283. # Sanity: the model-aware skip MUST NOT silently let X1C-class
  284. # printers off the hook. The store_to_sdcard=False path is the
  285. # one real bit of value this check provides for those models.
  286. with _Env(state=_state(store_to_sdcard=False)):
  287. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="X1C"))
  288. assert _statuses(result)["external_storage"] == "fail"