import io from types import SimpleNamespace import pytest from fastapi import FastAPI, HTTPException from fastapi.testclient import TestClient import api.routes.analyze as analyze_routes import api.routes.generate as generate_routes import api.routes.search as search_routes @pytest.fixture() def client(): app = FastAPI() app.include_router(analyze_routes.router, prefix="/api/v1") app.include_router(search_routes.router, prefix="/api/v1") app.include_router(generate_routes.router, prefix="/api/v1") return TestClient(app) def _post_file(client, data: bytes, name: str = "frame.jpg"): return client.post( "/api/v1/analyze-frame", files={"file": (name, io.BytesIO(data), "image/jpeg")}, ) # ─── analyze-frame ─────────────────────────────────────────────────────────── def test_analyze_rejects_empty_upload(client): response = _post_file(client, b"") assert response.status_code == 422 def test_analyze_rejects_oversized_upload(client, monkeypatch): monkeypatch.setattr(analyze_routes, "MAX_UPLOAD_BYTES", 8) response = _post_file(client, b"x" * 9) assert response.status_code == 413 def test_analyze_rejects_invalid_image(client, monkeypatch): def boom(_raw): raise analyze_routes.InvalidImageError("Uploaded file is not a valid image.") monkeypatch.setattr(analyze_routes, "_run_cv_pipeline", boom) response = _post_file(client, b"not-an-image") assert response.status_code == 422 assert response.json()["detail"] == "Uploaded file is not a valid image." def test_analyze_no_face(client, monkeypatch): monkeypatch.setattr( analyze_routes, "_run_cv_pipeline", lambda _raw: { "status": "no_face", "faces_detected": 0, "detection_score": 0.0, "attributes": [], "similarity": 0.0, }, ) response = _post_file(client, b"image") assert response.status_code == 200 body = response.json() assert body["status"] == "no_face_detected" assert body["match_confidence"] is None assert body["faces_detected"] == 0 def test_analyze_no_match_hides_confidence(client, monkeypatch): monkeypatch.setattr( analyze_routes, "_run_cv_pipeline", lambda _raw: { "status": "no_match", "faces_detected": 1, "detection_score": 0.99, "attributes": [], "similarity": 0.31, }, ) response = _post_file(client, b"image") assert response.status_code == 200 body = response.json() assert body["status"] == "no_match_found" assert body["match_confidence"] is None assert body["matched_attributes"] == [] assert "threshold" in body["agent_report"] def test_analyze_success_uses_cosine_confidence(client, monkeypatch): monkeypatch.setattr( analyze_routes, "_run_cv_pipeline", lambda _raw: { "status": "ok", "faces_detected": 1, "detection_score": 0.99, "attributes": ["Male", "Eyeglasses"], "similarity": 0.9812, }, ) async def fake_alert(attributes, similarity): assert attributes == ["Male", "Eyeglasses"] assert similarity == pytest.approx(0.9812) return { "agent_report": "[Test Engine] alert", "cascadeflow_metrics": {"latency_ms": 12.5, "cost_usd": 0.0001}, } monkeypatch.setattr(analyze_routes, "generate_alert", fake_alert) response = _post_file(client, b"image") assert response.status_code == 200 body = response.json() assert body["status"] == "success" assert body["match_confidence"] == pytest.approx(0.9812) assert body["matched_attributes"] == ["Male", "Eyeglasses"] assert body["agent_report"] == "[Test Engine] alert" assert body["cascadeflow_metrics"]["latency_ms"] == 12.5 # ─── semantic-search ───────────────────────────────────────────────────────── def _patch_extraction(monkeypatch, attrs): async def fake_extract(query): return { "attributes": attrs, "cascadeflow_metrics": {"latency_ms": 5.0, "cost_usd": 0.0}, } monkeypatch.setattr(search_routes, "extract_attributes_from_query", fake_extract) def test_semantic_search_no_attributes(client, monkeypatch): _patch_extraction(monkeypatch, []) response = client.post( "/api/v1/semantic-search", json={"query": "alien with three eyes", "top_k": 5}, ) assert response.status_code == 200 assert response.json()["status"] == "no_attributes_extracted" def test_semantic_search_no_matches_status(client, monkeypatch): _patch_extraction(monkeypatch, ["Male", "Eyeglasses"]) monkeypatch.setattr(search_routes, "search_by_attributes", lambda **kwargs: []) response = client.post( "/api/v1/semantic-search", json={"query": "male with eyeglasses", "top_k": 5}, ) assert response.status_code == 200 assert response.json()["status"] == "no_matches_found" assert response.json()["matches"] == [] def test_semantic_search_success(client, monkeypatch): _patch_extraction(monkeypatch, ["Male", "Eyeglasses"]) monkeypatch.setattr( search_routes, "search_by_attributes", lambda **kwargs: [{ "faiss_id": 0, "image_id": "000001.jpg", "attributes": ["Male", "Eyeglasses"], }], ) response = client.post( "/api/v1/semantic-search", json={"query": "male with eyeglasses", "top_k": 5}, ) assert response.status_code == 200 body = response.json() assert body["status"] == "success" assert body["matches"][0]["image_id"] == "000001.jpg" def test_semantic_search_applies_gender_exclusion(client, monkeypatch): async def fake_extract(query): return { "attributes": ["Smiling"], "excluded_attributes": ["Male"], "cascadeflow_metrics": {"latency_ms": 5.0, "cost_usd": 0.0}, } captured = {} def fake_search(**kwargs): captured.update(kwargs) return [{ "faiss_id": 1, "image_id": "000002.jpg", "attributes": ["Smiling", "Young"], }] monkeypatch.setattr(search_routes, "extract_attributes_from_query", fake_extract) monkeypatch.setattr(search_routes, "search_by_attributes", fake_search) response = client.post( "/api/v1/semantic-search", json={"query": "smiling woman", "top_k": 5}, ) assert response.status_code == 200 body = response.json() assert body["status"] == "success" assert body["excluded_attrs"] == ["Male"] assert captured["excluded_attrs"] == ["Male"] assert body["matches"][0]["image_id"] == "000002.jpg" def test_semantic_search_allows_exclusion_only_query(client, monkeypatch): async def fake_extract(query): return { "attributes": [], "excluded_attributes": ["Male"], "cascadeflow_metrics": {"latency_ms": 5.0, "cost_usd": 0.0}, } monkeypatch.setattr(search_routes, "extract_attributes_from_query", fake_extract) monkeypatch.setattr( search_routes, "search_by_attributes", lambda **kwargs: [{ "faiss_id": 1, "image_id": "000002.jpg", "attributes": ["Young"], }], ) response = client.post( "/api/v1/semantic-search", json={"query": "a woman", "top_k": 5}, ) assert response.status_code == 200 assert response.json()["status"] == "success" assert response.json()["extracted_attrs"] == [] # ─── image serving ─────────────────────────────────────────────────────────── @pytest.fixture() def image_dir(tmp_path, monkeypatch): from PIL import Image buf = io.BytesIO() Image.new("RGB", (8, 8), (10, 20, 30)).save(buf, format="JPEG") (tmp_path / "000001.jpg").write_bytes(buf.getvalue()) monkeypatch.setattr(search_routes, "IMAGES_DIR", tmp_path) monkeypatch.setattr(search_routes, "get_faiss_order", lambda: ["000001.jpg"]) return tmp_path def test_serve_valid_filename(client, image_dir): response = client.get("/api/v1/images/000001.jpg") assert response.status_code == 200 assert response.headers["content-type"] == "image/jpeg" def test_serve_numeric_faiss_id(client, image_dir): response = client.get("/api/v1/images/0") assert response.status_code == 200 def test_serve_rejects_other_extensions(client, image_dir): assert client.get("/api/v1/images/000001.png").status_code == 400 def test_serve_rejects_traversal(client, image_dir, tmp_path): (tmp_path.parent / "secret.txt").write_text("secret", encoding="utf-8") for identifier in ("../secret.txt", "..%2Fsecret.txt", "000001.jpg%5C..%5Csecret.txt"): response = client.get(f"/api/v1/images/{identifier}") assert response.status_code in (400, 404) def test_serve_missing_file_returns_404(client, image_dir): assert client.get("/api/v1/images/999999.jpg").status_code == 404 # ── generate-person ─────────────────────────────────────────────────────────── def test_generated_filenames_are_unique(): names = {generate_routes._output_filename() for _ in range(200)} assert len(names) == 200 assert all(n.startswith("generated_") and n.endswith(".jpg") for n in names) def test_generate_error_does_not_leak_provider_details(client, monkeypatch): def boom(): raise RuntimeError("internal project id 12345 / secret detail") monkeypatch.setattr(generate_routes, "_get_client", boom) response = client.post( "/api/v1/generate-person", json={"prompt": "a person", "save_to_disk": False}, ) assert response.status_code == 200 body = response.json() assert body["status"] == "error" assert body["error"] == "Image generation failed." assert "secret" not in response.text def _fake_image_client(image_bytes: bytes, captured: dict, result=None): class FakeModels: async def generate_content(self, **kwargs): captured.update(kwargs) if result is not None: return result return SimpleNamespace( candidates=[SimpleNamespace( content=SimpleNamespace(parts=[SimpleNamespace( inline_data=SimpleNamespace(data=image_bytes), )]), )], ) return SimpleNamespace(aio=SimpleNamespace(models=FakeModels())) def test_generate_uses_gemini_image_model(client, monkeypatch): from PIL import Image buf = io.BytesIO() Image.new("RGB", (16, 12), (10, 20, 30)).save(buf, format="JPEG") captured: dict = {} monkeypatch.setattr( generate_routes, "_get_client", lambda: _fake_image_client(buf.getvalue(), captured), ) monkeypatch.setattr(generate_routes, "IMAGE_COST_USD", 0.123) response = client.post( "/api/v1/generate-person", json={"prompt": "a smiling person", "save_to_disk": False}, ) assert response.status_code == 200 body = response.json() assert body["status"] == "success" assert body["width"] == 16 and body["height"] == 12 assert body["cascadeflow_metrics"]["cost_usd"] == pytest.approx(0.123) assert captured["model"] == "gemini-3.1-flash-image" assert "IMAGE" in captured["config"].response_modalities def test_generate_returns_502_when_provider_has_no_image(client, monkeypatch): captured: dict = {} empty = SimpleNamespace(candidates=[]) monkeypatch.setattr( generate_routes, "_get_client", lambda: _fake_image_client(b"", captured, result=empty), ) response = client.post( "/api/v1/generate-person", json={"prompt": "a person", "save_to_disk": False}, ) assert response.status_code == 502 assert "no image" in response.json()["detail"] def test_generate_propagates_http_exception(client, monkeypatch): class FakeModels: async def generate_content(self, **_kwargs): raise HTTPException(status_code=403, detail="blocked by safety policy") fake = SimpleNamespace(aio=SimpleNamespace(models=FakeModels())) monkeypatch.setattr(generate_routes, "_get_client", lambda: fake) response = client.post( "/api/v1/generate-person", json={"prompt": "a person", "save_to_disk": False}, ) assert response.status_code == 403 assert response.json()["detail"] == "blocked by safety policy"