test_camera_api.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. """Integration tests for Camera API endpoints.
  2. Tests the full request/response cycle for /api/v1/printers/{id}/camera/ endpoints.
  3. """
  4. from unittest.mock import AsyncMock, MagicMock, patch
  5. import pytest
  6. from httpx import AsyncClient
  7. class TestCameraAPI:
  8. """Integration tests for /api/v1/printers/{id}/camera/ endpoints."""
  9. # ========================================================================
  10. # Camera Stop Endpoint
  11. # ========================================================================
  12. @pytest.mark.asyncio
  13. @pytest.mark.integration
  14. async def test_stop_camera_stream_get(self, async_client: AsyncClient, printer_factory):
  15. """Verify camera stop endpoint works with GET method."""
  16. printer = await printer_factory()
  17. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/stop")
  18. assert response.status_code == 200
  19. result = response.json()
  20. assert "stopped" in result
  21. assert isinstance(result["stopped"], int)
  22. @pytest.mark.asyncio
  23. @pytest.mark.integration
  24. async def test_stop_camera_stream_post(self, async_client: AsyncClient, printer_factory):
  25. """Verify camera stop endpoint works with POST method (sendBeacon compatibility)."""
  26. printer = await printer_factory()
  27. response = await async_client.post(f"/api/v1/printers/{printer.id}/camera/stop")
  28. assert response.status_code == 200
  29. result = response.json()
  30. assert "stopped" in result
  31. assert isinstance(result["stopped"], int)
  32. @pytest.mark.asyncio
  33. @pytest.mark.integration
  34. async def test_stop_camera_stream_no_active_streams(self, async_client: AsyncClient, printer_factory):
  35. """Verify stop returns 0 when no active streams exist."""
  36. printer = await printer_factory()
  37. response = await async_client.post(f"/api/v1/printers/{printer.id}/camera/stop")
  38. assert response.status_code == 200
  39. assert response.json()["stopped"] == 0
  40. @pytest.mark.asyncio
  41. @pytest.mark.integration
  42. async def test_stop_camera_stream_with_active_stream(self, async_client: AsyncClient, printer_factory):
  43. """Verify stop terminates active streams for the printer."""
  44. printer = await printer_factory()
  45. # Mock an active stream — wait() must be AsyncMock since it's awaited
  46. mock_process = MagicMock()
  47. mock_process.returncode = None
  48. mock_process.pid = 99999
  49. mock_process.terminate = MagicMock()
  50. mock_process.wait = AsyncMock()
  51. with patch("backend.app.api.routes.camera._active_streams", {f"{printer.id}-abc123": mock_process}):
  52. response = await async_client.post(f"/api/v1/printers/{printer.id}/camera/stop")
  53. assert response.status_code == 200
  54. assert response.json()["stopped"] == 1
  55. mock_process.terminate.assert_called_once()
  56. @pytest.mark.asyncio
  57. @pytest.mark.integration
  58. async def test_stop_camera_stream_only_stops_matching_printer(self, async_client: AsyncClient, printer_factory):
  59. """Verify stop only terminates streams for the specified printer."""
  60. printer1 = await printer_factory(name="Printer 1")
  61. printer2 = await printer_factory(name="Printer 2")
  62. # Mock active streams for both printers — wait() must be AsyncMock since it's awaited
  63. mock_process1 = MagicMock()
  64. mock_process1.returncode = None
  65. mock_process1.pid = 99998
  66. mock_process1.terminate = MagicMock()
  67. mock_process1.wait = AsyncMock()
  68. mock_process2 = MagicMock()
  69. mock_process2.returncode = None
  70. mock_process2.pid = 99997
  71. mock_process2.terminate = MagicMock()
  72. mock_process2.wait = AsyncMock()
  73. active_streams = {
  74. f"{printer1.id}-abc123": mock_process1,
  75. f"{printer2.id}-def456": mock_process2,
  76. }
  77. with patch("backend.app.api.routes.camera._active_streams", active_streams):
  78. response = await async_client.post(f"/api/v1/printers/{printer1.id}/camera/stop")
  79. assert response.status_code == 200
  80. assert response.json()["stopped"] == 1
  81. mock_process1.terminate.assert_called_once()
  82. mock_process2.terminate.assert_not_called()
  83. @pytest.mark.asyncio
  84. @pytest.mark.integration
  85. async def test_stop_camera_stream_handles_fanout_stream_id(self, async_client: AsyncClient, printer_factory):
  86. """Stop must terminate streams keyed with the deterministic
  87. ``{printer_id}-fanout`` id used by the fan-out broadcaster (#1089).
  88. Regression guard against the prefix-match drifting away from the
  89. broadcaster's stream-id convention.
  90. """
  91. printer = await printer_factory()
  92. mock_process = MagicMock()
  93. mock_process.returncode = None
  94. mock_process.pid = 99996
  95. mock_process.terminate = MagicMock()
  96. mock_process.wait = AsyncMock()
  97. with patch(
  98. "backend.app.api.routes.camera._active_streams",
  99. {f"{printer.id}-fanout": mock_process},
  100. ):
  101. response = await async_client.post(f"/api/v1/printers/{printer.id}/camera/stop")
  102. assert response.status_code == 200
  103. assert response.json()["stopped"] == 1
  104. mock_process.terminate.assert_called_once()
  105. @pytest.mark.asyncio
  106. @pytest.mark.integration
  107. async def test_stop_camera_stream_invokes_broadcaster_shutdown(self, async_client: AsyncClient, printer_factory):
  108. """Stop must call ``shutdown_broadcaster`` so subscribers wake up via
  109. the upstream-gone sentinel rather than stalling on the queue (#1089)."""
  110. printer = await printer_factory()
  111. with patch(
  112. "backend.app.api.routes.camera.shutdown_broadcaster",
  113. AsyncMock(return_value=False),
  114. ) as mock_shutdown:
  115. response = await async_client.post(f"/api/v1/printers/{printer.id}/camera/stop")
  116. assert response.status_code == 200
  117. mock_shutdown.assert_awaited_once_with(f"printer-{printer.id}")
  118. # ========================================================================
  119. # Camera Test Endpoint
  120. # ========================================================================
  121. @pytest.mark.asyncio
  122. @pytest.mark.integration
  123. async def test_camera_test_printer_not_found(self, async_client: AsyncClient):
  124. """Verify 404 when testing camera for non-existent printer."""
  125. response = await async_client.get("/api/v1/printers/99999/camera/test")
  126. assert response.status_code == 404
  127. assert "not found" in response.json()["detail"].lower()
  128. @pytest.mark.asyncio
  129. @pytest.mark.integration
  130. async def test_camera_test_success(self, async_client: AsyncClient, printer_factory):
  131. """Verify camera test returns success when camera is accessible."""
  132. printer = await printer_factory()
  133. with patch("backend.app.api.routes.camera.test_camera_connection", new_callable=AsyncMock) as mock_test:
  134. mock_test.return_value = {"success": True, "message": "Camera connected"}
  135. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/test")
  136. assert response.status_code == 200
  137. result = response.json()
  138. assert result["success"] is True
  139. @pytest.mark.asyncio
  140. @pytest.mark.integration
  141. async def test_camera_test_failure(self, async_client: AsyncClient, printer_factory):
  142. """Verify camera test returns failure when camera is not accessible."""
  143. printer = await printer_factory()
  144. with patch("backend.app.api.routes.camera.test_camera_connection", new_callable=AsyncMock) as mock_test:
  145. mock_test.return_value = {"success": False, "message": "Connection timeout"}
  146. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/test")
  147. assert response.status_code == 200
  148. result = response.json()
  149. assert result["success"] is False
  150. # ========================================================================
  151. # Camera Snapshot Endpoint
  152. # ========================================================================
  153. @pytest.mark.asyncio
  154. @pytest.mark.integration
  155. async def test_camera_snapshot_printer_not_found(self, async_client: AsyncClient):
  156. """Verify 404 when capturing snapshot for non-existent printer."""
  157. response = await async_client.get("/api/v1/printers/99999/camera/snapshot")
  158. assert response.status_code == 404
  159. @pytest.mark.asyncio
  160. @pytest.mark.integration
  161. async def test_camera_snapshot_success(self, async_client: AsyncClient, printer_factory):
  162. """Verify snapshot returns JPEG image when successful."""
  163. printer = await printer_factory()
  164. # Create a fake JPEG (starts with FFD8)
  165. fake_jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00"
  166. with patch("backend.app.api.routes.camera.capture_camera_frame", new_callable=AsyncMock) as mock_capture:
  167. mock_capture.return_value = True
  168. # Mock the file read
  169. with patch("builtins.open", create=True) as mock_open:
  170. mock_open.return_value.__enter__.return_value.read.return_value = fake_jpeg
  171. with patch("pathlib.Path.exists", return_value=True), patch("pathlib.Path.unlink"):
  172. _response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/snapshot")
  173. # Note: The actual test might fail due to file operations, but this tests the endpoint structure
  174. # In production tests, we'd mock more comprehensively
  175. @pytest.mark.asyncio
  176. @pytest.mark.integration
  177. async def test_camera_snapshot_failure(self, async_client: AsyncClient, printer_factory):
  178. """Verify 503 when camera capture fails."""
  179. printer = await printer_factory()
  180. with patch("backend.app.api.routes.camera.capture_camera_frame", new_callable=AsyncMock) as mock_capture:
  181. mock_capture.return_value = False
  182. with patch("pathlib.Path.exists", return_value=False), patch("pathlib.Path.unlink"):
  183. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/snapshot")
  184. assert response.status_code == 503
  185. assert "Failed to capture" in response.json()["detail"]
  186. @pytest.mark.asyncio
  187. @pytest.mark.integration
  188. async def test_camera_snapshot_external_camera_success(self, async_client: AsyncClient, printer_factory):
  189. """Verify snapshot uses external camera when configured."""
  190. printer = await printer_factory(
  191. external_camera_enabled=True,
  192. external_camera_url="http://192.168.1.50/mjpeg",
  193. external_camera_type="mjpeg",
  194. )
  195. fake_jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00"
  196. with patch(
  197. "backend.app.services.external_camera.capture_frame",
  198. new_callable=AsyncMock,
  199. return_value=fake_jpeg,
  200. ):
  201. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/snapshot")
  202. assert response.status_code == 200
  203. assert response.headers["content-type"] == "image/jpeg"
  204. assert response.content == fake_jpeg
  205. @pytest.mark.asyncio
  206. @pytest.mark.integration
  207. async def test_camera_snapshot_external_camera_failure(self, async_client: AsyncClient, printer_factory):
  208. """Verify 503 when external camera capture fails."""
  209. printer = await printer_factory(
  210. external_camera_enabled=True,
  211. external_camera_url="http://192.168.1.50/mjpeg",
  212. external_camera_type="mjpeg",
  213. )
  214. with patch(
  215. "backend.app.services.external_camera.capture_frame",
  216. new_callable=AsyncMock,
  217. return_value=None,
  218. ):
  219. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/snapshot")
  220. assert response.status_code == 503
  221. assert "external camera" in response.json()["detail"].lower()
  222. # ========================================================================
  223. # Camera Stream Endpoint
  224. # ========================================================================
  225. @pytest.mark.asyncio
  226. @pytest.mark.integration
  227. async def test_camera_stream_printer_not_found(self, async_client: AsyncClient):
  228. """Verify 404 when streaming camera for non-existent printer."""
  229. response = await async_client.get("/api/v1/printers/99999/camera/stream")
  230. assert response.status_code == 404
  231. @pytest.mark.asyncio
  232. @pytest.mark.integration
  233. async def test_camera_stream_fps_validation(self, async_client: AsyncClient, printer_factory):
  234. """Verify FPS parameter is validated and clamped."""
  235. printer = await printer_factory()
  236. # FPS should be clamped between 1 and 30
  237. # Testing that the endpoint accepts various FPS values without error
  238. # (actual streaming would require mocking ffmpeg)
  239. with patch("backend.app.api.routes.camera.get_ffmpeg_path", return_value=None):
  240. # With no ffmpeg, stream should return error message but not crash
  241. response = await async_client.get(
  242. f"/api/v1/printers/{printer.id}/camera/stream",
  243. params={"fps": 100}, # Should be clamped to 30
  244. )
  245. # Response will be a streaming response with error
  246. assert response.status_code == 200
  247. # ========================================================================
  248. # Plate Detection Endpoints
  249. # ========================================================================
  250. @pytest.mark.asyncio
  251. @pytest.mark.integration
  252. async def test_plate_detection_status_printer_not_found(self, async_client: AsyncClient):
  253. """Verify 404 when checking plate detection status for non-existent printer."""
  254. response = await async_client.get("/api/v1/printers/99999/camera/plate-detection/status")
  255. assert response.status_code == 404
  256. @pytest.mark.asyncio
  257. @pytest.mark.integration
  258. async def test_plate_detection_status_opencv_not_available(self, async_client: AsyncClient, printer_factory):
  259. """Verify plate detection status returns unavailable when OpenCV not installed."""
  260. printer = await printer_factory()
  261. with patch("backend.app.services.plate_detection.OPENCV_AVAILABLE", False):
  262. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/plate-detection/status")
  263. assert response.status_code == 200
  264. result = response.json()
  265. assert result["available"] is False
  266. assert result["calibrated"] is False
  267. @pytest.mark.asyncio
  268. @pytest.mark.integration
  269. async def test_plate_detection_status_success(self, async_client: AsyncClient, printer_factory):
  270. """Verify plate detection status returns correctly when OpenCV available."""
  271. printer = await printer_factory()
  272. # OpenCV is available in test environment, just check the response structure
  273. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/plate-detection/status")
  274. assert response.status_code == 200
  275. result = response.json()
  276. assert "available" in result
  277. assert "calibrated" in result
  278. @pytest.mark.asyncio
  279. @pytest.mark.integration
  280. async def test_check_plate_empty_printer_not_found(self, async_client: AsyncClient):
  281. """Verify 404 when checking plate for non-existent printer."""
  282. response = await async_client.get("/api/v1/printers/99999/camera/check-plate")
  283. assert response.status_code == 404
  284. @pytest.mark.asyncio
  285. @pytest.mark.integration
  286. async def test_check_plate_empty_success_structure(self, async_client: AsyncClient, printer_factory):
  287. """Verify check plate returns proper structure when OpenCV available."""
  288. printer = await printer_factory()
  289. # Mock PlateDetectionResult to avoid camera timeout
  290. mock_result = MagicMock()
  291. mock_result.is_empty = True
  292. mock_result.confidence = 0.95
  293. mock_result.difference_percent = 0.5
  294. mock_result.message = "Plate appears empty"
  295. mock_result.needs_calibration = False
  296. mock_result.debug_image = None
  297. mock_result.to_dict.return_value = {
  298. "is_empty": True,
  299. "confidence": 0.95,
  300. "difference_percent": 0.5,
  301. "message": "Plate appears empty",
  302. "has_debug_image": False,
  303. "needs_calibration": False,
  304. }
  305. # Mock PlateDetector for reference count
  306. mock_detector = MagicMock()
  307. mock_detector.get_calibration_count.return_value = 0
  308. mock_detector.MAX_REFERENCES = 5
  309. with (
  310. patch("backend.app.services.plate_detection.is_plate_detection_available", return_value=True),
  311. patch("backend.app.services.plate_detection.check_plate_empty", new_callable=AsyncMock) as mock_check,
  312. patch("backend.app.services.plate_detection.PlateDetector", return_value=mock_detector),
  313. ):
  314. mock_check.return_value = mock_result
  315. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/check-plate")
  316. assert response.status_code == 200
  317. result = response.json()
  318. assert "is_empty" in result
  319. assert "confidence" in result
  320. assert "message" in result
  321. @pytest.mark.asyncio
  322. @pytest.mark.integration
  323. async def test_calibrate_plate_printer_not_found(self, async_client: AsyncClient):
  324. """Verify 404 when calibrating plate for non-existent printer."""
  325. response = await async_client.post("/api/v1/printers/99999/camera/plate-detection/calibrate")
  326. assert response.status_code == 404
  327. @pytest.mark.asyncio
  328. @pytest.mark.integration
  329. async def test_calibrate_plate_success_structure(self, async_client: AsyncClient, printer_factory):
  330. """Verify calibrate endpoint responds with proper structure."""
  331. printer = await printer_factory()
  332. # Mock calibrate_plate at the source module to avoid camera timeout
  333. with (
  334. patch("backend.app.services.plate_detection.is_plate_detection_available", return_value=True),
  335. patch("backend.app.services.plate_detection.calibrate_plate", new_callable=AsyncMock) as mock_calibrate,
  336. ):
  337. mock_calibrate.return_value = (True, "Calibration saved (1/5 references)", 0)
  338. response = await async_client.post(f"/api/v1/printers/{printer.id}/camera/plate-detection/calibrate")
  339. assert response.status_code == 200
  340. result = response.json()
  341. assert result["success"] is True
  342. assert "index" in result
  343. @pytest.mark.asyncio
  344. @pytest.mark.integration
  345. async def test_delete_calibration_printer_not_found(self, async_client: AsyncClient):
  346. """Verify 404 when deleting calibration for non-existent printer."""
  347. response = await async_client.delete("/api/v1/printers/99999/camera/plate-detection/calibrate")
  348. assert response.status_code == 404
  349. @pytest.mark.asyncio
  350. @pytest.mark.integration
  351. async def test_delete_calibration_success(self, async_client: AsyncClient, printer_factory):
  352. """Verify delete calibration returns proper structure."""
  353. printer = await printer_factory()
  354. with patch("backend.app.services.plate_detection.is_plate_detection_available", return_value=True):
  355. response = await async_client.delete(f"/api/v1/printers/{printer.id}/camera/plate-detection/calibrate")
  356. assert response.status_code == 200
  357. result = response.json()
  358. assert "success" in result
  359. assert "message" in result
  360. @pytest.mark.asyncio
  361. @pytest.mark.integration
  362. async def test_get_references_printer_not_found(self, async_client: AsyncClient):
  363. """Verify 404 when getting references for non-existent printer."""
  364. response = await async_client.get("/api/v1/printers/99999/camera/plate-detection/references")
  365. assert response.status_code == 404
  366. @pytest.mark.asyncio
  367. @pytest.mark.integration
  368. async def test_get_references_opencv_not_available(self, async_client: AsyncClient, printer_factory):
  369. """Verify get references returns unavailable when OpenCV not installed."""
  370. printer = await printer_factory()
  371. with patch("backend.app.services.plate_detection.OPENCV_AVAILABLE", False):
  372. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/plate-detection/references")
  373. assert response.status_code == 503
  374. @pytest.mark.asyncio
  375. @pytest.mark.integration
  376. async def test_get_references_success(self, async_client: AsyncClient, printer_factory):
  377. """Verify get references returns proper structure."""
  378. printer = await printer_factory()
  379. # Mock OpenCV availability and PlateDetector
  380. mock_detector = MagicMock()
  381. mock_detector.get_references.return_value = []
  382. mock_detector.MAX_REFERENCES = 5
  383. with (
  384. patch("backend.app.services.plate_detection.is_plate_detection_available", return_value=True),
  385. patch("backend.app.services.plate_detection.PlateDetector", return_value=mock_detector),
  386. ):
  387. response = await async_client.get(f"/api/v1/printers/{printer.id}/camera/plate-detection/references")
  388. assert response.status_code == 200
  389. result = response.json()
  390. assert "references" in result
  391. assert "max_references" in result
  392. assert isinstance(result["references"], list)
  393. @pytest.mark.asyncio
  394. @pytest.mark.integration
  395. async def test_update_reference_label_printer_not_found(self, async_client: AsyncClient):
  396. """Verify 404 when updating reference label for non-existent printer."""
  397. response = await async_client.put(
  398. "/api/v1/printers/99999/camera/plate-detection/references/0", params={"label": "New Label"}
  399. )
  400. assert response.status_code == 404
  401. @pytest.mark.asyncio
  402. @pytest.mark.integration
  403. async def test_delete_reference_printer_not_found(self, async_client: AsyncClient):
  404. """Verify 404 when deleting reference for non-existent printer."""
  405. response = await async_client.delete("/api/v1/printers/99999/camera/plate-detection/references/0")
  406. assert response.status_code == 404
  407. @pytest.mark.asyncio
  408. @pytest.mark.integration
  409. async def test_get_reference_thumbnail_printer_not_found(self, async_client: AsyncClient):
  410. """Verify 404 when getting reference thumbnail for non-existent printer."""
  411. response = await async_client.get("/api/v1/printers/99999/camera/plate-detection/references/0/thumbnail")
  412. assert response.status_code == 404
  413. # ========================================================================
  414. # USB Camera Endpoint
  415. # ========================================================================
  416. @pytest.mark.asyncio
  417. @pytest.mark.integration
  418. async def test_list_usb_cameras_returns_list(self, async_client: AsyncClient):
  419. """Verify USB cameras endpoint returns a list of cameras."""
  420. response = await async_client.get("/api/v1/printers/usb-cameras")
  421. assert response.status_code == 200
  422. result = response.json()
  423. assert "cameras" in result
  424. assert isinstance(result["cameras"], list)
  425. @pytest.mark.asyncio
  426. @pytest.mark.integration
  427. async def test_list_usb_cameras_structure(self, async_client: AsyncClient):
  428. """Verify USB cameras endpoint returns proper structure for each camera."""
  429. with patch("backend.app.services.external_camera.list_usb_cameras") as mock_list:
  430. mock_list.return_value = [
  431. {"device": "/dev/video0", "name": "Logitech Webcam C920", "index": 0},
  432. {"device": "/dev/video2", "name": "USB Camera", "index": 2},
  433. ]
  434. response = await async_client.get("/api/v1/printers/usb-cameras")
  435. assert response.status_code == 200
  436. result = response.json()
  437. assert len(result["cameras"]) == 2
  438. assert result["cameras"][0]["device"] == "/dev/video0"
  439. assert result["cameras"][0]["name"] == "Logitech Webcam C920"
  440. assert result["cameras"][1]["device"] == "/dev/video2"
  441. @pytest.mark.asyncio
  442. @pytest.mark.integration
  443. async def test_list_usb_cameras_empty_on_non_linux(self, async_client: AsyncClient):
  444. """Verify USB cameras endpoint returns empty list on non-Linux systems."""
  445. with patch("backend.app.services.external_camera.list_usb_cameras") as mock_list:
  446. # Simulate non-Linux system (no /dev/video* devices)
  447. mock_list.return_value = []
  448. response = await async_client.get("/api/v1/printers/usb-cameras")
  449. assert response.status_code == 200
  450. result = response.json()
  451. assert result["cameras"] == []