test_printer_diagnostic.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 ssl
  7. import types
  8. from contextlib import ExitStack
  9. from unittest.mock import AsyncMock, MagicMock, patch
  10. from backend.app.services.printer_diagnostic import (
  11. _check_ftps_tls,
  12. _same_subnet,
  13. run_connection_diagnostic,
  14. )
  15. MOD = "backend.app.services.printer_diagnostic"
  16. def _statuses(result):
  17. """Map of check id -> status for concise assertions."""
  18. return {c.id: c.status for c in result.checks}
  19. def _port_probe(overrides=None):
  20. """Sync side_effect for _check_port. Defaults: every port reachable.
  21. 990 is absent: the FTPS check runs a real TLS handshake through
  22. ``_check_ftps_tls`` rather than a bare TCP probe, and ``_Env(ftps=...)``
  23. drives it.
  24. """
  25. reachable = {8883: True, 322: True, 6000: True}
  26. reachable.update(overrides or {})
  27. def _probe(ip, port, timeout=3.0):
  28. return reachable[port]
  29. return _probe
  30. def _state(
  31. *,
  32. connected=True,
  33. developer_mode=True,
  34. store_to_sdcard=True,
  35. sdcard=True,
  36. sdcard_reported=False,
  37. last_project_url=None,
  38. ):
  39. # sdcard_reported defaults False — "the printer never mentioned its card",
  40. # which is what every pre-#2780 test in this file assumes and what keeps
  41. # the storage branches out of their way.
  42. return types.SimpleNamespace(
  43. connected=connected,
  44. developer_mode=developer_mode,
  45. store_to_sdcard=store_to_sdcard,
  46. sdcard=sdcard,
  47. sdcard_reported=sdcard_reported,
  48. last_project_url=last_project_url,
  49. )
  50. class _Env:
  51. """Patches the diagnostic's network/printer helpers for one run."""
  52. def __init__(
  53. self,
  54. *,
  55. ports=None,
  56. ftps="ok",
  57. in_docker=True,
  58. network_mode="host",
  59. host_ip="192.168.1.5",
  60. state=None,
  61. test_connection_success=True,
  62. report_messages_since_connect: int | None = 5,
  63. connect_error: str | None = None,
  64. ):
  65. self.ports = ports or _port_probe()
  66. # What the FTPS probe reports: "ok", "closed" or "no_tls" (#2780).
  67. self.ftps = ftps
  68. self.in_docker = in_docker
  69. self.network_mode = network_mode
  70. self.host_ip = host_ip
  71. self.state = state
  72. self.test_connection_success = test_connection_success
  73. # ``None`` means get_client returns None (e.g. pre-add flow); an int
  74. # means there's a client with that counter value.
  75. self.report_messages_since_connect = report_messages_since_connect
  76. # CONNACK-refusal slug the live client reports, or None when the last
  77. # connection attempt was never refused (#2698).
  78. self.connect_error = connect_error
  79. self._stack = ExitStack()
  80. def __enter__(self):
  81. manager = MagicMock()
  82. manager.get_status.return_value = self.state
  83. manager.test_connection = AsyncMock(
  84. return_value={
  85. "success": self.test_connection_success,
  86. "reason": None if self.test_connection_success else self.connect_error,
  87. }
  88. )
  89. if self.report_messages_since_connect is None:
  90. manager.get_client.return_value = None
  91. else:
  92. client = MagicMock()
  93. client.report_messages_since_connect = self.report_messages_since_connect
  94. client.last_connect_error = self.connect_error
  95. manager.get_client.return_value = client
  96. self._stack.enter_context(patch(f"{MOD}._check_port", new_callable=AsyncMock, side_effect=self.ports))
  97. self._stack.enter_context(patch(f"{MOD}._check_ftps_tls", new_callable=AsyncMock, return_value=self.ftps))
  98. self._stack.enter_context(patch(f"{MOD}.is_running_in_docker", return_value=self.in_docker))
  99. self._stack.enter_context(patch(f"{MOD}._detect_docker_network_mode", return_value=self.network_mode))
  100. self._stack.enter_context(patch(f"{MOD}._get_host_ip", return_value=self.host_ip))
  101. self._stack.enter_context(patch(f"{MOD}.printer_manager", manager))
  102. return self
  103. def __exit__(self, *exc):
  104. self._stack.close()
  105. return False
  106. def _printer(ip="192.168.1.50", model=None):
  107. return types.SimpleNamespace(id=1, ip_address=ip, model=model)
  108. class TestSameSubnet:
  109. def test_same_24(self):
  110. assert _same_subnet("192.168.1.10", "192.168.1.200") is True
  111. def test_different_24(self):
  112. assert _same_subnet("192.168.1.10", "192.168.2.10") is False
  113. def test_hostname_undeterminable(self):
  114. assert _same_subnet("printer.local", "192.168.1.10") is None
  115. def test_ipv6_undeterminable(self):
  116. assert _same_subnet("fe80::1", "192.168.1.10") is None
  117. class TestExistingPrinter:
  118. async def test_all_healthy(self):
  119. with _Env(
  120. state=_state(connected=True, developer_mode=True, store_to_sdcard=True),
  121. report_messages_since_connect=42,
  122. ):
  123. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  124. s = _statuses(result)
  125. assert result.overall == "ok"
  126. assert s == {
  127. "port_mqtt": "pass",
  128. "port_ftps": "pass",
  129. "port_rtsps": "pass",
  130. "network_mode": "pass",
  131. "subnet": "pass",
  132. "external_storage": "pass",
  133. "mqtt_auth": "pass",
  134. "developer_mode": "pass",
  135. "printer_publishing": "pass",
  136. }
  137. async def test_mqtt_port_unreachable_is_a_problem(self):
  138. with _Env(ports=_port_probe({8883: False}), state=_state()):
  139. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  140. s = _statuses(result)
  141. assert result.overall == "problems"
  142. assert s["port_mqtt"] == "fail"
  143. # Auth can't be judged when the broker port itself is closed.
  144. assert s["mqtt_auth"] == "skip"
  145. async def test_ftps_and_rtsps_only_warn(self):
  146. with _Env(ports=_port_probe({322: False}), ftps="closed", state=_state()):
  147. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  148. s = _statuses(result)
  149. # No critical failure -> warnings, not problems.
  150. assert result.overall == "warnings"
  151. assert s["port_ftps"] == "warn"
  152. assert s["port_rtsps"] == "warn"
  153. # Nothing was listening, so the message stays the generic "unblock the
  154. # port" one — no reason variant.
  155. ftps_check = next(c for c in result.checks if c.id == "port_ftps")
  156. assert ftps_check.params == {}
  157. async def test_open_port_that_cannot_negotiate_tls_says_so(self):
  158. """An open 990 that fails the handshake must not read as healthy.
  159. #2780's reporter saw port 990 green while every 3MF download died in
  160. the TLS handshake, so the archives arrived empty with nothing on
  161. screen to explain it. The reason variant selects a message that names
  162. a printer restart instead of sending the user to their firewall.
  163. """
  164. with _Env(ftps="no_tls", state=_state()):
  165. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="P2S"))
  166. assert _statuses(result)["port_ftps"] == "warn"
  167. ftps_check = next(c for c in result.checks if c.id == "port_ftps")
  168. assert ftps_check.params == {"reason": "no_tls"}
  169. assert result.overall == "warnings"
  170. async def test_a1_mini_uses_chamber_image_camera_port(self):
  171. # A1/P1-family printers use the chamber-image camera protocol on 6000,
  172. # not RTSPS on 322. A closed 322 must not create a false camera warning.
  173. with _Env(ports=_port_probe({322: False, 6000: True}), state=_state()):
  174. result = await run_connection_diagnostic(
  175. "192.168.1.50",
  176. printer=_printer(model="A1 Mini"),
  177. )
  178. assert _statuses(result)["port_rtsps"] == "pass"
  179. camera_check = next(c for c in result.checks if c.id == "port_rtsps")
  180. assert camera_check.params == {"port": 6000, "protocol": "Chamber Image"}
  181. async def test_rtsp_models_still_probe_rtsps_port(self):
  182. with _Env(ports=_port_probe({322: False, 6000: True}), state=_state()):
  183. result = await run_connection_diagnostic(
  184. "192.168.1.50",
  185. printer=_printer(model="X1C"),
  186. )
  187. assert _statuses(result)["port_rtsps"] == "warn"
  188. camera_check = next(c for c in result.checks if c.id == "port_rtsps")
  189. assert camera_check.params == {"port": 322, "protocol": "RTSPS"}
  190. async def test_developer_mode_off_is_a_problem(self):
  191. with _Env(state=_state(connected=True, developer_mode=False)):
  192. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  193. s = _statuses(result)
  194. assert s["developer_mode"] == "fail"
  195. assert result.overall == "problems"
  196. async def test_developer_mode_skipped_when_disconnected(self):
  197. # No live MQTT connection -> developer_mode can't be read.
  198. with _Env(state=_state(connected=False)):
  199. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  200. s = _statuses(result)
  201. assert s["developer_mode"] == "skip"
  202. # Reachable port but no connection -> credential failure class.
  203. assert s["mqtt_auth"] == "fail"
  204. # Can't observe report messages without a connection.
  205. assert s["printer_publishing"] == "skip"
  206. async def test_bridge_mode_warns_and_skips_subnet(self):
  207. with _Env(network_mode="bridge", state=_state()):
  208. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  209. s = _statuses(result)
  210. assert s["network_mode"] == "warn"
  211. # Container IP isn't the host IP in bridge mode -> subnet check is meaningless.
  212. assert s["subnet"] == "skip"
  213. async def test_network_mode_skipped_outside_docker(self):
  214. with _Env(in_docker=False, state=_state()):
  215. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  216. assert _statuses(result)["network_mode"] == "skip"
  217. async def test_different_subnet_warns(self):
  218. with _Env(host_ip="10.0.0.5", state=_state()):
  219. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  220. assert _statuses(result)["subnet"] == "warn"
  221. async def test_printer_publishing_passes_when_reports_seen(self):
  222. # Counter > 0 means the printer is publishing on the report topic.
  223. with _Env(state=_state(), report_messages_since_connect=1):
  224. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  225. assert _statuses(result)["printer_publishing"] == "pass"
  226. async def test_printer_publishing_fails_when_zero_reports_after_wait(self):
  227. # Counter stays at 0 across the wait window — printer never published.
  228. # Tiny wait_for_publish_seconds keeps the test sub-second.
  229. with _Env(state=_state(), report_messages_since_connect=0):
  230. result = await run_connection_diagnostic(
  231. "192.168.1.50",
  232. printer=_printer(),
  233. wait_for_publish_seconds=0.05,
  234. )
  235. s = _statuses(result)
  236. assert s["printer_publishing"] == "fail"
  237. # Overall escalates because fail is present.
  238. assert result.overall == "problems"
  239. # The check exposes the wait budget so the UI can render a countdown.
  240. params = next(c.params for c in result.checks if c.id == "printer_publishing")
  241. assert params == {"max_wait_seconds": 0.05}
  242. async def test_printer_publishing_skips_when_disconnected(self):
  243. # No live MQTT connection -> can't observe report messages.
  244. with _Env(state=_state(connected=False), report_messages_since_connect=0):
  245. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  246. assert _statuses(result)["printer_publishing"] == "skip"
  247. async def test_printer_publishing_skips_when_no_client(self):
  248. # State says connected but printer_manager has no client object
  249. # (race between client teardown and a fresh diagnostic request).
  250. with _Env(state=_state(), report_messages_since_connect=None):
  251. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  252. assert _statuses(result)["printer_publishing"] == "skip"
  253. async def test_printer_publishing_no_wait_returns_instantly_on_zero(self):
  254. # Default wait is 0 — instant pass/fail without polling. Used by the
  255. # support-package code path so bundling stays fast.
  256. with _Env(state=_state(), report_messages_since_connect=0):
  257. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  258. s = _statuses(result)
  259. assert s["printer_publishing"] == "fail"
  260. params = next(c.params for c in result.checks if c.id == "printer_publishing")
  261. # No wait -> no max_wait_seconds param surfaced to the UI.
  262. assert params == {}
  263. class TestAuthRejectedReason:
  264. """#2698: "not connected" and "credentials refused" are different answers.
  265. `state.connected == False` only says we have no session — the printer may
  266. be rebooting, at its connection limit, or refusing the access code. When
  267. the printer actually sent a CONNACK refusal the client records it, and the
  268. check surfaces it as a `params.reason` variant so the UI can name the cause
  269. instead of making the user guess. Without a recorded refusal the params
  270. stay empty and the generic text is used.
  271. """
  272. def _params(self, result):
  273. return next(c.params for c in result.checks if c.id == "mqtt_auth")
  274. async def test_recorded_refusal_surfaces_reason(self):
  275. with _Env(state=_state(connected=False), connect_error="auth_rejected"):
  276. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  277. assert _statuses(result)["mqtt_auth"] == "fail"
  278. assert self._params(result) == {"reason": "auth_rejected"}
  279. async def test_disconnected_without_refusal_stays_generic(self):
  280. with _Env(state=_state(connected=False)):
  281. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  282. assert _statuses(result)["mqtt_auth"] == "fail"
  283. assert self._params(result) == {}
  284. async def test_unknown_slug_falls_back_to_generic(self):
  285. # `refused` has no dedicated message — degrade to the plain fail text
  286. # rather than asking the frontend for a key that doesn't exist.
  287. with _Env(state=_state(connected=False), connect_error="refused"):
  288. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  289. assert self._params(result) == {}
  290. async def test_connected_printer_carries_no_reason(self):
  291. with _Env(state=_state(connected=True), connect_error="auth_rejected"):
  292. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  293. assert _statuses(result)["mqtt_auth"] == "pass"
  294. assert self._params(result) == {}
  295. async def test_pre_add_probe_surfaces_reason(self):
  296. with _Env(test_connection_success=False, connect_error="auth_rejected"):
  297. result = await run_connection_diagnostic("192.168.1.50", serial_number="01P", access_code="wrong")
  298. assert _statuses(result)["mqtt_auth"] == "fail"
  299. assert self._params(result) == {"reason": "auth_rejected"}
  300. class TestPreAddFlow:
  301. async def test_bad_credentials_fail_mqtt_auth(self):
  302. with _Env(test_connection_success=False):
  303. result = await run_connection_diagnostic("192.168.1.50", serial_number="01P", access_code="wrong")
  304. s = _statuses(result)
  305. assert s["mqtt_auth"] == "fail"
  306. # No saved printer -> developer mode can't be read.
  307. assert s["developer_mode"] == "skip"
  308. async def test_good_credentials_pass_mqtt_auth(self):
  309. with _Env(test_connection_success=True):
  310. result = await run_connection_diagnostic("192.168.1.50", serial_number="01P", access_code="right")
  311. assert _statuses(result)["mqtt_auth"] == "pass"
  312. async def test_no_credentials_skips_mqtt_auth(self):
  313. with _Env():
  314. result = await run_connection_diagnostic("192.168.1.50")
  315. assert _statuses(result)["mqtt_auth"] == "skip"
  316. class TestExternalStorageCheck:
  317. """Install step 4 — "Store sent files on external storage".
  318. Detected via ``state.store_to_sdcard`` (parsed from MQTT push_status
  319. ``home_flag`` bit 11). Only catches the printer-side variant of the
  320. setting on newer firmware (P2S 01.02 / Studio 2.6+) — the older
  321. slicer-side variant is undetectable from outside the slicer and is
  322. covered separately by the no-3MF archive-fallback banner.
  323. """
  324. async def test_passes_when_store_to_sdcard_true(self):
  325. with _Env(state=_state(store_to_sdcard=True)):
  326. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  327. assert _statuses(result)["external_storage"] == "pass"
  328. async def test_fails_when_store_to_sdcard_false(self):
  329. # Bit 11 reported as 0 -> printer-side toggle is off. Overall
  330. # escalates to "problems" because a fail is present.
  331. with _Env(state=_state(store_to_sdcard=False)):
  332. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  333. assert _statuses(result)["external_storage"] == "fail"
  334. assert result.overall == "problems"
  335. async def test_skips_when_disconnected(self):
  336. # State exists (we have a saved printer) but the MQTT connection
  337. # dropped, so the latest store_to_sdcard value can't be trusted.
  338. with _Env(state=_state(connected=False, store_to_sdcard=True)):
  339. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  340. assert _statuses(result)["external_storage"] == "skip"
  341. async def test_skips_pre_add_flow(self):
  342. # No saved printer -> no state -> nothing to read. The check has
  343. # to skip; pre-add can't probe this without a live MQTT session.
  344. with _Env():
  345. result = await run_connection_diagnostic(
  346. "192.168.1.50",
  347. serial_number="01P",
  348. access_code="probe-code",
  349. )
  350. assert _statuses(result)["external_storage"] == "skip"
  351. async def test_skips_when_field_missing(self):
  352. # State exists and is connected but store_to_sdcard was never
  353. # populated (firmware that doesn't push home_flag). Skip rather
  354. # than fabricate a False from a missing field.
  355. bare = types.SimpleNamespace(connected=True, developer_mode=True)
  356. with _Env(state=bare):
  357. result = await run_connection_diagnostic("192.168.1.50", printer=_printer())
  358. assert _statuses(result)["external_storage"] == "skip"
  359. async def test_skips_on_a1_no_external_storage_slot(self):
  360. # Regression for #1703: A1 and A1 Mini ship without a MicroSD slot
  361. # at all, so home_flag bit 11 is never set and a naive read would
  362. # report `fail` for every A1-series user. The model-aware skip
  363. # branch suppresses that — and the overall result must NOT escalate
  364. # to "problems" purely because of this check.
  365. with _Env(state=_state(store_to_sdcard=False)):
  366. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="A1"))
  367. assert _statuses(result)["external_storage"] == "skip"
  368. assert result.overall == "ok"
  369. async def test_skips_on_a1_mini_no_external_storage_slot(self):
  370. with _Env(state=_state(store_to_sdcard=False)):
  371. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="A1 Mini"))
  372. assert _statuses(result)["external_storage"] == "skip"
  373. async def test_still_fails_on_x1c_when_toggle_off(self):
  374. # Sanity: the model-aware skip MUST NOT silently let X1C-class
  375. # printers off the hook. The store_to_sdcard=False path is the
  376. # one real bit of value this check provides for those models.
  377. with _Env(state=_state(store_to_sdcard=False)):
  378. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="X1C"))
  379. assert _statuses(result)["external_storage"] == "fail"
  380. async def test_skips_on_p1s_no_reachable_toggle(self):
  381. # #2524: P1S HAS a MicroSD slot (so has_external_storage is True and
  382. # the check proceeds), but current P1 firmware never publishes the
  383. # capability that renders the toggle in Bambu Studio and the P1S has
  384. # no screen — store_to_sdcard is stuck False with no way to fix it.
  385. # Report an informational skip (with a reason the UI explains), not a
  386. # permanently-unresolvable fail; overall must not escalate.
  387. with _Env(state=_state(store_to_sdcard=False)):
  388. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="P1S"))
  389. check = next(c for c in result.checks if c.id == "external_storage")
  390. assert check.status == "skip"
  391. assert check.params == {"reason": "unsupported_model"}
  392. assert result.overall == "ok"
  393. async def test_skips_on_p1p_no_reachable_toggle(self):
  394. with _Env(state=_state(store_to_sdcard=False)):
  395. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="P1P"))
  396. check = next(c for c in result.checks if c.id == "external_storage")
  397. assert check.status == "skip"
  398. assert check.params == {"reason": "unsupported_model"}
  399. async def test_p1s_still_passes_when_store_to_sdcard_true(self):
  400. # If a P1S somehow reports the option ON, respect it — pass, don't
  401. # mask it as an unsupported-model skip.
  402. with _Env(state=_state(store_to_sdcard=True)):
  403. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="P1S"))
  404. assert _statuses(result)["external_storage"] == "pass"
  405. # --- #2780: the toggle being on is not the same as it working ---------
  406. async def test_fails_when_the_toggle_is_on_but_the_slot_is_empty(self):
  407. """#2780's H2C reported `store_to_sdcard` set and `sdcard` False for
  408. three solid weeks. The check called that a clean pass while every one
  409. of its 23 archives came out blank -- the toggle can be on and still
  410. achieve nothing with nothing in the slot.
  411. """
  412. with _Env(state=_state(store_to_sdcard=True, sdcard=False, sdcard_reported=True)):
  413. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="H2C"))
  414. check = next(c for c in result.checks if c.id == "external_storage")
  415. assert check.status == "fail"
  416. assert check.params == {"reason": "no_media"}
  417. assert result.overall == "problems"
  418. async def test_warns_when_the_printer_kept_the_print_internally(self):
  419. """Toggle on, card in, and the printer still used internal storage --
  420. which is what H2-series and P2S firmware does. A pass would be a lie
  421. and a fail would be unresolvable, so it warns."""
  422. state = _state(
  423. store_to_sdcard=True,
  424. sdcard=True,
  425. sdcard_reported=True,
  426. last_project_url="brtc://emmc/Benchy.gcode.3mf",
  427. )
  428. with _Env(state=state):
  429. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="H2C"))
  430. check = next(c for c in result.checks if c.id == "external_storage")
  431. assert check.status == "warn"
  432. assert check.params == {"reason": "internal_storage"}
  433. assert result.overall == "warnings"
  434. async def test_an_external_storage_dispatch_still_passes(self):
  435. """The regression guard: an X1C dispatch says `ftp://`, and that must
  436. read exactly as it did before any of this existed."""
  437. state = _state(
  438. store_to_sdcard=True,
  439. sdcard=True,
  440. sdcard_reported=True,
  441. last_project_url="ftp://Benchy.gcode.3mf",
  442. )
  443. with _Env(state=state):
  444. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="X1C"))
  445. assert _statuses(result)["external_storage"] == "pass"
  446. async def test_a_p1_series_keeps_its_non_nagging_skip_with_no_card(self):
  447. """#2524 outranks #2780 here. Current P1 firmware exposes no way to
  448. turn the option on, so "insert a card" would promise a fix that
  449. inserting a card does not deliver -- the unresolvable-fail nagging
  450. that #2524 removed, back under a different label.
  451. """
  452. with _Env(state=_state(store_to_sdcard=False, sdcard=False, sdcard_reported=True)):
  453. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="P1S"))
  454. check = next(c for c in result.checks if c.id == "external_storage")
  455. assert check.status == "skip"
  456. assert check.params == {"reason": "unsupported_model"}
  457. assert result.overall == "ok"
  458. async def test_a_model_with_a_reachable_toggle_does_report_the_empty_slot(self):
  459. """The counterpart: on an X1C the advice is actionable, so give it."""
  460. with _Env(state=_state(store_to_sdcard=False, sdcard=False, sdcard_reported=True)):
  461. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="X1C"))
  462. check = next(c for c in result.checks if c.id == "external_storage")
  463. assert check.status == "fail"
  464. assert check.params == {"reason": "no_media"}
  465. async def test_an_empty_slot_outranks_the_internal_storage_warning(self):
  466. """Both apply on a stickless H2C. "Put a card in" is the one the
  467. operator can act on, so it must not be masked by the softer warning.
  468. """
  469. state = _state(
  470. store_to_sdcard=True,
  471. sdcard=False,
  472. sdcard_reported=True,
  473. last_project_url="brtc://emmc/Benchy.gcode.3mf",
  474. )
  475. with _Env(state=state):
  476. result = await run_connection_diagnostic("192.168.1.50", printer=_printer(model="H2C"))
  477. check = next(c for c in result.checks if c.id == "external_storage")
  478. assert check.status == "fail"
  479. assert check.params == {"reason": "no_media"}
  480. class TestFtpsTlsProbe:
  481. """The FTPS probe must reach the handshake, not stop at the TCP accept.
  482. #2780: a printer whose file service stops answering with TLS still
  483. accepts the connection on 990, so the old bare TCP probe reported it
  484. green while every archive came back empty.
  485. """
  486. async def test_completed_handshake_is_ok(self):
  487. writer = MagicMock()
  488. writer.wait_closed = AsyncMock()
  489. with patch(f"{MOD}.asyncio.open_connection", new_callable=AsyncMock, return_value=(MagicMock(), writer)):
  490. assert await _check_ftps_tls("192.168.1.50", "X1C") == "ok"
  491. writer.close.assert_called_once()
  492. async def test_handshake_failure_on_an_open_port_is_no_tls(self):
  493. with patch(
  494. f"{MOD}.asyncio.open_connection",
  495. new_callable=AsyncMock,
  496. side_effect=ssl.SSLError("[SSL: WRONG_VERSION_NUMBER] wrong version number"),
  497. ):
  498. assert await _check_ftps_tls("192.168.1.50", "P2S") == "no_tls"
  499. async def test_refused_connection_is_closed(self):
  500. with patch(f"{MOD}.asyncio.open_connection", new_callable=AsyncMock, side_effect=ConnectionRefusedError):
  501. assert await _check_ftps_tls("192.168.1.50", "X1C") == "closed"
  502. async def test_timeout_is_closed_not_no_tls(self):
  503. # A printer that is switched off never gets far enough to say anything
  504. # about TLS — that has to stay the generic "port unreachable" advice.
  505. with patch(f"{MOD}.asyncio.open_connection", new_callable=AsyncMock, side_effect=TimeoutError):
  506. assert await _check_ftps_tls("192.168.1.50", "X1C") == "closed"
  507. async def test_probe_mirrors_the_model_tls_cap(self):
  508. """The probe must negotiate exactly what the FTP client negotiates.
  509. A P2S is pinned to TLS 1.2 by its ftp_profiles entry; probing it on a
  510. context that also offers 1.3 could pass where the real transfer fails
  511. (or the reverse), which is the class of false green this check exists
  512. to remove.
  513. """
  514. contexts = []
  515. async def _capture(host, port, ssl=None):
  516. contexts.append(ssl)
  517. writer = MagicMock()
  518. writer.wait_closed = AsyncMock()
  519. return MagicMock(), writer
  520. with patch(f"{MOD}.asyncio.open_connection", new=_capture):
  521. await _check_ftps_tls("192.168.1.50", "P2S")
  522. await _check_ftps_tls("192.168.1.50", "X1C")
  523. capped, uncapped = contexts
  524. assert capped.maximum_version == ssl.TLSVersion.TLSv1_2
  525. assert capped.minimum_version == ssl.TLSVersion.TLSv1_2
  526. assert uncapped.maximum_version != ssl.TLSVersion.TLSv1_2
  527. assert uncapped.minimum_version == ssl.TLSVersion.TLSv1_2