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.

Tests/increase coverage high value (#2991)

LearningCircuit821fc0da99c5
diff --git a/tests/search_engines/test_search_engine_gutenberg_deep_coverage.py b/tests/search_engines/test_search_engine_gutenberg_deep_coverage.py
new file mode 100644
index 0000000000..797b59b839
--- /dev/null
+++ b/tests/search_engines/test_search_engine_gutenberg_deep_coverage.py
@@ -0,0 +1,160 @@
+"""
+Tests for uncovered code paths in GutenbergSearchEngine.
+
+Targets:
+- _get_full_content: subjects, bookshelves, translators, content building, download_count
+- get_book: success, rate limit, exception
+- search_by_topic: topic switching, cleanup on exception
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (
+ GutenbergSearchEngine,
+)
+from local_deep_research.web_search_engines.rate_limiting import RateLimitError
+
+MODULE = (
+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg"
+)
+
+
+def engine():
+ eng = GutenbergSearchEngine(max_results=5)
+ eng.rate_tracker = Mock()
+ eng.rate_tracker.apply_rate_limit.return_value = 0
+ return eng
+
+
+def _mock_response(status_code=200, json_data=None):
+ resp = Mock()
+ resp.status_code = status_code
+ resp.json.return_value = json_data or {}
+ resp.raise_for_status = Mock()
+ if status_code >= 400:
+ resp.raise_for_status.side_effect = Exception(f"HTTP {status_code}")
+ return resp
+
+
+# ---------------------------------------------------------------------------
+# _get_full_content
+# ---------------------------------------------------------------------------
+
+
+class TestGetFullContent:
+ def test_builds_content_with_all_fields(self, engine):
+ """Content string includes authors, subjects, bookshelves, downloads."""
+ items = [
+ {
+ "title": "Alice in Wonderland",
+ "authors": ["Lewis Carroll"],
+ "download_count": 50000,
+ "read_url": "https://gutenberg.org/ebooks/11",
+ "_raw": {
+ "subjects": ["Fantasy", "Children's literature"],
+ "bookshelves": ["Children's Fiction"],
+ "translators": [{"name": "Someone", "birth_year": 1900}],
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ content = results[0]["content"]
+ assert "Authors: Lewis Carroll" in content
+ assert "Subjects: Fantasy, Children's literature" in content
+ assert "Bookshelves: Children's Fiction" in content
+ assert "Downloads: 50000" in content
+ assert "Read online:" in content
+ assert results[0]["translators"] is not None
+ assert "_raw" not in results[0]
+
+ def test_without_raw(self, engine):
+ """Items without _raw pass through."""
+ items = [{"title": "Minimal"}]
+
+ results = engine._get_full_content(items)
+ assert len(results) == 1
+ assert "_raw" not in results[0]
+
+ def test_empty_raw_fields(self, engine):
+ """Handles empty subjects, bookshelves, translators."""
+ items = [
+ {
+ "title": "Test",
+ "_raw": {
+ "subjects": [],
+ "bookshelves": [],
+ "translators": [],
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+ content = results[0].get("content", "")
+ assert "Subjects:" not in content
+ assert "Bookshelves:" not in content
+
+
+# ---------------------------------------------------------------------------
+# get_book
+# ---------------------------------------------------------------------------
+
+
+class TestGetBook:
+ @patch(f"{MODULE}.safe_get")
+ def test_success(self, mock_get, engine):
+ """Returns book dict on success."""
+ book = {"id": 11, "title": "Alice in Wonderland"}
+ mock_get.return_value = _mock_response(200, book)
+
+ result = engine.get_book(11)
+
+ assert result["id"] == 11
+ assert result["title"] == "Alice in Wonderland"
+
+ @patch(f"{MODULE}.safe_get")
+ def test_rate_limit_propagates(self, mock_get, engine):
+ """RateLimitError is re-raised."""
+ mock_get.return_value = _mock_response(429)
+ engine._raise_if_rate_limit = Mock(side_effect=RateLimitError("429"))
+
+ with pytest.raises(RateLimitError):
+ engine.get_book(11)
+
+ @patch(f"{MODULE}.safe_get")
+ def test_exception_returns_none(self, mock_get, engine):
+ """Other exceptions return None."""
+ mock_get.side_effect = ConnectionError("fail")
+
+ result = engine.get_book(11)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# search_by_topic
+# ---------------------------------------------------------------------------
+
+
+class TestSearchByTopic:
+ def test_sets_topic_and_restores(self, engine):
+ """Temporarily sets topic filter and restores."""
+ engine.topic = None
+ with patch.object(engine, "run", return_value=[]) as mock_run:
+ engine.search_by_topic("science fiction")
+
+ mock_run.assert_called_once_with("")
+ assert engine.topic is None
+
+ def test_restores_on_exception(self, engine):
+ """Topic is restored even on exception."""
+ engine.topic = "original"
+ with patch.object(engine, "run", side_effect=Exception("fail")):
+ with pytest.raises(Exception, match="fail"):
+ engine.search_by_topic("new topic")
+
+ assert engine.topic == "original"
diff --git a/tests/search_engines/test_search_engine_openlibrary_deep_coverage.py b/tests/search_engines/test_search_engine_openlibrary_deep_coverage.py
new file mode 100644
index 0000000000..6271941d84
--- /dev/null
+++ b/tests/search_engines/test_search_engine_openlibrary_deep_coverage.py
@@ -0,0 +1,166 @@
+"""
+Tests for uncovered code paths in OpenLibrarySearchEngine.
+
+Targets:
+- _get_full_content: language/subject/publisher normalization, content building, has_fulltext
+- get_author: success, rate limit, exception
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (
+ OpenLibrarySearchEngine,
+)
+from local_deep_research.web_search_engines.rate_limiting import RateLimitError
+
+MODULE = (
+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary"
+)
+
+
+def engine():
+ eng = OpenLibrarySearchEngine(max_results=5)
+ eng.rate_tracker = Mock()
+ eng.rate_tracker.apply_rate_limit.return_value = 0
+ return eng
+
+
+def _mock_response(status_code=200, json_data=None):
+ resp = Mock()
+ resp.status_code = status_code
+ resp.json.return_value = json_data or {}
+ resp.raise_for_status = Mock()
+ if status_code >= 400:
+ resp.raise_for_status.side_effect = Exception(f"HTTP {status_code}")
+ return resp
+
+
+# ---------------------------------------------------------------------------
+# _get_full_content
+# ---------------------------------------------------------------------------
+
+
+class TestGetFullContent:
+ def test_builds_content_with_all_fields(self, engine):
+ """Content string includes authors, year, editions, subjects."""
+ items = [
+ {
+ "title": "The Lord of the Rings",
+ "authors": ["J.R.R. Tolkien"],
+ "first_publish_year": 1954,
+ "edition_count": 200,
+ "has_fulltext": True,
+ "_raw": {
+ "language": ["eng", "fre"],
+ "subject": ["Fantasy", "Adventure", "Epic"],
+ "publisher": ["HarperCollins", "Houghton Mifflin"],
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ content = results[0]["content"]
+ assert "Authors: J.R.R. Tolkien" in content
+ assert "First published: 1954" in content
+ assert "Editions: 200" in content
+ assert "Fantasy" in content
+ assert "Full text available" in content
+ assert results[0]["languages"] == ["eng", "fre"]
+ assert results[0]["publishers"] == ["HarperCollins", "Houghton Mifflin"]
+ assert "_raw" not in results[0]
+
+ def test_language_string_normalized_to_list(self, engine):
+ """String language values are converted to list."""
+ items = [
+ {
+ "title": "Test",
+ "_raw": {"language": "eng", "subject": [], "publisher": []},
+ }
+ ]
+
+ results = engine._get_full_content(items)
+ assert results[0]["languages"] == ["eng"]
+
+ def test_subject_string_normalized_to_list(self, engine):
+ """String subject values are converted to list."""
+ items = [
+ {
+ "title": "Test",
+ "_raw": {"language": [], "subject": "Science", "publisher": []},
+ }
+ ]
+
+ results = engine._get_full_content(items)
+ assert results[0]["subjects"] == ["Science"]
+
+ def test_publisher_string_normalized_to_list(self, engine):
+ """String publisher values are converted to list."""
+ items = [
+ {
+ "title": "Test",
+ "_raw": {"language": [], "subject": [], "publisher": "Penguin"},
+ }
+ ]
+
+ results = engine._get_full_content(items)
+ assert results[0]["publishers"] == ["Penguin"]
+
+ def test_without_raw(self, engine):
+ """Items without _raw data still pass through."""
+ items = [{"title": "Minimal Book"}]
+
+ results = engine._get_full_content(items)
+ assert len(results) == 1
+ assert "_raw" not in results[0]
+
+ def test_no_fulltext_omitted(self, engine):
+ """Content omits fulltext line when has_fulltext is False."""
+ items = [
+ {
+ "title": "Test",
+ "has_fulltext": False,
+ "_raw": {"language": [], "subject": [], "publisher": []},
+ }
+ ]
+
+ results = engine._get_full_content(items)
+ assert "Full text" not in results[0].get("content", "")
+
+
+# ---------------------------------------------------------------------------
+# get_author
+# ---------------------------------------------------------------------------
+
+
+class TestGetAuthor:
+ @patch(f"{MODULE}.safe_get")
+ def test_success(self, mock_get, engine):
+ """Returns author dict on success."""
+ author = {"name": "Tolkien", "birth_date": "1892"}
+ mock_get.return_value = _mock_response(200, author)
+
+ result = engine.get_author("/authors/OL26320A")
+
+ assert result["name"] == "Tolkien"
+
+ @patch(f"{MODULE}.safe_get")
+ def test_rate_limit_propagates(self, mock_get, engine):
+ """RateLimitError is re-raised."""
+ mock_get.return_value = _mock_response(429)
+ engine._raise_if_rate_limit = Mock(side_effect=RateLimitError("429"))
+
+ with pytest.raises(RateLimitError):
+ engine.get_author("/authors/OL26320A")
+
+ @patch(f"{MODULE}.safe_get")
+ def test_exception_returns_none(self, mock_get, engine):
+ """Other exceptions return None."""
+ mock_get.side_effect = ConnectionError("fail")
+
+ result = engine.get_author("/authors/OL26320A")
+ assert result is None
diff --git a/tests/search_engines/test_search_engine_stackexchange_deep_coverage.py b/tests/search_engines/test_search_engine_stackexchange_deep_coverage.py
new file mode 100644
index 0000000000..2de9f303b2
--- /dev/null
+++ b/tests/search_engines/test_search_engine_stackexchange_deep_coverage.py
@@ -0,0 +1,208 @@
+"""
+Tests for uncovered code paths in StackExchangeSearchEngine.
+
+Targets:
+- _get_full_content: content building, HTML cleaning, accepted answer, tags
+- get_question: success, rate limit, exception, empty items
+- get_answers: success, rate limit, exception
+- search_by_tag: tag switching, cleanup on exception
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (
+ StackExchangeSearchEngine,
+)
+from local_deep_research.web_search_engines.rate_limiting import RateLimitError
+
+MODULE = (
+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange"
+)
+
+
+def engine():
+ eng = StackExchangeSearchEngine(max_results=5, site="stackoverflow")
+ eng.rate_tracker = Mock()
+ eng.rate_tracker.apply_rate_limit.return_value = 0
+ return eng
+
+
+def _mock_response(status_code=200, json_data=None):
+ resp = Mock()
+ resp.status_code = status_code
+ resp.json.return_value = json_data or {}
+ resp.raise_for_status = Mock()
+ if status_code >= 400:
+ resp.raise_for_status.side_effect = Exception(f"HTTP {status_code}")
+ return resp
+
+
+# ---------------------------------------------------------------------------
+# _get_full_content
+# ---------------------------------------------------------------------------
+
+
+class TestGetFullContent:
+ def test_builds_content_from_raw(self, engine):
+ """Builds content string from raw question data."""
+ items = [
+ {
+ "title": "How to sort a list",
+ "author": "alice",
+ "score": 42,
+ "answer_count": 3,
+ "has_accepted_answer": True,
+ "tags": ["python", "sorting"],
+ "_raw": {
+ "body": "<p>I want to sort a <b>list</b> in Python.</p>"
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ content = results[0]["content"]
+ assert "Question: How to sort a list" in content
+ assert "Author: alice" in content
+ assert "Score: 42" in content
+ assert "Answers: 3" in content
+ assert "Has accepted answer: Yes" in content
+ assert "Tags: python, sorting" in content
+ assert "sort a list in Python" in content
+ assert "<p>" not in content # HTML stripped
+ assert "_raw" not in results[0]
+
+ def test_no_accepted_answer(self, engine):
+ """Content omits accepted answer line when False."""
+ items = [
+ {
+ "title": "Q",
+ "has_accepted_answer": False,
+ "tags": [],
+ "_raw": {
+ "body": "<p>Body text that is long enough to test.</p>"
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+ assert "accepted answer" not in results[0].get("content", "")
+
+ def test_without_raw(self, engine):
+ """Items without _raw get no content added."""
+ items = [{"title": "Q", "snippet": "existing"}]
+
+ results = engine._get_full_content(items)
+ assert len(results) == 1
+ assert "content" not in results[0]
+
+
+# ---------------------------------------------------------------------------
+# get_question
+# ---------------------------------------------------------------------------
+
+
+class TestGetQuestion:
+ @patch(f"{MODULE}.safe_get")
+ def test_success(self, mock_get, engine):
+ """Returns question dict on success."""
+ question = {"question_id": 12345, "title": "Test"}
+ mock_get.return_value = _mock_response(
+ 200, {"items": [question], "backoff": None}
+ )
+
+ result = engine.get_question(12345)
+
+ assert result["question_id"] == 12345
+
+ @patch(f"{MODULE}.safe_get")
+ def test_empty_items(self, mock_get, engine):
+ """Returns None when no items."""
+ mock_get.return_value = _mock_response(200, {"items": []})
+
+ result = engine.get_question(99999)
+ assert result is None
+
+ @patch(f"{MODULE}.safe_get")
+ def test_rate_limit_propagates(self, mock_get, engine):
+ """RateLimitError is re-raised."""
+ mock_get.return_value = _mock_response(429)
+ engine._raise_if_rate_limit = Mock(side_effect=RateLimitError("429"))
+
+ with pytest.raises(RateLimitError):
+ engine.get_question(12345)
+
+ @patch(f"{MODULE}.safe_get")
+ def test_exception_returns_none(self, mock_get, engine):
+ """Other exceptions return None."""
+ mock_get.side_effect = ConnectionError("fail")
+
+ result = engine.get_question(12345)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# get_answers
+# ---------------------------------------------------------------------------
+
+
+class TestGetAnswers:
+ @patch(f"{MODULE}.safe_get")
+ def test_success(self, mock_get, engine):
+ """Returns list of answers."""
+ answers = [
+ {"answer_id": 1, "body": "Answer 1"},
+ {"answer_id": 2, "body": "Answer 2"},
+ ]
+ mock_get.return_value = _mock_response(200, {"items": answers})
+
+ result = engine.get_answers(12345)
+
+ assert len(result) == 2
+ assert result[0]["answer_id"] == 1
+
+ @patch(f"{MODULE}.safe_get")
+ def test_rate_limit_propagates(self, mock_get, engine):
+ """RateLimitError is re-raised."""
+ mock_get.return_value = _mock_response(429)
+ engine._raise_if_rate_limit = Mock(side_effect=RateLimitError("429"))
+
+ with pytest.raises(RateLimitError):
+ engine.get_answers(12345)
+
+ @patch(f"{MODULE}.safe_get")
+ def test_exception_returns_empty(self, mock_get, engine):
+ """Other exceptions return empty list."""
+ mock_get.side_effect = ConnectionError("fail")
+
+ result = engine.get_answers(12345)
+ assert result == []
+
+
+# ---------------------------------------------------------------------------
+# search_by_tag
+# ---------------------------------------------------------------------------
+
+
+class TestSearchByTag:
+ def test_sets_tag_and_restores(self, engine):
+ """Temporarily sets tagged filter and restores."""
+ engine.tagged = None
+ with patch.object(engine, "run", return_value=[]) as mock_run:
+ engine.search_by_tag("python", "sorting")
+
+ mock_run.assert_called_once_with("sorting")
+ assert engine.tagged is None
+
+ def test_restores_on_exception(self, engine):
+ """Tagged is restored even on exception."""
+ engine.tagged = "original"
+ with patch.object(engine, "run", side_effect=Exception("fail")):
+ with pytest.raises(Exception, match="fail"):
+ engine.search_by_tag("python")
+
+ assert engine.tagged == "original"
diff --git a/tests/web_search_engines/engines/test_search_engine_nasa_ads_deep_coverage.py b/tests/web_search_engines/engines/test_search_engine_nasa_ads_deep_coverage.py
new file mode 100644
index 0000000000..57c78bf856
--- /dev/null
+++ b/tests/web_search_engines/engines/test_search_engine_nasa_ads_deep_coverage.py
@@ -0,0 +1,202 @@
+"""
+Tests for uncovered code paths in NASAADSSearchEngine._format_doc_preview.
+
+Targets:
+- bibstem as string vs list
+- DOI as string vs list
+- missing abstract
+- non-arXiv paper
+- empty keywords
+- exception in formatting returns None
+- journal from bibstem fallback
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.web_search_engines.engines.search_engine_nasa_ads import (
+ NasaAdsSearchEngine,
+)
+
+MODULE = "local_deep_research.web_search_engines.engines.search_engine_nasa_ads"
+
+
+def engine():
+ """Create engine with mocked init to avoid settings context requirement."""
+ with patch(f"{MODULE}.JournalReputationFilter"):
+ eng = NasaAdsSearchEngine(
+ api_key="test-key",
+ max_results=5,
+ settings_snapshot={
+ "llm.ollama.url": {"value": "http://localhost:11434"},
+ },
+ )
+ eng.rate_tracker = Mock()
+ eng.rate_tracker.apply_rate_limit.return_value = 0
+ return eng
+
+
+class TestFormatDocPreview:
+ def test_basic_document(self, engine):
+ """Formats basic document correctly."""
+ doc = {
+ "bibcode": "2024ApJ...123...45S",
+ "title": ["A Study of Stars"],
+ "abstract": "We study stars in detail.",
+ "year": "2024",
+ "pubdate": "2024-01-15",
+ "pub": "The Astrophysical Journal",
+ "author": ["Smith, J.", "Doe, A."],
+ "citation_count": 42,
+ "doi": ["10.1234/test"],
+ "keyword": ["stars", "astronomy"],
+ }
+
+ preview = engine._format_doc_preview(doc)
+
+ assert preview is not None
+ assert preview["title"] == "A Study of Stars"
+ assert preview["year"] == "2024"
+ assert preview["journal"] == "The Astrophysical Journal"
+ assert preview["citations"] == 42
+ assert "Smith, J., Doe, A." in preview["authors"]
+ assert preview["keywords"] == ["stars", "astronomy"]
+ assert "doi.org" in preview["link"]
+
+ def test_bibstem_as_string(self, engine):
+ """Handles bibstem as string instead of list."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": ["Test"],
+ "bibstem": "ApJ",
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert preview["journal"] == "ApJ"
+
+ def test_bibstem_as_list(self, engine):
+ """Handles bibstem as list."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": ["Test"],
+ "bibstem": ["MNRAS"],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert preview["journal"] == "MNRAS"
+
+ def test_empty_bibstem(self, engine):
+ """Handles empty bibstem list."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": ["Test"],
+ "bibstem": [],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert preview["journal"] == "unknown"
+
+ def test_doi_as_string(self, engine):
+ """Handles DOI as string."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": ["Test"],
+ "doi": "10.1234/test",
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert "doi.org/10.1234/test" in preview["link"]
+
+ def test_doi_as_list(self, engine):
+ """Handles DOI as list."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": ["Test"],
+ "doi": ["10.5678/test"],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert "doi.org/10.5678/test" in preview["link"]
+
+ def test_no_doi_uses_ads_url(self, engine):
+ """Falls back to ADS URL when no DOI."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": ["Test"],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert "adsabs.harvard.edu" in preview["link"]
+ assert "2024Test" in preview["link"]
+
+ def test_no_abstract_uses_title(self, engine):
+ """Snippet uses title when no abstract."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": ["Important Discovery"],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert "Important Discovery" in preview["snippet"]
+
+ def test_arxiv_detection(self, engine):
+ """Detects arXiv papers from bibstem."""
+ doc = {
+ "bibcode": "2024arXiv",
+ "title": ["arXiv Paper"],
+ "bibstem": ["arXiv"],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert preview["is_arxiv"] is True
+
+ def test_non_arxiv(self, engine):
+ """Non-arXiv papers are correctly identified."""
+ doc = {
+ "bibcode": "2024ApJ",
+ "title": ["Journal Paper"],
+ "bibstem": ["ApJ"],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert preview["is_arxiv"] is False
+
+ def test_empty_keywords(self, engine):
+ """Handles missing keywords."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": ["Test"],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert preview["keywords"] == []
+
+ def test_many_authors_truncated(self, engine):
+ """Authors list truncated to 5 with 'et al.'."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": ["Test"],
+ "author": [f"Author{i}" for i in range(10)],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert "et al." in preview["authors"]
+
+ def test_empty_title_list(self, engine):
+ """Handles empty title list."""
+ doc = {
+ "bibcode": "2024Test",
+ "title": [],
+ }
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert preview["title"] == "No title"
+
+ def test_no_title_key(self, engine):
+ """Handles document with no title key at all."""
+ doc = {"bibcode": "2024Test"}
+ preview = engine._format_doc_preview(doc)
+ assert preview is not None
+ assert preview["title"] == "No title"