Spaces:
Sleeping
Sleeping
File size: 13,091 Bytes
db7c1e8 | 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 | """
Unit tests for API endpoints
"""
import pytest
from fastapi.testclient import TestClient
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import UUID, uuid4
from datetime import datetime
from ..main import app
from ..auth.auth import TokenData
from ..config.database import get_db_session
from ..db import crud
@pytest.fixture
def client():
"""Test client fixture"""
return TestClient(app)
@pytest.mark.asyncio
async def test_health_endpoint(client):
"""Test health endpoint"""
# Mock the service health checks
with patch('..routes.health.test_database_health', return_value=True):
with patch('..routes.health.test_qdrant_health', return_value=True):
with patch('..routes.health.test_gemini_health', return_value=True):
response = client.get("/health/")
assert response.status_code == 200
data = response.json()
assert "status" in data
assert "services" in data
assert data["status"] == "healthy"
@pytest.mark.asyncio
async def test_auth_signup_endpoint(client):
"""Test auth signup endpoint"""
# Mock the database operations
mock_db = AsyncMock()
mock_user = MagicMock()
mock_user.id = uuid4()
mock_user.email = "test@example.com"
mock_user.full_name = "Test User"
mock_user.is_active = True
mock_user.created_at = datetime.utcnow()
with patch('..config.database.get_db_session', return_value=mock_db):
with patch('..db.crud.get_user_by_email', return_value=None): # User doesn't exist yet
with patch('..db.crud.create_user', return_value=mock_user):
with patch('..auth.auth.create_user_token', return_value="fake_jwt_token"):
response = client.post("/auth/signup", json={
"email": "test@example.com",
"password": "testpassword",
"full_name": "Test User"
})
assert response.status_code == 200
data = response.json()
assert "access_token" in data
assert data["token_type"] == "bearer"
@pytest.mark.asyncio
async def test_auth_login_endpoint(client):
"""Test auth login endpoint"""
# Mock the database operations
mock_db = AsyncMock()
mock_user = MagicMock()
mock_user.id = uuid4()
mock_user.email = "test@example.com"
mock_user.hashed_password = "hashed_password"
mock_user.is_active = True
with patch('..config.database.get_db_session', return_value=mock_db):
with patch('..db.crud.get_user_by_email', return_value=mock_user):
with patch('..auth.auth.verify_password', return_value=True):
with patch('..auth.auth.create_user_token', return_value="fake_jwt_token"):
response = client.post("/auth/login", json={
"email": "test@example.com",
"password": "testpassword"
})
assert response.status_code == 200
data = response.json()
assert "access_token" in data
assert data["token_type"] == "bearer"
@pytest.mark.asyncio
async def test_auth_me_endpoint(client):
"""Test auth me endpoint"""
# Mock the token decoding
mock_token_data = TokenData(username="test@example.com", user_id=str(uuid4()))
# Mock the database operations
mock_db = AsyncMock()
mock_user = MagicMock()
mock_user.id = uuid4()
mock_user.email = "test@example.com"
mock_user.full_name = "Test User"
mock_user.is_active = True
mock_user.created_at = datetime.utcnow()
with patch('..config.database.get_db_session', return_value=mock_db):
with patch('..auth.auth.get_current_user', return_value=mock_token_data):
with patch('..db.crud.get_user_by_id', return_value=mock_user):
response = client.get("/auth/me", headers={
"Authorization": "Bearer fake_jwt_token"
})
assert response.status_code == 200
data = response.json()
assert "id" in data
assert data["email"] == "test@example.com"
@pytest.mark.asyncio
async def test_save_document_endpoint(client):
"""Test save document endpoint"""
# Mock the token decoding
mock_token_data = TokenData(username="test@example.com", user_id=str(uuid4()))
# Mock the database operations
mock_db = AsyncMock()
mock_document = MagicMock()
mock_document.id = uuid4()
with patch('..config.database.get_db_session', return_value=mock_db):
with patch('..auth.auth.get_current_user', return_value=mock_token_data):
with patch('..db.crud.get_document_by_hash', return_value=None): # Document doesn't exist
with patch('..db.crud.create_document', return_value=mock_document):
with patch('..rag.pipeline.process_document_for_rag', return_value=True):
response = client.post("/documents/", json={
"title": "Test Document",
"content": "This is the content of the test document."
}, headers={
"Authorization": "Bearer fake_jwt_token"
})
assert response.status_code == 200
data = response.json()
assert "document_id" in data
assert data["success"] is True
@pytest.mark.asyncio
async def test_search_endpoint(client):
"""Test search endpoint"""
# Mock the token decoding
mock_token_data = TokenData(username="test@example.com", user_id=str(uuid4()))
# Mock the search results
mock_search_results = [
{
"id": "point_id_1",
"document_id": str(uuid4()),
"score": 0.95,
"payload": {"chunk_text": "This is relevant context for the search.", "user_id": str(uuid4())}
}
]
with patch('..auth.auth.get_current_user', return_value=mock_token_data):
with patch('..rag.pipeline.search_documents', return_value=mock_search_results):
response = client.post("/search/", json={
"query": "Test search query",
"top_k": 5
}, headers={
"Authorization": "Bearer fake_jwt_token"
})
assert response.status_code == 200
data = response.json()
assert "results" in data
assert "query" in data
assert len(data["results"]) >= 0 # May have 0 or more results
@pytest.mark.asyncio
async def test_chat_endpoint(client):
"""Test chat endpoint"""
# Mock the token decoding
mock_token_data = TokenData(username="test@example.com", user_id=str(uuid4()))
# Mock the RAG result
mock_rag_result = {
"response": "This is a test response from the AI model.",
"sources": [{"chunk_text": "Relevant context"}],
"context_used": [{"chunk_text": "Relevant context"}],
"query_embedding": [0.1, 0.2, 0.3] + [0.0] * (1536 - 3)
}
with patch('..auth.auth.get_current_user', return_value=mock_token_data):
with patch('..rag.pipeline.query_rag', return_value=mock_rag_result):
response = client.post("/search/chat", json={
"query": "Test chat query?",
"top_k": 5
}, headers={
"Authorization": "Bearer fake_jwt_token"
})
assert response.status_code == 200
data = response.json()
assert "response" in data
assert "sources" in data
assert data["response"] == "This is a test response from the AI model."
@pytest.mark.asyncio
async def test_get_chat_history_endpoint(client):
"""Test get chat history endpoint"""
# Mock the token decoding
mock_token_data = TokenData(username="test@example.com", user_id=str(uuid4()))
# Mock the database operations
mock_db = AsyncMock()
mock_chat_history = MagicMock()
mock_chat_history.id = uuid4()
mock_chat_history.query = "Test query?"
mock_chat_history.response = "Test response"
mock_chat_history.created_at = datetime.utcnow()
mock_chat_history.updated_at = datetime.utcnow()
with patch('..config.database.get_db_session', return_value=mock_db):
with patch('..auth.auth.get_current_user', return_value=mock_token_data):
with patch('..db.crud.get_chat_histories_by_user', return_value=[mock_chat_history]):
with patch('..db.crud.get_user_chat_history_count', return_value=1):
response = client.get("/history/?page=1&limit=20", headers={
"Authorization": "Bearer fake_jwt_token"
})
assert response.status_code == 200
data = response.json()
assert "history" in data
assert "total" in data
assert len(data["history"]) >= 0
@pytest.mark.asyncio
async def test_unauthorized_access(client):
"""Test unauthorized access to protected endpoints"""
response = client.get("/auth/me") # No authorization header
# Should return 403 or 401 for unauthorized access
assert response.status_code in [401, 403]
@pytest.mark.asyncio
async def test_invalid_token_access(client):
"""Test access with invalid token"""
with patch('..auth.auth.get_current_user', side_effect=Exception("Invalid token")):
response = client.get("/auth/me", headers={
"Authorization": "Bearer invalid_token"
})
# Should return 401 for invalid token
assert response.status_code == 401
@pytest.mark.asyncio
async def test_detailed_health_endpoint(client):
"""Test detailed health endpoint"""
# Mock the service health checks
with patch('..routes.health.test_database_health', return_value=True):
with patch('..routes.health.test_qdrant_health', return_value=True):
with patch('..routes.health.test_gemini_health', return_value=True):
response = client.get("/health/detailed")
assert response.status_code == 200
data = response.json()
assert "status" in data
assert "services" in data
assert "system" in data
assert data["status"] == "healthy"
@pytest.mark.asyncio
async def test_get_specific_conversation(client):
"""Test getting a specific conversation"""
# Mock the token decoding
mock_token_data = TokenData(username="test@example.com", user_id=str(uuid4()))
# Mock the database operations
mock_db = AsyncMock()
mock_chat_history = MagicMock()
mock_chat_history.id = uuid4()
mock_chat_history.query = "Test query?"
mock_chat_history.response = "Test response"
mock_chat_history.created_at = datetime.utcnow()
mock_chat_history.updated_at = datetime.utcnow()
mock_chat_history.user_id = mock_token_data.user_id
conversation_id = str(mock_chat_history.id)
with patch('..config.database.get_db_session', return_value=mock_db):
with patch('..auth.auth.get_current_user', return_value=mock_token_data):
with patch('..db.crud.get_chat_history_by_id', return_value=mock_chat_history):
response = client.get(f"/history/{conversation_id}", headers={
"Authorization": "Bearer fake_jwt_token"
})
assert response.status_code == 200
data = response.json()
assert "id" in data
assert data["query"] == "Test query?"
@pytest.mark.asyncio
async def test_get_document_endpoint(client):
"""Test getting a specific document"""
# Mock the token decoding
mock_token_data = TokenData(username="test@example.com", user_id=str(uuid4()))
# Mock the database operations
mock_db = AsyncMock()
mock_document = MagicMock()
mock_document.id = uuid4()
mock_document.title = "Test Document"
mock_document.content = "Test content"
mock_document.created_at = datetime.utcnow()
mock_document.updated_at = datetime.utcnow()
mock_document.user_id = mock_token_data.user_id
document_id = str(mock_document.id)
with patch('..config.database.get_db_session', return_value=mock_db):
with patch('..auth.auth.get_current_user', return_value=mock_token_data):
with patch('..db.crud.get_document_by_id', return_value=mock_document):
response = client.get(f"/documents/{document_id}", headers={
"Authorization": "Bearer fake_jwt_token"
})
assert response.status_code == 200
data = response.json()
assert "id" in data
assert data["title"] == "Test Document" |