askme-public/tests/test_evaluate.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

174 lines
6.0 KiB
Python

"""Tests for src/askme/evaluation/evaluate.py."""
from __future__ import annotations
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pandas as pd
import pytest
from askme.evaluation.evaluate import _query_all, _strip_sources, run_eval
def _mock_rag_with_aquery(aquery: AsyncMock) -> MagicMock:
rag = MagicMock()
rag.initialize_storages = AsyncMock()
rag.finalize_storages = AsyncMock()
rag.aquery = aquery
return rag
def test_query_all_runs_with_bounded_concurrency():
"""
Scenario: testset questions are queried concurrently, capped at 2
Given a 4-question testset and a slow aquery
When _query_all runs
Then at most 2 queries are ever in flight at once (not serial, not all)
"""
inflight = 0
max_inflight = 0
async def slow_aquery(question, param=None):
nonlocal inflight, max_inflight
inflight += 1
max_inflight = max(max_inflight, inflight)
await asyncio.sleep(0.05)
inflight -= 1
return "answer"
testset = [{"question": f"q{i}", "ground_truth": "", "contexts": []} for i in range(4)]
rag = _mock_rag_with_aquery(AsyncMock(side_effect=slow_aquery))
with patch("askme.evaluation.evaluate.create_rag", return_value=rag):
samples = asyncio.run(_query_all(testset))
assert max_inflight == 2
assert [s.user_input for s in samples] == ["q0", "q1", "q2", "q3"]
def test_query_all_times_out_a_hung_query():
"""
Scenario: a hung query fails fast instead of stalling the whole eval
Given an aquery that never returns within the per-query timeout
When _query_all runs
Then it raises TimeoutError rather than blocking indefinitely
"""
async def hung_aquery(question, param=None):
await asyncio.sleep(10)
return "never"
testset = [{"question": "q", "ground_truth": "", "contexts": []}]
rag = _mock_rag_with_aquery(AsyncMock(side_effect=hung_aquery))
with (
patch("askme.evaluation.evaluate.create_rag", return_value=rag),
patch("askme.evaluation.evaluate._QUERY_TIMEOUT", 0.05),
):
with pytest.raises((asyncio.TimeoutError, TimeoutError)):
asyncio.run(_query_all(testset))
# ── _strip_sources ────────────────────────────────────────────────────────────
def test_strip_sources_no_section():
answer, contexts = _strip_sources("Scanpy clusters cells.")
assert answer == "Scanpy clusters cells."
assert contexts == []
def test_strip_sources_with_section():
raw = "Answer text.\n\n## Sources\n- file.py: some excerpt\n- other.ipynb: more"
answer, contexts = _strip_sources(raw)
assert answer == "Answer text."
assert len(contexts) == 2
assert "file.py" in contexts[0]
# ── run_eval ──────────────────────────────────────────────────────────────────
TESTSET = [
{
"question": "What is scanpy?",
"ground_truth": "Scanpy is for single-cell analysis.",
"contexts": ["Scanpy is a Python library for single-cell analysis."],
}
]
def _mock_eval_result() -> MagicMock:
df = pd.DataFrame(
[{"faithfulness": 0.9, "answer_relevancy": 0.85, "context_precision": 0.8}]
)
result = MagicMock()
result.to_pandas.return_value = df
return result
def test_run_eval_persists_samples_before_metrics(tmp_path):
"""
Scenario: query samples survive a metrics-phase failure
Given the RAGAS evaluate() step raises (missing dep, embedding OOM)
When run_eval has already queried the testset
Then the samples were written to disk before metrics ran, so the
expensive query phase is not lost
"""
import json
samples_file = tmp_path / "samples.json"
mock_rag = MagicMock()
mock_rag.initialize_storages = AsyncMock()
mock_rag.finalize_storages = AsyncMock()
mock_rag.aquery = AsyncMock(return_value="Scanpy is for single-cell analysis.")
with (
patch("askme.evaluation.evaluate.create_rag", return_value=mock_rag),
patch("askme.evaluation.evaluate._make_llm"),
patch("askme.evaluation.evaluate._make_embeddings"),
patch("askme.evaluation.evaluate.evaluate", side_effect=RuntimeError("boom")),
):
with pytest.raises(RuntimeError):
run_eval(TESTSET, samples_path=samples_file)
assert samples_file.exists()
data = json.loads(samples_file.read_text())
assert data[0]["user_input"] == "What is scanpy?"
def test_run_eval_returns_score_keys():
mock_rag = MagicMock()
mock_rag.initialize_storages = AsyncMock()
mock_rag.finalize_storages = AsyncMock()
mock_rag.aquery = AsyncMock(return_value="Scanpy is used for single-cell analysis.")
with (
patch("askme.evaluation.evaluate.create_rag", return_value=mock_rag),
patch("askme.evaluation.evaluate._make_llm"),
patch("askme.evaluation.evaluate._make_embeddings"),
patch("askme.evaluation.evaluate.evaluate", return_value=_mock_eval_result()),
):
result = run_eval(TESTSET)
assert "faithfulness" in result
assert "answer_relevancy" in result
assert "context_precision" in result
assert "samples" in result
def test_run_eval_scores_are_floats():
mock_rag = MagicMock()
mock_rag.initialize_storages = AsyncMock()
mock_rag.finalize_storages = AsyncMock()
mock_rag.aquery = AsyncMock(return_value="Scanpy is used for single-cell analysis.")
with (
patch("askme.evaluation.evaluate.create_rag", return_value=mock_rag),
patch("askme.evaluation.evaluate._make_llm"),
patch("askme.evaluation.evaluate._make_embeddings"),
patch("askme.evaluation.evaluate.evaluate", return_value=_mock_eval_result()),
):
result = run_eval(TESTSET)
assert isinstance(result["faithfulness"], float)
assert 0.0 <= result["faithfulness"] <= 1.0