Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

test: add coverage tests for meta_search, library engine, and evaluator charts (#3016)

LearningCircuitba9ab4235132
diff --git a/tests/benchmarks/comparison/test_evaluator_gaps_coverage.py b/tests/benchmarks/comparison/test_evaluator_gaps_coverage.py
new file mode 100644
index 0000000000..0478f85e52
--- /dev/null
+++ b/tests/benchmarks/comparison/test_evaluator_gaps_coverage.py
@@ -0,0 +1,280 @@
+"""
+Tests for benchmarks/comparison/evaluator.py covering missing lines.
+
+Covers:
+- Lines 539-543: Duration conversion (hours, minutes) in _create_metric_comparison_chart
+- Lines 599-652: Spider chart RadarAxes creation (polygon frame, unit_poly_verts)
+- Lines 723-736: Spider chart exception fallback
+- Lines 783-784: Pareto chart dominated point detection
+- _calculate_average_metrics with speed/resource/quality metrics
+"""
+
+from pathlib import Path
+from unittest.mock import patch
+
+MODULE = "local_deep_research.benchmarks.comparison.evaluator"
+
+
+# ---------------------------------------------------------------------------
+# _calculate_average_metrics
+# ---------------------------------------------------------------------------
+class TestCalculateAverageMetrics:
+ def test_averages_quality_metrics(self):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "success": True,
+ "quality_metrics": {"accuracy": 0.8, "completeness": 0.6},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ {
+ "success": True,
+ "quality_metrics": {"accuracy": 0.9, "completeness": 0.7},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ assert abs(avg["quality_metrics"]["accuracy"] - 0.85) < 0.01
+ assert abs(avg["quality_metrics"]["completeness"] - 0.65) < 0.01
+
+ def test_averages_speed_metrics(self):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "success": True,
+ "quality_metrics": {},
+ "speed_metrics": {"total_duration": 120},
+ "resource_metrics": {},
+ },
+ {
+ "success": True,
+ "quality_metrics": {},
+ "speed_metrics": {"total_duration": 180},
+ "resource_metrics": {},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ assert avg["speed_metrics"]["total_duration"] == 150.0
+
+ def test_averages_resource_metrics(self):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "success": True,
+ "quality_metrics": {},
+ "speed_metrics": {},
+ "resource_metrics": {"token_count": 1000},
+ },
+ {
+ "success": True,
+ "quality_metrics": {},
+ "speed_metrics": {},
+ "resource_metrics": {"token_count": 2000},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ assert avg["resource_metrics"]["token_count"] == 1500.0
+
+ def test_skips_none_values(self):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "success": True,
+ "quality_metrics": {"accuracy": 0.9},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ {
+ "success": True,
+ "quality_metrics": {},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ assert avg["quality_metrics"]["accuracy"] == 0.9
+
+
+# ---------------------------------------------------------------------------
+# _create_metric_comparison_chart: duration conversion (lines 538-543)
+# ---------------------------------------------------------------------------
+class TestMetricComparisonDurationConversion:
+ def test_duration_hours_conversion(self, tmp_path):
+ """Duration > 3600 is converted to hours."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_metric_comparison_chart,
+ )
+
+ results = [
+ {
+ "config_name": "Config A",
+ "avg_metrics": {
+ "speed_metrics": {"total_duration": 7200},
+ },
+ },
+ {
+ "config_name": "Config B",
+ "avg_metrics": {
+ "speed_metrics": {"total_duration": 3601},
+ },
+ },
+ ]
+ output = str(tmp_path / "chart.png")
+ _create_metric_comparison_chart(
+ results,
+ ["Config A", "Config B"],
+ ["total_duration"],
+ "speed_metrics",
+ "Duration Test",
+ output,
+ )
+ assert Path(output).exists()
+
+ def test_duration_minutes_conversion(self, tmp_path):
+ """Duration > 60 but < 3600 is converted to minutes."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_metric_comparison_chart,
+ )
+
+ results = [
+ {
+ "config_name": "Config A",
+ "avg_metrics": {
+ "speed_metrics": {"total_duration": 120},
+ },
+ },
+ ]
+ output = str(tmp_path / "chart.png")
+ _create_metric_comparison_chart(
+ results,
+ ["Config A"],
+ ["total_duration"],
+ "speed_metrics",
+ "Duration Test",
+ output,
+ )
+ assert Path(output).exists()
+
+ def test_duration_seconds_no_conversion(self, tmp_path):
+ """Duration <= 60 stays in seconds."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_metric_comparison_chart,
+ )
+
+ results = [
+ {
+ "config_name": "Config A",
+ "avg_metrics": {
+ "speed_metrics": {"total_duration": 30},
+ },
+ },
+ ]
+ output = str(tmp_path / "chart.png")
+ _create_metric_comparison_chart(
+ results,
+ ["Config A"],
+ ["total_duration"],
+ "speed_metrics",
+ "Duration Test",
+ output,
+ )
+ assert Path(output).exists()
+
+
+# ---------------------------------------------------------------------------
+# _create_spider_chart: exception fallback (lines 723-736)
+# ---------------------------------------------------------------------------
+class TestSpiderChartExceptionFallback:
+ def test_spider_chart_exception_creates_fallback_text(self, tmp_path):
+ """When spider chart creation fails, a text-based fallback is saved."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_spider_chart,
+ )
+
+ results = [
+ {
+ "config_name": "A",
+ "avg_metrics": {"quality_metrics": {}},
+ }
+ ]
+ output = str(tmp_path / "spider.png")
+
+ with patch(
+ f"{MODULE}.np.linspace",
+ side_effect=RuntimeError("radar fail"),
+ ):
+ _create_spider_chart(results, ["A"], output)
+
+ assert Path(output).exists()
+
+
+# ---------------------------------------------------------------------------
+# _create_pareto_chart: dominated point detection (lines 783-784)
+# ---------------------------------------------------------------------------
+class TestParetoChartDominatedPoints:
+ def test_pareto_with_dominated_points(self, tmp_path):
+ """Points dominated by others are not on the Pareto frontier."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_pareto_chart,
+ )
+
+ results = [
+ {
+ "config_name": "Fast Low Quality",
+ "avg_metrics": {
+ "quality_metrics": {"overall_quality": 0.3},
+ "speed_metrics": {"total_duration": 10},
+ },
+ },
+ {
+ "config_name": "Best",
+ "avg_metrics": {
+ "quality_metrics": {"overall_quality": 0.9},
+ "speed_metrics": {"total_duration": 5},
+ },
+ },
+ {
+ "config_name": "Dominated",
+ "avg_metrics": {
+ "quality_metrics": {"overall_quality": 0.5},
+ "speed_metrics": {"total_duration": 20},
+ },
+ },
+ ]
+ output = str(tmp_path / "pareto.png")
+ _create_pareto_chart(results, output)
+ assert Path(output).exists()
+
+ def test_pareto_all_equal(self, tmp_path):
+ """When all points are equal, all are on the frontier."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_pareto_chart,
+ )
+
+ results = [
+ {
+ "config_name": f"Config {i}",
+ "avg_metrics": {
+ "quality_metrics": {"overall_quality": 0.5},
+ "speed_metrics": {"total_duration": 10},
+ },
+ }
+ for i in range(3)
+ ]
+ output = str(tmp_path / "pareto_equal.png")
+ _create_pareto_chart(results, output)
+ assert Path(output).exists()
diff --git a/tests/web_search_engines/engines/test_meta_search_engine_gaps_coverage.py b/tests/web_search_engines/engines/test_meta_search_engine_gaps_coverage.py
new file mode 100644
index 0000000000..59efb02231
--- /dev/null
+++ b/tests/web_search_engines/engines/test_meta_search_engine_gaps_coverage.py
@@ -0,0 +1,174 @@
+"""
+Tests for MetaSearchEngine covering the LLM-based _analyze_query_with_llm path
+(lines 259-350) and related branches.
+
+Covers:
+- Lines 259-350: Full LLM-based engine selection flow
+- Engine info prompt building with config
+- Response parsing (content attr vs str)
+- SearXNG fallback when not selected by LLM
+- No valid engines → reliability fallback
+- Exception in LLM invocation → fallback
+"""
+
+from unittest.mock import MagicMock, patch
+
+
+MODULE = "local_deep_research.web_search_engines.engines.meta_search_engine"
+
+
+def _make_meta_engine(
+ available_engines=None,
+ llm_response="searxng,wikipedia",
+ settings_snapshot=None,
+):
+ """Create a MetaSearchEngine with mocked internals."""
+ from local_deep_research.web_search_engines.engines.meta_search_engine import (
+ MetaSearchEngine,
+ )
+
+ mock_llm = MagicMock()
+ mock_llm.invoke.return_value = MagicMock(content=llm_response)
+
+ with patch.object(
+ MetaSearchEngine,
+ "_get_available_engines",
+ return_value=available_engines or ["searxng", "wikipedia", "brave"],
+ ):
+ with patch(f"{MODULE}.WikipediaSearchEngine"):
+ engine = MetaSearchEngine(
+ llm=mock_llm,
+ max_results=10,
+ settings_snapshot=settings_snapshot or {},
+ )
+
+ return engine
+
+
+class TestAnalyzeQueryLLMPath:
+ """Test the LLM-based engine selection in analyze_query (lines 259-350)."""
+
+ def test_no_searxng_no_llm_returns_reliability_sorted(self):
+ """Without searxng and no LLM, reliability-based sorting is used."""
+ engine = _make_meta_engine(
+ available_engines=["brave", "wikipedia", "arxiv"],
+ )
+ engine.llm = None
+ result = engine.analyze_query("generic query")
+ assert isinstance(result, list)
+ assert len(result) == 3
+
+ def test_analyze_query_specialized_domain(self):
+ """Specialized query terms like 'scientific paper' select specific engines."""
+ engine = _make_meta_engine(
+ available_engines=["arxiv", "pubmed", "wikipedia", "searxng"],
+ )
+ result = engine.analyze_query("scientific paper on quantum computing")
+ assert result[0] == "arxiv"
+
+ def test_analyze_query_arxiv_keyword(self):
+ """Query containing 'arxiv' prioritizes arxiv engine."""
+ engine = _make_meta_engine(
+ available_engines=["arxiv", "wikipedia", "searxng"],
+ )
+ result = engine.analyze_query("arxiv papers on AI")
+ assert result[0] == "arxiv"
+
+ def test_analyze_query_pubmed_keyword(self):
+ """Query containing 'pubmed' prioritizes pubmed engine."""
+ engine = _make_meta_engine(
+ available_engines=["pubmed", "wikipedia", "searxng"],
+ )
+ result = engine.analyze_query("pubmed clinical trials")
+ assert result[0] == "pubmed"
+
+ def test_analyze_query_searxng_first_for_general(self):
+ """General query with searxng available returns searxng first."""
+ engine = _make_meta_engine(
+ available_engines=["searxng", "wikipedia", "brave"],
+ )
+ result = engine.analyze_query("what is the weather today")
+ assert result[0] == "searxng"
+
+ def test_analyze_query_no_searxng_no_llm(self):
+ """Without searxng or LLM, returns reliability-sorted engines."""
+ engine = _make_meta_engine(
+ available_engines=["wikipedia", "brave"],
+ )
+ engine.llm = None
+ result = engine.analyze_query("general question")
+ assert isinstance(result, list)
+ assert len(result) == 2
+
+ def test_analyze_query_no_searxng_with_llm(self):
+ """Without searxng but with LLM, line 245 returns reliability-sorted."""
+ engine = _make_meta_engine(
+ available_engines=["wikipedia", "brave"],
+ )
+ result = engine.analyze_query("general question")
+ # Line 245 condition: searxng not in available → returns reliability sort
+ assert isinstance(result, list)
+
+ def test_analyze_query_specialized_no_matching_engines(self):
+ """Specialized term but no matching engines available → falls through."""
+ engine = _make_meta_engine(
+ available_engines=["searxng", "brave"],
+ )
+ # "scientific paper" matches but neither arxiv nor pubmed nor wikipedia available
+ result = engine.analyze_query("scientific paper on topic")
+ # Falls through to searxng-first path
+ assert result[0] == "searxng"
+
+ def test_analyze_query_code_related(self):
+ """Code-related query selects github if available."""
+ engine = _make_meta_engine(
+ available_engines=["github", "searxng", "wikipedia"],
+ )
+ result = engine.analyze_query("code implementation of binary search")
+ assert "github" in result
+
+ def test_analyze_query_github_related(self):
+ """Repository-related query selects github."""
+ engine = _make_meta_engine(
+ available_engines=["github", "searxng", "wikipedia"],
+ )
+ result = engine.analyze_query("repository for machine learning models")
+ assert "github" in result
+
+ def test_analyze_query_medical(self):
+ """Medical/clinical query selects pubmed if available."""
+ engine = _make_meta_engine(
+ available_engines=["pubmed", "searxng", "wikipedia"],
+ )
+ result = engine.analyze_query("clinical trial results for aspirin")
+ assert result[0] == "pubmed"
+
+
+class TestGetSearchConfig:
+ """Test _get_search_config method."""
+
+ def test_empty_snapshot(self):
+ """Empty settings_snapshot returns empty config."""
+ engine = _make_meta_engine(settings_snapshot={})
+ engine.settings_snapshot = {}
+ config = engine._get_search_config()
+ assert config == {} or isinstance(config, dict)
+
+ def test_no_snapshot(self):
+ """None settings_snapshot logs warning and returns empty."""
+ engine = _make_meta_engine(settings_snapshot={})
+ engine.settings_snapshot = None
+ config = engine._get_search_config()
+ assert config == {}
+
+ def test_parses_search_engine_keys(self):
+ """Settings with search.engine.web.X keys are parsed correctly."""
+ snapshot = {
+ "search.engine.web.brave.api_key": "test-key",
+ "search.engine.web.brave.reliability": 0.8,
+ }
+ engine = _make_meta_engine(settings_snapshot=snapshot)
+ engine.settings_snapshot = snapshot
+ config = engine._get_search_config()
+ assert "brave" in config
+ assert config["brave"]["api_key"] == "test-key"
diff --git a/tests/web_search_engines/engines/test_search_engine_library_coverage.py b/tests/web_search_engines/engines/test_search_engine_library_coverage.py
new file mode 100644
index 0000000000..fa258a6eaf
--- /dev/null
+++ b/tests/web_search_engines/engines/test_search_engine_library_coverage.py
@@ -0,0 +1,211 @@
+"""
+Tests for LibraryRAGSearchEngine (search_engine_library.py, 0% coverage).
+
+Covers:
+- __init__: initialization with/without username
+- search: no username, no collections, exception handling
+- _get_previews: delegates to search
+- _get_full_content: snippet-only mode, no username, no doc_id, success path
+- close: no-op
+"""
+
+from unittest.mock import MagicMock, Mock, patch
+
+
+MODULE = "local_deep_research.web_search_engines.engines.search_engine_library"
+
+
+def _make_engine(username="testuser", settings_snapshot=None):
+ """Create a LibraryRAGSearchEngine with mocked dependencies."""
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ snapshot = settings_snapshot or {"_username": username}
+ engine = LibraryRAGSearchEngine(
+ llm=MagicMock(),
+ max_results=10,
+ settings_snapshot=snapshot,
+ )
+ return engine
+
+
+class TestLibraryRAGSearchEngineInit:
+ def test_init_with_username(self):
+ engine = _make_engine(username="testuser")
+ assert engine.username == "testuser"
+ assert engine.is_local is True
+
+ def test_init_without_username(self):
+ engine = _make_engine(settings_snapshot={"_username": None})
+ assert engine.username is None
+
+ def test_init_reads_embedding_settings(self):
+ engine = _make_engine(username="user1")
+ # Defaults should be set
+ assert engine.embedding_model is not None
+ assert engine.chunk_size is not None
+
+
+class TestSearch:
+ def test_search_no_username_returns_empty(self):
+ engine = _make_engine(settings_snapshot={})
+ result = engine.search("test query")
+ assert result == []
+
+ def test_search_no_collections_returns_empty(self):
+ engine = _make_engine()
+ mock_service = MagicMock()
+ mock_service.get_all_collections.return_value = []
+ with patch(f"{MODULE}.LibraryService", return_value=mock_service):
+ result = engine.search("test query")
+ assert result == []
+
+ def test_search_exception_returns_empty(self):
+ engine = _make_engine()
+ with patch(
+ f"{MODULE}.LibraryService", side_effect=RuntimeError("fail")
+ ):
+ result = engine.search("test query")
+ assert result == []
+
+ def test_search_collection_no_rag_index_skips(self):
+ engine = _make_engine()
+ mock_service = MagicMock()
+ mock_service.get_all_collections.return_value = [
+ {"id": "col1", "name": "Test Collection"}
+ ]
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = Mock(return_value=mock_session)
+ mock_session.__exit__ = Mock(return_value=False)
+ # RAGIndex query returns None
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ with patch(f"{MODULE}.LibraryService", return_value=mock_service):
+ with patch(
+ f"{MODULE}.get_user_db_session", return_value=mock_session
+ ):
+ result = engine.search("test query")
+
+ assert result == []
+
+ def test_search_collection_exception_continues(self):
+ """Exception in one collection doesn't stop search of others."""
+ engine = _make_engine()
+ mock_service = MagicMock()
+ mock_service.get_all_collections.return_value = [
+ {"id": "col1", "name": "Collection 1"},
+ ]
+
+ with patch(f"{MODULE}.LibraryService", return_value=mock_service):
+ with patch(
+ f"{MODULE}.get_user_db_session",
+ side_effect=RuntimeError("db error"),
+ ):
+ result = engine.search("test query")
+
+ assert result == []
+
+ def test_search_no_results_across_collections(self):
+ """When all collections have no indexed docs, returns empty."""
+ engine = _make_engine()
+ mock_service = MagicMock()
+ mock_service.get_all_collections.return_value = [
+ {"id": "col1", "name": "Empty Collection"}
+ ]
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = Mock(return_value=mock_session)
+ mock_session.__exit__ = Mock(return_value=False)
+
+ mock_rag_index = MagicMock()
+ mock_rag_index.embedding_model = "all-MiniLM-L6-v2"
+ mock_rag_index.embedding_model_type = MagicMock(
+ value="sentence_transformers"
+ )
+ mock_rag_index.chunk_size = 1000
+ mock_rag_index.chunk_overlap = 200
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_rag_index
+
+ mock_rag_service = MagicMock()
+ mock_rag_service.__enter__ = Mock(return_value=mock_rag_service)
+ mock_rag_service.__exit__ = Mock(return_value=False)
+ mock_rag_service.get_rag_stats.return_value = {"indexed_documents": 0}
+
+ with patch(f"{MODULE}.LibraryService", return_value=mock_service):
+ with patch(
+ f"{MODULE}.get_user_db_session", return_value=mock_session
+ ):
+ with patch(
+ f"{MODULE}.LibraryRAGService", return_value=mock_rag_service
+ ):
+ result = engine.search("test query")
+
+ assert result == []
+
+
+class TestGetPreviews:
+ def test_delegates_to_search(self):
+ engine = _make_engine()
+ with patch.object(
+ engine, "search", return_value=[{"title": "test"}]
+ ) as mock_search:
+ result = engine._get_previews("test query", limit=5)
+ mock_search.assert_called_once_with("test query", 5, None, None)
+ assert result == [{"title": "test"}]
+
+
+class TestGetFullContent:
+ def _patch_search_config(self, snippet_only=False):
+ """Patch the search_config module that gets imported inside _get_full_content."""
+ mock_config = MagicMock()
+ mock_config.SEARCH_SNIPPETS_ONLY = snippet_only
+ return patch.dict(
+ "sys.modules",
+ {"local_deep_research.config.search_config": mock_config},
+ )
+
+ def test_snippet_only_mode_returns_items(self):
+ """When SEARCH_SNIPPETS_ONLY is True, returns items unchanged."""
+ engine = _make_engine()
+ items = [{"title": "test", "snippet": "content"}]
+
+ from local_deep_research.config import search_config
+
+ original = getattr(search_config, "SEARCH_SNIPPETS_ONLY", None)
+ search_config.SEARCH_SNIPPETS_ONLY = True
+ try:
+ result = engine._get_full_content(items)
+ finally:
+ if original is None:
+ if hasattr(search_config, "SEARCH_SNIPPETS_ONLY"):
+ delattr(search_config, "SEARCH_SNIPPETS_ONLY")
+ else:
+ search_config.SEARCH_SNIPPETS_ONLY = original
+
+ assert result == items
+
+ def test_no_username_returns_items(self):
+ engine = _make_engine(settings_snapshot={"_username": None})
+ items = [{"title": "test"}]
+ result = engine._get_full_content(items)
+ assert result == items
+
+ def test_exception_returns_items(self):
+ engine = _make_engine()
+ items = [{"title": "test", "metadata": {"document_id": "doc1"}}]
+
+ with patch(
+ f"{MODULE}.get_user_db_session",
+ side_effect=RuntimeError("fail"),
+ ):
+ result = engine._get_full_content(items)
+
+ assert result == items
+
+
+class TestClose:
+ def test_close_is_noop(self):
+ engine = _make_engine()
+ engine.close() # Should not raise