"""Tests for src/askme/evaluation/local_eval.py.""" from __future__ import annotations from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch from typer.testing import CliRunner from askme.evaluation.local_eval import _client, _make_judge, app, run_local_eval runner = CliRunner() def test_trim_context_prefers_chunks_then_caps(): """ Scenario: the judge sees the document chunks, bounded to its window Given LightRAG's ~27k-token dump (Entities -> Relations -> Document Chunks) When _trim_context is applied before judging Then it starts at the Document Chunks section (actual source text — what context_precision and faithfulness need, not the KG entity triples) and is capped to _CONTEXT_CHAR_CAP """ from askme.evaluation.local_eval import _CONTEXT_CHAR_CAP, _trim_context dump = "Knowledge Graph Data (Entity): ...lots... Document Chunks: src " + "z" * 100_000 out = _trim_context(dump) assert out.startswith("Document Chunks") assert len(out) <= _CONTEXT_CHAR_CAP # No chunks marker -> fall back to a plain cap assert _trim_context("x" * 100_000) == "x" * _CONTEXT_CHAR_CAP assert _trim_context("short") == "short" def test_client_sets_a_timeout(monkeypatch): """ Scenario: a dropped Ollama response fails fast instead of wedging the run When the OpenAI-compatible client is built Then it carries an explicit timeout (Ollama drops in-flight responses under load; without a timeout the judge call hangs indefinitely) """ monkeypatch.setattr( "askme.evaluation.local_eval.settings.ollama_host", "http://ollama:11434" ) with patch("askme.evaluation.local_eval.AsyncOpenAI") as mock_client: _client() assert mock_client.call_args.kwargs.get("timeout") is not None def test_make_judge_uses_instructor_factory_at_ollama_v1(monkeypatch): """ Scenario: the judge is a schema-enforcing instructor LLM on Ollama Given ragas_judge_model="gemma4:12b" and ollama_host When _make_judge builds the judge Then it points an OpenAI client at /v1 and builds the LLM via llm_factory(provider="openai") — the instructor path that enforces the metric schema (fixes RagasOutputParserException) """ monkeypatch.setattr("askme.evaluation.local_eval.settings.ragas_judge_model", "gemma4:12b") monkeypatch.setattr( "askme.evaluation.local_eval.settings.ollama_host", "http://ollama:11434" ) with ( patch("askme.evaluation.local_eval.AsyncOpenAI") as mock_client, patch("askme.evaluation.local_eval.llm_factory") as mock_factory, ): _make_judge() assert mock_client.call_args.kwargs["base_url"] == "http://ollama:11434/v1" assert mock_factory.call_args.args[0] == "gemma4:12b" assert mock_factory.call_args.kwargs["provider"] == "openai" # Generous max_tokens — faithfulness statement-extraction output is long; # the default truncated it ("output incomplete due to max_tokens"). assert mock_factory.call_args.kwargs["max_tokens"] >= 2048 def _metric_returning(value: float) -> MagicMock: """A metric class whose instances' .ascore returns a fixed-value result.""" inst = MagicMock() inst.ascore = AsyncMock(return_value=MagicMock(value=value)) cls = MagicMock(return_value=inst) return cls def test_run_local_eval_aggregates_triad_means(): """ Scenario: the triad is scored per question and averaged Given a 2-question testset and a RAG that answers When run_local_eval runs with the three collections metrics Then it returns mean faithfulness/answer_relevancy/context_precision and a per-question breakdown """ testset = [ {"question": "q1", "reference": "r1"}, {"question": "q2", "reference": "r2"}, ] rag = MagicMock() rag.initialize_storages = AsyncMock() rag.finalize_storages = AsyncMock() rag.aquery = AsyncMock(return_value="an answer") with ( patch("askme.evaluation.local_eval.create_rag", return_value=rag), patch("askme.evaluation.local_eval._make_judge"), patch("askme.evaluation.local_eval._make_modern_embeddings"), patch("askme.evaluation.local_eval.Faithfulness", _metric_returning(1.0)), patch("askme.evaluation.local_eval.AnswerRelevancy", _metric_returning(0.8)), patch( "askme.evaluation.local_eval.ContextPrecisionWithReference", _metric_returning(0.6), ), ): scores = run_local_eval(testset) assert scores["n"] == 2 assert scores["faithfulness"] == 1.0 assert scores["answer_relevancy"] == 0.8 assert scores["context_precision"] == 0.6 assert [r["question"] for r in scores["results"]] == ["q1", "q2"] def test_eval_local_cli_writes_timed_report(tmp_path: Path): """ Scenario: the CLI writes a timed report with the triad means When askme-eval-local runs Then it exits 0 and the report holds the scores + elapsed_seconds + judge """ import json report = tmp_path / "report.json" fake = { "faithfulness": 0.9, "answer_relevancy": 0.8, "context_precision": 0.7, "n": 1, "results": [{"question": "q", "faithfulness": 0.9, "answer_relevancy": 0.8, "context_precision": 0.7}], } testset = tmp_path / "testset.json" testset.write_text(json.dumps([{"question": "q", "reference": "r"}])) with patch("askme.evaluation.local_eval.run_local_eval", return_value=fake): result = runner.invoke( app, ["--n", "1", "--testset", str(testset), "--output", str(report)] ) assert result.exit_code == 0 data = json.loads(report.read_text()) assert data["faithfulness"] == 0.9 assert isinstance(data["elapsed_seconds"], (int, float)) assert data["judge_model"] def test_eval_local_cli_defaults_to_data_dir_testset(tmp_path: Path, monkeypatch): """ Scenario: the private testset lives in the data dir, not in code Given settings.data_dir holds testset.json with one question When askme-eval-local runs without --testset Then that file's questions are scored """ import json (tmp_path / "testset.json").write_text(json.dumps([{"question": "dq", "reference": "r"}])) monkeypatch.setattr("askme.evaluation.local_eval.settings.data_dir", str(tmp_path)) fake = {"faithfulness": 1.0, "answer_relevancy": 1.0, "context_precision": 1.0, "n": 1, "results": []} with patch("askme.evaluation.local_eval.run_local_eval", return_value=fake) as run: result = runner.invoke(app, ["--output", str(tmp_path / "r.json")]) assert result.exit_code == 0 assert run.call_args.args[0] == [{"question": "dq", "reference": "r"}] def test_eval_local_cli_missing_testset_points_to_example(tmp_path: Path, monkeypatch): """ Scenario: a fresh clone has no testset yet Given no testset.json in settings.data_dir When askme-eval-local runs without --testset Then it exits non-zero and points the user at eval/testset.example.json """ monkeypatch.setattr("askme.evaluation.local_eval.settings.data_dir", str(tmp_path)) result = runner.invoke(app, ["--output", str(tmp_path / "r.json")]) assert result.exit_code != 0 assert "testset.example.json" in result.output