askme-public/tests/test_main.py
Lukasz Boryn 0e0bae4b9b feat: initial public release of askme
* local question answering over analysis notebooks with LightRAG, Neo4j, Qdrant and Ollama
* RAGAS evaluation with a generator x judge comparison matrix, fully local
* docs in README and OKF
2026-11-03 17:50:52 +01:00

189 lines
6.7 KiB
Python

"""Tests for src/askme/api/main.py."""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi.testclient import TestClient
from askme.api.main import _parse_sources, app
# ── _parse_sources ────────────────────────────────────────────────────────────
def test_parse_sources_no_section():
answer, sources = _parse_sources("Scanpy is used for single-cell analysis.")
assert answer == "Scanpy is used for single-cell analysis."
assert sources == []
def test_parse_sources_with_section():
raw = (
"Scanpy clusters cells.\n\n"
"## Sources\n"
"- notebooks/tutorial.ipynb: Scanpy is a Python library\n"
"- scripts/run.py: sc.pp.normalize_total(adata)\n"
)
answer, sources = _parse_sources(raw)
assert answer == "Scanpy clusters cells."
assert len(sources) == 2
assert sources[0].file == "notebooks/tutorial.ipynb"
assert "Scanpy" in sources[0].excerpt
assert sources[1].file == "scripts/run.py"
def test_parse_sources_case_insensitive():
raw = "Answer.\n\n### sources\n- file.py: some excerpt"
answer, sources = _parse_sources(raw)
assert answer == "Answer."
assert len(sources) == 1
# ── /query endpoint ───────────────────────────────────────────────────────────
@pytest.fixture
def client(mock_rag):
"""Test client with RAG initialisation patched out."""
with (
patch("askme.api.main.create_rag", return_value=mock_rag),
patch("askme.api.main._rag", mock_rag),
):
mock_rag.aquery = AsyncMock(
return_value=(
"Scanpy is used for single-cell analysis.\n\n"
"## Sources\n"
"- notebooks/tutorial.ipynb: Scanpy is a Python library\n"
)
)
with TestClient(app, raise_server_exceptions=True) as c:
yield c
def test_query_returns_answer(client):
resp = client.post("/query", json={"question": "What is scanpy?"})
assert resp.status_code == 200
data = resp.json()
assert "answer" in data
assert "sources" in data
assert isinstance(data["sources"], list)
def test_query_answer_stripped_of_sources_section(client):
resp = client.post("/query", json={"question": "What is scanpy?"})
data = resp.json()
assert "## Sources" not in data["answer"]
assert "## sources" not in data["answer"].lower()
def test_query_sources_populated(client):
resp = client.post("/query", json={"question": "What is scanpy?"})
sources = resp.json()["sources"]
assert len(sources) == 1
assert sources[0]["file"] == "notebooks/tutorial.ipynb"
def test_query_mode_forwarded(client, mock_rag):
client.post("/query", json={"question": "q", "mode": "local"})
call_kwargs = mock_rag.aquery.call_args
param = call_kwargs.kwargs.get("param") or call_kwargs.args[1]
assert param.mode == "local"
def test_query_invalid_mode_returns_422(client):
resp = client.post("/query", json={"question": "q", "mode": "invalid"})
assert resp.status_code == 422
# ── /health ───────────────────────────────────────────────────────────────────
def _all_ok_patches():
mock_driver = MagicMock()
mock_driver.verify_connectivity = AsyncMock()
mock_driver.close = AsyncMock()
mock_neo4j = MagicMock(return_value=mock_driver)
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
mock_resp.json = MagicMock(return_value={"result": {"points_count": 10}})
mock_http = MagicMock()
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
mock_http.__aexit__ = AsyncMock(return_value=False)
mock_http.get = AsyncMock(return_value=mock_resp)
return mock_neo4j, mock_http
def test_health_all_ok(mock_rag):
mock_neo4j, mock_http = _all_ok_patches()
with (
patch("askme.api.main.create_rag", return_value=mock_rag),
patch("askme.api.main._rag", mock_rag),
patch("askme.api.main.AsyncGraphDatabase.driver", mock_neo4j),
patch("askme.api.main.httpx.AsyncClient", return_value=mock_http),
):
with TestClient(app) as c:
resp = c.get("/health")
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "ok"
assert data["services"]["neo4j"] == "ok"
assert data["services"]["qdrant"] == "ok"
assert data["services"]["ollama"] == "ok"
def test_health_degraded_when_service_fails(mock_rag):
mock_driver = MagicMock()
mock_driver.verify_connectivity = AsyncMock(side_effect=Exception("connection refused"))
mock_driver.close = AsyncMock()
mock_neo4j = MagicMock(return_value=mock_driver)
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
mock_http = MagicMock()
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
mock_http.__aexit__ = AsyncMock(return_value=False)
mock_http.get = AsyncMock(return_value=mock_resp)
with (
patch("askme.api.main.create_rag", return_value=mock_rag),
patch("askme.api.main._rag", mock_rag),
patch("askme.api.main.AsyncGraphDatabase.driver", mock_neo4j),
patch("askme.api.main.httpx.AsyncClient", return_value=mock_http),
):
with TestClient(app) as c:
resp = c.get("/health")
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "degraded"
assert "error" in data["services"]["neo4j"]
# ── /collections ──────────────────────────────────────────────────────────────
def test_collections_returns_counts(mock_rag):
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
mock_resp.json = MagicMock(return_value={"result": {"points_count": 42}})
mock_http = MagicMock()
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
mock_http.__aexit__ = AsyncMock(return_value=False)
mock_http.get = AsyncMock(return_value=mock_resp)
with (
patch("askme.api.main.create_rag", return_value=mock_rag),
patch("askme.api.main._rag", mock_rag),
patch("askme.api.main.httpx.AsyncClient", return_value=mock_http),
):
with TestClient(app) as c:
resp = c.get("/collections")
assert resp.status_code == 200
data = resp.json()
assert data["chunks"] == 42
assert data["entities"] == 42
assert data["relationships"] == 42