test_routes.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import sys
  2. import os
  3. import threading
  4. import time
  5. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  6. from unittest.mock import MagicMock
  7. import cv2
  8. import numpy as np
  9. import pytest
  10. from pathlib import Path
  11. from fastapi.testclient import TestClient
  12. from app import create_app
  13. import web.state as _web_state_module
  14. @pytest.fixture
  15. def client():
  16. app = create_app(test_mode=True)
  17. return TestClient(app)
  18. @pytest.fixture
  19. def client_with_mocks():
  20. app = create_app(test_mode=True)
  21. client = TestClient(app)
  22. scanner = MagicMock()
  23. scanner.run.return_value = {
  24. "samples": [],
  25. "panorama_path": None,
  26. "config": {},
  27. }
  28. scheduler = MagicMock()
  29. ptz = MagicMock()
  30. ptz_stream = MagicMock()
  31. ptz_stream.get_frame.return_value = np.zeros((100, 100, 3), dtype=np.uint8)
  32. stream_manager = MagicMock()
  33. stream_manager.get.return_value = ptz_stream
  34. _web_state_module.web_state.scanners["group_1"] = scanner
  35. _web_state_module.web_state.schedulers["group_1"] = scheduler
  36. _web_state_module.web_state.ptz_cameras["group_1"] = ptz
  37. _web_state_module.web_state.stream_manager = stream_manager
  38. return client, scanner, scheduler, ptz, ptz_stream
  39. def test_status_endpoint(client):
  40. response = client.get("/api/status")
  41. assert response.status_code == 200
  42. assert "groups" in response.json()
  43. def test_add_and_list_points(client):
  44. response = client.post("/api/points/group_1", json={
  45. "pan": 30.0,
  46. "tilt": 0.0,
  47. "zoom": 1,
  48. "dwell_time": 3.0,
  49. })
  50. assert response.status_code == 200
  51. data = response.json()
  52. assert data["pan"] == 30.0
  53. response = client.get("/api/points/group_1")
  54. assert response.status_code == 200
  55. points = response.json()["points"]
  56. assert len(points) == 1
  57. def test_add_point_validation(client):
  58. response = client.post("/api/points/group_1", json={
  59. "pan": 400.0,
  60. "tilt": 0.0,
  61. "zoom": 1,
  62. "dwell_time": 3.0,
  63. })
  64. assert response.status_code == 422
  65. def test_delete_point(client):
  66. response = client.post("/api/points/group_1", json={
  67. "pan": 60.0,
  68. "tilt": 10.0,
  69. "zoom": 1,
  70. "dwell_time": 2.0,
  71. })
  72. point_id = response.json()["id"]
  73. response = client.delete(f"/api/points/group_1/{point_id}")
  74. assert response.status_code == 200
  75. response = client.get("/api/points/group_1")
  76. assert len(response.json()["points"]) == 0
  77. def test_static_index(client):
  78. response = client.get("/")
  79. assert response.status_code == 200
  80. assert "text/html" in response.headers["content-type"]
  81. def test_panorama_not_found(client):
  82. response = client.get("/api/panorama/group_1")
  83. assert response.status_code == 404
  84. def test_scan_start_returns_202(client_with_mocks):
  85. client, scanner, _, _, _ = client_with_mocks
  86. started = threading.Event()
  87. def run_with_event(*args, **kwargs):
  88. started.set()
  89. return scanner.run.return_value
  90. scanner.run.side_effect = run_with_event
  91. response = client.post("/api/scan/group_1")
  92. assert response.status_code == 202
  93. assert response.json()["group_id"] == "group_1"
  94. deadline = time.time() + 2.0
  95. while time.time() < deadline and not started.is_set():
  96. time.sleep(0.01)
  97. assert started.is_set(), "Scanner run() was not invoked"
  98. def test_scan_uses_full_vertical_range(client_with_mocks):
  99. """360° 扫描应覆盖 -90° 到 +90° 的完整上下范围。"""
  100. client, scanner, _, _, _ = client_with_mocks
  101. started = threading.Event()
  102. def run_with_event(*args, **kwargs):
  103. started.set()
  104. return scanner.run.return_value
  105. scanner.run.side_effect = run_with_event
  106. response = client.post("/api/scan/group_1")
  107. assert response.status_code == 202
  108. deadline = time.time() + 2.0
  109. while time.time() < deadline and not started.is_set():
  110. time.sleep(0.01)
  111. assert started.is_set(), "Scanner run() was not invoked"
  112. _, kwargs = scanner.run.call_args
  113. tilt_layers = kwargs.get("tilt_layers", ())
  114. assert min(tilt_layers) == -60
  115. assert max(tilt_layers) == 60
  116. def test_poll_start_and_stop(client_with_mocks):
  117. client, _, scheduler, _, _ = client_with_mocks
  118. response = client.post("/api/poll/group_1/start")
  119. assert response.status_code == 200
  120. scheduler.start.assert_called_once()
  121. response = client.post("/api/poll/group_1/stop")
  122. assert response.status_code == 200
  123. scheduler.stop.assert_called_once()
  124. def test_live_stream_not_found(client):
  125. response = client.get("/api/live/panorama/group_1")
  126. assert response.status_code == 404
  127. def test_static_css_served(client):
  128. response = client.get("/static/style.css")
  129. assert response.status_code == 200
  130. assert "text/css" in response.headers["content-type"]
  131. def test_static_js_served(client):
  132. response = client.get("/static/app.js")
  133. assert response.status_code == 200
  134. assert "javascript" in response.headers["content-type"]
  135. def test_mutating_endpoints_require_api_key(client_with_mocks, monkeypatch):
  136. client, scanner, scheduler, _, _ = client_with_mocks
  137. monkeypatch.setattr("web.auth.DEVICE_CONFIG", {"api_key": "secret123"})
  138. # Scan
  139. response = client.post("/api/scan/group_1")
  140. assert response.status_code == 401
  141. # Poll start/stop
  142. response = client.post("/api/poll/group_1/start")
  143. assert response.status_code == 401
  144. response = client.post("/api/poll/group_1/stop")
  145. assert response.status_code == 401
  146. # Points add/delete
  147. response = client.post("/api/points/group_1", json={"pan": 30, "tilt": 0})
  148. assert response.status_code == 401
  149. response = client.delete("/api/points/group_1/1")
  150. assert response.status_code == 401
  151. scanner.run.assert_not_called()
  152. scheduler.start.assert_not_called()
  153. def test_mutating_endpoints_accept_api_key(client_with_mocks, monkeypatch):
  154. client, scanner, scheduler, _, _ = client_with_mocks
  155. monkeypatch.setattr("web.auth.DEVICE_CONFIG", {"api_key": "secret123"})
  156. response = client.post(
  157. "/api/poll/group_1/start",
  158. headers={"X-API-Key": "secret123"},
  159. )
  160. assert response.status_code == 200
  161. scheduler.start.assert_called_once()
  162. def test_readonly_endpoints_remain_open_with_api_key(client, monkeypatch):
  163. monkeypatch.setattr("web.auth.DEVICE_CONFIG", {"api_key": "secret123"})
  164. response = client.get("/api/status")
  165. assert response.status_code == 200
  166. response = client.get("/api/points/group_1")
  167. assert response.status_code == 200
  168. response = client.get("/api/scan/group_1/progress")
  169. assert response.status_code == 200
  170. def test_preview_does_not_update_saved_point_image(client_with_mocks):
  171. """点球机预览只临时抓拍并显示,不应更新保存点的 preview_image。"""
  172. client, _, _, _, _ = client_with_mocks
  173. # 创建一个带有固定 preview_image 的保存点
  174. response = client.post("/api/points/group_1", json={
  175. "pan": 30.0,
  176. "tilt": 0.0,
  177. "zoom": 1,
  178. "dwell_time": 3.0,
  179. "preview_image": "data/previews/group_1/existing.jpg",
  180. })
  181. assert response.status_code == 200
  182. point_id = response.json()["id"]
  183. response = client.post("/api/preview/group_1", json={
  184. "pan": 30.0,
  185. "tilt": 0.0,
  186. "zoom": 1,
  187. "point_id": point_id,
  188. })
  189. assert response.status_code == 200
  190. assert response.json()["snapshot_url"] is not None
  191. response = client.get(f"/api/points/group_1")
  192. assert response.status_code == 200
  193. point = next(p for p in response.json()["points"] if p["id"] == point_id)
  194. # 保存点的 preview_image 应保持原值,不被预览抓拍覆盖
  195. assert point["preview_image"] == "data/previews/group_1/existing.jpg"
  196. def test_list_samples_returns_scan_samples(client_with_mocks):
  197. client, _, _, _, _ = client_with_mocks
  198. samples = [
  199. {"id": 1, "pan": 0.0, "tilt": 0.0, "zoom": 1, "thumbnail": "data/group_1/samples/p0_t0.jpg"},
  200. {"id": 2, "pan": 30.0, "tilt": -10.0, "zoom": 1, "thumbnail": "data/group_1/samples/p30_t-10.jpg"},
  201. ]
  202. _web_state_module.web_state.scan_store.set_samples("group_1", samples)
  203. response = client.get("/api/samples/group_1")
  204. assert response.status_code == 200
  205. data = response.json()
  206. assert len(data["samples"]) == 2
  207. assert data["samples"][0]["pan"] == 0.0
  208. assert data["samples"][1]["pan"] == 30.0
  209. def test_sample_image_serves_file_and_rejects_traversal(client_with_mocks, tmp_path):
  210. client, _, _, _, _ = client_with_mocks
  211. sample_dir = Path("data/group_1/samples")
  212. sample_dir.mkdir(parents=True, exist_ok=True)
  213. sample_path = sample_dir / "test.jpg"
  214. cv2.imwrite(str(sample_path), np.zeros((20, 20, 3), dtype=np.uint8))
  215. response = client.get("/api/sample-image?path=data/group_1/samples/test.jpg")
  216. assert response.status_code == 200
  217. assert int(response.headers["content-length"]) > 0
  218. response = client.get("/api/sample-image?path=data/group_1/samples/missing.jpg")
  219. assert response.status_code == 404
  220. response = client.get("/api/sample-image?path=../../etc/passwd")
  221. assert response.status_code == 400