test_obico_detection.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. """Unit tests for Obico detection service (#172)."""
  2. from unittest.mock import AsyncMock, MagicMock, patch
  3. import pytest
  4. from backend.app.schemas.settings import AppSettingsUpdate
  5. from backend.app.services.obico_detection import (
  6. FRAME_CACHE_TTL,
  7. ObicoDetectionService,
  8. _frame_cache,
  9. pop_frame,
  10. stash_frame,
  11. )
  12. from backend.app.services.obico_smoothing import WARMUP_FRAMES
  13. FAKE_JPEG = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xd9"
  14. class TestSettingsSchemaValidators:
  15. """Guard rails on the new obico_* AppSettings fields."""
  16. def test_sensitivity_accepts_valid_values(self):
  17. for value in ("low", "medium", "high"):
  18. u = AppSettingsUpdate(obico_sensitivity=value)
  19. assert u.obico_sensitivity == value
  20. def test_sensitivity_rejects_garbage(self):
  21. with pytest.raises(ValueError, match="obico_sensitivity"):
  22. AppSettingsUpdate(obico_sensitivity="extreme")
  23. def test_action_accepts_valid_values(self):
  24. for value in ("notify", "pause", "pause_and_off"):
  25. assert AppSettingsUpdate(obico_action=value).obico_action == value
  26. def test_action_rejects_garbage(self):
  27. with pytest.raises(ValueError, match="obico_action"):
  28. AppSettingsUpdate(obico_action="explode")
  29. def test_enabled_printers_accepts_empty(self):
  30. assert AppSettingsUpdate(obico_enabled_printers="").obico_enabled_printers == ""
  31. assert AppSettingsUpdate(obico_enabled_printers=None).obico_enabled_printers is None
  32. def test_enabled_printers_accepts_int_array(self):
  33. u = AppSettingsUpdate(obico_enabled_printers="[1, 2, 3]")
  34. assert u.obico_enabled_printers == "[1, 2, 3]"
  35. def test_enabled_printers_rejects_non_json(self):
  36. with pytest.raises(ValueError, match="valid JSON"):
  37. AppSettingsUpdate(obico_enabled_printers="1,2,3")
  38. def test_enabled_printers_rejects_non_list(self):
  39. with pytest.raises(ValueError, match="JSON array"):
  40. AppSettingsUpdate(obico_enabled_printers='{"1": true}')
  41. def test_enabled_printers_rejects_non_int_elements(self):
  42. with pytest.raises(ValueError, match="JSON array"):
  43. AppSettingsUpdate(obico_enabled_printers='[1, "two"]')
  44. def test_poll_interval_bounds(self):
  45. with pytest.raises(ValueError):
  46. AppSettingsUpdate(obico_poll_interval=4)
  47. with pytest.raises(ValueError):
  48. AppSettingsUpdate(obico_poll_interval=121)
  49. assert AppSettingsUpdate(obico_poll_interval=10).obico_poll_interval == 10
  50. class TestGetStatus:
  51. def test_empty_initial_status(self):
  52. svc = ObicoDetectionService()
  53. s = svc.get_status()
  54. assert s["is_running"] is False
  55. assert s["per_printer"] == {}
  56. assert s["history"] == []
  57. assert "low" in s["thresholds"] and "high" in s["thresholds"]
  58. def test_thresholds_reflect_configured_sensitivity(self):
  59. """#1469 — get_status() reports the thresholds for the passed
  60. sensitivity, not a hardcoded 'medium'. Each level must be distinct so
  61. the Status panel changes when the user changes the setting."""
  62. svc = ObicoDetectionService()
  63. low = svc.get_status("low")["thresholds"]
  64. medium = svc.get_status("medium")["thresholds"]
  65. high = svc.get_status("high")["thresholds"]
  66. # Higher sensitivity → lower thresholds (easier to trigger).
  67. assert low["low"] > medium["low"] > high["low"]
  68. assert low["high"] > medium["high"] > high["high"]
  69. # Default and unknown values fall back to medium.
  70. assert svc.get_status()["thresholds"] == medium
  71. assert svc.get_status("bogus")["thresholds"] == medium
  72. class TestTestConnection:
  73. @pytest.mark.asyncio
  74. async def test_empty_url_via_route(self):
  75. """Service does not special-case empty URL — the route does."""
  76. svc = ObicoDetectionService()
  77. # This will fail DNS/connect, but should return ok=False
  78. result = await svc.test_connection("http://nonexistent-obico-host-xyz.invalid:3333")
  79. assert result["ok"] is False
  80. assert result["error"] is not None
  81. @pytest.mark.asyncio
  82. async def test_healthy_response_is_ok(self):
  83. svc = ObicoDetectionService()
  84. mock_response = MagicMock(status_code=200, text="ok")
  85. mock_client = MagicMock()
  86. mock_client.get = AsyncMock(return_value=mock_response)
  87. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  88. mock_client.__aexit__ = AsyncMock(return_value=False)
  89. with patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client):
  90. result = await svc.test_connection("http://obico:3333")
  91. assert result["ok"] is True
  92. assert result["status_code"] == 200
  93. assert result["body"] == "ok"
  94. assert result["error"] is None
  95. @pytest.mark.asyncio
  96. async def test_non_ok_body_is_not_ok(self):
  97. svc = ObicoDetectionService()
  98. mock_response = MagicMock(status_code=200, text="something else")
  99. mock_client = MagicMock()
  100. mock_client.get = AsyncMock(return_value=mock_response)
  101. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  102. mock_client.__aexit__ = AsyncMock(return_value=False)
  103. with patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client):
  104. result = await svc.test_connection("http://obico:3333/")
  105. assert result["ok"] is False
  106. assert result["body"] == "something else"
  107. class TestMlApiToken:
  108. """Obico's ML API gates /p/ behind ML_API_TOKEN (#2733)."""
  109. def test_auth_headers_only_when_configured(self):
  110. from backend.app.services.obico_detection import auth_headers
  111. assert auth_headers("s3cret") == {"Authorization": "Bearer s3cret"}
  112. # Unconfigured must stay byte-identical to the pre-setting request.
  113. assert auth_headers("") == {}
  114. assert auth_headers(None) == {}
  115. assert auth_headers(" ") == {}
  116. # Whitespace around a real token is a paste artefact, not part of it.
  117. assert auth_headers(" s3cret ") == {"Authorization": "Bearer s3cret"}
  118. def test_settings_schema_accepts_a_token(self):
  119. assert AppSettingsUpdate(obico_ml_token="s3cret").obico_ml_token == "s3cret"
  120. assert AppSettingsUpdate(obico_ml_token="").obico_ml_token == ""
  121. assert AppSettingsUpdate().obico_ml_token is None
  122. @staticmethod
  123. def _settings(**overrides):
  124. base = {
  125. "enabled": True,
  126. "ml_url": "http://obico:3333",
  127. "ml_token": "",
  128. "sensitivity": "medium",
  129. "action": "notify",
  130. "poll_interval": 10,
  131. "enabled_printers": None,
  132. "external_url": "http://bambuddy:8000",
  133. }
  134. base.update(overrides)
  135. return base
  136. @staticmethod
  137. def _client(response):
  138. mock_client = MagicMock()
  139. mock_client.get = AsyncMock(return_value=response)
  140. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  141. mock_client.__aexit__ = AsyncMock(return_value=False)
  142. return mock_client
  143. @pytest.mark.asyncio
  144. async def test_detection_call_carries_the_bearer_header(self):
  145. svc = ObicoDetectionService()
  146. response = MagicMock(status_code=200)
  147. response.json.return_value = {"detections": []}
  148. response.raise_for_status = MagicMock()
  149. mock_client = self._client(response)
  150. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  151. with (
  152. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  153. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  154. ):
  155. await svc._check_printer(1, status, self._settings(ml_token="s3cret"))
  156. assert mock_client.get.await_args.kwargs["headers"] == {"Authorization": "Bearer s3cret"}
  157. @pytest.mark.asyncio
  158. async def test_detection_call_sends_no_header_without_a_token(self):
  159. svc = ObicoDetectionService()
  160. response = MagicMock(status_code=200)
  161. response.json.return_value = {"detections": []}
  162. response.raise_for_status = MagicMock()
  163. mock_client = self._client(response)
  164. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  165. with (
  166. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  167. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  168. ):
  169. await svc._check_printer(1, status, self._settings())
  170. assert mock_client.get.await_args.kwargs["headers"] == {}
  171. @pytest.mark.asyncio
  172. async def test_401_reports_the_token_rather_than_a_bare_http_error(self):
  173. svc = ObicoDetectionService()
  174. response = MagicMock(status_code=401)
  175. # raise_for_status would also raise here; the status check must come first
  176. # so the user gets an actionable message instead of "401 Unauthorized".
  177. response.raise_for_status = MagicMock(side_effect=AssertionError("must not reach raise_for_status"))
  178. mock_client = self._client(response)
  179. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  180. with (
  181. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  182. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  183. ):
  184. await svc._check_printer(1, status, self._settings(ml_token="wrong"))
  185. assert "401" in svc._last_error
  186. assert "ML_API_TOKEN" in svc._last_error
  187. # A rejected call must not be scored as a clean frame.
  188. assert 1 not in svc._states or svc._states[1].frame_count == 0
  189. @pytest.mark.asyncio
  190. async def test_401_message_does_not_leak_the_token(self):
  191. svc = ObicoDetectionService()
  192. response = MagicMock(status_code=401)
  193. response.raise_for_status = MagicMock()
  194. mock_client = self._client(response)
  195. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  196. with (
  197. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  198. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  199. ):
  200. await svc._check_printer(1, status, self._settings(ml_token="sup3rs3cret"))
  201. assert "sup3rs3cret" not in svc._last_error
  202. class TestTestConnectionTokenProbe:
  203. """/hc/ is ungated, so health alone cannot validate the token (#2733)."""
  204. @staticmethod
  205. def _client(responses):
  206. mock_client = MagicMock()
  207. mock_client.get = AsyncMock(side_effect=responses)
  208. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  209. mock_client.__aexit__ = AsyncMock(return_value=False)
  210. return mock_client
  211. @pytest.mark.asyncio
  212. async def test_healthy_but_rejected_token_is_not_ok(self):
  213. svc = ObicoDetectionService()
  214. mock_client = self._client([MagicMock(status_code=200, text="ok"), MagicMock(status_code=401)])
  215. with patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client):
  216. result = await svc.test_connection("http://obico:3333", "wrong")
  217. assert result["ok"] is False
  218. assert result["auth_ok"] is False
  219. assert result["status_code"] == 401
  220. assert "ML_API_TOKEN" in result["error"]
  221. @pytest.mark.asyncio
  222. async def test_accepted_token_is_ok(self):
  223. svc = ObicoDetectionService()
  224. # 422 = "Invalid request params": auth passed, then the handler rejected
  225. # the img-less probe. That is the success signal.
  226. mock_client = self._client([MagicMock(status_code=200, text="ok"), MagicMock(status_code=422)])
  227. with patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client):
  228. result = await svc.test_connection("http://obico:3333", "right")
  229. assert result["ok"] is True
  230. assert result["auth_ok"] is True
  231. assert result["error"] is None
  232. @pytest.mark.asyncio
  233. async def test_probe_failure_leaves_the_token_unknown_but_keeps_the_test_ok(self):
  234. svc = ObicoDetectionService()
  235. mock_client = self._client([MagicMock(status_code=200, text="ok"), RuntimeError("read timeout")])
  236. with patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client):
  237. result = await svc.test_connection("http://obico:3333", "maybe")
  238. assert result["ok"] is True
  239. assert result["auth_ok"] is None
  240. @pytest.mark.asyncio
  241. async def test_unhealthy_server_is_not_probed(self):
  242. svc = ObicoDetectionService()
  243. mock_client = self._client([MagicMock(status_code=200, text="error")])
  244. with patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client):
  245. result = await svc.test_connection("http://obico:3333", "any")
  246. assert result["ok"] is False
  247. assert result["auth_ok"] is None
  248. assert mock_client.get.await_count == 1
  249. @pytest.mark.asyncio
  250. async def test_both_requests_carry_the_header(self):
  251. svc = ObicoDetectionService()
  252. mock_client = self._client([MagicMock(status_code=200, text="ok"), MagicMock(status_code=422)])
  253. with patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client):
  254. await svc.test_connection("http://obico:3333", "s3cret")
  255. assert [call.args[0] for call in mock_client.get.await_args_list] == [
  256. "http://obico:3333/hc/",
  257. "http://obico:3333/p/",
  258. ]
  259. for call in mock_client.get.await_args_list:
  260. assert call.kwargs["headers"] == {"Authorization": "Bearer s3cret"}
  261. @pytest.mark.asyncio
  262. async def test_url_policy_still_applies_before_any_request(self):
  263. svc = ObicoDetectionService()
  264. result = await svc.test_connection("http://169.254.169.254/latest/meta-data/", "s3cret")
  265. assert result["ok"] is False
  266. assert result["auth_ok"] is None
  267. assert result["error"]
  268. class TestPollOneStateLifecycle:
  269. """Confirms per-printer state is reset when a new print starts."""
  270. @pytest.mark.asyncio
  271. async def test_new_task_name_resets_state(self):
  272. svc = ObicoDetectionService()
  273. # Seed a state that has been running for a while
  274. from backend.app.services.obico_smoothing import PrintState
  275. seeded = PrintState()
  276. for _ in range(WARMUP_FRAMES + 5):
  277. seeded.update(0.5)
  278. svc._states[1] = seeded
  279. svc._state_keys[1] = "old_task"
  280. svc._action_fired[1] = True
  281. settings = {
  282. "enabled": True,
  283. "ml_url": "http://obico:3333",
  284. "sensitivity": "medium",
  285. "action": "notify",
  286. "poll_interval": 10,
  287. "enabled_printers": None,
  288. "external_url": "http://bambuddy:8000",
  289. }
  290. status = MagicMock(state="RUNNING", task_name="new_task", subtask_name="")
  291. mock_response = MagicMock()
  292. mock_response.json.return_value = {"detections": []}
  293. mock_response.raise_for_status = MagicMock()
  294. mock_client = MagicMock()
  295. mock_client.get = AsyncMock(return_value=mock_response)
  296. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  297. mock_client.__aexit__ = AsyncMock(return_value=False)
  298. with (
  299. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  300. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  301. ):
  302. await svc._check_printer(1, status, settings)
  303. # State was reset (frame_count is 1 after the single update, not 36)
  304. assert svc._states[1].frame_count == 1
  305. assert svc._state_keys[1] == "new_task"
  306. assert svc._action_fired[1] is False
  307. @pytest.mark.asyncio
  308. async def test_ml_api_error_does_not_crash(self):
  309. svc = ObicoDetectionService()
  310. settings = {
  311. "enabled": True,
  312. "ml_url": "http://obico:3333",
  313. "sensitivity": "medium",
  314. "action": "notify",
  315. "poll_interval": 10,
  316. "enabled_printers": None,
  317. "external_url": "http://bambuddy:8000",
  318. }
  319. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  320. mock_client = MagicMock()
  321. mock_client.get = AsyncMock(side_effect=RuntimeError("connection refused"))
  322. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  323. mock_client.__aexit__ = AsyncMock(return_value=False)
  324. with (
  325. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  326. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  327. ):
  328. await svc._check_printer(1, status, settings)
  329. assert svc._last_error is not None
  330. assert "connection refused" in svc._last_error
  331. @pytest.mark.asyncio
  332. async def test_ml_api_empty_exception_message_falls_back_to_type(self):
  333. """If str(exc) is empty, log the exception class name instead of a blank suffix."""
  334. svc = ObicoDetectionService()
  335. settings = {
  336. "enabled": True,
  337. "ml_url": "http://obico:3333",
  338. "sensitivity": "medium",
  339. "action": "notify",
  340. "poll_interval": 10,
  341. "enabled_printers": None,
  342. "external_url": "http://bambuddy:8000",
  343. }
  344. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  345. class _SilentError(Exception):
  346. def __str__(self) -> str:
  347. return ""
  348. mock_client = MagicMock()
  349. mock_client.get = AsyncMock(side_effect=_SilentError())
  350. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  351. mock_client.__aexit__ = AsyncMock(return_value=False)
  352. with (
  353. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  354. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  355. ):
  356. await svc._check_printer(1, status, settings)
  357. assert svc._last_error is not None
  358. assert "_SilentError" in svc._last_error
  359. # The suffix is never blank
  360. assert not svc._last_error.rstrip().endswith(":")
  361. @pytest.mark.asyncio
  362. async def test_failure_fires_action_only_once(self):
  363. """Once a failure has fired for a print, subsequent failures should not re-fire."""
  364. svc = ObicoDetectionService()
  365. settings = {
  366. "enabled": True,
  367. "ml_url": "http://obico:3333",
  368. "sensitivity": "medium",
  369. "action": "notify",
  370. "poll_interval": 10,
  371. "enabled_printers": None,
  372. "external_url": "http://bambuddy:8000",
  373. }
  374. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  375. # Seed state so the next frame crosses HIGH immediately
  376. from backend.app.services.obico_smoothing import PrintState
  377. seeded = PrintState()
  378. for _ in range(WARMUP_FRAMES + 500):
  379. seeded.update(1.0)
  380. svc._states[1] = seeded
  381. svc._state_keys[1] = "job"
  382. svc._action_fired[1] = False
  383. mock_response = MagicMock()
  384. mock_response.json.return_value = {"detections": [["failure", 0.9, [0, 0, 1, 1]]]}
  385. mock_response.raise_for_status = MagicMock()
  386. mock_client = MagicMock()
  387. mock_client.get = AsyncMock(return_value=mock_response)
  388. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  389. mock_client.__aexit__ = AsyncMock(return_value=False)
  390. with (
  391. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  392. patch("backend.app.services.obico_actions.execute_action", new=AsyncMock()) as mock_action,
  393. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  394. ):
  395. await svc._check_printer(1, status, settings)
  396. assert mock_action.call_count == 1
  397. await svc._check_printer(1, status, settings)
  398. # Second call must not dispatch again
  399. assert mock_action.call_count == 1
  400. class TestCaptureFrameSharesBroadcasterUpstream:
  401. """#1271: Obico's per-poll snapshot must reuse the live-stream broadcaster's
  402. buffered frame when a viewer is watching, instead of opening a second RTSP
  403. socket. On X2D firmware 01.01.00.00 the second socket kicks the live stream.
  404. """
  405. @pytest.mark.asyncio
  406. async def test_returns_buffered_frame_when_stream_active(self):
  407. printer = MagicMock(
  408. external_camera_enabled=False,
  409. external_camera_url=None,
  410. ip_address="192.168.1.10",
  411. access_code="12345678",
  412. model="N6",
  413. )
  414. mock_session = MagicMock()
  415. mock_session.get = AsyncMock(return_value=printer)
  416. mock_ctx = MagicMock()
  417. mock_ctx.__aenter__ = AsyncMock(return_value=mock_session)
  418. mock_ctx.__aexit__ = AsyncMock(return_value=None)
  419. svc = ObicoDetectionService()
  420. with (
  421. patch("backend.app.services.obico_detection.async_session", return_value=mock_ctx),
  422. patch(
  423. "backend.app.api.routes.camera.is_stream_active",
  424. return_value=True,
  425. ),
  426. patch(
  427. "backend.app.api.routes.camera.try_get_active_buffered_frame",
  428. return_value=FAKE_JPEG,
  429. ),
  430. patch(
  431. "backend.app.services.camera.capture_camera_frame_bytes",
  432. new=AsyncMock(return_value=b"FRESH-CAPTURE-SHOULD-NOT-BE-USED"),
  433. ) as mock_fresh,
  434. ):
  435. result = await svc._capture_frame(printer_id=1)
  436. assert result == FAKE_JPEG
  437. mock_fresh.assert_not_called()
  438. @pytest.mark.asyncio
  439. async def test_skips_poll_when_stream_active_but_buffer_empty(self):
  440. """#1348: viewer attached + buffer empty must NOT open a competing socket."""
  441. printer = MagicMock(
  442. external_camera_enabled=False,
  443. external_camera_url=None,
  444. ip_address="192.168.1.10",
  445. access_code="12345678",
  446. model="X1C",
  447. )
  448. mock_session = MagicMock()
  449. mock_session.get = AsyncMock(return_value=printer)
  450. mock_ctx = MagicMock()
  451. mock_ctx.__aenter__ = AsyncMock(return_value=mock_session)
  452. mock_ctx.__aexit__ = AsyncMock(return_value=None)
  453. svc = ObicoDetectionService()
  454. with (
  455. patch("backend.app.services.obico_detection.async_session", return_value=mock_ctx),
  456. patch(
  457. "backend.app.api.routes.camera.is_stream_active",
  458. return_value=True,
  459. ),
  460. patch(
  461. "backend.app.api.routes.camera.try_get_active_buffered_frame",
  462. return_value=None, # Stream active, but first frame not buffered yet
  463. ),
  464. patch(
  465. "backend.app.services.camera.capture_camera_frame_bytes",
  466. new=AsyncMock(return_value=b"FRESH-CAPTURE-WOULD-KICK-VIEWER"),
  467. ) as mock_fresh,
  468. ):
  469. result = await svc._capture_frame(printer_id=1)
  470. assert result is None, "must skip this poll cycle, not open a competing socket"
  471. mock_fresh.assert_not_called()
  472. @pytest.mark.asyncio
  473. async def test_falls_back_to_fresh_capture_when_no_stream(self):
  474. printer = MagicMock(
  475. external_camera_enabled=False,
  476. external_camera_url=None,
  477. ip_address="192.168.1.10",
  478. access_code="12345678",
  479. model="N6",
  480. )
  481. mock_session = MagicMock()
  482. mock_session.get = AsyncMock(return_value=printer)
  483. mock_ctx = MagicMock()
  484. mock_ctx.__aenter__ = AsyncMock(return_value=mock_session)
  485. mock_ctx.__aexit__ = AsyncMock(return_value=None)
  486. svc = ObicoDetectionService()
  487. with (
  488. patch("backend.app.services.obico_detection.async_session", return_value=mock_ctx),
  489. patch(
  490. "backend.app.api.routes.camera.is_stream_active",
  491. return_value=False,
  492. ),
  493. patch(
  494. "backend.app.services.camera.capture_camera_frame_bytes",
  495. new=AsyncMock(return_value=FAKE_JPEG),
  496. ) as mock_fresh,
  497. ):
  498. result = await svc._capture_frame(printer_id=1)
  499. assert result == FAKE_JPEG
  500. mock_fresh.assert_called_once()
  501. class TestFrameCache:
  502. """One-shot JPEG cache that lets us sidestep Obico's 5s read timeout.
  503. Obico's ML API fetches snapshots via `GET /p/?img=URL` with `timeout=(0.1, 5)`.
  504. Our /camera/snapshot can exceed that on cold calls (RTSP keyframe wait). So the
  505. detection loop captures locally, stashes the JPEG bytes under a nonce, then hands
  506. Obico a URL that returns those bytes instantly. The cache is single-use + TTLed
  507. so a leaked nonce can't be replayed.
  508. """
  509. def setup_method(self):
  510. _frame_cache.clear()
  511. @pytest.mark.asyncio
  512. async def test_stash_and_pop_roundtrip(self):
  513. nonce = await stash_frame(FAKE_JPEG)
  514. assert nonce # non-empty URL-safe token
  515. data = await pop_frame(nonce)
  516. assert data == FAKE_JPEG
  517. @pytest.mark.asyncio
  518. async def test_nonce_is_single_use(self):
  519. nonce = await stash_frame(FAKE_JPEG)
  520. assert await pop_frame(nonce) == FAKE_JPEG
  521. # Second pop returns None — caches replay protection
  522. assert await pop_frame(nonce) is None
  523. @pytest.mark.asyncio
  524. async def test_unknown_nonce_returns_none(self):
  525. assert await pop_frame("not-a-real-nonce") is None
  526. @pytest.mark.asyncio
  527. async def test_stash_produces_unique_nonces(self):
  528. nonces = {await stash_frame(FAKE_JPEG) for _ in range(10)}
  529. assert len(nonces) == 10
  530. @pytest.mark.asyncio
  531. async def test_expired_entries_are_pruned_on_stash(self):
  532. """New entries trigger pruning of TTL-expired ones — prevents unbounded growth."""
  533. # Manually seed an entry with a stale timestamp
  534. import time as time_module
  535. _frame_cache["stale-nonce"] = (FAKE_JPEG, time_module.monotonic() - FRAME_CACHE_TTL - 1)
  536. await stash_frame(FAKE_JPEG)
  537. # Stale entry was pruned
  538. assert "stale-nonce" not in _frame_cache
  539. @pytest.mark.asyncio
  540. async def test_pop_rejects_expired_nonce(self):
  541. """Even if the entry is still in the dict, an expired TTL returns None."""
  542. import time as time_module
  543. _frame_cache["aging-nonce"] = (FAKE_JPEG, time_module.monotonic() - FRAME_CACHE_TTL - 1)
  544. assert await pop_frame("aging-nonce") is None
  545. class TestCheckPrinterUsesCachedFrameUrl:
  546. """The URL sent to Obico must point at our nonce endpoint, not /camera/snapshot."""
  547. def setup_method(self):
  548. _frame_cache.clear()
  549. @pytest.mark.asyncio
  550. async def test_ml_api_called_with_cached_frame_url(self):
  551. svc = ObicoDetectionService()
  552. settings = {
  553. "enabled": True,
  554. "ml_url": "http://obico:3333",
  555. "sensitivity": "medium",
  556. "action": "notify",
  557. "poll_interval": 10,
  558. "enabled_printers": None,
  559. "external_url": "http://bambuddy:8000",
  560. }
  561. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  562. mock_response = MagicMock()
  563. mock_response.json.return_value = {"detections": []}
  564. mock_response.raise_for_status = MagicMock()
  565. mock_client = MagicMock()
  566. mock_client.get = AsyncMock(return_value=mock_response)
  567. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  568. mock_client.__aexit__ = AsyncMock(return_value=False)
  569. with (
  570. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  571. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  572. ):
  573. await svc._check_printer(1, status, settings)
  574. # ML API was called via GET (Obico's /p/ is GET-only)
  575. mock_client.get.assert_called_once()
  576. _args, kwargs = mock_client.get.call_args
  577. assert _args[0] == "http://obico:3333/p/"
  578. img_url = kwargs["params"]["img"]
  579. assert img_url.startswith("http://bambuddy:8000/api/v1/obico/cached-frame/")
  580. # The path segment after /cached-frame/ is the nonce itself — that nonce must
  581. # resolve back to our stashed frame (single-use guarantees freshness).
  582. nonce = img_url.rsplit("/", 1)[-1]
  583. assert await pop_frame(nonce) == FAKE_JPEG
  584. @pytest.mark.asyncio
  585. async def test_capture_failure_skips_ml_call(self):
  586. """If we can't capture a frame, don't bother the ML API."""
  587. svc = ObicoDetectionService()
  588. settings = {
  589. "enabled": True,
  590. "ml_url": "http://obico:3333",
  591. "sensitivity": "medium",
  592. "action": "notify",
  593. "poll_interval": 10,
  594. "enabled_printers": None,
  595. "external_url": "http://bambuddy:8000",
  596. }
  597. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  598. mock_client = MagicMock()
  599. mock_client.get = AsyncMock()
  600. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  601. mock_client.__aexit__ = AsyncMock(return_value=False)
  602. with (
  603. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  604. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=None)),
  605. ):
  606. await svc._check_printer(1, status, settings)
  607. mock_client.get.assert_not_called()
  608. assert svc._last_error is not None
  609. assert "Failed to capture snapshot" in svc._last_error
  610. @pytest.mark.asyncio
  611. async def test_missing_external_url_skips_ml_call(self):
  612. """Without external_url, Obico can't reach our cached-frame endpoint."""
  613. svc = ObicoDetectionService()
  614. settings = {
  615. "enabled": True,
  616. "ml_url": "http://obico:3333",
  617. "sensitivity": "medium",
  618. "action": "notify",
  619. "poll_interval": 10,
  620. "enabled_printers": None,
  621. "external_url": "",
  622. }
  623. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  624. mock_client = MagicMock()
  625. mock_client.get = AsyncMock()
  626. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  627. mock_client.__aexit__ = AsyncMock(return_value=False)
  628. with (
  629. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  630. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  631. ):
  632. await svc._check_printer(1, status, settings)
  633. mock_client.get.assert_not_called()
  634. assert svc._last_error is not None
  635. assert "external_url" in svc._last_error
  636. @pytest.mark.asyncio
  637. async def test_successful_cycle_clears_previous_error(self):
  638. """A cold-start RTSP timeout sets _last_error; the next successful poll must clear it.
  639. Regression for #172: the Status card banner ("Failed to capture snapshot for
  640. printer 1") stuck around after a one-off cold-start failure even though every
  641. subsequent poll captured + detected successfully.
  642. """
  643. svc = ObicoDetectionService()
  644. settings = {
  645. "enabled": True,
  646. "ml_url": "http://obico:3333",
  647. "sensitivity": "medium",
  648. "action": "notify",
  649. "poll_interval": 10,
  650. "enabled_printers": None,
  651. "external_url": "http://bambuddy:8000",
  652. }
  653. status = MagicMock(state="RUNNING", task_name="job", subtask_name="")
  654. # Seed a prior transient error, as would be left by a cold-start capture timeout.
  655. svc._last_error = "Failed to capture snapshot for printer 1"
  656. mock_response = MagicMock()
  657. mock_response.json.return_value = {"detections": []}
  658. mock_response.raise_for_status = MagicMock()
  659. mock_client = MagicMock()
  660. mock_client.get = AsyncMock(return_value=mock_response)
  661. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  662. mock_client.__aexit__ = AsyncMock(return_value=False)
  663. with (
  664. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=mock_client),
  665. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  666. ):
  667. await svc._check_printer(1, status, settings)
  668. assert svc._last_error is None
  669. class TestNoVerdictIsNotSafe:
  670. """A printer nothing is looking at must not report itself as safe (#2952).
  671. ``get_per_printer`` used to default to ``"safe"`` whenever no verdict had
  672. been recorded, and the state entry is created when the print is first seen —
  673. before the first capture, let alone the first inference. So a rejected token,
  674. an unreachable ML API, a camera that never yields a frame and an unset
  675. External URL all rendered as a green "Safe" badge at score 0.000, identical
  676. to a healthy monitored print.
  677. The reporter of #2952 read exactly that, concluded the detection loop had
  678. never started, and spent an evening on the network path — while the loop was
  679. calling the ML API every 10s and being turned away with a 401 that Obico's
  680. auth decorator rejects before its own request log ever sees it.
  681. """
  682. SETTINGS = {
  683. "enabled": True,
  684. "ml_url": "http://obico:3333",
  685. "ml_token": "wrong-token",
  686. "sensitivity": "medium",
  687. "action": "notify",
  688. "poll_interval": 10,
  689. "enabled_printers": None,
  690. "external_url": "http://bambuddy:8000",
  691. }
  692. @staticmethod
  693. def _status():
  694. return MagicMock(state="RUNNING", task_name="job", subtask_name="")
  695. @staticmethod
  696. def _client(**kwargs):
  697. client = MagicMock()
  698. client.get = AsyncMock(**kwargs)
  699. client.__aenter__ = AsyncMock(return_value=client)
  700. client.__aexit__ = AsyncMock(return_value=False)
  701. return client
  702. @pytest.mark.asyncio
  703. async def test_rejected_token_reports_error_and_names_the_setting(self):
  704. svc = ObicoDetectionService()
  705. response = MagicMock(status_code=401)
  706. with (
  707. patch(
  708. "backend.app.services.obico_detection.httpx.AsyncClient",
  709. return_value=self._client(return_value=response),
  710. ),
  711. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  712. ):
  713. await svc._check_printer(1, self._status(), self.SETTINGS)
  714. entry = svc.get_per_printer()[1]
  715. assert entry["class"] == "error"
  716. assert "ML API Token" in entry["error"]
  717. assert entry["frame_count"] == 0
  718. @pytest.mark.asyncio
  719. async def test_unreachable_ml_api_reports_error(self):
  720. svc = ObicoDetectionService()
  721. with (
  722. patch(
  723. "backend.app.services.obico_detection.httpx.AsyncClient",
  724. return_value=self._client(side_effect=RuntimeError("connection refused")),
  725. ),
  726. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  727. ):
  728. await svc._check_printer(1, self._status(), self.SETTINGS)
  729. entry = svc.get_per_printer()[1]
  730. assert entry["class"] == "error"
  731. assert "connection refused" in entry["error"]
  732. @pytest.mark.asyncio
  733. async def test_failed_capture_reports_error(self):
  734. svc = ObicoDetectionService()
  735. with patch.object(svc, "_capture_frame", new=AsyncMock(return_value=None)):
  736. await svc._check_printer(1, self._status(), self.SETTINGS)
  737. entry = svc.get_per_printer()[1]
  738. assert entry["class"] == "error"
  739. assert "capture" in entry["error"].lower()
  740. @pytest.mark.asyncio
  741. async def test_missing_external_url_reports_error(self):
  742. svc = ObicoDetectionService()
  743. settings = {**self.SETTINGS, "external_url": ""}
  744. with patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)):
  745. await svc._check_printer(1, self._status(), settings)
  746. entry = svc.get_per_printer()[1]
  747. assert entry["class"] == "error"
  748. assert "External URL" in entry["error"]
  749. @pytest.mark.asyncio
  750. async def test_a_recovered_printer_goes_back_to_a_real_verdict(self):
  751. """The error must not stick once polling works again — otherwise the
  752. badge trades one permanent lie for another."""
  753. svc = ObicoDetectionService()
  754. with patch.object(svc, "_capture_frame", new=AsyncMock(return_value=None)):
  755. await svc._check_printer(1, self._status(), self.SETTINGS)
  756. assert svc.get_per_printer()[1]["class"] == "error"
  757. ok = MagicMock(status_code=200)
  758. ok.json.return_value = {"detections": []}
  759. ok.raise_for_status = MagicMock()
  760. with (
  761. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=self._client(return_value=ok)),
  762. patch.object(svc, "_capture_frame", new=AsyncMock(return_value=FAKE_JPEG)),
  763. ):
  764. await svc._check_printer(1, self._status(), self.SETTINGS)
  765. entry = svc.get_per_printer()[1]
  766. assert entry["class"] == "safe"
  767. assert entry["error"] is None
  768. assert entry["frame_count"] == 1
  769. @pytest.mark.asyncio
  770. async def test_state_exists_before_the_first_inference_reports_unknown(self):
  771. """The window between "print seen" and "first result" is not safe either."""
  772. from backend.app.services.obico_smoothing import PrintState
  773. svc = ObicoDetectionService()
  774. svc._states[1] = PrintState()
  775. svc._state_keys[1] = "job"
  776. entry = svc.get_per_printer()[1]
  777. assert entry["class"] == "unknown"
  778. assert entry["error"] is None
  779. @pytest.mark.asyncio
  780. async def test_error_is_cleared_when_the_print_ends(self):
  781. """A stale error must not carry into the next print's first poll."""
  782. svc = ObicoDetectionService()
  783. with patch.object(svc, "_capture_frame", new=AsyncMock(return_value=None)):
  784. await svc._check_printer(1, self._status(), self.SETTINGS)
  785. assert 1 in svc._errors
  786. idle = MagicMock(state="IDLE", task_name="", subtask_name="")
  787. manager = MagicMock()
  788. manager.get_all_statuses.return_value = {1: idle}
  789. manager.is_connected.return_value = True
  790. with patch.dict(
  791. "sys.modules",
  792. {"backend.app.services.printer_manager": MagicMock(printer_manager=manager)},
  793. ):
  794. await svc._poll_once(self.SETTINGS)
  795. assert svc._errors == {}
  796. assert svc._last_class == {}
  797. assert svc.get_per_printer() == {}