File size: 14,701 Bytes
ed5d828 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | """Unit tests for api/server.py - FastAPI endpoints."""
import json
from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient
class TestHealthEndpoint:
"""Tests for the /health endpoint."""
def test_health_check_returns_ok(self):
"""Test that health check returns status ok."""
from api.server import app
client = TestClient(app)
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
class TestCompaniesEndpoint:
"""Tests for the /companies endpoint."""
def test_list_companies_returns_list(self):
"""Test listing companies returns a list."""
with (
patch("api.server.get_kg_client") as mock_get_client,
patch("api.server.get_companies_list") as mock_get_companies,
):
mock_get_companies.return_value = [
{"id": "company-1", "name": "Acme Corp"},
{"id": "company-2", "name": "TechStart"},
]
from api.server import app
client = TestClient(app)
response = client.get("/companies")
assert response.status_code == 200
data = response.json()
assert len(data) == 2
assert data[0]["id"] == "company-1"
assert data[0]["name"] == "Acme Corp"
def test_list_companies_empty(self):
"""Test listing companies when none exist."""
with (
patch("api.server.get_kg_client") as mock_get_client,
patch("api.server.get_companies_list") as mock_get_companies,
):
mock_get_companies.return_value = []
from api.server import app
client = TestClient(app)
response = client.get("/companies")
assert response.status_code == 200
assert response.json() == []
def test_list_companies_missing_env_vars(self):
"""Test listing companies fails when env vars missing."""
with patch.dict("os.environ", {}, clear=True):
# Reset the global client
import api.server as server_module
server_module._kg_client = None
from api.server import app
client = TestClient(app, raise_server_exceptions=False)
response = client.get("/companies")
assert response.status_code == 500
assert "SUPABASE_URL" in response.json()["detail"]
class TestCompanyStatsEndpoint:
"""Tests for the /companies/{company_id}/stats endpoint."""
def test_get_company_stats(self):
"""Test getting stats for a company."""
with (
patch("api.server.get_kg_client") as mock_get_client,
patch("api.server.get_company_stats") as mock_get_stats,
):
mock_get_stats.return_value = {"doc_count": 15, "chunk_count": 120}
from api.server import app
client = TestClient(app)
response = client.get("/companies/company-123/stats")
assert response.status_code == 200
data = response.json()
assert data["doc_count"] == 15
assert data["chunk_count"] == 120
def test_get_company_stats_zero_counts(self):
"""Test getting stats for company with no documents."""
with (
patch("api.server.get_kg_client") as mock_get_client,
patch("api.server.get_company_stats") as mock_get_stats,
):
mock_get_stats.return_value = {"doc_count": 0, "chunk_count": 0}
from api.server import app
client = TestClient(app)
response = client.get("/companies/nonexistent/stats")
assert response.status_code == 200
data = response.json()
assert data["doc_count"] == 0
assert data["chunk_count"] == 0
class TestGenerateReportEndpoint:
"""Tests for the /reports/generate endpoint."""
def test_generate_report_success(self):
"""Test successful report generation."""
mock_result = json.dumps(
{
"details": [{"key": "Market Size", "description": "Large TAM"}],
"flags": [],
}
)
with (
patch("api.server.get_kg_client") as mock_get_client,
patch("api.server.get_llm_provider") as mock_get_llm,
patch("api.server.run_kg_generation") as mock_run_gen,
):
mock_run_gen.return_value = mock_result
from api.server import app
client = TestClient(app)
response = client.post(
"/reports/generate",
json={
"company_id": "company-123",
"section": "tam",
},
)
assert response.status_code == 200
data = response.json()
assert data["success"] is True
assert data["section"] == "tam"
assert data["data"]["details"][0]["key"] == "Market Size"
assert data["error"] is None
def test_generate_report_with_all_options(self):
"""Test report generation with all optional parameters."""
mock_result = json.dumps({"details": [], "flags": []})
with (
patch("api.server.get_kg_client") as mock_get_client,
patch("api.server.get_llm_provider") as mock_get_llm,
patch("api.server.run_kg_generation") as mock_run_gen,
):
mock_run_gen.return_value = mock_result
from api.server import app
client = TestClient(app)
response = client.post(
"/reports/generate",
json={
"company_id": "company-123",
"section": "product",
"model": "gpt-4o",
"retrieval_mode": "full_documents",
"extra_queries": ["What is the tech stack?"],
"top_k": 20,
},
)
assert response.status_code == 200
assert response.json()["success"] is True
# Verify run_kg_generation was called with correct params
call_kwargs = mock_run_gen.call_args.kwargs
assert call_kwargs["company_id"] == "company-123"
assert call_kwargs["retrieval_mode"] == "full_documents"
assert call_kwargs["extra_queries"] == ["What is the tech stack?"]
assert call_kwargs["top_k"] == 20
def test_generate_report_generation_fails(self):
"""Test report generation when LLM returns None."""
with (
patch("api.server.get_kg_client") as mock_get_client,
patch("api.server.get_llm_provider") as mock_get_llm,
patch("api.server.run_kg_generation") as mock_run_gen,
):
mock_run_gen.return_value = None
from api.server import app
client = TestClient(app)
response = client.post(
"/reports/generate",
json={
"company_id": "company-123",
"section": "team",
},
)
assert response.status_code == 200
data = response.json()
assert data["success"] is False
assert data["section"] == "team"
assert data["data"] is None
assert "Generation failed" in data["error"]
def test_generate_report_invalid_json_response(self):
"""Test report generation when LLM returns invalid JSON."""
with (
patch("api.server.get_kg_client") as mock_get_client,
patch("api.server.get_llm_provider") as mock_get_llm,
patch("api.server.run_kg_generation") as mock_run_gen,
):
mock_run_gen.return_value = "not valid json {"
from api.server import app
client = TestClient(app)
response = client.post(
"/reports/generate",
json={
"company_id": "company-123",
"section": "customer_signals",
},
)
assert response.status_code == 200
data = response.json()
assert data["success"] is False
assert "Failed to parse" in data["error"]
def test_generate_report_invalid_section(self):
"""Test report generation with invalid section name."""
from api.server import app
client = TestClient(app)
response = client.post(
"/reports/generate",
json={
"company_id": "company-123",
"section": "invalid_section",
},
)
assert response.status_code == 422 # Validation error
def test_generate_report_missing_company_id(self):
"""Test report generation without company_id."""
from api.server import app
client = TestClient(app)
response = client.post(
"/reports/generate",
json={
"section": "tam",
},
)
assert response.status_code == 422 # Validation error
def test_generate_report_invalid_top_k(self):
"""Test report generation with out-of-range top_k."""
from api.server import app
client = TestClient(app)
# top_k > 100
response = client.post(
"/reports/generate",
json={
"company_id": "company-123",
"section": "tam",
"top_k": 150,
},
)
assert response.status_code == 422
# top_k < 1
response = client.post(
"/reports/generate",
json={
"company_id": "company-123",
"section": "tam",
"top_k": 0,
},
)
assert response.status_code == 422
class TestGetLlmProvider:
"""Tests for the get_llm_provider helper function."""
def test_get_gemini_provider(self):
"""Test getting Gemini LLM provider."""
with patch.dict("os.environ", {"GEMINI_API_KEY": "test-gemini-key"}):
from api.server import ModelProvider, get_llm_provider
from services.llm import GeminiLLM
provider = get_llm_provider(ModelProvider.gemini_flash_lite)
assert isinstance(provider, GeminiLLM)
assert provider.model_name == "gemini-2.0-flash-lite"
def test_get_openai_provider(self):
"""Test getting OpenAI LLM provider."""
with patch.dict("os.environ", {"OPENAI_API_KEY": "test-openai-key"}):
from api.server import ModelProvider, get_llm_provider
from services.llm import OpenAiLLM
provider = get_llm_provider(ModelProvider.gpt_4o)
assert isinstance(provider, OpenAiLLM)
assert provider.model_name == "gpt-4o"
def test_get_gemini_provider_missing_key(self):
"""Test Gemini provider raises when API key missing."""
with patch.dict("os.environ", {}, clear=True):
from fastapi import HTTPException
from api.server import ModelProvider, get_llm_provider
with pytest.raises(HTTPException) as exc_info:
get_llm_provider(ModelProvider.gemini_flash)
assert exc_info.value.status_code == 500
assert "GEMINI_API_KEY" in exc_info.value.detail
def test_get_openai_provider_missing_key(self):
"""Test OpenAI provider raises when API key missing."""
with patch.dict("os.environ", {}, clear=True):
from fastapi import HTTPException
from api.server import ModelProvider, get_llm_provider
with pytest.raises(HTTPException) as exc_info:
get_llm_provider(ModelProvider.gpt_4o_mini)
assert exc_info.value.status_code == 500
assert "OPENAI_API_KEY" in exc_info.value.detail
class TestGetKgClient:
"""Tests for the get_kg_client helper function."""
def test_get_kg_client_creates_instance(self):
"""Test that get_kg_client creates KGClient with env vars."""
import api.server as server_module
server_module._kg_client = None
with (
patch.dict(
"os.environ",
{"SUPABASE_URL": "https://test.supabase.co", "SUPABASE_KEY": "test-key"},
),
patch("services.kg.client.create_client"),
):
from api.server import get_kg_client
client = get_kg_client()
assert client is not None
assert client.url == "https://test.supabase.co"
server_module._kg_client = None
def test_get_kg_client_singleton(self):
"""Test that get_kg_client returns same instance."""
import api.server as server_module
server_module._kg_client = None
with (
patch.dict(
"os.environ",
{"SUPABASE_URL": "https://test.supabase.co", "SUPABASE_KEY": "test-key"},
),
patch("services.kg.client.create_client"),
):
from api.server import get_kg_client
client1 = get_kg_client()
client2 = get_kg_client()
assert client1 is client2
server_module._kg_client = None
def test_get_kg_client_missing_url(self):
"""Test get_kg_client raises when SUPABASE_URL missing."""
import api.server as server_module
server_module._kg_client = None
with patch.dict("os.environ", {"SUPABASE_KEY": "test-key"}, clear=True):
from fastapi import HTTPException
from api.server import get_kg_client
with pytest.raises(HTTPException) as exc_info:
get_kg_client()
assert exc_info.value.status_code == 500
assert "SUPABASE_URL" in exc_info.value.detail
server_module._kg_client = None
def test_get_kg_client_missing_key(self):
"""Test get_kg_client raises when SUPABASE_KEY missing."""
import api.server as server_module
server_module._kg_client = None
with patch.dict("os.environ", {"SUPABASE_URL": "https://test.supabase.co"}, clear=True):
from fastapi import HTTPException
from api.server import get_kg_client
with pytest.raises(HTTPException) as exc_info:
get_kg_client()
assert exc_info.value.status_code == 500
assert "SUPABASE_KEY" in exc_info.value.detail
server_module._kg_client = None
|