test_obico_api.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """Integration tests for Obico API endpoints (#172 follow-up).
  2. Verifies the /obico/cached-frame/{nonce} endpoint used by Obico's ML API to fetch
  3. pre-captured JPEG frames. This endpoint lets the detection loop sidestep Obico's
  4. hardcoded 5s read timeout by pre-populating a cache before issuing the ML call.
  5. """
  6. import pytest
  7. from httpx import AsyncClient
  8. from backend.app.services.obico_detection import _frame_cache, obico_detection_service, stash_frame
  9. from backend.app.services.obico_smoothing import PrintState
  10. FAKE_JPEG = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xd9"
  11. @pytest.fixture(autouse=True)
  12. def clear_cache():
  13. _frame_cache.clear()
  14. yield
  15. _frame_cache.clear()
  16. class TestObicoCachedFrame:
  17. @pytest.mark.asyncio
  18. @pytest.mark.integration
  19. async def test_valid_nonce_returns_jpeg(self, async_client: AsyncClient):
  20. """A stashed nonce returns the stored JPEG bytes with image/jpeg."""
  21. nonce = await stash_frame(FAKE_JPEG)
  22. response = await async_client.get(f"/api/v1/obico/cached-frame/{nonce}")
  23. assert response.status_code == 200
  24. assert response.headers["content-type"] == "image/jpeg"
  25. assert response.content == FAKE_JPEG
  26. @pytest.mark.asyncio
  27. @pytest.mark.integration
  28. async def test_unknown_nonce_is_404(self, async_client: AsyncClient):
  29. """An unguessable URL must not leak that the endpoint exists — return 404."""
  30. response = await async_client.get("/api/v1/obico/cached-frame/definitely-not-a-real-nonce")
  31. assert response.status_code == 404
  32. @pytest.mark.asyncio
  33. @pytest.mark.integration
  34. async def test_nonce_is_single_use(self, async_client: AsyncClient):
  35. """A second fetch with the same nonce returns 404 — prevents replay."""
  36. nonce = await stash_frame(FAKE_JPEG)
  37. first = await async_client.get(f"/api/v1/obico/cached-frame/{nonce}")
  38. assert first.status_code == 200
  39. second = await async_client.get(f"/api/v1/obico/cached-frame/{nonce}")
  40. assert second.status_code == 404
  41. @pytest.mark.asyncio
  42. @pytest.mark.integration
  43. async def test_endpoint_is_public(self, async_client: AsyncClient):
  44. """Obico's ML API can't send auth headers, so the nonce IS the credential.
  45. The path must be in PUBLIC_API_PATTERNS (no auth wall)."""
  46. nonce = await stash_frame(FAKE_JPEG)
  47. # Intentionally omit any auth headers even if the fixture would normally inject them
  48. response = await async_client.get(
  49. f"/api/v1/obico/cached-frame/{nonce}",
  50. headers={}, # no Authorization header
  51. )
  52. assert response.status_code == 200
  53. @pytest.mark.asyncio
  54. @pytest.mark.integration
  55. async def test_response_is_not_cached(self, async_client: AsyncClient):
  56. """Browsers/proxies must not hold onto the image after Obico consumes it."""
  57. nonce = await stash_frame(FAKE_JPEG)
  58. response = await async_client.get(f"/api/v1/obico/cached-frame/{nonce}")
  59. assert response.status_code == 200
  60. assert "no-store" in response.headers.get("cache-control", "")
  61. class TestObicoPrinterStatus:
  62. """The lightweight /obico/printer-status endpoint for printer-card badges (#1546)."""
  63. @pytest.fixture(autouse=True)
  64. def clear_detection_state(self):
  65. obico_detection_service._states.clear()
  66. obico_detection_service._last_class.clear()
  67. obico_detection_service._errors.clear()
  68. obico_detection_service._last_error = None
  69. yield
  70. obico_detection_service._states.clear()
  71. obico_detection_service._last_class.clear()
  72. obico_detection_service._errors.clear()
  73. obico_detection_service._last_error = None
  74. @pytest.mark.asyncio
  75. @pytest.mark.integration
  76. async def test_returns_per_printer_classification(self, async_client: AsyncClient):
  77. state = PrintState()
  78. state.update(0.5)
  79. obico_detection_service._states[1] = state
  80. obico_detection_service._last_class[1] = "warning"
  81. response = await async_client.get("/api/v1/obico/printer-status")
  82. assert response.status_code == 200
  83. data = response.json()
  84. assert "enabled" in data
  85. # None = all printers monitored (no obico_enabled_printers subset configured)
  86. assert data["monitored_printers"] is None
  87. entry = data["per_printer"]["1"]
  88. assert entry["class"] == "warning"
  89. assert entry["frame_count"] == 1
  90. assert isinstance(entry["score"], float)
  91. @pytest.mark.asyncio
  92. @pytest.mark.integration
  93. async def test_empty_when_nothing_monitored(self, async_client: AsyncClient):
  94. response = await async_client.get("/api/v1/obico/printer-status")
  95. assert response.status_code == 200
  96. assert response.json()["per_printer"] == {}
  97. @pytest.mark.asyncio
  98. @pytest.mark.integration
  99. async def test_monitored_subset_is_returned(self, async_client: AsyncClient):
  100. """A configured obico_enabled_printers subset surfaces (as a sorted list) so
  101. the frontend can show the idle badge only on monitored printers."""
  102. update = await async_client.put("/api/v1/settings/", json={"obico_enabled_printers": "[3, 1]"})
  103. assert update.status_code == 200
  104. try:
  105. response = await async_client.get("/api/v1/obico/printer-status")
  106. assert response.json()["monitored_printers"] == [1, 3]
  107. finally:
  108. await async_client.put("/api/v1/settings/", json={"obico_enabled_printers": ""})
  109. @pytest.mark.asyncio
  110. @pytest.mark.integration
  111. async def test_last_error_is_surfaced(self, async_client: AsyncClient):
  112. """The badge modal shows the service's last error (auth disabled in the
  113. test env, so the settings:read gate on the field is open)."""
  114. obico_detection_service._last_error = "Failed to capture snapshot for printer 1"
  115. response = await async_client.get("/api/v1/obico/printer-status")
  116. assert response.json()["last_error"] == "Failed to capture snapshot for printer 1"
  117. @pytest.mark.asyncio
  118. @pytest.mark.integration
  119. async def test_does_not_leak_settings(self, async_client: AsyncClient):
  120. """Unlike /obico/status, this endpoint is readable with printers:read only,
  121. so it must not expose the ML URL or other configuration."""
  122. response = await async_client.get("/api/v1/obico/printer-status")
  123. data = response.json()
  124. for key in ("ml_url", "action", "history", "poll_interval", "external_url_configured"):
  125. assert key not in data
  126. class TestObicoPrinterStatusNoVerdict:
  127. """A printer whose detection is not working must not read as monitored (#2952)."""
  128. @pytest.fixture(autouse=True)
  129. def clear_detection_state(self):
  130. obico_detection_service._states.clear()
  131. obico_detection_service._last_class.clear()
  132. obico_detection_service._errors.clear()
  133. obico_detection_service._last_error = None
  134. yield
  135. obico_detection_service._states.clear()
  136. obico_detection_service._last_class.clear()
  137. obico_detection_service._errors.clear()
  138. obico_detection_service._last_error = None
  139. @pytest.mark.asyncio
  140. @pytest.mark.integration
  141. async def test_error_class_and_reason_reach_the_card(self, async_client: AsyncClient):
  142. obico_detection_service._states[1] = PrintState()
  143. obico_detection_service._errors[1] = "Obico ML API rejected the token (401)."
  144. response = await async_client.get("/api/v1/obico/printer-status")
  145. entry = response.json()["per_printer"]["1"]
  146. assert entry["class"] == "error"
  147. assert entry["error"] == "Obico ML API rejected the token (401)."
  148. @pytest.mark.asyncio
  149. @pytest.mark.integration
  150. async def test_monitored_but_no_result_yet_is_unknown_not_safe(self, async_client: AsyncClient):
  151. obico_detection_service._states[1] = PrintState()
  152. response = await async_client.get("/api/v1/obico/printer-status")
  153. entry = response.json()["per_printer"]["1"]
  154. assert entry["class"] == "unknown"
  155. assert entry["error"] is None
  156. @pytest.mark.asyncio
  157. @pytest.mark.integration
  158. async def test_reason_is_withheld_without_settings_read_but_the_class_is_not(self):
  159. """The reason can name the ML API base or the External URL, so it stays
  160. behind settings:read. Whether the print is being watched is not
  161. configuration, so a printers:read user still gets the class."""
  162. from unittest.mock import AsyncMock, MagicMock, patch
  163. from backend.app.api.routes.obico import get_printer_status
  164. obico_detection_service._states[1] = PrintState()
  165. obico_detection_service._errors[1] = "ML API call failed: http://192.168.8.9:3333 refused"
  166. user = MagicMock()
  167. user.has_permission.return_value = False
  168. # The route calls _load_settings for the enabled/monitored fields; the
  169. # redaction under test is independent of them.
  170. loaded = {"enabled": True, "enabled_printers": None}
  171. with patch.object(obico_detection_service, "_load_settings", new=AsyncMock(return_value=loaded)):
  172. data = await get_printer_status(user=user)
  173. entry = data["per_printer"][1]
  174. assert entry["class"] == "error"
  175. assert entry["error"] is None
  176. assert data["last_error"] is None
  177. assert "192.168.8.9" not in str(data)