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 102 high-value tests targeting coverage gaps (#2979)

LearningCircuit89d978024ca9
diff --git a/tests/benchmarks/test_graders_deep_coverage.py b/tests/benchmarks/test_graders_deep_coverage.py
new file mode 100644
index 0000000000..de793220c9
--- /dev/null
+++ b/tests/benchmarks/test_graders_deep_coverage.py
@@ -0,0 +1,404 @@
+"""
+Tests for uncovered code paths in graders.py.
+
+Targets:
+- extract_answer_from_response: browsecomp mode, missing matches
+- grade_single_result: various LLM interfaces (chat_messages, content attr, callable)
+- grade_results / _grade_results_inner: browsecomp extraction, progress callbacks, error handling
+- human_evaluation: non-interactive mode
+"""
+
+import json
+from unittest.mock import Mock, patch
+
+
+class TestExtractAnswerFromResponse:
+ """Tests for extract_answer_from_response."""
+
+ def test_simpleqa_returns_full_response(self):
+ """SimpleQA mode returns full response as extracted answer."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ result = extract_answer_from_response(
+ "The answer is 42 [1] with citations [2]", "simpleqa"
+ )
+
+ assert "42" in result["extracted_answer"]
+ assert result["confidence"] == "100"
+ # Citations should be stripped
+ assert "[1]" not in result["extracted_answer"]
+ assert "[2]" not in result["extracted_answer"]
+
+ def test_browsecomp_extracts_answer_and_confidence(self):
+ """BrowseComp mode extracts answer and confidence from structured response."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ response = "Exact Answer: The Great Wall of China\nConfidence: 85%"
+ result = extract_answer_from_response(response, "browsecomp")
+
+ assert result["extracted_answer"] == "The Great Wall of China"
+ assert result["confidence"] == "85"
+
+ def test_browsecomp_missing_answer_field(self):
+ """BrowseComp mode returns 'None' when answer field is missing."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ result = extract_answer_from_response(
+ "Some unstructured response", "browsecomp"
+ )
+
+ assert result["extracted_answer"] == "None"
+
+ def test_browsecomp_missing_confidence(self):
+ """BrowseComp mode defaults to 100 when confidence is missing."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ result = extract_answer_from_response(
+ "Exact Answer: Something\nNo confidence here", "browsecomp"
+ )
+
+ assert result["confidence"] == "100"
+
+ def test_citations_stripped_from_response(self):
+ """Citation markers like [1], [23] are removed."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ result = extract_answer_from_response(
+ "The answer [1] is 42 [23] exactly.", "simpleqa"
+ )
+
+ assert "[1]" not in result["extracted_answer"]
+ assert "[23]" not in result["extracted_answer"]
+ assert "42" in result["extracted_answer"]
+
+
+class TestGradeSingleResult:
+ """Tests for grade_single_result."""
+
+ @patch("local_deep_research.benchmarks.graders.get_evaluation_llm")
+ @patch("local_deep_research.utilities.resource_utils.safe_close")
+ def test_grade_single_result_with_content_attr(
+ self, mock_close, mock_get_llm
+ ):
+ """grade_single_result handles LLM response with .content attribute."""
+ from local_deep_research.benchmarks.graders import grade_single_result
+
+ mock_llm = Mock()
+ mock_response = Mock()
+ mock_response.content = (
+ "Extracted Answer: 42\nReasoning: Matches exactly\nCorrect: yes"
+ )
+ mock_llm.invoke.return_value = mock_response
+ mock_llm.chat_messages = None # Has invoke but not chat_messages
+ # Remove chat_messages to trigger the else branch
+ del mock_llm.chat_messages
+ mock_get_llm.return_value = mock_llm
+
+ result = grade_single_result(
+ {
+ "problem": "What is 6 * 7?",
+ "correct_answer": "42",
+ "response": "The answer is 42",
+ },
+ dataset_type="simpleqa",
+ )
+
+ assert result["is_correct"] is True
+ assert result["extracted_by_grader"] == "42"
+
+ @patch("local_deep_research.benchmarks.graders.get_evaluation_llm")
+ @patch("local_deep_research.utilities.resource_utils.safe_close")
+ def test_grade_single_result_browsecomp(self, mock_close, mock_get_llm):
+ """grade_single_result handles browsecomp extraction format."""
+ from local_deep_research.benchmarks.graders import grade_single_result
+
+ mock_llm = Mock()
+ mock_response = Mock()
+ mock_response.content = (
+ "extracted_final_answer: The Great Wall\n"
+ "reasoning: The response correctly identifies the structure\n\n"
+ "correct: yes\n"
+ "confidence: 90"
+ )
+ mock_llm.invoke.return_value = mock_response
+ del mock_llm.chat_messages
+ mock_get_llm.return_value = mock_llm
+
+ result = grade_single_result(
+ {
+ "problem": "What is the longest wall?",
+ "correct_answer": "The Great Wall",
+ "response": "The Great Wall of China",
+ },
+ dataset_type="browsecomp",
+ )
+
+ assert result["is_correct"] is True
+ assert result["extracted_by_grader"] == "The Great Wall"
+ assert result["graded_confidence"] == "90"
+
+ @patch("local_deep_research.benchmarks.graders.get_evaluation_llm")
+ @patch("local_deep_research.utilities.resource_utils.safe_close")
+ def test_grade_single_result_callable_fallback(
+ self, mock_close, mock_get_llm
+ ):
+ """grade_single_result falls back to calling LLM as callable."""
+ from local_deep_research.benchmarks.graders import grade_single_result
+
+ mock_llm = Mock()
+ # Remove invoke to trigger callable fallback
+ del mock_llm.invoke
+ mock_llm.return_value = (
+ "Extracted Answer: 42\nReasoning: ok\nCorrect: yes"
+ )
+ mock_get_llm.return_value = mock_llm
+
+ result = grade_single_result(
+ {
+ "problem": "What?",
+ "correct_answer": "42",
+ "response": "42",
+ },
+ )
+
+ assert result["is_correct"] is True
+
+ @patch("local_deep_research.benchmarks.graders.get_evaluation_llm")
+ @patch("local_deep_research.utilities.resource_utils.safe_close")
+ def test_grade_single_result_exception(self, mock_close, mock_get_llm):
+ """grade_single_result handles exceptions gracefully."""
+ from local_deep_research.benchmarks.graders import grade_single_result
+
+ mock_llm = Mock()
+ mock_llm.invoke.side_effect = Exception("LLM failed")
+ del mock_llm.chat_messages
+ mock_get_llm.return_value = mock_llm
+
+ result = grade_single_result(
+ {"problem": "Q", "correct_answer": "A", "response": "R"},
+ )
+
+ assert result["is_correct"] is False
+ assert "grading_error" in result
+ assert "LLM failed" in result["grading_error"]
+
+ @patch("local_deep_research.benchmarks.graders.get_evaluation_llm")
+ @patch("local_deep_research.utilities.resource_utils.safe_close")
+ def test_grade_single_result_no_correct_match(
+ self, mock_close, mock_get_llm
+ ):
+ """grade_single_result defaults to incorrect when no 'Correct:' match."""
+ from local_deep_research.benchmarks.graders import grade_single_result
+
+ mock_llm = Mock()
+ mock_response = Mock()
+ mock_response.content = "Some response without the expected format"
+ mock_llm.invoke.return_value = mock_response
+ del mock_llm.chat_messages
+ mock_get_llm.return_value = mock_llm
+
+ result = grade_single_result(
+ {"problem": "Q", "correct_answer": "A", "response": "R"},
+ )
+
+ assert result["is_correct"] is False
+ assert result["extracted_by_grader"] == "None"
+
+
+class TestHumanEvaluation:
+ """Tests for human_evaluation non-interactive mode."""
+
+ def test_non_interactive_mode(self, tmp_path):
+ """human_evaluation in non-interactive mode marks all as incorrect."""
+ from local_deep_research.benchmarks.graders import human_evaluation
+
+ # Create input file
+ input_file = tmp_path / "results.jsonl"
+ results = [
+ {
+ "problem": "Q1",
+ "correct_answer": "A1",
+ "response": "R1",
+ "extracted_answer": "E1",
+ },
+ {
+ "problem": "Q2",
+ "correct_answer": "A2",
+ "response": "R2",
+ "extracted_answer": "E2",
+ },
+ ]
+ input_file.write_text("\n".join(json.dumps(r) for r in results))
+
+ output_file = tmp_path / "graded.jsonl"
+
+ graded = human_evaluation(
+ str(input_file), str(output_file), interactive=False
+ )
+
+ assert len(graded) == 2
+ assert all(r["is_correct"] is False for r in graded)
+ assert all(r["human_evaluation"] is True for r in graded)
+ assert all(
+ r["reasoning"] == "Non-interactive evaluation" for r in graded
+ )
+
+ # Check output file was written
+ assert output_file.exists()
+ lines = output_file.read_text().strip().split("\n")
+ assert len(lines) == 2
+
+ def test_non_interactive_empty_results(self, tmp_path):
+ """human_evaluation handles empty results file."""
+ from local_deep_research.benchmarks.graders import human_evaluation
+
+ input_file = tmp_path / "empty.jsonl"
+ input_file.write_text("")
+
+ output_file = tmp_path / "graded.jsonl"
+
+ graded = human_evaluation(
+ str(input_file), str(output_file), interactive=False
+ )
+
+ assert len(graded) == 0
+
+
+class TestGradeResultsInner:
+ """Tests for _grade_results_inner."""
+
+ def test_grade_results_with_progress_callback(self, tmp_path):
+ """_grade_results_inner calls progress callback correctly."""
+ from local_deep_research.benchmarks.graders import _grade_results_inner
+
+ # Create input file
+ input_file = tmp_path / "results.jsonl"
+ input_file.write_text(
+ json.dumps(
+ {
+ "problem": "Q1",
+ "correct_answer": "42",
+ "response": "42",
+ }
+ )
+ )
+ output_file = tmp_path / "graded.jsonl"
+
+ mock_llm = Mock()
+ mock_response = Mock()
+ mock_response.content = (
+ "Extracted Answer: 42\nReasoning: ok\nCorrect: yes"
+ )
+ mock_llm.invoke.return_value = mock_response
+ del mock_llm.chat_messages
+
+ callback_calls = []
+
+ def progress_callback(idx, total, data):
+ callback_calls.append((idx, total, data))
+
+ result = _grade_results_inner(
+ mock_llm,
+ str(input_file),
+ str(output_file),
+ "simpleqa",
+ progress_callback,
+ )
+
+ assert len(result) == 1
+ assert result[0]["is_correct"] is True
+ # Should have at least 2 callbacks: grading + graded
+ assert len(callback_calls) >= 2
+
+ def test_grade_results_error_handling(self, tmp_path):
+ """_grade_results_inner handles grading errors per result."""
+ from local_deep_research.benchmarks.graders import _grade_results_inner
+
+ input_file = tmp_path / "results.jsonl"
+ input_file.write_text(
+ json.dumps({"problem": "Q", "correct_answer": "A", "response": "R"})
+ )
+ output_file = tmp_path / "graded.jsonl"
+
+ mock_llm = Mock()
+ mock_llm.invoke.side_effect = Exception("LLM error")
+ del mock_llm.chat_messages
+
+ result = _grade_results_inner(
+ mock_llm, str(input_file), str(output_file), "simpleqa", None
+ )
+
+ assert len(result) == 1
+ assert "grading_error" in result[0]
+
+ def test_grade_results_browsecomp_extraction(self, tmp_path):
+ """_grade_results_inner uses browsecomp extraction format."""
+ from local_deep_research.benchmarks.graders import _grade_results_inner
+
+ input_file = tmp_path / "results.jsonl"
+ input_file.write_text(
+ json.dumps(
+ {
+ "problem": "What is X?",
+ "correct_answer": "Y",
+ "response": "Y is correct",
+ }
+ )
+ )
+ output_file = tmp_path / "graded.jsonl"
+
+ mock_llm = Mock()
+ mock_response = Mock()
+ mock_response.content = (
+ "extracted_final_answer: Y\n"
+ "reasoning: Exact match\n\n"
+ "correct: yes\n"
+ "confidence: 95"
+ )
+ mock_llm.invoke.return_value = mock_response
+ del mock_llm.chat_messages
+
+ result = _grade_results_inner(
+ mock_llm, str(input_file), str(output_file), "browsecomp", None
+ )
+
+ assert len(result) == 1
+ assert result[0]["is_correct"] is True
+ assert result[0]["graded_confidence"] == "95"
+
+ def test_grade_results_removes_existing_output(self, tmp_path):
+ """_grade_results_inner removes existing output file before writing."""
+ from local_deep_research.benchmarks.graders import _grade_results_inner
+
+ input_file = tmp_path / "results.jsonl"
+ input_file.write_text(
+ json.dumps({"problem": "Q", "correct_answer": "A", "response": "R"})
+ )
+ output_file = tmp_path / "graded.jsonl"
+ output_file.write_text("old data\n")
+
+ mock_llm = Mock()
+ mock_response = Mock()
+ mock_response.content = (
+ "Extracted Answer: A\nReasoning: ok\nCorrect: yes"
+ )
+ mock_llm.invoke.return_value = mock_response
+ del mock_llm.chat_messages
+
+ _grade_results_inner(
+ mock_llm, str(input_file), str(output_file), "simpleqa", None
+ )
+
+ # Output should not contain old data
+ content = output_file.read_text()
+ assert "old data" not in content
diff --git a/tests/embeddings/test_embeddings_config_deep_coverage.py b/tests/embeddings/test_embeddings_config_deep_coverage.py
new file mode 100644
index 0000000000..4074a239cc
--- /dev/null
+++ b/tests/embeddings/test_embeddings_config_deep_coverage.py
@@ -0,0 +1,232 @@
+"""
+Tests for uncovered code paths in embeddings_config.py.
+
+Targets:
+- get_embeddings: invalid provider, None provider from settings, provider normalization
+- get_embedding_function: returns callable
+- get_available_embedding_providers: with mocked availability checks
+- _get_provider_classes: lazy loading and caching
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+MODULE = "local_deep_research.embeddings.embeddings_config"
+
+
+class TestGetEmbeddings:
+ """Tests for get_embeddings function."""
+
+ def test_invalid_provider_raises(self):
+ """Invalid provider raises ValueError."""
+ from local_deep_research.embeddings.embeddings_config import (
+ get_embeddings,
+ )
+
+ with pytest.raises(ValueError, match="Invalid embedding provider"):
+ get_embeddings(provider="nonexistent_provider")
+
+ def test_provider_normalization(self):
+ """Provider string is normalized (stripped, lowered)."""
+ from local_deep_research.embeddings.embeddings_config import (
+ get_embeddings,
+ )
+
+ with patch(f"{MODULE}._get_provider_classes") as mock_classes:
+ mock_provider = Mock()
+ mock_provider.create_embeddings.return_value = Mock()
+ mock_classes.return_value = {
+ "sentence_transformers": mock_provider,
+ "ollama": Mock(),
+ "openai": Mock(),
+ }
+
+ get_embeddings(provider=' "sentence_transformers" ')
+
+ mock_provider.create_embeddings.assert_called_once()
+
+ def test_provider_from_settings_snapshot(self):
+ """Provider is read from settings when not specified."""
+ from local_deep_research.embeddings.embeddings_config import (
+ get_embeddings,
+ )
+
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot", return_value="ollama"
+ ):
+ with patch(f"{MODULE}._get_provider_classes") as mock_classes:
+ mock_provider = Mock()
+ mock_provider.create_embeddings.return_value = Mock()
+ mock_classes.return_value = {
+ "sentence_transformers": Mock(),
+ "ollama": mock_provider,
+ "openai": Mock(),
+ }
+
+ get_embeddings(
+ settings_snapshot={"embeddings.provider": "ollama"}
+ )
+
+ mock_provider.create_embeddings.assert_called_once()
+
+ def test_model_passed_to_provider(self):
+ """Model name is passed through to provider."""
+ from local_deep_research.embeddings.embeddings_config import (
+ get_embeddings,
+ )
+
+ with patch(f"{MODULE}._get_provider_classes") as mock_classes:
+ mock_provider = Mock()
+ mock_provider.create_embeddings.return_value = Mock()
+ mock_classes.return_value = {
+ "sentence_transformers": mock_provider,
+ "ollama": Mock(),
+ "openai": Mock(),
+ }
+
+ get_embeddings(
+ provider="sentence_transformers", model="all-MiniLM-L6-v2"
+ )
+
+ mock_provider.create_embeddings.assert_called_once_with(
+ model="all-MiniLM-L6-v2", settings_snapshot=None
+ )
+
+
+class TestGetEmbeddingFunction:
+ """Tests for get_embedding_function."""
+
+ def test_returns_callable(self):
+ """Returns embed_documents method from embeddings object."""
+ from local_deep_research.embeddings.embeddings_config import (
+ get_embedding_function,
+ )
+
+ with patch(f"{MODULE}.get_embeddings") as mock_get:
+ mock_embeddings = Mock()
+ mock_embeddings.embed_documents = Mock(return_value=[[0.1, 0.2]])
+ mock_get.return_value = mock_embeddings
+
+ fn = get_embedding_function(provider="sentence_transformers")
+
+ assert callable(fn)
+ result = fn(["test text"])
+ assert result == [[0.1, 0.2]]
+
+
+class TestGetAvailableProviders:
+ """Tests for get_available_embedding_providers."""
+
+ def test_all_available(self):
+ """Returns all providers when all are available."""
+ from local_deep_research.embeddings.embeddings_config import (
+ get_available_embedding_providers,
+ )
+
+ with patch(
+ f"{MODULE}.is_sentence_transformers_available", return_value=True
+ ):
+ with patch(
+ f"{MODULE}.is_ollama_embeddings_available", return_value=True
+ ):
+ with patch(
+ f"{MODULE}.is_openai_embeddings_available",
+ return_value=True,
+ ):
+ providers = get_available_embedding_providers()
+
+ assert "sentence_transformers" in providers
+ assert "ollama" in providers
+ assert "openai" in providers
+
+ def test_none_available(self):
+ """Returns empty dict when no providers available."""
+ from local_deep_research.embeddings.embeddings_config import (
+ get_available_embedding_providers,
+ )
+
+ with patch(
+ f"{MODULE}.is_sentence_transformers_available", return_value=False
+ ):
+ with patch(
+ f"{MODULE}.is_ollama_embeddings_available", return_value=False
+ ):
+ with patch(
+ f"{MODULE}.is_openai_embeddings_available",
+ return_value=False,
+ ):
+ providers = get_available_embedding_providers()
+
+ assert providers == {}
+
+ def test_partial_availability(self):
+ """Returns only available providers."""
+ from local_deep_research.embeddings.embeddings_config import (
+ get_available_embedding_providers,
+ )
+
+ with patch(
+ f"{MODULE}.is_sentence_transformers_available", return_value=True
+ ):
+ with patch(
+ f"{MODULE}.is_ollama_embeddings_available", return_value=False
+ ):
+ with patch(
+ f"{MODULE}.is_openai_embeddings_available",
+ return_value=True,
+ ):
+ providers = get_available_embedding_providers()
+
+ assert "sentence_transformers" in providers
+ assert "ollama" not in providers
+ assert "openai" in providers
+
+
+class TestProviderAvailabilityChecks:
+ """Tests for individual provider availability checks."""
+
+ def test_sentence_transformers_available(self):
+ """is_sentence_transformers_available delegates to provider."""
+ from local_deep_research.embeddings.embeddings_config import (
+ is_sentence_transformers_available,
+ )
+
+ with patch(f"{MODULE}._get_provider_classes") as mock_classes:
+ mock_st = Mock()
+ mock_st.is_available.return_value = True
+ mock_classes.return_value = {"sentence_transformers": mock_st}
+
+ assert is_sentence_transformers_available() is True
+ mock_st.is_available.assert_called_once()
+
+ def test_ollama_available_with_snapshot(self):
+ """is_ollama_embeddings_available passes settings_snapshot."""
+ from local_deep_research.embeddings.embeddings_config import (
+ is_ollama_embeddings_available,
+ )
+
+ snapshot = {"ollama.url": "http://localhost:11434"}
+
+ with patch(f"{MODULE}._get_provider_classes") as mock_classes:
+ mock_ollama = Mock()
+ mock_ollama.is_available.return_value = False
+ mock_classes.return_value = {"ollama": mock_ollama}
+
+ result = is_ollama_embeddings_available(snapshot)
+
+ assert result is False
+ mock_ollama.is_available.assert_called_once_with(snapshot)
+
+ def test_openai_available(self):
+ """is_openai_embeddings_available delegates to provider."""
+ from local_deep_research.embeddings.embeddings_config import (
+ is_openai_embeddings_available,
+ )
+
+ with patch(f"{MODULE}._get_provider_classes") as mock_classes:
+ mock_openai = Mock()
+ mock_openai.is_available.return_value = True
+ mock_classes.return_value = {"openai": mock_openai}
+
+ assert is_openai_embeddings_available() is True
diff --git a/tests/research_library/downloaders/test_generic_downloader_deep_coverage.py b/tests/research_library/downloaders/test_generic_downloader_deep_coverage.py
new file mode 100644
index 0000000000..e6bb807614
--- /dev/null
+++ b/tests/research_library/downloaders/test_generic_downloader_deep_coverage.py
@@ -0,0 +1,403 @@
+"""
+Tests for uncovered code paths in GenericDownloader.
+
+Targets:
+- download_with_result: diagnostic HTTP status code handling (200 HTML, 404, 403, 401, 500+, other)
+- download_with_result: timeout, connection error, generic request error
+- download_with_result: PDF content type with text extraction
+- download_with_result: .pdf URL append fallback
+- _download_pdf: URL with .pdf extension already (skips append)
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+import requests
+
+from local_deep_research.research_library.downloaders.generic import (
+ GenericDownloader,
+)
+from local_deep_research.research_library.downloaders.base import (
+ ContentType,
+)
+
+MODULE = "local_deep_research.research_library.downloaders.generic"
+
+
+def downloader():
+ dl = GenericDownloader(timeout=30)
+ return dl
+
+
+class TestDownloadWithResultDiagnostic:
+ """Tests for download_with_result diagnostic HTTP status branches."""
+
+ def test_200_html_returns_login_required(self, downloader):
+ """200 with HTML content type suggests login/subscription needed."""
+ # Mock both _download_pdf calls to fail
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ # Mock diagnostic request
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.headers = {"content-type": "text/html; charset=utf-8"}
+ mock_response.__enter__ = Mock(return_value=mock_response)
+ mock_response.__exit__ = Mock(return_value=False)
+
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_response
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "login or subscription" in result.skip_reason
+
+ def test_200_unexpected_content_type(self, downloader):
+ """200 with non-HTML non-PDF content type."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.headers = {"content-type": "application/xml"}
+ mock_response.__enter__ = Mock(return_value=mock_response)
+ mock_response.__exit__ = Mock(return_value=False)
+
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_response
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "Unexpected content type" in result.skip_reason
+
+ def test_404_returns_not_found(self, downloader):
+ """404 produces correct skip reason."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ mock_response = Mock()
+ mock_response.status_code = 404
+ mock_response.headers = {}
+ mock_response.__enter__ = Mock(return_value=mock_response)
+ mock_response.__exit__ = Mock(return_value=False)
+
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_response
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "not found (404)" in result.skip_reason
+
+ def test_403_returns_access_denied(self, downloader):
+ """403 produces access denied skip reason."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ mock_response = Mock()
+ mock_response.status_code = 403
+ mock_response.headers = {}
+ mock_response.__enter__ = Mock(return_value=mock_response)
+ mock_response.__exit__ = Mock(return_value=False)
+
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_response
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "Access denied (403)" in result.skip_reason
+
+ def test_401_returns_auth_required(self, downloader):
+ """401 produces authentication required skip reason."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ mock_response = Mock()
+ mock_response.status_code = 401
+ mock_response.headers = {}
+ mock_response.__enter__ = Mock(return_value=mock_response)
+ mock_response.__exit__ = Mock(return_value=False)
+
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_response
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "Authentication required" in result.skip_reason
+
+ def test_500_returns_server_error(self, downloader):
+ """500+ produces server error skip reason."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ mock_response = Mock()
+ mock_response.status_code = 503
+ mock_response.headers = {}
+ mock_response.__enter__ = Mock(return_value=mock_response)
+ mock_response.__exit__ = Mock(return_value=False)
+
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_response
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "Server error (503)" in result.skip_reason
+
+ def test_other_status_code(self, downloader):
+ """Other status codes produce generic error."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ mock_response = Mock()
+ mock_response.status_code = 451 # Unavailable For Legal Reasons
+ mock_response.headers = {}
+ mock_response.__enter__ = Mock(return_value=mock_response)
+ mock_response.__exit__ = Mock(return_value=False)
+
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_response
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "451" in result.skip_reason
+
+
+class TestDownloadWithResultNetworkErrors:
+ """Tests for network error handling in download_with_result."""
+
+ def test_timeout_error(self, downloader):
+ """Timeout produces correct skip reason."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ downloader.session = Mock()
+ downloader.session.get.side_effect = requests.exceptions.Timeout()
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "timed out" in result.skip_reason
+
+ def test_connection_error(self, downloader):
+ """Connection error produces correct skip reason."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ downloader.session = Mock()
+ downloader.session.get.side_effect = (
+ requests.exceptions.ConnectionError()
+ )
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "Could not connect" in result.skip_reason
+
+ def test_generic_request_error(self, downloader):
+ """Generic request exception produces network error skip reason."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ downloader.session = Mock()
+ downloader.session.get.side_effect = requests.RequestException(
+ "weird error"
+ )
+
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is False
+ assert "Network error" in result.skip_reason
+
+
+class TestDownloadWithResultTextContent:
+ """Tests for text content extraction in download_with_result."""
+
+ def test_text_content_success(self, downloader):
+ """Text content type downloads PDF and extracts text."""
+ with patch.object(
+ downloader, "_download_pdf", return_value=b"fake pdf"
+ ):
+ with patch.object(
+ downloader,
+ "extract_text_from_pdf",
+ return_value="Extracted text content",
+ ):
+ result = downloader.download_with_result(
+ "https://example.com/paper", ContentType.TEXT
+ )
+
+ assert result.is_success is True
+ assert result.content == b"Extracted text content"
+
+ def test_text_content_extraction_fails(self, downloader):
+ """Text extraction fails after PDF download."""
+ with patch.object(
+ downloader, "_download_pdf", return_value=b"fake pdf"
+ ):
+ with patch.object(
+ downloader, "extract_text_from_pdf", return_value=None
+ ):
+ result = downloader.download_with_result(
+ "https://example.com/paper", ContentType.TEXT
+ )
+
+ assert result.is_success is False
+ assert "text extraction failed" in result.skip_reason
+
+ def test_text_content_pdf_download_fails(self, downloader):
+ """PDF download fails for text content type."""
+ with patch.object(downloader, "_download_pdf", return_value=None):
+ result = downloader.download_with_result(
+ "https://example.com/paper", ContentType.TEXT
+ )
+
+ assert result.is_success is False
+ assert "Could not download PDF" in result.skip_reason
+
+
+class TestDownloadWithResultPdfFallback:
+ """Tests for .pdf URL append fallback in download_with_result."""
+
+ def test_pdf_url_append_succeeds(self, downloader):
+ """Appending .pdf to URL succeeds when direct download fails."""
+ call_count = [0]
+
+ def mock_download(url, *args, **kwargs):
+ call_count[0] += 1
+ if call_count[0] == 1:
+ return None # Direct download fails
+ return b"%PDF-1.4 fake pdf" # .pdf appended URL succeeds
+
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ side_effect=mock_download,
+ ):
+ result = downloader.download_with_result(
+ "https://example.com/paper"
+ )
+
+ assert result.is_success is True
+
+ def test_pdf_url_already_has_extension(self, downloader):
+ """URL already ending in .pdf doesn't get .pdf appended."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ mock_response = Mock()
+ mock_response.status_code = 404
+ mock_response.headers = {}
+ mock_response.__enter__ = Mock(return_value=mock_response)
+ mock_response.__exit__ = Mock(return_value=False)
+
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_response
+
+ result = downloader.download_with_result(
+ "https://example.com/paper.pdf"
+ )
+
+ assert result.is_success is False
+ # Should NOT try appending .pdf again
+
+
+class TestDownloadPdf:
+ """Tests for _download_pdf method."""
+
+ def test_direct_download_success(self, downloader):
+ """Direct download succeeds."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=b"%PDF",
+ ):
+ result = downloader._download_pdf("https://example.com/paper.pdf")
+ assert result == b"%PDF"
+
+ def test_appends_pdf_extension(self, downloader):
+ """Appends .pdf to URL when direct download fails."""
+ call_count = [0]
+
+ def mock_download(url, *args, **kwargs):
+ call_count[0] += 1
+ if ".pdf" in url and call_count[0] > 1:
+ return b"%PDF"
+ return None
+
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ side_effect=mock_download,
+ ):
+ result = downloader._download_pdf("https://example.com/paper")
+
+ assert result == b"%PDF"
+
+ def test_both_downloads_fail(self, downloader):
+ """Returns None when both downloads fail."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ result = downloader._download_pdf("https://example.com/paper")
+ assert result is None
+
+ def test_url_already_has_pdf_extension(self, downloader):
+ """URL with .pdf extension doesn't try double append."""
+ with patch.object(
+ downloader.__class__.__bases__[0],
+ "_download_pdf",
+ return_value=None,
+ ):
+ result = downloader._download_pdf("https://example.com/paper.pdf")
+ assert result is None
diff --git a/tests/research_library/downloaders/test_html_downloader_deep_coverage.py b/tests/research_library/downloaders/test_html_downloader_deep_coverage.py
new file mode 100644
index 0000000000..283078fcc6
--- /dev/null
+++ b/tests/research_library/downloaders/test_html_downloader_deep_coverage.py
@@ -0,0 +1,436 @@
+"""
+Tests for uncovered code paths in HTMLDownloader.
+
+Targets:
+- can_handle: non-http schemes, exception handling
+- download: PDF content type rejection, extraction failure
+- download_with_result: all branches (PDF, empty content, extraction failure, exception)
+- _fetch_html: non-200, non-HTML content type, exception
+- _extract_content: article/main/div/body fallback chain, tag formatting (h/li/blockquote/pre)
+- _format_extracted_content: all field formatting
+- get_metadata: success, failure, missing fields
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.research_library.downloaders.html import (
+ HTMLDownloader,
+)
+from local_deep_research.research_library.downloaders.base import (
+ ContentType,
+)
+
+
+def downloader():
+ dl = HTMLDownloader(timeout=30)
+ dl.rate_tracker = Mock()
+ dl.rate_tracker.apply_rate_limit.return_value = 0
+ dl.rate_tracker.record_outcome = Mock()
+ return dl
+
+
+# ---------------------------------------------------------------------------
+# can_handle
+# ---------------------------------------------------------------------------
+
+
+class TestCanHandle:
+ def test_http_url(self, downloader):
+ assert downloader.can_handle("http://example.com") is True
+
+ def test_https_url(self, downloader):
+ assert downloader.can_handle("https://example.com/page") is True
+
+ def test_ftp_url(self, downloader):
+ assert downloader.can_handle("ftp://files.example.com/data") is False
+
+ def test_invalid_url(self, downloader):
+ # urlparse doesn't usually raise, but we test the except branch
+ assert downloader.can_handle("") is False
+
+
+# ---------------------------------------------------------------------------
+# download
+# ---------------------------------------------------------------------------
+
+
+class TestDownload:
+ def test_pdf_content_type_rejected(self, downloader):
+ """PDF content type returns None."""
+ result = downloader.download(
+ "https://example.com/paper", ContentType.PDF
+ )
+ assert result is None
+
+ def test_success_returns_bytes(self, downloader):
+ """Successful download returns UTF-8 encoded text."""
+ html = """
+ <html><head><title>Test</title></head>
+ <body><article><p>This is a substantial paragraph with enough text to pass the length filter.</p></article></body>
+ </html>
+ """
+ with patch.object(downloader, "_fetch_html", return_value=html):
+ result = downloader.download("https://example.com/page")
+
+ assert result is not None
+ assert isinstance(result, bytes)
+ assert b"substantial paragraph" in result
+
+ def test_fetch_failure_returns_none(self, downloader):
+ """Returns None when fetch fails."""
+ with patch.object(downloader, "_fetch_html", return_value=None):
+ result = downloader.download("https://example.com/page")
+ assert result is None
+
+ def test_extraction_failure_returns_none(self, downloader):
+ """Returns None when content extraction fails."""
+ with patch.object(
+ downloader, "_fetch_html", return_value="<html></html>"
+ ):
+ with patch.object(
+ downloader, "_extract_content", return_value=None
+ ):
+ result = downloader.download("https://example.com/page")
+ assert result is None
+
+ def test_exception_returns_none(self, downloader):
+ """Returns None on unexpected exception."""
+ with patch.object(
+ downloader, "_fetch_html", side_effect=RuntimeError("fail")
+ ):
+ result = downloader.download("https://example.com/page")
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# download_with_result
+# ---------------------------------------------------------------------------
+
+
+class TestDownloadWithResult:
+ def test_pdf_content_type(self, downloader):
+ """PDF content type returns skip reason."""
+ result = downloader.download_with_result(
+ "https://example.com", ContentType.PDF
+ )
+ assert result.is_success is False
+ assert "PDF" in result.skip_reason
+
+ def test_fetch_failure(self, downloader):
+ """Fetch failure returns skip reason."""
+ with patch.object(downloader, "_fetch_html", return_value=None):
+ result = downloader.download_with_result("https://example.com")
+ assert result.is_success is False
+ assert "Failed to fetch" in result.skip_reason
+
+ def test_extraction_failure(self, downloader):
+ """Extraction failure returns skip reason."""
+ with patch.object(
+ downloader, "_fetch_html", return_value="<html></html>"
+ ):
+ with patch.object(
+ downloader, "_extract_content", return_value=None
+ ):
+ result = downloader.download_with_result("https://example.com")
+ assert result.is_success is False
+ assert "extract" in result.skip_reason.lower()
+
+ def test_empty_content(self, downloader):
+ """Empty extracted content returns skip reason."""
+ with patch.object(
+ downloader, "_fetch_html", return_value="<html></html>"
+ ):
+ with patch.object(
+ downloader,
+ "_extract_content",
+ return_value={"title": "T", "content": "ok", "url": "u"},
+ ):
+ with patch.object(
+ downloader, "_format_extracted_content", return_value=" "
+ ):
+ result = downloader.download_with_result(
+ "https://example.com"
+ )
+ assert result.is_success is False
+ assert "empty" in result.skip_reason.lower()
+
+ def test_success(self, downloader):
+ """Successful extraction returns content."""
+ with patch.object(
+ downloader, "_fetch_html", return_value="<html></html>"
+ ):
+ with patch.object(
+ downloader,
+ "_extract_content",
+ return_value={
+ "title": "T",
+ "content": "Real content",
+ "url": "https://example.com",
+ },
+ ):
+ with patch.object(
+ downloader,
+ "_format_extracted_content",
+ return_value="# T\n\nReal content",
+ ):
+ result = downloader.download_with_result(
+ "https://example.com"
+ )
+ assert result.is_success is True
+ assert b"Real content" in result.content
+
+ def test_exception(self, downloader):
+ """Exception returns error skip reason."""
+ with patch.object(
+ downloader, "_fetch_html", side_effect=ValueError("bad url")
+ ):
+ result = downloader.download_with_result("https://example.com")
+ assert result.is_success is False
+ assert "Error" in result.skip_reason
+
+
+# ---------------------------------------------------------------------------
+# _fetch_html
+# ---------------------------------------------------------------------------
+
+
+class TestFetchHtml:
+ def test_non_200_returns_none(self, downloader):
+ """Non-200 status returns None and records failure."""
+ mock_resp = Mock()
+ mock_resp.status_code = 403
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_resp
+
+ result = downloader._fetch_html("https://example.com")
+
+ assert result is None
+ downloader.rate_tracker.record_outcome.assert_called()
+
+ def test_non_html_content_type(self, downloader):
+ """Non-HTML content type returns None."""
+ mock_resp = Mock()
+ mock_resp.status_code = 200
+ mock_resp.headers = {"content-type": "application/pdf"}
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_resp
+
+ result = downloader._fetch_html("https://example.com")
+ assert result is None
+
+ def test_success_html(self, downloader):
+ """200 with HTML content type returns text."""
+ mock_resp = Mock()
+ mock_resp.status_code = 200
+ mock_resp.headers = {"content-type": "text/html; charset=utf-8"}
+ mock_resp.text = "<html><body>Hello</body></html>"
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_resp
+
+ result = downloader._fetch_html("https://example.com")
+ assert result == "<html><body>Hello</body></html>"
+
+ def test_xhtml_content_type(self, downloader):
+ """application/xhtml content type is accepted."""
+ mock_resp = Mock()
+ mock_resp.status_code = 200
+ mock_resp.headers = {"content-type": "application/xhtml+xml"}
+ mock_resp.text = "<html>XHTML</html>"
+ downloader.session = Mock()
+ downloader.session.get.return_value = mock_resp
+
+ result = downloader._fetch_html("https://example.com")
+ assert result == "<html>XHTML</html>"
+
+ def test_exception_returns_none(self, downloader):
+ """Network exception returns None and records failure."""
+ downloader.session = Mock()
+ downloader.session.get.side_effect = ConnectionError("fail")
+
+ result = downloader._fetch_html("https://example.com")
+
+ assert result is None
+ downloader.rate_tracker.record_outcome.assert_called()
+
+
+# ---------------------------------------------------------------------------
+# _extract_content - tag formatting
+# ---------------------------------------------------------------------------
+
+
+class TestExtractContent:
+ def test_article_tag_preferred(self, downloader):
+ """Article tag is preferred content container."""
+ html = """
+ <html><body>
+ <div class="sidebar">Sidebar content here is long enough</div>
+ <article><p>Article content that is substantial and long enough to pass filter easily.</p></article>
+ </body></html>
+ """
+ result = downloader._extract_content(html, "https://example.com")
+ assert result is not None
+ assert "Article content" in result["content"]
+
+ def test_main_tag_fallback(self, downloader):
+ """Falls back to main tag when no article."""
+ html = """
+ <html><body>
+ <main><p>Main content that has enough text to be considered real content in the extraction.</p></main>
+ </body></html>
+ """
+ result = downloader._extract_content(html, "https://example.com")
+ assert result is not None
+ assert "Main content" in result["content"]
+
+ def test_body_fallback(self, downloader):
+ """Falls back to body when no article/main/content divs."""
+ html = """
+ <html><body>
+ <p>Body paragraph that has enough text content to pass the minimum length filters.</p>
+ </body></html>
+ """
+ result = downloader._extract_content(html, "https://example.com")
+ assert result is not None
+ assert "Body paragraph" in result["content"]
+
+ def test_heading_formatting(self, downloader):
+ """Headings are formatted with ## prefix."""
+ html = """
+ <html><body><article>
+ <h2>Important Section Title Here</h2>
+ <p>Paragraph content that is substantial and long enough to pass the minimum length filter.</p>
+ </article></body></html>
+ """
+ result = downloader._extract_content(html, "https://example.com")
+ assert result is not None
+ assert "## Important Section Title Here" in result["content"]
+
+ def test_list_item_formatting(self, downloader):
+ """List items get bullet prefix."""
+ html = """
+ <html><body><article>
+ <p>Introduction paragraph with enough text content to pass the filter requirements.</p>
+ <li>First list item that is long enough to not be filtered out by length</li>
+ </article></body></html>
+ """
+ result = downloader._extract_content(html, "https://example.com")
+ if result:
+ # li items get bullet prefix if long enough
+ assert "First list item" in result["content"]
+
+ def test_og_title_preferred(self, downloader):
+ """Open Graph title takes precedence over regular title."""
+ html = """
+ <html><head>
+ <title>Regular Title</title>
+ <meta property="og:title" content="OG Title">
+ </head><body><article>
+ <p>Content that is substantial enough to pass the minimum length requirements for extraction.</p>
+ </article></body></html>
+ """
+ result = downloader._extract_content(html, "https://example.com")
+ assert result is not None
+ assert result["title"] == "OG Title"
+
+ def test_meta_description_extracted(self, downloader):
+ """Meta description is extracted."""
+ html = """
+ <html><head>
+ <meta name="description" content="Page description here">
+ </head><body><article>
+ <p>Content that is substantial enough to pass the minimum length requirements for extraction.</p>
+ </article></body></html>
+ """
+ result = downloader._extract_content(html, "https://example.com")
+ assert result is not None
+ assert result["description"] == "Page description here"
+
+ def test_short_content_returns_none(self, downloader):
+ """Content shorter than 50 chars returns None."""
+ html = """
+ <html><body><p>Short</p></body></html>
+ """
+ result = downloader._extract_content(html, "https://example.com")
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# _format_extracted_content
+# ---------------------------------------------------------------------------
+
+
+class TestFormatExtractedContent:
+ def test_all_fields(self, downloader):
+ """Formats all available fields."""
+ extracted = {
+ "title": "Test Title",
+ "description": "A description",
+ "url": "https://example.com",
+ "content": "Main content here",
+ }
+ result = downloader._format_extracted_content(extracted)
+
+ assert "# Test Title" in result
+ assert "*A description*" in result
+ assert "Source: https://example.com" in result
+ assert "Main content here" in result
+
+ def test_minimal_fields(self, downloader):
+ """Formats with only content field."""
+ extracted = {"content": "Just content"}
+ result = downloader._format_extracted_content(extracted)
+
+ assert result == "Just content"
+
+ def test_no_content(self, downloader):
+ """Handles missing content field."""
+ extracted = {"title": "Only Title"}
+ result = downloader._format_extracted_content(extracted)
+
+ assert "# Only Title" in result
+
+
+# ---------------------------------------------------------------------------
+# get_metadata
+# ---------------------------------------------------------------------------
+
+
+class TestGetMetadata:
+ def test_success(self, downloader):
+ """Extracts metadata from HTML."""
+ html = """
+ <html><head>
+ <title>Page Title</title>
+ <meta name="description" content="Page desc">
+ <meta name="author" content="John Doe">
+ <meta property="article:published_time" content="2024-01-15">
+ </head><body></body></html>
+ """
+ with patch.object(downloader, "_fetch_html", return_value=html):
+ meta = downloader.get_metadata("https://example.com")
+
+ assert meta["title"] == "Page Title"
+ assert meta["description"] == "Page desc"
+ assert meta["author"] == "John Doe"
+ assert meta["published_date"] == "2024-01-15"
+
+ def test_fetch_failure(self, downloader):
+ """Returns empty dict when fetch fails."""
+ with patch.object(downloader, "_fetch_html", return_value=None):
+ meta = downloader.get_metadata("https://example.com")
+ assert meta == {}
+
+ def test_minimal_metadata(self, downloader):
+ """Returns what's available when some meta tags are missing."""
+ html = (
+ "<html><head><title>Just Title</title></head><body></body></html>"
+ )
+ with patch.object(downloader, "_fetch_html", return_value=html):
+ meta = downloader.get_metadata("https://example.com")
+
+ assert meta["title"] == "Just Title"
+ assert "author" not in meta
+ assert "published_date" not in meta
diff --git a/tests/search_engines/test_search_engine_pubchem_deep_coverage.py b/tests/search_engines/test_search_engine_pubchem_deep_coverage.py
new file mode 100644
index 0000000000..611e684583
--- /dev/null
+++ b/tests/search_engines/test_search_engine_pubchem_deep_coverage.py
@@ -0,0 +1,488 @@
+"""
+Tests for uncovered code paths in PubChemSearchEngine.
+
+Targets:
+- _get_compound_properties: error handling, rate limit, empty properties
+- _get_compound_description: 404, no description, rate limit
+- _get_compound_synonyms: entire method (untested)
+- get_compound: entire method (untested)
+- search_by_formula: entire method (untested)
+- _get_previews: direct lookup fallback, deduplication, compound processing errors
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.web_search_engines.engines.search_engine_pubchem import (
+ PubChemSearchEngine,
+)
+from local_deep_research.web_search_engines.rate_limiting import RateLimitError
+
+MODULE = "local_deep_research.web_search_engines.engines.search_engine_pubchem"
+
+
+def engine():
+ """Create a PubChem engine with mocked rate tracker."""
+ eng = PubChemSearchEngine(max_results=5, include_synonyms=True)
+ 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_compound_properties
+# ---------------------------------------------------------------------------
+
+
+class TestGetCompoundProperties:
+ @patch(f"{MODULE}.safe_get")
+ def test_successful_properties(self, mock_get, engine):
+ """Returns first property dict from successful response."""
+ mock_get.return_value = _mock_response(
+ 200,
+ {
+ "PropertyTable": {
+ "Properties": [
+ {"CID": 2519, "MolecularFormula": "C8H10N4O2"}
+ ]
+ }
+ },
+ )
+ result = engine._get_compound_properties(2519)
+ assert result["MolecularFormula"] == "C8H10N4O2"
+
+ @patch(f"{MODULE}.safe_get")
+ def test_empty_properties(self, mock_get, engine):
+ """Returns empty dict when Properties list is empty."""
+ mock_get.return_value = _mock_response(
+ 200, {"PropertyTable": {"Properties": []}}
+ )
+ result = engine._get_compound_properties(999)
+ assert result == {}
+
+ @patch(f"{MODULE}.safe_get")
+ def test_missing_property_table(self, mock_get, engine):
+ """Returns empty dict when PropertyTable is missing."""
+ mock_get.return_value = _mock_response(200, {})
+ result = engine._get_compound_properties(999)
+ assert result == {}
+
+ @patch(f"{MODULE}.safe_get")
+ def test_http_error_returns_empty(self, mock_get, engine):
+ """Returns empty dict on HTTP error."""
+ mock_get.return_value = _mock_response(500)
+ result = engine._get_compound_properties(999)
+ assert result == {}
+
+ @patch(f"{MODULE}.safe_get")
+ def test_rate_limit_error_propagates(self, mock_get, engine):
+ """RateLimitError is re-raised, not caught."""
+ resp = _mock_response(429)
+ mock_get.return_value = resp
+ engine._raise_if_rate_limit = Mock(side_effect=RateLimitError("429"))
+
+ with pytest.raises(RateLimitError):
+ engine._get_compound_properties(2519)
+
+
+# ---------------------------------------------------------------------------
+# _get_compound_description
+# ---------------------------------------------------------------------------
+
+
+class TestGetCompoundDescription:
+ @patch(f"{MODULE}.safe_get")
+ def test_successful_description(self, mock_get, engine):
+ """Returns first description from response."""
+ mock_get.return_value = _mock_response(
+ 200,
+ {
+ "InformationList": {
+ "Information": [
+ {
+ "CID": 2519,
+ "Description": "Caffeine is a stimulant.",
+ },
+ {
+ "CID": 2519,
+ "Title": "Some title without description",
+ },
+ ]
+ }
+ },
+ )
+ result = engine._get_compound_description(2519)
+ assert result == "Caffeine is a stimulant."
+
+ @patch(f"{MODULE}.safe_get")
+ def test_404_returns_empty(self, mock_get, engine):
+ """Returns empty string on 404."""
+ resp = _mock_response(404)
+ resp.raise_for_status = Mock() # Don't raise for 404
+ mock_get.return_value = resp
+ result = engine._get_compound_description(99999)
+ assert result == ""
+
+ @patch(f"{MODULE}.safe_get")
+ def test_no_description_in_info(self, mock_get, engine):
+ """Returns empty string when no Information has Description field."""
+ mock_get.return_value = _mock_response(
+ 200,
+ {
+ "InformationList": {
+ "Information": [
+ {"CID": 2519, "Title": "No desc here"},
+ ]
+ }
+ },
+ )
+ result = engine._get_compound_description(2519)
+ assert result == ""
+
+ @patch(f"{MODULE}.safe_get")
+ def test_empty_information_list(self, mock_get, engine):
+ """Returns empty string when InformationList is empty."""
+ mock_get.return_value = _mock_response(
+ 200, {"InformationList": {"Information": []}}
+ )
+ result = engine._get_compound_description(2519)
+ assert result == ""
+
+ @patch(f"{MODULE}.safe_get")
+ def test_rate_limit_propagates(self, mock_get, engine):
+ """RateLimitError propagates from description fetch."""
+ resp = _mock_response(429)
+ mock_get.return_value = resp
+ engine._raise_if_rate_limit = Mock(side_effect=RateLimitError("429"))
+
+ with pytest.raises(RateLimitError):
+ engine._get_compound_description(2519)
+
+ @patch(f"{MODULE}.safe_get")
+ def test_exception_returns_empty(self, mock_get, engine):
+ """Other exceptions return empty string."""
+ mock_get.side_effect = ConnectionError("Network error")
+ result = engine._get_compound_description(2519)
+ assert result == ""
+
+
+# ---------------------------------------------------------------------------
+# _get_compound_synonyms
+# ---------------------------------------------------------------------------
+
+
+class TestGetCompoundSynonyms:
+ @patch(f"{MODULE}.safe_get")
+ def test_successful_synonyms(self, mock_get, engine):
+ """Returns synonym list from response."""
+ mock_get.return_value = _mock_response(
+ 200,
+ {
+ "InformationList": {
+ "Information": [
+ {
+ "CID": 2519,
+ "Synonym": [
+ "Caffeine",
+ "1,3,7-Trimethylxanthine",
+ "Theine",
+ "Guaranine",
+ ],
+ }
+ ]
+ }
+ },
+ )
+ result = engine._get_compound_synonyms(2519, limit=3)
+ assert len(result) == 3
+ assert result[0] == "Caffeine"
+
+ @patch(f"{MODULE}.safe_get")
+ def test_404_returns_empty_list(self, mock_get, engine):
+ """Returns empty list on 404."""
+ resp = _mock_response(404)
+ resp.raise_for_status = Mock()
+ mock_get.return_value = resp
+ result = engine._get_compound_synonyms(99999)
+ assert result == []
+
+ @patch(f"{MODULE}.safe_get")
+ def test_empty_information(self, mock_get, engine):
+ """Returns empty list when Information is empty."""
+ mock_get.return_value = _mock_response(
+ 200, {"InformationList": {"Information": []}}
+ )
+ result = engine._get_compound_synonyms(2519)
+ assert result == []
+
+ @patch(f"{MODULE}.safe_get")
+ def test_no_synonym_key(self, mock_get, engine):
+ """Returns empty list when no Synonym key in first info entry."""
+ mock_get.return_value = _mock_response(
+ 200, {"InformationList": {"Information": [{"CID": 2519}]}}
+ )
+ result = engine._get_compound_synonyms(2519)
+ assert result == []
+
+ @patch(f"{MODULE}.safe_get")
+ def test_respects_limit(self, mock_get, engine):
+ """Respects the limit parameter."""
+ synonyms = [f"Syn{i}" for i in range(20)]
+ mock_get.return_value = _mock_response(
+ 200,
+ {
+ "InformationList": {
+ "Information": [{"CID": 2519, "Synonym": synonyms}]
+ }
+ },
+ )
+ result = engine._get_compound_synonyms(2519, limit=5)
+ assert len(result) == 5
+
+ @patch(f"{MODULE}.safe_get")
+ def test_rate_limit_propagates(self, mock_get, engine):
+ """RateLimitError propagates."""
+ resp = _mock_response(429)
+ mock_get.return_value = resp
+ engine._raise_if_rate_limit = Mock(side_effect=RateLimitError("429"))
+
+ with pytest.raises(RateLimitError):
+ engine._get_compound_synonyms(2519)
+
+ @patch(f"{MODULE}.safe_get")
+ def test_exception_returns_empty_list(self, mock_get, engine):
+ """Other exceptions return empty list."""
+ mock_get.side_effect = ConnectionError("fail")
+ result = engine._get_compound_synonyms(2519)
+ assert result == []
+
+
+# ---------------------------------------------------------------------------
+# get_compound
+# ---------------------------------------------------------------------------
+
+
+class TestGetCompound:
+ def test_successful_compound(self, engine):
+ """Returns compound dict with all fields."""
+ engine._get_compound_properties = Mock(
+ return_value={"MolecularFormula": "C8H10N4O2"}
+ )
+ engine._get_compound_description = Mock(return_value="A stimulant")
+ engine._get_compound_synonyms = Mock(
+ return_value=["Caffeine", "Theine"]
+ )
+
+ result = engine.get_compound(2519)
+
+ assert result is not None
+ assert result["cid"] == 2519
+ assert result["properties"]["MolecularFormula"] == "C8H10N4O2"
+ assert result["description"] == "A stimulant"
+ assert result["synonyms"] == ["Caffeine", "Theine"]
+
+ def test_rate_limit_propagates(self, engine):
+ """RateLimitError propagates from get_compound."""
+ engine._get_compound_properties = Mock(
+ side_effect=RateLimitError("429")
+ )
+
+ with pytest.raises(RateLimitError):
+ engine.get_compound(2519)
+
+ def test_exception_returns_none(self, engine):
+ """Other exceptions return None."""
+ engine._get_compound_properties = Mock(side_effect=ValueError("bad"))
+
+ result = engine.get_compound(2519)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# search_by_formula
+# ---------------------------------------------------------------------------
+
+
+class TestSearchByFormula:
+ @patch(f"{MODULE}.safe_get")
+ def test_successful_search(self, mock_get, engine):
+ """Returns compounds for matching formula."""
+ mock_get.return_value = _mock_response(
+ 200, {"IdentifierList": {"CID": [2519, 1234]}}
+ )
+ engine.get_compound = Mock(
+ side_effect=[
+ {
+ "cid": 2519,
+ "properties": {},
+ "description": "",
+ "synonyms": [],
+ },
+ {
+ "cid": 1234,
+ "properties": {},
+ "description": "",
+ "synonyms": [],
+ },
+ ]
+ )
+
+ result = engine.search_by_formula("C8H10N4O2")
+
+ assert len(result) == 2
+ assert result[0]["cid"] == 2519
+
+ @patch(f"{MODULE}.safe_get")
+ def test_404_returns_empty(self, mock_get, engine):
+ """Returns empty list when formula not found."""
+ resp = _mock_response(404)
+ resp.raise_for_status = Mock()
+ mock_get.return_value = resp
+
+ result = engine.search_by_formula("INVALID")
+ assert result == []
+
+ @patch(f"{MODULE}.safe_get")
+ def test_respects_max_results(self, mock_get, engine):
+ """Only processes up to max_results CIDs."""
+ engine.max_results = 2
+ mock_get.return_value = _mock_response(
+ 200, {"IdentifierList": {"CID": [1, 2, 3, 4, 5]}}
+ )
+ engine.get_compound = Mock(
+ return_value={
+ "cid": 1,
+ "properties": {},
+ "description": "",
+ "synonyms": [],
+ }
+ )
+
+ engine.search_by_formula("H2O")
+
+ # Should only call get_compound for first 2 CIDs
+ assert engine.get_compound.call_count == 2
+
+ @patch(f"{MODULE}.safe_get")
+ def test_skips_none_compounds(self, mock_get, engine):
+ """Skips compounds that return None."""
+ mock_get.return_value = _mock_response(
+ 200, {"IdentifierList": {"CID": [1, 2]}}
+ )
+ engine.get_compound = Mock(
+ side_effect=[
+ None,
+ {"cid": 2, "properties": {}, "description": "", "synonyms": []},
+ ]
+ )
+
+ result = engine.search_by_formula("H2O")
+ assert len(result) == 1
+
+ @patch(f"{MODULE}.safe_get")
+ def test_rate_limit_propagates(self, mock_get, engine):
+ """RateLimitError propagates."""
+ resp = _mock_response(429)
+ mock_get.return_value = resp
+ engine._raise_if_rate_limit = Mock(side_effect=RateLimitError("429"))
+
+ with pytest.raises(RateLimitError):
+ engine.search_by_formula("H2O")
+
+ @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.search_by_formula("H2O")
+ assert result == []
+
+
+# ---------------------------------------------------------------------------
+# _get_previews: direct lookup fallback and deduplication
+# ---------------------------------------------------------------------------
+
+
+class TestGetPreviewsEdgeCases:
+ def test_direct_lookup_fallback(self, engine):
+ """Falls back to direct lookup when autocomplete returns nothing."""
+ # _search_compounds returns empty -> triggers direct lookup
+ engine._search_compounds = Mock(return_value=[])
+ engine._get_compound_by_name = Mock(
+ return_value={
+ "cid": 2519,
+ "properties": {
+ "MolecularFormula": "C8H10N4O2",
+ "IUPACName": "caffeine",
+ },
+ "description": "A stimulant",
+ }
+ )
+
+ previews = engine._get_previews("caffeine")
+ assert len(previews) == 1
+ assert "2519" in str(previews[0]["id"])
+
+ def test_deduplication_by_cid(self, engine):
+ """Compounds with duplicate CIDs are deduplicated."""
+ engine._search_compounds = Mock(return_value=["Caffeine", "caffeine"])
+ engine._get_compound_by_name = Mock(
+ return_value={
+ "cid": 2519,
+ "properties": {
+ "MolecularFormula": "C8H10N4O2",
+ "IUPACName": "caffeine",
+ },
+ "description": "A stimulant",
+ }
+ )
+
+ previews = engine._get_previews("caffeine")
+
+ # Both names resolve to same CID, so only one preview
+ assert len(previews) == 1
+
+ def test_stops_at_max_results(self, engine):
+ """Processing stops at max_results."""
+ engine.max_results = 2
+ names = [f"Compound{i}" for i in range(10)]
+ engine._search_compounds = Mock(return_value=names)
+ engine._get_compound_by_name = Mock(
+ side_effect=lambda n: {
+ "cid": hash(n) % 10000,
+ "properties": {"IUPACName": n},
+ "description": "",
+ }
+ )
+
+ previews = engine._get_previews("test")
+ assert len(previews) == 2
+
+ def test_compound_processing_error_continues(self, engine):
+ """Error processing one compound doesn't break the loop."""
+ engine._search_compounds = Mock(return_value=["Bad", "Good"])
+
+ def get_by_name(name):
+ if name == "Bad":
+ raise ValueError("Parse error")
+ return {
+ "cid": 123,
+ "properties": {"IUPACName": "good"},
+ "description": "ok",
+ }
+
+ engine._get_compound_by_name = Mock(side_effect=get_by_name)
+
+ previews = engine._get_previews("test")
+ assert len(previews) == 1
diff --git a/tests/search_engines/test_search_engine_zenodo_deep_coverage.py b/tests/search_engines/test_search_engine_zenodo_deep_coverage.py
new file mode 100644
index 0000000000..c93a8f4416
--- /dev/null
+++ b/tests/search_engines/test_search_engine_zenodo_deep_coverage.py
@@ -0,0 +1,360 @@
+"""
+Tests for uncovered code paths in ZenodoSearchEngine.
+
+Targets:
+- get_record: success, rate limit, exception
+- search_datasets / search_software: resource_type switching, cleanup on exception
+- _get_full_content: files info, references, related_identifiers, content building
+- _get_previews: record parsing exception continues loop, license_info handling
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.web_search_engines.engines.search_engine_zenodo import (
+ ZenodoSearchEngine,
+)
+from local_deep_research.web_search_engines.rate_limiting import RateLimitError
+
+MODULE = "local_deep_research.web_search_engines.engines.search_engine_zenodo"
+
+
+def engine():
+ eng = ZenodoSearchEngine(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_record
+# ---------------------------------------------------------------------------
+
+
+class TestGetRecord:
+ @patch(f"{MODULE}.safe_get")
+ def test_success(self, mock_get, engine):
+ """Returns record dict on success."""
+ record = {"id": 12345, "metadata": {"title": "Test Record"}}
+ mock_get.return_value = _mock_response(200, record)
+
+ result = engine.get_record(12345)
+
+ assert result["id"] == 12345
+ assert result["metadata"]["title"] == "Test Record"
+
+ @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_record(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_record(12345)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# search_datasets / search_software
+# ---------------------------------------------------------------------------
+
+
+class TestSpecializedSearch:
+ def test_search_datasets_sets_type(self, engine):
+ """search_datasets temporarily sets resource_type to 'dataset'."""
+ engine.resource_type = None
+ with patch.object(
+ engine, "run", return_value=[{"title": "Dataset"}]
+ ) as mock_run:
+ result = engine.search_datasets("climate data")
+
+ assert len(result) == 1
+ mock_run.assert_called_once_with("climate data")
+ # resource_type should be restored
+ assert engine.resource_type is None
+
+ def test_search_software_sets_type(self, engine):
+ """search_software temporarily sets resource_type to 'software'."""
+ engine.resource_type = "publication"
+ with patch.object(engine, "run", return_value=[]) as mock_run:
+ engine.search_software("python library")
+
+ mock_run.assert_called_once_with("python library")
+ # resource_type should be restored to original
+ assert engine.resource_type == "publication"
+
+ def test_search_datasets_restores_type_on_exception(self, engine):
+ """resource_type is restored even when run() raises."""
+ engine.resource_type = "publication"
+ with patch.object(engine, "run", side_effect=Exception("fail")):
+ with pytest.raises(Exception, match="fail"):
+ engine.search_datasets("broken")
+
+ assert engine.resource_type == "publication"
+
+
+# ---------------------------------------------------------------------------
+# _get_full_content
+# ---------------------------------------------------------------------------
+
+
+class TestGetFullContent:
+ def test_full_content_with_files(self, engine):
+ """Full content includes file information."""
+ items = [
+ {
+ "title": "Test",
+ "authors": ["Alice"],
+ "resource_type": "dataset",
+ "publication_date": "2024-01-01",
+ "doi": "10.5281/zenodo.12345",
+ "keywords": ["ML", "AI"],
+ "license": "CC-BY-4.0",
+ "description": "",
+ "_raw": {
+ "metadata": {"description": "Full description here"},
+ "files": [
+ {
+ "key": "data.csv",
+ "size": 1024,
+ "checksum": "md5:abc",
+ },
+ {
+ "key": "readme.md",
+ "size": 512,
+ "checksum": "md5:def",
+ },
+ ],
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ assert len(results[0]["files"]) == 2
+ assert results[0]["files"][0]["filename"] == "data.csv"
+ assert results[0]["files"][0]["size"] == 1024
+ assert "Full description here" in results[0]["description"]
+ assert "_raw" not in results[0]
+
+ def test_full_content_with_references(self, engine):
+ """Full content includes references."""
+ items = [
+ {
+ "title": "Test",
+ "authors": [],
+ "_raw": {
+ "metadata": {
+ "description": "",
+ "keywords": ["test"],
+ "related_identifiers": [{"identifier": "10.1234/ref"}],
+ "references": ["Smith et al., 2020"],
+ },
+ "files": [],
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert results[0]["references"] == ["Smith et al., 2020"]
+ assert results[0]["related_identifiers"] == [
+ {"identifier": "10.1234/ref"}
+ ]
+
+ def test_full_content_builds_content_string(self, engine):
+ """Content string is built from all available fields."""
+ items = [
+ {
+ "title": "Test",
+ "authors": ["Alice", "Bob"],
+ "resource_type": "publication",
+ "publication_date": "2024-01",
+ "doi": "10.5281/zenodo.99",
+ "keywords": ["ML"],
+ "license": "MIT",
+ "description": "",
+ "_raw": {
+ "metadata": {
+ "description": "<p>A <b>bold</b> study</p>",
+ "keywords": ["ML"],
+ },
+ "files": [],
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+ content = results[0]["content"]
+
+ assert "Authors: Alice, Bob" in content
+ assert "Type: publication" in content
+ assert "Published: 2024-01" in content
+ assert "DOI: 10.5281/zenodo.99" in content
+ assert "Keywords: ML" in content
+ assert "License: MIT" in content
+ assert "A bold study" in content # HTML stripped
+
+ def test_full_content_without_raw(self, engine):
+ """Items without _raw get minimal content."""
+ items = [{"title": "No raw", "description": "Basic"}]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ assert "_raw" not in results[0]
+
+ def test_full_content_no_files(self, engine):
+ """Handles records with no files field."""
+ items = [
+ {
+ "title": "Test",
+ "_raw": {
+ "metadata": {"description": ""},
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert results[0]["files"] == []
+
+ def test_full_content_html_stripped_from_description(self, engine):
+ """HTML tags and entities are cleaned from description."""
+ items = [
+ {
+ "title": "Test",
+ "_raw": {
+ "metadata": {
+ "description": "<p>This is &amp; that &lt;important&gt;</p>",
+ },
+ "files": [],
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert "&amp;" not in results[0]["description"]
+ assert "<p>" not in results[0]["description"]
+ assert "This is & that <important>" in results[0]["description"]
+
+
+# ---------------------------------------------------------------------------
+# _get_previews edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestGetPreviewsEdgeCases:
+ @patch(f"{MODULE}.safe_get")
+ def test_record_parsing_error_continues(self, mock_get, engine):
+ """Error parsing one record doesn't stop processing others."""
+ mock_get.return_value = _mock_response(
+ 200,
+ {
+ "hits": {
+ "total": 2,
+ "hits": [
+ {
+ "id": 1
+ }, # Missing metadata - will still parse (with defaults)
+ {
+ "id": 2,
+ "metadata": {
+ "title": "Good Record",
+ "creators": [{"name": "Author"}],
+ },
+ "links": {},
+ },
+ ],
+ }
+ },
+ )
+
+ previews = engine._get_previews("test")
+ # Both should parse since we handle missing fields with defaults
+ assert len(previews) == 2
+
+ @patch(f"{MODULE}.safe_get")
+ def test_license_info_none(self, mock_get, engine):
+ """Handles license_info being None."""
+ mock_get.return_value = _mock_response(
+ 200,
+ {
+ "hits": {
+ "total": 1,
+ "hits": [
+ {
+ "id": 1,
+ "metadata": {
+ "title": "Test",
+ "creators": [],
+ "license": None, # Explicitly None
+ },
+ "links": {},
+ }
+ ],
+ }
+ },
+ )
+
+ previews = engine._get_previews("test")
+ assert len(previews) == 1
+ assert previews[0]["license"] == ""
+
+ @patch(f"{MODULE}.safe_get")
+ def test_snippet_with_access_and_license(self, mock_get, engine):
+ """Snippet includes access right and license."""
+ mock_get.return_value = _mock_response(
+ 200,
+ {
+ "hits": {
+ "total": 1,
+ "hits": [
+ {
+ "id": 1,
+ "metadata": {
+ "title": "Test",
+ "creators": [{"name": "Alice"}],
+ "resource_type": {"title": "Dataset"},
+ "access_right": "open",
+ "license": {"id": "cc-by-4.0"},
+ "publication_date": "2024-01-01",
+ "description": "Test desc",
+ },
+ "links": {
+ "self_html": "https://zenodo.org/records/1"
+ },
+ }
+ ],
+ }
+ },
+ )
+
+ previews = engine._get_previews("test")
+ snippet = previews[0]["snippet"]
+
+ assert "Alice" in snippet
+ assert "Dataset" in snippet
+ assert "Open" in snippet
+ assert "CC-BY-4.0" in snippet
diff --git a/tests/security/test_path_validator_deep_coverage.py b/tests/security/test_path_validator_deep_coverage.py
new file mode 100644
index 0000000000..0439e52eea
--- /dev/null
+++ b/tests/security/test_path_validator_deep_coverage.py
@@ -0,0 +1,225 @@
+"""
+Tests for uncovered code paths in PathValidator.
+
+Targets:
+- validate_config_path: absolute path branch, restricted prefixes, null bytes
+- sanitize_for_filesystem_ops: non-absolute path, safe_join failure
+- validate_model_path: non-existent file, not-a-file, model_root creation
+- validate_local_filesystem_path: control characters, tilde expansion, relative path
+"""
+
+import os
+from pathlib import Path
+
+import pytest
+
+from local_deep_research.security.path_validator import PathValidator
+
+
+class TestValidateConfigPathAbsolute:
+ """Tests for validate_config_path with absolute paths."""
+
+ def test_absolute_path_rejected_by_safe_join(self, tmp_path):
+ """Absolute Unix paths are rejected by safe_join in validate_config_path.
+
+ werkzeug safe_join("/", "/absolute/path") returns None because the
+ second argument starts with "/" which is treated as escaping the base.
+ This covers the `if safe_path is None: raise ValueError` branch.
+ """
+ config_file = tmp_path / "test.json"
+ config_file.write_text("{}")
+
+ with pytest.raises(ValueError, match="Invalid"):
+ PathValidator.validate_config_path(str(config_file))
+
+ def test_config_path_null_bytes(self):
+ """Config path with null bytes raises ValueError."""
+ with pytest.raises(ValueError, match="Null bytes"):
+ PathValidator.validate_config_path("/some/path\x00.json")
+
+ def test_config_path_empty_string(self):
+ """Empty config path raises ValueError."""
+ with pytest.raises(ValueError, match="Invalid config path input"):
+ PathValidator.validate_config_path("")
+
+ def test_config_path_non_string(self):
+ """Non-string config path raises ValueError."""
+ with pytest.raises(ValueError, match="Invalid config path input"):
+ PathValidator.validate_config_path(None) # type: ignore
+
+ def test_config_path_traversal_attempt(self):
+ """Config path with .. raises ValueError."""
+ with pytest.raises(ValueError, match="traversal"):
+ PathValidator.validate_config_path("../../../etc/passwd")
+
+
+class TestConfigPathRestrictedPrefixes:
+ """Tests for restricted system directory prefixes in config path."""
+
+ @pytest.mark.parametrize(
+ "path",
+ [
+ "etc/passwd",
+ "/etc/passwd",
+ "proc/self/status",
+ "sys/kernel",
+ "dev/null",
+ ],
+ )
+ def test_restricted_prefixes_blocked(self, path):
+ """Config paths targeting system directories are blocked."""
+ with pytest.raises(ValueError, match="restricted system directory"):
+ PathValidator.validate_config_path(path)
+
+
+class TestConfigPathRelative:
+ """Tests for validate_config_path with relative paths."""
+
+ def test_relative_config_path_with_valid_extension(self, tmp_path):
+ """Relative config path resolves within config_root."""
+ config_file = tmp_path / "settings.yaml"
+ config_file.write_text("key: value")
+
+ result = PathValidator.validate_config_path(
+ "settings.yaml", config_root=str(tmp_path)
+ )
+ assert result == config_file
+
+ def test_relative_config_path_invalid_extension(self, tmp_path):
+ """Relative config path with wrong extension raises ValueError."""
+ with pytest.raises(ValueError, match="Invalid file type"):
+ PathValidator.validate_config_path(
+ "script.sh", config_root=str(tmp_path)
+ )
+
+
+class TestSanitizeForFilesystemOps:
+ """Tests for sanitize_for_filesystem_ops."""
+
+ def test_valid_absolute_path(self, tmp_path):
+ """Valid absolute path is returned unchanged."""
+ result = PathValidator.sanitize_for_filesystem_ops(tmp_path)
+ assert result == tmp_path
+
+ def test_non_absolute_path_raises(self):
+ """Relative path raises ValueError."""
+ with pytest.raises(ValueError, match="Path must be absolute"):
+ PathValidator.sanitize_for_filesystem_ops(Path("relative/path"))
+
+
+class TestValidateModelPath:
+ """Tests for validate_model_path edge cases."""
+
+ def test_model_path_nonexistent_file(self, tmp_path):
+ """Model path to nonexistent file raises ValueError."""
+ with pytest.raises(ValueError, match="Model file not found"):
+ PathValidator.validate_model_path(
+ "nonexistent.bin", model_root=str(tmp_path)
+ )
+
+ def test_model_path_is_directory(self, tmp_path):
+ """Model path pointing to directory raises ValueError."""
+ subdir = tmp_path / "model_dir"
+ subdir.mkdir()
+
+ with pytest.raises(ValueError, match="not a file"):
+ PathValidator.validate_model_path(
+ "model_dir", model_root=str(tmp_path)
+ )
+
+ def test_model_path_valid_file(self, tmp_path):
+ """Valid model file is returned."""
+ model_file = tmp_path / "model.bin"
+ model_file.write_bytes(b"fake model data")
+
+ result = PathValidator.validate_model_path(
+ "model.bin", model_root=str(tmp_path)
+ )
+ assert result == model_file
+
+ def test_model_path_creates_root_directory(self, tmp_path):
+ """Model root directory is created if it doesn't exist."""
+ new_root = tmp_path / "new_model_root"
+
+ # The directory doesn't exist yet but will be created
+ # Then the file won't exist, so it should raise
+ with pytest.raises(ValueError, match="Model file not found"):
+ PathValidator.validate_model_path(
+ "model.bin", model_root=str(new_root)
+ )
+
+ # But the directory should have been created
+ assert new_root.exists()
+
+
+class TestValidateLocalFilesystemPath:
+ """Tests for validate_local_filesystem_path edge cases."""
+
+ def test_control_characters_rejected(self):
+ """Paths with control characters are rejected."""
+ with pytest.raises(ValueError, match="Control characters"):
+ PathValidator.validate_local_filesystem_path("/tmp/test\x01file")
+
+ def test_tilde_expansion(self, tmp_path):
+ """Tilde is expanded to home directory."""
+ result = PathValidator.validate_local_filesystem_path("~")
+ assert result == Path.home().resolve()
+
+ def test_tilde_with_subpath(self, tmp_path):
+ """Tilde with subpath is expanded correctly."""
+ result = PathValidator.validate_local_filesystem_path("~/Documents")
+ expected = (Path.home() / "Documents").resolve()
+ assert result == expected
+
+ def test_relative_path_resolved_to_cwd(self):
+ """Relative path is resolved relative to CWD."""
+ result = PathValidator.validate_local_filesystem_path("some_dir")
+ expected = (Path(os.getcwd()) / "some_dir").resolve()
+ assert result == expected
+
+ def test_restricted_directories_blocked(self):
+ """System directories like /etc are blocked."""
+ with pytest.raises(
+ ValueError, match="Cannot access system directories"
+ ):
+ PathValidator.validate_local_filesystem_path("/etc/passwd")
+
+ def test_custom_restricted_dirs(self, tmp_path):
+ """Custom restricted directories are respected."""
+ restricted = tmp_path / "restricted"
+ restricted.mkdir()
+
+ with pytest.raises(
+ ValueError, match="Cannot access system directories"
+ ):
+ PathValidator.validate_local_filesystem_path(
+ str(restricted / "file.txt"),
+ restricted_dirs=[restricted],
+ )
+
+ def test_path_traversal_blocked(self):
+ """Path traversal with .. is blocked."""
+ with pytest.raises(ValueError, match="Path traversal"):
+ PathValidator.validate_local_filesystem_path("/tmp/../etc/passwd")
+
+ def test_null_bytes_blocked(self):
+ """Null bytes in path are blocked."""
+ with pytest.raises(ValueError, match="Null bytes"):
+ PathValidator.validate_local_filesystem_path("/tmp/file\x00.txt")
+
+
+class TestValidateDataPath:
+ """Tests for validate_data_path."""
+
+ def test_valid_data_path(self, tmp_path):
+ """Valid relative data path is accepted."""
+ result = PathValidator.validate_data_path(
+ "subdir/file.txt", str(tmp_path)
+ )
+ assert result.parent.name == "subdir"
+ assert result.name == "file.txt"
+
+ def test_data_path_traversal_blocked(self, tmp_path):
+ """Data path traversal is blocked."""
+ with pytest.raises(ValueError):
+ PathValidator.validate_data_path("../../etc/passwd", str(tmp_path))
diff --git a/tests/utilities/test_log_utils_deep_coverage.py b/tests/utilities/test_log_utils_deep_coverage.py
new file mode 100644
index 0000000000..c714850ab3
--- /dev/null
+++ b/tests/utilities/test_log_utils_deep_coverage.py
@@ -0,0 +1,431 @@
+"""
+Tests for uncovered code paths in log_utils.py.
+
+Targets:
+- _get_research_id: record with extra, record without extra, no app context
+- _process_log_queue: no app context (requeue), queue full, empty queue
+- database_sink: background thread queueing, main thread direct write
+- frontend_progress_sink: no research_id skips
+- flush_log_queue: flushes entries, handles exceptions
+- config_logger: MILESTONE level already exists, file logging, debug mode
+- InterceptHandler: level not found fallback
+"""
+
+import queue
+from unittest.mock import Mock, patch
+
+
+MODULE = "local_deep_research.utilities.log_utils"
+
+
+class TestGetResearchId:
+ """Tests for _get_research_id."""
+
+ def test_from_record_extra(self):
+ """Extracts research_id from record extra."""
+ from local_deep_research.utilities.log_utils import _get_research_id
+
+ record = {"extra": {"research_id": "test-123"}}
+ with patch(f"{MODULE}.has_app_context", return_value=False):
+ result = _get_research_id(record)
+ assert result == "test-123"
+
+ def test_record_without_extra_uses_flask_g(self, app):
+ """Falls back to Flask g when record has no extra."""
+ from local_deep_research.utilities.log_utils import _get_research_id
+ from flask import g
+
+ record = {"level": "INFO"}
+ with app.test_request_context():
+ g.research_id = "flask-456"
+ result = _get_research_id(record)
+ assert result == "flask-456"
+
+ def test_none_record_uses_flask_g(self, app):
+ """None record falls back to Flask g."""
+ from local_deep_research.utilities.log_utils import _get_research_id
+ from flask import g
+
+ with app.test_request_context():
+ g.research_id = "g-789"
+ result = _get_research_id(None)
+ assert result == "g-789"
+
+ def test_no_app_context_no_record(self):
+ """Returns None when no app context and no record."""
+ from local_deep_research.utilities.log_utils import _get_research_id
+
+ with patch(f"{MODULE}.has_app_context", return_value=False):
+ result = _get_research_id(None)
+ assert result is None
+
+ def test_record_with_extra_but_no_research_id(self):
+ """Record with extra but no research_id falls back to Flask g."""
+ from local_deep_research.utilities.log_utils import _get_research_id
+
+ record = {"extra": {"username": "bob"}}
+ with patch(f"{MODULE}.has_app_context", return_value=False):
+ result = _get_research_id(record)
+ assert result is None
+
+
+class TestProcessLogQueue:
+ """Tests for _process_log_queue."""
+
+ def test_processes_entry_with_app_context(self):
+ """Processes log entry when app context is available."""
+ from local_deep_research.utilities.log_utils import (
+ _process_log_queue,
+ _log_queue,
+ _stop_queue,
+ )
+
+ entry = {"message": "test", "research_id": "123"}
+ _log_queue.put(entry)
+
+ # Set stop flag after one iteration
+ def stop_after_one(*args, **kwargs):
+ _stop_queue.set()
+
+ with patch(f"{MODULE}.has_app_context", return_value=True):
+ with patch(
+ f"{MODULE}._write_log_to_database", side_effect=stop_after_one
+ ) as mock_write:
+ _stop_queue.clear()
+ _process_log_queue()
+ mock_write.assert_called_once_with(entry)
+
+ _stop_queue.clear()
+
+ def test_requeues_without_app_context(self):
+ """Puts entry back when no app context."""
+ from local_deep_research.utilities.log_utils import (
+ _process_log_queue,
+ _log_queue,
+ _stop_queue,
+ )
+
+ # Clear queue
+ while not _log_queue.empty():
+ try:
+ _log_queue.get_nowait()
+ except queue.Empty:
+ break
+
+ entry = {"message": "test", "research_id": "123"}
+ _log_queue.put(entry)
+
+ call_count = [0]
+
+ def count_and_stop(*args, **kwargs):
+ call_count[0] += 1
+ if call_count[0] >= 2:
+ _stop_queue.set()
+ return False
+
+ with patch(f"{MODULE}.has_app_context", side_effect=count_and_stop):
+ _stop_queue.clear()
+ _process_log_queue()
+
+ _stop_queue.clear()
+ # Entry should still be in queue (requeued)
+ assert not _log_queue.empty()
+ # Clean up
+ while not _log_queue.empty():
+ try:
+ _log_queue.get_nowait()
+ except queue.Empty:
+ break
+
+ def test_skips_none_entry(self):
+ """Skips None entries."""
+ from local_deep_research.utilities.log_utils import (
+ _process_log_queue,
+ _log_queue,
+ _stop_queue,
+ )
+
+ _log_queue.put(None)
+ _stop_queue.clear()
+
+ call_count = [0]
+
+ def mock_get(timeout=None):
+ call_count[0] += 1
+ if call_count[0] == 1:
+ return None
+ _stop_queue.set()
+ raise queue.Empty()
+
+ with patch.object(_log_queue, "get", side_effect=mock_get):
+ _process_log_queue()
+
+ _stop_queue.clear()
+
+
+class TestDatabaseSink:
+ """Tests for database_sink."""
+
+ def test_background_thread_queues(self):
+ """Queues log entry from background thread."""
+ from local_deep_research.utilities.log_utils import (
+ database_sink,
+ _log_queue,
+ )
+
+ # Clear queue
+ while not _log_queue.empty():
+ try:
+ _log_queue.get_nowait()
+ except queue.Empty:
+ break
+
+ msg = Mock()
+ msg.record = {
+ "time": "2024-01-01",
+ "message": "test",
+ "name": "module",
+ "function": "func",
+ "line": 42,
+ "level": Mock(name="INFO"),
+ "extra": {},
+ }
+
+ with patch(f"{MODULE}.has_app_context", return_value=False):
+ database_sink(msg)
+
+ # Entry should be in queue
+ assert not _log_queue.empty()
+ entry = _log_queue.get_nowait()
+ assert entry["message"] == "test"
+ assert entry["line_no"] == 42
+
+ def test_main_thread_writes_directly(self, app):
+ """Writes directly from main thread with app context."""
+ from local_deep_research.utilities.log_utils import database_sink
+
+ msg = Mock()
+ msg.record = {
+ "time": "2024-01-01",
+ "message": "test",
+ "name": "module",
+ "function": "func",
+ "line": 42,
+ "level": Mock(name="INFO"),
+ "extra": {"username": "bob"},
+ }
+
+ with app.test_request_context():
+ with patch(f"{MODULE}.threading.current_thread") as mock_thread:
+ mock_thread.return_value.name = "MainThread"
+ with patch(f"{MODULE}._write_log_to_database") as mock_write:
+ database_sink(msg)
+ mock_write.assert_called_once()
+
+ def test_queue_full_drops_silently(self):
+ """Drops log when queue is full."""
+ from local_deep_research.utilities.log_utils import database_sink
+
+ msg = Mock()
+ msg.record = {
+ "time": "2024-01-01",
+ "message": "test",
+ "name": "module",
+ "function": "func",
+ "line": 1,
+ "level": Mock(name="DEBUG"),
+ "extra": {},
+ }
+
+ with patch(f"{MODULE}.has_app_context", return_value=False):
+ with patch(f"{MODULE}._log_queue") as mock_queue:
+ mock_queue.put_nowait.side_effect = queue.Full()
+ # Should not raise
+ database_sink(msg)
+
+
+class TestFrontendProgressSink:
+ """Tests for frontend_progress_sink."""
+
+ def test_no_research_id_returns_early(self):
+ """Returns early when no research_id."""
+ from local_deep_research.utilities.log_utils import (
+ frontend_progress_sink,
+ )
+
+ msg = Mock()
+ msg.record = {
+ "message": "test",
+ "level": Mock(name="INFO"),
+ "time": Mock(isoformat=Mock(return_value="2024-01-01T00:00:00")),
+ "extra": {},
+ }
+
+ with patch(f"{MODULE}._get_research_id", return_value=None):
+ with patch(f"{MODULE}.SocketIOService") as mock_sio:
+ frontend_progress_sink(msg)
+ mock_sio.assert_not_called()
+
+ def test_with_research_id_emits(self):
+ """Emits to subscribers when research_id exists."""
+ from local_deep_research.utilities.log_utils import (
+ frontend_progress_sink,
+ )
+
+ msg = Mock()
+ msg.record = {
+ "message": "Progress update",
+ "level": Mock(name="INFO"),
+ "time": Mock(isoformat=Mock(return_value="2024-01-01T00:00:00")),
+ "extra": {"research_id": "r-123"},
+ }
+
+ with patch(f"{MODULE}._get_research_id", return_value="r-123"):
+ with patch(f"{MODULE}.SocketIOService") as mock_sio_cls:
+ mock_sio = Mock()
+ mock_sio_cls.return_value = mock_sio
+
+ frontend_progress_sink(msg)
+
+ mock_sio.emit_to_subscribers.assert_called_once()
+ call_args = mock_sio.emit_to_subscribers.call_args
+ assert call_args[0][0] == "progress"
+ assert call_args[0][1] == "r-123"
+
+
+class TestFlushLogQueue:
+ """Tests for flush_log_queue."""
+
+ def test_flushes_entries(self):
+ """Flushes all entries from queue to database."""
+ from local_deep_research.utilities.log_utils import (
+ flush_log_queue,
+ _log_queue,
+ )
+
+ # Clear queue
+ while not _log_queue.empty():
+ try:
+ _log_queue.get_nowait()
+ except queue.Empty:
+ break
+
+ _log_queue.put({"message": "entry1"})
+ _log_queue.put({"message": "entry2"})
+
+ with patch(f"{MODULE}._write_log_to_database") as mock_write:
+ flush_log_queue()
+ assert mock_write.call_count == 2
+
+ def test_empty_queue(self):
+ """Handles empty queue gracefully."""
+ from local_deep_research.utilities.log_utils import (
+ flush_log_queue,
+ _log_queue,
+ )
+
+ # Clear queue
+ while not _log_queue.empty():
+ try:
+ _log_queue.get_nowait()
+ except queue.Empty:
+ break
+
+ with patch(f"{MODULE}._write_log_to_database") as mock_write:
+ flush_log_queue()
+ mock_write.assert_not_called()
+
+
+class TestInterceptHandler:
+ """Tests for InterceptHandler."""
+
+ def _make_log_record(self, levelname="WARNING", levelno=30, msg="test"):
+ """Create a mock log record without importing logging directly."""
+ record = Mock()
+ record.levelname = levelname
+ record.levelno = levelno
+ record.getMessage.return_value = msg
+ record.exc_info = None
+ return record
+
+ def test_emit_with_known_level(self):
+ """Emits log with matching loguru level."""
+ from local_deep_research.utilities.log_utils import InterceptHandler
+
+ handler = InterceptHandler()
+ record = self._make_log_record("WARNING", 30, "test warning")
+
+ with patch(f"{MODULE}.logger") as mock_logger:
+ mock_logger.level.return_value = Mock(name="WARNING")
+ mock_logger.opt.return_value = mock_logger
+ handler.emit(record)
+ mock_logger.opt.assert_called()
+
+ def test_emit_with_unknown_level(self):
+ """Falls back to numeric level for unknown level names."""
+ from local_deep_research.utilities.log_utils import InterceptHandler
+
+ handler = InterceptHandler()
+ record = self._make_log_record("CUSTOM", 42, "custom level msg")
+
+ with patch(f"{MODULE}.logger") as mock_logger:
+ mock_logger.level.side_effect = ValueError("Unknown level")
+ mock_logger.opt.return_value = mock_logger
+ handler.emit(record)
+ mock_logger.opt.assert_called()
+
+
+class TestConfigLogger:
+ """Tests for config_logger."""
+
+ def test_milestone_level_already_exists(self):
+ """Handles MILESTONE level already existing."""
+ from local_deep_research.utilities.log_utils import config_logger
+
+ with patch(f"{MODULE}.logger") as mock_logger:
+ mock_logger.level.side_effect = ValueError("Level already exists")
+ mock_logger.configure = Mock()
+ mock_logger.enable = Mock()
+ mock_logger.remove = Mock()
+ mock_logger.add = Mock()
+ mock_logger.warning = Mock()
+
+ # Should not raise
+ config_logger("test", debug=False)
+
+ def test_file_logging_enabled(self):
+ """File logging adds file handler when env var set."""
+ from local_deep_research.utilities.log_utils import config_logger
+
+ with patch.dict("os.environ", {"LDR_ENABLE_FILE_LOGGING": "true"}):
+ with patch(f"{MODULE}.logger") as mock_logger:
+ mock_logger.level = Mock(return_value=Mock())
+ mock_logger.configure = Mock()
+ mock_logger.enable = Mock()
+ mock_logger.remove = Mock()
+ mock_logger.add = Mock()
+ mock_logger.warning = Mock()
+
+ config_logger("test", debug=False)
+
+ # Should have 4 adds: stderr, database_sink, frontend_progress, file
+ assert mock_logger.add.call_count == 4
+
+ def test_debug_mode_logs_warning(self):
+ """Debug mode logs security warning."""
+ from local_deep_research.utilities.log_utils import config_logger
+
+ with patch(f"{MODULE}.logger") as mock_logger:
+ mock_logger.level = Mock(return_value=Mock())
+ mock_logger.configure = Mock()
+ mock_logger.enable = Mock()
+ mock_logger.remove = Mock()
+ mock_logger.add = Mock()
+ mock_logger.warning = Mock()
+
+ config_logger("test", debug=True)
+
+ # Should warn about debug logging
+ mock_logger.warning.assert_called()
+ warning_msg = mock_logger.warning.call_args_list[0][0][0]
+ assert "DEBUG logging is enabled" in warning_msg
diff --git a/tests/web_search_engines/engines/test_full_search_coverage.py b/tests/web_search_engines/engines/test_full_search_coverage.py
new file mode 100644
index 0000000000..38c1098718
--- /dev/null
+++ b/tests/web_search_engines/engines/test_full_search_coverage.py
@@ -0,0 +1,275 @@
+"""
+Tests for uncovered code paths in FullSearchResults.
+
+Targets:
+- _get_full_content() method (entirely untested)
+- SSRF validation blocking all URLs
+- check_urls with null LLM
+- run() with SSRF-blocked URLs returning results without full content
+"""
+
+from unittest.mock import Mock, patch
+
+
+class TestGetFullContent:
+ """Tests for _get_full_content method."""
+
+ def _make_engine(self):
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ mock_llm = Mock()
+ mock_web_search = Mock()
+ engine = FullSearchResults(llm=mock_llm, web_search=mock_web_search)
+ return engine
+
+ def test_get_full_content_all_urls_valid(self):
+ """_get_full_content fetches content for valid URLs."""
+ engine = self._make_engine()
+
+ items = [
+ {"link": "https://example.com/1", "title": "R1"},
+ {"link": "https://example.com/2", "title": "R2"},
+ ]
+
+ mock_doc1 = Mock()
+ mock_doc1.page_content = "<p>Content 1</p>"
+ mock_doc1.metadata = {"source": "https://example.com/1"}
+ mock_doc2 = Mock()
+ mock_doc2.page_content = "<p>Content 2</p>"
+ mock_doc2.metadata = {"source": "https://example.com/2"}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
+ ) as mock_loader:
+ mock_loader.return_value.load.return_value = [
+ mock_doc1,
+ mock_doc2,
+ ]
+ engine.bs_transformer = Mock()
+ engine.bs_transformer.transform_documents.return_value = [
+ mock_doc1,
+ mock_doc2,
+ ]
+
+ with patch.object(
+ engine,
+ "remove_boilerplate",
+ side_effect=["Clean 1", "Clean 2"],
+ ):
+ result = engine._get_full_content(items)
+
+ assert result[0]["full_content"] == "Clean 1"
+ assert result[1]["full_content"] == "Clean 2"
+
+ def test_get_full_content_no_valid_urls(self):
+ """_get_full_content returns items with None content when all URLs fail SSRF."""
+ engine = self._make_engine()
+
+ items = [
+ {"link": "http://192.168.1.1/internal", "title": "R1"},
+ {"link": "http://10.0.0.1/secret", "title": "R2"},
+ ]
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ return_value=False,
+ ):
+ result = engine._get_full_content(items)
+
+ assert result[0]["full_content"] is None
+ assert result[1]["full_content"] is None
+
+ def test_get_full_content_loader_exception(self):
+ """_get_full_content returns None content on loader exception."""
+ engine = self._make_engine()
+
+ items = [{"link": "https://example.com/1", "title": "R1"}]
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
+ ) as mock_loader:
+ mock_loader.return_value.load.side_effect = Exception(
+ "Network error"
+ )
+
+ result = engine._get_full_content(items)
+
+ assert result[0]["full_content"] is None
+
+ def test_get_full_content_item_without_link(self):
+ """_get_full_content handles items without link key."""
+ engine = self._make_engine()
+
+ items = [
+ {"title": "No link item"},
+ {"link": "https://example.com/1", "title": "Has link"},
+ ]
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
+ ) as mock_loader:
+ mock_doc = Mock()
+ mock_doc.page_content = "<p>Content</p>"
+ mock_doc.metadata = {"source": "https://example.com/1"}
+ mock_loader.return_value.load.return_value = [mock_doc]
+ engine.bs_transformer = Mock()
+ engine.bs_transformer.transform_documents.return_value = [
+ mock_doc
+ ]
+
+ with patch.object(
+ engine, "remove_boilerplate", return_value="Clean"
+ ):
+ result = engine._get_full_content(items)
+
+ assert result[0]["full_content"] is None # No link -> None
+ assert result[1]["full_content"] == "Clean"
+
+ def test_get_full_content_mixed_ssrf_validation(self):
+ """_get_full_content handles mix of valid and SSRF-blocked URLs."""
+ engine = self._make_engine()
+
+ items = [
+ {"link": "https://example.com/ok", "title": "Good"},
+ {"link": "http://192.168.1.1/bad", "title": "Bad"},
+ ]
+
+ def mock_validate(url):
+ return "example.com" in url
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ side_effect=mock_validate,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
+ ) as mock_loader:
+ mock_doc = Mock()
+ mock_doc.page_content = "<p>Content</p>"
+ mock_doc.metadata = {"source": "https://example.com/ok"}
+ mock_loader.return_value.load.return_value = [mock_doc]
+ engine.bs_transformer = Mock()
+ engine.bs_transformer.transform_documents.return_value = [
+ mock_doc
+ ]
+
+ with patch.object(
+ engine, "remove_boilerplate", return_value="Clean"
+ ):
+ result = engine._get_full_content(items)
+
+ assert result[0]["full_content"] == "Clean"
+ # Item with SSRF-blocked link won't be in url_to_content
+ assert result[1]["full_content"] is None
+
+
+class TestCheckUrlsNullLlm:
+ """Tests for check_urls with null LLM."""
+
+ def test_check_urls_null_llm_returns_results_unchanged(self):
+ """check_urls returns results unchanged when LLM is None."""
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ mock_web_search = Mock()
+ engine = FullSearchResults(llm=None, web_search=mock_web_search)
+
+ results = [
+ {"link": "https://example.com/1", "title": "Result 1"},
+ {"link": "https://example.com/2", "title": "Result 2"},
+ ]
+
+ filtered = engine.check_urls(results, "test query")
+
+ assert filtered == results
+ assert len(filtered) == 2
+
+
+class TestRunSsrfBlocking:
+ """Tests for run() SSRF blocking paths."""
+
+ def test_run_all_urls_ssrf_blocked(self):
+ """run() returns results without full content when all URLs fail SSRF."""
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ mock_llm = Mock()
+ mock_web_search = Mock()
+ mock_web_search.invoke.return_value = [
+ {"link": "http://192.168.1.1/internal", "title": "Internal"},
+ ]
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",
+ False,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ return_value=False,
+ ):
+ engine = FullSearchResults(
+ llm=mock_llm, web_search=mock_web_search
+ )
+ results = engine.run("test query")
+
+ assert len(results) == 1
+ assert results[0]["full_content"] is None
+
+ def test_run_doc_without_source_metadata(self):
+ """run() handles documents without source in metadata."""
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ mock_llm = Mock()
+ mock_web_search = Mock()
+ mock_web_search.invoke.return_value = [
+ {"link": "https://example.com/1", "title": "R1"},
+ ]
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",
+ False,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
+ ) as mock_loader:
+ # Doc without source metadata
+ mock_doc = Mock()
+ mock_doc.page_content = "<p>Content</p>"
+ mock_doc.metadata = {} # No source
+ mock_loader.return_value.load.return_value = [mock_doc]
+
+ engine = FullSearchResults(
+ llm=mock_llm, web_search=mock_web_search
+ )
+ engine.bs_transformer = Mock()
+ engine.bs_transformer.transform_documents.return_value = [
+ mock_doc
+ ]
+
+ results = engine.run("test query")
+
+ assert len(results) == 1
+ # No source in metadata -> no content mapped
+ assert results[0]["full_content"] is None