ativa-ia/tests/test_rag_api_endpoints.py

423 lines
16 KiB
Python

"""HTTP contract tests for the FastAPI application with mocked upstreams."""
import sys
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "rag-api"))
try:
import httpx
import app as rag_app
except ModuleNotFoundError as exc: # Keep the dependency-free suite runnable.
httpx = None
rag_app = None
API_TEST_IMPORT_ERROR = exc.name
else:
API_TEST_IMPORT_ERROR = ""
@unittest.skipIf(
httpx is None,
f"FastAPI test dependencies unavailable: {API_TEST_IMPORT_ERROR}",
)
class RagApiEndpointTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.client = httpx.AsyncClient(
transport=httpx.ASGITransport(app=rag_app.app),
base_url="http://testserver",
)
self.api_key_patch = patch.object(rag_app, "API_KEY", "test-service-key")
self.api_key_patch.start()
self.addCleanup(self.api_key_patch.stop)
self.addAsyncCleanup(self.client.aclose)
async def test_health_reports_both_dependencies(self):
class Response:
def raise_for_status(self):
return None
class AsyncClient:
def __init__(self, **kwargs):
self.timeout = kwargs.get("timeout")
async def __aenter__(self):
return self
async def __aexit__(self, *args):
return False
async def get(self, url):
self_test.assertIn(url, expected_urls)
seen_urls.append(url)
return Response()
self_test = self
expected_urls = (
f"{rag_app.QDRANT_URL}/collections/{rag_app.COLLECTION}",
f"{rag_app.OLLAMA_URL}/api/tags",
)
seen_urls = []
with patch.object(rag_app, "httpx", SimpleNamespace(AsyncClient=AsyncClient)):
response = await self.client.get("/health")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["status"], "ok")
self.assertTrue(response.json()["qdrant"])
self.assertTrue(response.json()["ollama"])
self.assertEqual(tuple(seen_urls), expected_urls)
async def test_health_degrades_when_a_dependency_fails(self):
class Response:
def raise_for_status(self):
return None
class AsyncClient:
def __init__(self, **kwargs):
self.timeout = kwargs.get("timeout")
async def __aenter__(self):
return self
async def __aexit__(self, *args):
return False
async def get(self, url):
if "/collections/" in url:
raise OSError("simulated Qdrant outage")
return Response()
with patch.object(rag_app, "httpx", SimpleNamespace(AsyncClient=AsyncClient)):
response = await self.client.get("/health")
self.assertEqual(response.status_code, 503)
self.assertEqual(response.json()["status"], "degraded")
self.assertFalse(response.json()["qdrant"])
self.assertTrue(response.json()["ollama"])
async def test_query_requires_api_key(self):
response = await self.client.post("/query", json={"question": "pergunta"})
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json()["detail"], "Não autorizado.")
async def test_query_rejects_whitespace_only_question(self):
response = await self.client.post(
"/query",
headers={"X-API-Key": "test-service-key"},
json={"question": " "},
)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["detail"], "Pergunta vazia.")
async def test_query_returns_answer_and_source_metadata(self):
search_results = [{
"score": 0.9,
"payload": {
"source": "manual.pdf",
"text": "Conteúdo sintético de teste.",
"file_type": "pdf",
"page": 4,
"document_id": "doc-synthetic",
"chunk_index": 2,
},
}]
with (
patch.object(rag_app, "embed", new=AsyncMock(return_value=[0.1, 0.2])) as embed,
patch.object(rag_app, "search_qdrant", new=AsyncMock(return_value=search_results)) as search,
patch.object(rag_app, "generate", new=AsyncMock(return_value="resposta")) as generate,
):
response = await self.client.post(
"/query",
headers={"X-API-Key": "test-service-key"},
json={"question": " pergunta válida ", "top_k": 3, "score_threshold": 0.7},
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["question"], "pergunta válida")
self.assertEqual(response.json()["answer"], "resposta")
self.assertEqual(response.json()["sources"], [{
"source": "manual.pdf",
"score": 0.9,
"file_type": "pdf",
"page": 4,
"document_id": "doc-synthetic",
"chunk_index": 2,
}])
embed.assert_awaited_once_with("pergunta válida")
search.assert_awaited_once_with([0.1, 0.2], 3, 0.7)
self.assertIn("Conteúdo sintético de teste.", generate.await_args.args[0])
async def test_query_without_results_builds_abstention_context(self):
with (
patch.object(rag_app, "embed", new=AsyncMock(return_value=[0.1])),
patch.object(rag_app, "search_qdrant", new=AsyncMock(return_value=[])),
patch.object(rag_app, "generate", new=AsyncMock(return_value="Não disponível na base.")) as generate,
):
response = await self.client.post(
"/query",
headers={"X-API-Key": "test-service-key"},
json={"question": "pergunta fora da base"},
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["sources"], [])
self.assertEqual(response.json()["answer"], "Não disponível na base.")
self.assertIn("[Nenhum contexto relevante foi recuperado.]", generate.await_args.args[0])
async def test_query_maps_upstream_http_failure_to_502(self):
request = rag_app.httpx.Request("POST", "http://qdrant.invalid/search")
upstream_response = rag_app.httpx.Response(
503,
text="simulated upstream failure",
request=request,
)
error = rag_app.httpx.HTTPStatusError(
"upstream unavailable",
request=request,
response=upstream_response,
)
with patch.object(rag_app, "embed", new=AsyncMock(side_effect=error)):
response = await self.client.post(
"/query",
headers={"X-API-Key": "test-service-key"},
json={"question": "pergunta"},
)
self.assertEqual(response.status_code, 502)
self.assertIn("Falha em serviço interno", response.json()["detail"])
self.assertNotIn("simulated upstream failure", response.json()["detail"])
async def test_query_maps_upstream_timeout_to_504(self):
request = httpx.Request("POST", "http://ollama.invalid/api/embed")
timeout = httpx.ReadTimeout("simulated private timeout detail", request=request)
with patch.object(rag_app, "embed", new=AsyncMock(side_effect=timeout)):
response = await self.client.post(
"/query",
headers={"X-API-Key": "test-service-key"},
json={"question": "pergunta"},
)
self.assertEqual(response.status_code, 504)
self.assertEqual(
response.json()["detail"],
"Tempo esgotado ao consultar serviço interno.",
)
self.assertNotIn("simulated private timeout detail", response.json()["detail"])
async def test_query_hides_unexpected_internal_error_details(self):
with patch.object(
rag_app,
"embed",
new=AsyncMock(side_effect=RuntimeError("private path /srv/secret")),
):
response = await self.client.post(
"/query",
headers={"X-API-Key": "test-service-key"},
json={"question": "pergunta"},
)
self.assertEqual(response.status_code, 500)
self.assertEqual(response.json()["detail"], "Erro interno no RAG.")
self.assertNotIn("/srv/secret", response.json()["detail"])
async def test_query_validates_top_k_schema(self):
response = await self.client.post(
"/query",
headers={"X-API-Key": "test-service-key"},
json={"question": "pergunta", "top_k": 0},
)
self.assertEqual(response.status_code, 422)
async def test_chat_rejects_missing_user_message(self):
response = await self.client.post(
"/v1/chat/completions",
headers={"X-API-Key": "test-service-key"},
json={"messages": [{"role": "assistant", "content": "resposta"}]},
)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.json()["detail"],
"Nenhuma mensagem de usuário encontrada.",
)
async def test_chat_requires_api_key(self):
response = await self.client.post(
"/v1/chat/completions",
json={"messages": [{"role": "user", "content": "pergunta"}]},
)
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json()["detail"], "Não autorizado.")
async def test_chat_maps_upstream_timeout_to_504(self):
request = httpx.Request("POST", "http://ollama.invalid/api/embed")
timeout = httpx.ReadTimeout("simulated private timeout detail", request=request)
with patch.object(rag_app, "embed", new=AsyncMock(side_effect=timeout)):
response = await self.client.post(
"/v1/chat/completions",
headers={"X-API-Key": "test-service-key"},
json={"messages": [{"role": "user", "content": "pergunta"}]},
)
self.assertEqual(response.status_code, 504)
self.assertEqual(
response.json()["detail"],
"Tempo esgotado ao consultar serviço interno.",
)
self.assertNotIn("simulated private timeout detail", response.text)
async def test_chat_maps_upstream_http_failure_to_502(self):
request = httpx.Request("POST", "http://qdrant.invalid/search")
upstream_response = httpx.Response(
503,
text="simulated upstream failure",
request=request,
)
error = httpx.HTTPStatusError(
"upstream unavailable",
request=request,
response=upstream_response,
)
with patch.object(rag_app, "embed", new=AsyncMock(side_effect=error)):
response = await self.client.post(
"/v1/chat/completions",
headers={"X-API-Key": "test-service-key"},
json={"messages": [{"role": "user", "content": "pergunta"}]},
)
self.assertEqual(response.status_code, 502)
self.assertEqual(response.json()["detail"], "Falha em serviço interno.")
self.assertNotIn("simulated upstream failure", response.text)
async def test_chat_hides_unexpected_internal_error_details(self):
with patch.object(
rag_app,
"embed",
new=AsyncMock(side_effect=RuntimeError("private path /srv/secret")),
):
response = await self.client.post(
"/v1/chat/completions",
headers={"X-API-Key": "test-service-key"},
json={"messages": [{"role": "user", "content": "pergunta"}]},
)
self.assertEqual(response.status_code, 500)
self.assertEqual(response.json()["detail"], "Erro interno no RAG.")
self.assertNotIn("/srv/secret", response.text)
async def test_chat_rejects_invalid_temperature_schema(self):
response = await self.client.post(
"/v1/chat/completions",
headers={"X-API-Key": "test-service-key"},
json={"temperature": "inválida", "messages": [{"role": "user", "content": "pergunta"}]},
)
self.assertEqual(response.status_code, 422)
async def test_query_validates_score_threshold_schema(self):
response = await self.client.post(
"/query",
headers={"X-API-Key": "test-service-key"},
json={"question": "pergunta", "score_threshold": 1.1},
)
self.assertEqual(response.status_code, 422)
async def test_models_requires_key_and_returns_configured_model(self):
denied = await self.client.get("/v1/models")
allowed = await self.client.get(
"/v1/models",
headers={"Authorization": "Bearer test-service-key"},
)
self.assertEqual(denied.status_code, 401)
self.assertEqual(allowed.status_code, 200)
self.assertEqual(allowed.json()["data"][0]["id"], rag_app.CHAT_MODEL)
async def test_chat_completion_returns_sources(self):
search_results = [{
"score": 0.8,
"payload": {
"source": "manual.pdf",
"text": "Trecho sintético de referência.",
"section": "Cadastro",
"document_id": "doc-synthetic",
"chunk_index": 1,
},
}]
with (
patch.object(rag_app, "embed", new=AsyncMock(return_value=[0.4])),
patch.object(rag_app, "search_qdrant", new=AsyncMock(return_value=search_results)),
patch.object(rag_app, "generate", new=AsyncMock(return_value="resposta do chat")) as generate,
):
response = await self.client.post(
"/v1/chat/completions",
headers={"X-API-Key": "test-service-key"},
json={"messages": [{"role": "user", "content": "pergunta"}]},
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.json()["choices"][0]["message"]["content"],
"resposta do chat",
)
self.assertEqual(response.json()["x_ativa_sources"], [{
"source": "manual.pdf",
"score": 0.8,
"section": "Cadastro",
"document_id": "doc-synthetic",
"chunk_index": 1,
}])
self.assertIn("Trecho sintético de referência.", generate.await_args.kwargs["prompt"])
self.assertEqual(generate.await_args.kwargs["temperature"], 0.1)
async def test_chat_completion_honors_zero_temperature(self):
with (
patch.object(rag_app, "embed", new=AsyncMock(return_value=[0.4])),
patch.object(rag_app, "search_qdrant", new=AsyncMock(return_value=[])),
patch.object(rag_app, "build_context", return_value=("contexto", [])),
patch.object(rag_app, "generate", new=AsyncMock(return_value="resposta")) as generate,
):
response = await self.client.post(
"/v1/chat/completions",
headers={"X-API-Key": "test-service-key"},
json={
"temperature": 0,
"messages": [{"role": "user", "content": "pergunta"}],
},
)
self.assertEqual(response.status_code, 200)
self.assertEqual(generate.await_args.kwargs["temperature"], 0)
async def test_chat_completion_stream_emits_completion_sentinel(self):
with (
patch.object(rag_app, "embed", new=AsyncMock(return_value=[0.4])),
patch.object(rag_app, "search_qdrant", new=AsyncMock(return_value=[])),
patch.object(rag_app, "build_context", return_value=("contexto", [])),
patch.object(rag_app, "generate", new=AsyncMock(return_value="resposta em stream")),
):
response = await self.client.post(
"/v1/chat/completions",
headers={"X-API-Key": "test-service-key"},
json={
"stream": True,
"messages": [{"role": "user", "content": "pergunta"}],
},
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-type"], "text/event-stream; charset=utf-8")
self.assertIn("resposta em stream", response.text)
self.assertTrue(response.text.endswith("data: [DONE]\n\n"))
if __name__ == "__main__":
unittest.main()