feat: consolida backend RAG e documentação
This commit is contained in:
parent
7c18727f62
commit
d72572ee6f
28 changed files with 2193 additions and 275 deletions
34
tests/fixtures/rag-eval/synthetic-dataset.json
vendored
Normal file
34
tests/fixtures/rag-eval/synthetic-dataset.json
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
{
|
||||
"dataset_id": "ativa-synthetic-v1",
|
||||
"synthetic_only": true,
|
||||
"documents": [
|
||||
{
|
||||
"source": "synthetic-acesso.md",
|
||||
"content": "No Centro Aurora fictício, a recepção funciona de segunda a sexta-feira, das 8h às 17h."
|
||||
},
|
||||
{
|
||||
"source": "synthetic-agendamento.md",
|
||||
"content": "No Centro Aurora fictício, solicitações de agendamento são encaminhadas à equipe de atendimento."
|
||||
}
|
||||
],
|
||||
"cases": [
|
||||
{
|
||||
"id": "SYN-01",
|
||||
"question": "Qual é o horário da recepção do Centro Aurora fictício?",
|
||||
"expected_sources": ["synthetic-acesso.md"],
|
||||
"expects_abstention": false
|
||||
},
|
||||
{
|
||||
"id": "SYN-02",
|
||||
"question": "Para quem vai uma solicitação de agendamento?",
|
||||
"expected_sources": ["synthetic-agendamento.md"],
|
||||
"expects_abstention": false
|
||||
},
|
||||
{
|
||||
"id": "SYN-03",
|
||||
"question": "Qual é a previsão do tempo no Centro Aurora?",
|
||||
"expected_sources": [],
|
||||
"expects_abstention": true
|
||||
}
|
||||
]
|
||||
}
|
||||
84
tests/test_backup_restore.py
Normal file
84
tests/test_backup_restore.py
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
BACKUP_SCRIPT = REPO_ROOT / "scripts/backup.sh"
|
||||
|
||||
|
||||
class BackupRestoreTests(unittest.TestCase):
|
||||
def run_backup(self, env):
|
||||
return subprocess.run(
|
||||
["bash", str(BACKUP_SCRIPT)],
|
||||
env={**os.environ, **env},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
def test_backup_requires_explicit_external_paths_and_opt_in(self):
|
||||
completed = self.run_backup({})
|
||||
|
||||
self.assertNotEqual(completed.returncode, 0)
|
||||
self.assertIn("BACKUP_ROOT", completed.stderr)
|
||||
|
||||
def test_synthetic_backup_excludes_secrets_and_restores_in_temp(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary)
|
||||
source = root / "knowledge-source"
|
||||
output = root / "backups"
|
||||
source.mkdir()
|
||||
(source / "subdir").mkdir()
|
||||
expected = b"Conteudo totalmente sintetico.\n"
|
||||
(source / "subdir" / "fixture.md").write_bytes(expected)
|
||||
(source / "credentials.txt").write_text("synthetic-secret", encoding="utf-8")
|
||||
(source / ".env").write_text("TOKEN=synthetic-secret", encoding="utf-8")
|
||||
(source / "notes.pdf").write_bytes(b"fake-pdf")
|
||||
(source / "ignored.csv").write_text("not allowlisted", encoding="utf-8")
|
||||
try:
|
||||
(source / "linked.md").symlink_to(source / "subdir" / "fixture.md")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
completed = self.run_backup({
|
||||
"BACKUP_ROOT": str(output),
|
||||
"ATIVA_KNOWLEDGE_ROOT": str(source),
|
||||
"INCLUDE_KNOWLEDGE": "YES",
|
||||
})
|
||||
self.assertEqual(completed.returncode, 0, completed.stderr)
|
||||
backups = list(output.iterdir())
|
||||
self.assertEqual(len(backups), 1)
|
||||
backup = backups[0]
|
||||
stored = backup / "knowledge/subdir/fixture.md"
|
||||
self.assertEqual(stored.read_bytes(), expected)
|
||||
self.assertFalse((backup / "knowledge/credentials.txt").exists())
|
||||
self.assertFalse((backup / "knowledge/.env").exists())
|
||||
self.assertFalse((backup / "knowledge/ignored.csv").exists())
|
||||
|
||||
restore = root / "restored-isolated"
|
||||
shutil.copytree(backup / "knowledge", restore)
|
||||
self.assertEqual((restore / "subdir/fixture.md").read_bytes(), expected)
|
||||
digest = hashlib.sha256(expected).hexdigest()
|
||||
manifest = (backup / "SHA256SUMS").read_text(encoding="utf-8")
|
||||
self.assertIn(digest, manifest)
|
||||
self.assertEqual((backup / "MANIFESTO.txt").stat().st_mode & 0o777, 0o600)
|
||||
|
||||
def test_backup_refuses_checkout_destination(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
source = Path(temporary) / "source"
|
||||
source.mkdir()
|
||||
completed = self.run_backup({
|
||||
"BACKUP_ROOT": str(REPO_ROOT),
|
||||
"ATIVA_KNOWLEDGE_ROOT": str(source),
|
||||
"INCLUDE_KNOWLEDGE": "YES",
|
||||
})
|
||||
|
||||
self.assertNotEqual(completed.returncode, 0)
|
||||
self.assertIn("não pode ser o checkout", completed.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
423
tests/test_rag_api_endpoints.py
Normal file
423
tests/test_rag_api_endpoints.py
Normal file
|
|
@ -0,0 +1,423 @@
|
|||
"""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()
|
||||
62
tests/test_rag_config.py
Normal file
62
tests/test_rag_config.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO_ROOT / "rag-api"))
|
||||
from config import Settings
|
||||
|
||||
|
||||
class RagConfigTests(unittest.TestCase):
|
||||
def test_defaults_are_canonical_and_do_not_contain_a_secret(self):
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
settings = Settings.from_environment()
|
||||
|
||||
self.assertEqual(settings.qdrant_url, "http://192.168.0.153:6333")
|
||||
self.assertEqual(settings.ollama_url, "http://192.168.0.106:11434")
|
||||
self.assertEqual(settings.collection, "ativa_knowledge")
|
||||
self.assertEqual(settings.api_key, "")
|
||||
|
||||
def test_environment_overrides_values_and_normalizes_urls(self):
|
||||
values = {
|
||||
"QDRANT_URL": "http://qdrant.test/",
|
||||
"OLLAMA_URL": "http://ollama.test/",
|
||||
"QDRANT_COLLECTION": "synthetic_collection",
|
||||
"ATIVA_RAG_API_KEY": " sample-key ",
|
||||
"RAG_SCORE_THRESHOLD": "0.25",
|
||||
"RAG_MAX_CONTEXT_CHARS": "4000",
|
||||
"RAG_MAX_QUESTION_CHARS": "800",
|
||||
}
|
||||
with patch.dict(os.environ, values, clear=True):
|
||||
settings = Settings.from_environment()
|
||||
|
||||
self.assertEqual(settings.qdrant_url, "http://qdrant.test")
|
||||
self.assertEqual(settings.ollama_url, "http://ollama.test")
|
||||
self.assertEqual(settings.collection, "synthetic_collection")
|
||||
self.assertEqual(settings.api_key, "sample-key")
|
||||
self.assertEqual(settings.score_threshold, 0.25)
|
||||
self.assertEqual(settings.max_context_chars, 4000)
|
||||
self.assertEqual(settings.max_question_chars, 800)
|
||||
|
||||
def test_env_example_has_no_credential_value(self):
|
||||
example = (REPO_ROOT / "rag-api/.env.example").read_text(encoding="utf-8")
|
||||
compose = (REPO_ROOT / "rag-api/docker-compose.yml").read_text(encoding="utf-8")
|
||||
|
||||
self.assertNotRegex(example, r"(?m)^ATIVA_RAG_API_KEY\s*=")
|
||||
self.assertIn("Provisionar ATIVA_RAG_API_KEY", example)
|
||||
self.assertIn("valores padrão canônicos estão em config.py", example)
|
||||
self.assertIn('${ATIVA_RAG_API_KEY:?provide via approved secret manager}', compose)
|
||||
key_mapping = next(
|
||||
line.strip() for line in compose.splitlines()
|
||||
if line.strip().startswith("ATIVA_RAG_API_KEY:")
|
||||
)
|
||||
self.assertEqual(
|
||||
key_mapping,
|
||||
'ATIVA_RAG_API_KEY: "${ATIVA_RAG_API_KEY:?provide via approved secret manager}"',
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
143
tests/test_rag_evaluation.py
Normal file
143
tests/test_rag_evaluation.py
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO_ROOT / "rag-api"))
|
||||
from evaluation import evaluate
|
||||
|
||||
|
||||
class RagEvaluationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dataset = json.loads(
|
||||
(REPO_ROOT / "tests/fixtures/rag-eval/synthetic-dataset.json").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
)
|
||||
self.results = {
|
||||
"runs": [
|
||||
{
|
||||
"case_id": "SYN-01",
|
||||
"retrieved_sources": ["synthetic-acesso.md"],
|
||||
"cited_sources": ["synthetic-acesso.md"],
|
||||
"answer": "A recepção funciona das 8h às 17h.",
|
||||
"latency_ms": 100,
|
||||
"human_fidelity_review": "pending",
|
||||
},
|
||||
{
|
||||
"case_id": "SYN-02",
|
||||
"retrieved_sources": ["outro.md", "synthetic-agendamento.md"],
|
||||
"cited_sources": ["outro.md"],
|
||||
"answer": "A solicitação vai à equipe de atendimento.",
|
||||
"latency_ms": 200,
|
||||
"human_fidelity_review": "pending",
|
||||
},
|
||||
{
|
||||
"case_id": "SYN-03",
|
||||
"retrieved_sources": [],
|
||||
"cited_sources": [],
|
||||
"answer": "Essa informação não está disponível na base.",
|
||||
"latency_ms": 50,
|
||||
"human_fidelity_review": "pending",
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
def test_descriptive_baseline_metrics(self):
|
||||
report = evaluate(self.dataset, self.results, k=2)
|
||||
|
||||
self.assertEqual(report["evaluation"], "baseline_descriptive_only")
|
||||
self.assertIsNone(report["gate"])
|
||||
self.assertEqual(report["retrieval_hit_at_k"]["rate"], 1.0)
|
||||
self.assertEqual(report["citation_precision"]["rate"], 0.5)
|
||||
self.assertEqual(report["abstention_marker_rate"]["rate"], 1.0)
|
||||
self.assertEqual(report["latency_ms"]["mean"], 350 / 3)
|
||||
self.assertEqual(report["latency_ms"]["p50_median"], 100.0)
|
||||
self.assertEqual(report["latency_ms"]["p95_nearest_rank"], 200.0)
|
||||
self.assertEqual(report["human_fidelity_reviews_pending"], 3)
|
||||
|
||||
def test_incomplete_run_is_reported_without_failure(self):
|
||||
report = evaluate(self.dataset, {"runs": self.results["runs"][:1]})
|
||||
|
||||
self.assertEqual(report["cases_evaluated"], 1)
|
||||
self.assertEqual(report["missing_results"], ["SYN-02", "SYN-03"])
|
||||
|
||||
def test_duplicate_run_is_rejected(self):
|
||||
results = {"runs": [self.results["runs"][0], self.results["runs"][0]]}
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "resultado duplicado"):
|
||||
evaluate(self.dataset, results)
|
||||
|
||||
def test_repeated_run_reports_binary_outcome_stability(self):
|
||||
first = dict(self.results["runs"][0], repeat=1)
|
||||
repeated = dict(self.results["runs"][0], repeat=2, latency_ms=125)
|
||||
report = evaluate(self.dataset, {"runs": [first, repeated]})
|
||||
|
||||
self.assertEqual(report["cases_evaluated"], 1)
|
||||
self.assertEqual(report["stability"]["repeated_cases"], 1)
|
||||
self.assertEqual(report["stability"]["outcome_consistency_rate"], 1.0)
|
||||
|
||||
def test_unstable_repeated_outcomes_are_visible(self):
|
||||
first = dict(self.results["runs"][0], repeat=1)
|
||||
repeated = dict(
|
||||
self.results["runs"][0], repeat=2, retrieved_sources=[], latency_ms=125
|
||||
)
|
||||
report = evaluate(self.dataset, {"runs": [first, repeated]})
|
||||
|
||||
self.assertEqual(report["stability"]["consistent_cases"], 0)
|
||||
self.assertEqual(report["stability"]["outcome_consistency_rate"], 0.0)
|
||||
|
||||
def test_unknown_case_is_rejected(self):
|
||||
with self.assertRaisesRegex(ValueError, "case_id desconhecido"):
|
||||
evaluate(self.dataset, {"runs": [{"case_id": "missing"}]})
|
||||
|
||||
def test_non_string_case_id_is_rejected_cleanly(self):
|
||||
with self.assertRaisesRegex(ValueError, "case_id desconhecido"):
|
||||
evaluate(self.dataset, {"runs": [{"case_id": ["SYN-01"]}]})
|
||||
|
||||
def test_incomplete_result_is_rejected(self):
|
||||
with self.assertRaisesRegex(ValueError, "resultado incompleto"):
|
||||
evaluate(self.dataset, {"runs": [{"case_id": "SYN-01"}]})
|
||||
|
||||
def test_non_finite_latency_is_rejected(self):
|
||||
result = dict(self.results["runs"][0], latency_ms=float("nan"))
|
||||
with self.assertRaisesRegex(ValueError, "latency_ms inválida"):
|
||||
evaluate(self.dataset, {"runs": [result]})
|
||||
|
||||
def test_non_string_expected_source_is_rejected(self):
|
||||
dataset = dict(self.dataset)
|
||||
dataset["cases"] = [dict(self.dataset["cases"][0], expected_sources=[{}])]
|
||||
with self.assertRaisesRegex(ValueError, "expected_sources inválido"):
|
||||
evaluate(dataset, {"runs": []})
|
||||
|
||||
def test_non_object_top_level_json_is_rejected(self):
|
||||
with self.assertRaisesRegex(ValueError, "precisam ser objetos JSON"):
|
||||
evaluate([], {})
|
||||
|
||||
def test_cli_prints_json_report(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
results_path = Path(directory) / "results.json"
|
||||
results_path.write_text(json.dumps(self.results), encoding="utf-8")
|
||||
completed = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(REPO_ROOT / "scripts/rag_eval.py"),
|
||||
"--dataset",
|
||||
str(REPO_ROOT / "tests/fixtures/rag-eval/synthetic-dataset.json"),
|
||||
"--results",
|
||||
str(results_path),
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
report = json.loads(completed.stdout)
|
||||
self.assertEqual(report["cases_total"], 3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
25
tests/test_runtime_port_config.py
Normal file
25
tests/test_runtime_port_config.py
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import json
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class RuntimePortConfigTests(unittest.TestCase):
|
||||
def test_docker_expose_matches_uvicorn_port(self):
|
||||
dockerfile = (REPO_ROOT / "rag-api/Dockerfile").read_text(encoding="utf-8")
|
||||
expose = re.search(r"(?m)^EXPOSE\s+(\d+)\s*$", dockerfile)
|
||||
command = re.search(r"(?m)^CMD\s+(\[.*\])\s*$", dockerfile)
|
||||
|
||||
self.assertIsNotNone(expose, "Dockerfile precisa declarar uma porta EXPOSE")
|
||||
self.assertIsNotNone(command, "Dockerfile precisa declarar o comando do runtime")
|
||||
|
||||
command_args = json.loads(command.group(1))
|
||||
port_index = command_args.index("--port") + 1
|
||||
self.assertEqual(expose.group(1), command_args[port_index])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Add table
Add a link
Reference in a new issue