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.

Add tests for core modules and search engines

LearningCircuit13bc67538c62
diff --git a/tests/core/test_citation_handler.py b/tests/core/test_citation_handler.py
new file mode 100644
index 0000000000..2b585c8f87
--- /dev/null
+++ b/tests/core/test_citation_handler.py
@@ -0,0 +1,334 @@
+"""
+Tests for citation_handler.py
+
+Tests cover:
+- CitationHandler initialization
+- Handler type selection
+- Method delegation
+"""
+
+from unittest.mock import Mock, patch
+
+
+class TestCitationHandlerInit:
+ """Tests for CitationHandler initialization."""
+
+ def test_default_handler_type(self):
+ """Test default handler type is standard."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ handler = CitationHandler(mock_llm)
+
+ mock_handler_class.assert_called_once()
+ assert handler._handler == mock_handler
+
+ def test_explicit_standard_handler(self):
+ """Test explicit standard handler type."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, handler_type="standard")
+
+ mock_handler_class.assert_called_once()
+
+ def test_forced_handler_type(self):
+ """Test forced handler type."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.forced_answer_citation_handler.ForcedAnswerCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, handler_type="forced")
+
+ mock_handler_class.assert_called_once()
+
+ def test_browsecomp_handler_type(self):
+ """Test browsecomp handler type maps to forced."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.forced_answer_citation_handler.ForcedAnswerCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, handler_type="browsecomp")
+
+ mock_handler_class.assert_called_once()
+
+ def test_precision_handler_type(self):
+ """Test precision handler type."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.precision_extraction_handler.PrecisionExtractionHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, handler_type="precision")
+
+ mock_handler_class.assert_called_once()
+
+ def test_simpleqa_handler_type(self):
+ """Test simpleqa handler type maps to precision."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.precision_extraction_handler.PrecisionExtractionHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, handler_type="simpleqa")
+
+ mock_handler_class.assert_called_once()
+
+ def test_unknown_handler_type_fallback(self):
+ """Test unknown handler type falls back to standard."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, handler_type="unknown_type")
+
+ # Called twice - once for unknown fallback
+ assert mock_handler_class.call_count >= 1
+
+ def test_handler_type_from_settings_snapshot(self):
+ """Test handler type from settings snapshot."""
+ mock_llm = Mock()
+ settings_snapshot = {"citation.handler_type": "forced"}
+
+ with patch(
+ "local_deep_research.citation_handlers.forced_answer_citation_handler.ForcedAnswerCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, settings_snapshot=settings_snapshot)
+
+ mock_handler_class.assert_called_once()
+
+ def test_handler_type_from_settings_snapshot_dict_value(self):
+ """Test handler type from settings snapshot with dict value."""
+ mock_llm = Mock()
+ settings_snapshot = {"citation.handler_type": {"value": "precision"}}
+
+ with patch(
+ "local_deep_research.citation_handlers.precision_extraction_handler.PrecisionExtractionHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, settings_snapshot=settings_snapshot)
+
+ mock_handler_class.assert_called_once()
+
+ def test_handler_type_case_insensitive(self):
+ """Test handler type is case insensitive."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.forced_answer_citation_handler.ForcedAnswerCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, handler_type="FORCED")
+
+ mock_handler_class.assert_called_once()
+
+
+class TestCitationHandlerMethods:
+ """Tests for CitationHandler method delegation."""
+
+ def test_analyze_initial_delegation(self):
+ """Test analyze_initial delegates to handler."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler.analyze_initial.return_value = {"result": "test"}
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ handler = CitationHandler(mock_llm)
+ result = handler.analyze_initial("test query", [])
+
+ mock_handler.analyze_initial.assert_called_once_with(
+ "test query", []
+ )
+ assert result == {"result": "test"}
+
+ def test_analyze_followup_delegation(self):
+ """Test analyze_followup delegates to handler."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler.analyze_followup.return_value = {"result": "followup"}
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ handler = CitationHandler(mock_llm)
+ result = handler.analyze_followup(
+ "test question", [], "previous knowledge", 5
+ )
+
+ mock_handler.analyze_followup.assert_called_once_with(
+ "test question", [], "previous knowledge", 5
+ )
+ assert result == {"result": "followup"}
+
+ def test_backward_compatibility_methods_exposed(self):
+ """Test backward compatibility methods are exposed."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_handler_class:
+ mock_create_docs = Mock()
+ mock_format_sources = Mock()
+
+ mock_handler = Mock()
+ mock_handler._create_documents = mock_create_docs
+ mock_handler._format_sources = mock_format_sources
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ handler = CitationHandler(mock_llm)
+
+ assert handler._create_documents == mock_create_docs
+ assert handler._format_sources == mock_format_sources
+
+
+class TestCitationHandlerSettings:
+ """Tests for CitationHandler settings handling."""
+
+ def test_empty_settings_snapshot(self):
+ """Test with empty settings snapshot."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, settings_snapshot={})
+
+ # Should use standard handler as default
+ mock_handler_class.assert_called_once()
+
+ def test_settings_passed_to_handler(self):
+ """Test settings are passed to underlying handler."""
+ mock_llm = Mock()
+ settings_snapshot = {"some_setting": "value"}
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm, settings_snapshot=settings_snapshot)
+
+ call_kwargs = mock_handler_class.call_args[1]
+ assert call_kwargs["settings_snapshot"] == settings_snapshot
+
+ def test_llm_passed_to_handler(self):
+ """Test LLM is passed to underlying handler."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_handler_class:
+ mock_handler = Mock()
+ mock_handler._create_documents = Mock()
+ mock_handler._format_sources = Mock()
+ mock_handler_class.return_value = mock_handler
+
+ from local_deep_research.citation_handler import CitationHandler
+
+ CitationHandler(mock_llm)
+
+ call_args = mock_handler_class.call_args[0]
+ assert call_args[0] == mock_llm
diff --git a/tests/core/test_constants.py b/tests/core/test_constants.py
new file mode 100644
index 0000000000..789f4f5a8d
--- /dev/null
+++ b/tests/core/test_constants.py
@@ -0,0 +1,90 @@
+"""
+Tests for constants.py
+
+Tests cover:
+- USER_AGENT constant
+- BROWSER_USER_AGENT constant
+"""
+
+
+class TestUserAgent:
+ """Tests for USER_AGENT constant."""
+
+ def test_user_agent_exists(self):
+ """Test USER_AGENT constant exists."""
+ from local_deep_research.constants import USER_AGENT
+
+ assert USER_AGENT is not None
+ assert isinstance(USER_AGENT, str)
+
+ def test_user_agent_contains_project_name(self):
+ """Test USER_AGENT contains project name."""
+ from local_deep_research.constants import USER_AGENT
+
+ assert "Local-Deep-Research" in USER_AGENT
+
+ def test_user_agent_contains_version(self):
+ """Test USER_AGENT contains version."""
+ from local_deep_research.constants import USER_AGENT
+ from local_deep_research.__version__ import __version__
+
+ assert __version__ in USER_AGENT
+
+ def test_user_agent_contains_github_url(self):
+ """Test USER_AGENT contains GitHub URL."""
+ from local_deep_research.constants import USER_AGENT
+
+ assert "github.com/LearningCircuit/local-deep-research" in USER_AGENT
+
+ def test_user_agent_contains_description(self):
+ """Test USER_AGENT contains description."""
+ from local_deep_research.constants import USER_AGENT
+
+ assert "Academic Research Tool" in USER_AGENT
+
+
+class TestBrowserUserAgent:
+ """Tests for BROWSER_USER_AGENT constant."""
+
+ def test_browser_user_agent_exists(self):
+ """Test BROWSER_USER_AGENT constant exists."""
+ from local_deep_research.constants import BROWSER_USER_AGENT
+
+ assert BROWSER_USER_AGENT is not None
+ assert isinstance(BROWSER_USER_AGENT, str)
+
+ def test_browser_user_agent_looks_like_browser(self):
+ """Test BROWSER_USER_AGENT looks like a browser."""
+ from local_deep_research.constants import BROWSER_USER_AGENT
+
+ assert "Mozilla" in BROWSER_USER_AGENT
+ assert "AppleWebKit" in BROWSER_USER_AGENT
+
+ def test_browser_user_agent_contains_chrome(self):
+ """Test BROWSER_USER_AGENT contains Chrome."""
+ from local_deep_research.constants import BROWSER_USER_AGENT
+
+ assert "Chrome" in BROWSER_USER_AGENT
+
+ def test_browser_user_agent_contains_windows(self):
+ """Test BROWSER_USER_AGENT contains Windows."""
+ from local_deep_research.constants import BROWSER_USER_AGENT
+
+ assert "Windows" in BROWSER_USER_AGENT
+
+
+class TestVersionImport:
+ """Tests for version import."""
+
+ def test_version_exists(self):
+ """Test __version__ exists."""
+ from local_deep_research.__version__ import __version__
+
+ assert __version__ is not None
+ assert isinstance(__version__, str)
+
+ def test_version_not_empty(self):
+ """Test __version__ is not empty."""
+ from local_deep_research.__version__ import __version__
+
+ assert len(__version__) > 0
diff --git a/tests/core/test_report_generator.py b/tests/core/test_report_generator.py
new file mode 100644
index 0000000000..a5c5a50680
--- /dev/null
+++ b/tests/core/test_report_generator.py
@@ -0,0 +1,493 @@
+"""
+Tests for report_generator.py
+
+Tests cover:
+- IntegratedReportGenerator initialization
+- get_report_generator function
+- Report structure determination
+- Section generation
+- Error handling
+"""
+
+from unittest.mock import Mock, patch
+
+
+class TestGetReportGenerator:
+ """Tests for get_report_generator function."""
+
+ def test_get_report_generator_default(self):
+ """Test get_report_generator returns IntegratedReportGenerator."""
+ with patch(
+ "local_deep_research.report_generator.IntegratedReportGenerator"
+ ) as mock_class:
+ mock_instance = Mock()
+ mock_class.return_value = mock_instance
+
+ from local_deep_research.report_generator import (
+ get_report_generator,
+ )
+
+ result = get_report_generator()
+
+ mock_class.assert_called_once_with(search_system=None)
+ assert result == mock_instance
+
+ def test_get_report_generator_with_search_system(self):
+ """Test get_report_generator with search system."""
+ mock_search_system = Mock()
+
+ with patch(
+ "local_deep_research.report_generator.IntegratedReportGenerator"
+ ) as mock_class:
+ mock_instance = Mock()
+ mock_class.return_value = mock_instance
+
+ from local_deep_research.report_generator import (
+ get_report_generator,
+ )
+
+ get_report_generator(search_system=mock_search_system)
+
+ mock_class.assert_called_once_with(search_system=mock_search_system)
+
+
+class TestIntegratedReportGeneratorInit:
+ """Tests for IntegratedReportGenerator initialization."""
+
+ def test_init_with_search_system(self):
+ """Test initialization with search system."""
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ assert generator.search_system == mock_search_system
+ assert generator.model == mock_search_system.model
+ assert generator.searches_per_section == 2
+
+ def test_init_with_llm(self):
+ """Test initialization with LLM only."""
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.report_generator.AdvancedSearchSystem"
+ ) as mock_search_class:
+ mock_search = Mock()
+ mock_search_class.return_value = mock_search
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(llm=mock_llm)
+
+ assert generator.model == mock_llm
+ mock_search_class.assert_called_once_with(llm=mock_llm)
+
+ def test_init_with_custom_searches_per_section(self):
+ """Test initialization with custom searches per section."""
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(
+ search_system=mock_search_system, searches_per_section=5
+ )
+
+ assert generator.searches_per_section == 5
+
+ def test_init_search_system_overrides_llm(self):
+ """Test search system's LLM is used when both provided."""
+ mock_search_system = Mock()
+ mock_search_system.model = Mock(name="search_system_model")
+ mock_external_llm = Mock(name="external_llm")
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(
+ search_system=mock_search_system, llm=mock_external_llm
+ )
+
+ # When both provided, external llm is used if specified
+ assert generator.model == mock_external_llm
+
+
+class TestDetermineReportStructure:
+ """Tests for _determine_report_structure method."""
+
+ def test_determine_structure_parses_response(self):
+ """Test structure is parsed from LLM response."""
+ mock_search_system = Mock()
+ mock_llm = Mock()
+ mock_search_system.model = mock_llm
+
+ mock_response = Mock()
+ mock_response.content = """
+STRUCTURE
+1. Introduction
+ - Overview | Provide context
+ - Background | Historical context
+2. Main Analysis
+ - Data | Present findings
+END_STRUCTURE
+"""
+ mock_llm.invoke.return_value = mock_response
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ findings = {"current_knowledge": "Test content " * 100}
+ structure = generator._determine_report_structure(
+ findings, "test query"
+ )
+
+ assert len(structure) == 2
+ assert structure[0]["name"] == "Introduction"
+ assert len(structure[0]["subsections"]) == 2
+ assert structure[0]["subsections"][0]["name"] == "Overview"
+ assert structure[0]["subsections"][0]["purpose"] == "Provide context"
+
+ def test_determine_structure_removes_source_sections(self):
+ """Test source-related sections are removed."""
+ mock_search_system = Mock()
+ mock_llm = Mock()
+ mock_search_system.model = mock_llm
+
+ mock_response = Mock()
+ mock_response.content = """
+STRUCTURE
+1. Introduction
+ - Overview | Provide context
+2. Sources and References
+ - Citations | List sources
+END_STRUCTURE
+"""
+ mock_llm.invoke.return_value = mock_response
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ findings = {"current_knowledge": "Test content " * 100}
+ structure = generator._determine_report_structure(
+ findings, "test query"
+ )
+
+ # Should remove the Sources section
+ assert len(structure) == 1
+ assert structure[0]["name"] == "Introduction"
+
+ def test_determine_structure_handles_subsection_without_purpose(self):
+ """Test subsections without purpose get default."""
+ mock_search_system = Mock()
+ mock_llm = Mock()
+ mock_search_system.model = mock_llm
+
+ mock_response = Mock()
+ mock_response.content = """
+STRUCTURE
+1. Introduction
+ - Overview
+END_STRUCTURE
+"""
+ mock_llm.invoke.return_value = mock_response
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ findings = {"current_knowledge": "Test content " * 100}
+ structure = generator._determine_report_structure(
+ findings, "test query"
+ )
+
+ assert structure[0]["subsections"][0]["name"] == "Overview"
+ assert "Overview" in structure[0]["subsections"][0]["purpose"]
+
+
+class TestResearchAndGenerateSections:
+ """Tests for _research_and_generate_sections method."""
+
+ def test_research_sections_basic(self):
+ """Test basic section research and generation."""
+ mock_search_system = Mock()
+ mock_llm = Mock()
+ mock_search_system.model = mock_llm
+ mock_search_system.max_iterations = 3
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "Section content here"
+ }
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ structure = [
+ {
+ "name": "Introduction",
+ "subsections": [
+ {"name": "Overview", "purpose": "Provide overview"}
+ ],
+ }
+ ]
+ initial_findings = {"questions_by_iteration": {}}
+
+ sections = generator._research_and_generate_sections(
+ initial_findings, structure, "test query"
+ )
+
+ assert "Introduction" in sections
+ assert "Section content here" in sections["Introduction"]
+
+ def test_research_sections_preserves_questions(self):
+ """Test that questions from initial research are preserved."""
+ mock_search_system = Mock()
+ mock_llm = Mock()
+ mock_search_system.model = mock_llm
+ mock_search_system.max_iterations = 3
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "Content"
+ }
+ mock_search_system.questions_by_iteration = {}
+
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = {}
+ mock_search_system.strategy = mock_strategy
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ initial_findings = {"questions_by_iteration": {"0": ["Q1", "Q2"]}}
+ structure = [
+ {
+ "name": "Section",
+ "subsections": [{"name": "Sub", "purpose": "Test"}],
+ }
+ ]
+
+ generator._research_and_generate_sections(
+ initial_findings, structure, "test query"
+ )
+
+ # Questions should be set on strategy
+ assert mock_strategy.questions_by_iteration == {"0": ["Q1", "Q2"]}
+
+ def test_research_sections_creates_subsection_for_empty(self):
+ """Test subsection is created if none provided."""
+ mock_search_system = Mock()
+ mock_llm = Mock()
+ mock_search_system.model = mock_llm
+ mock_search_system.max_iterations = 3
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "Content"
+ }
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ structure = [
+ {
+ "name": "Introduction",
+ "subsections": [], # Empty!
+ }
+ ]
+ initial_findings = {}
+
+ generator._research_and_generate_sections(
+ initial_findings, structure, "test query"
+ )
+
+ # analyze_topic should still be called
+ mock_search_system.analyze_topic.assert_called()
+
+
+class TestFormatFinalReport:
+ """Tests for _format_final_report method."""
+
+ def test_format_final_report_structure(self):
+ """Test final report has correct structure."""
+ mock_search_system = Mock()
+ mock_llm = Mock()
+ mock_search_system.model = mock_llm
+ mock_search_system.all_links_of_system = []
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ sections = {"Introduction": "# Introduction\nContent here"}
+ structure = [
+ {
+ "name": "Introduction",
+ "subsections": [
+ {"name": "Overview", "purpose": "Provide overview"}
+ ],
+ }
+ ]
+
+ with patch(
+ "local_deep_research.report_generator.importlib.import_module"
+ ) as mock_import:
+ mock_utilities = Mock()
+ mock_utilities.search_utilities.format_links_to_markdown.return_value = "- [Link](url)"
+ mock_import.return_value = mock_utilities
+
+ result = generator._format_final_report(
+ sections, structure, "test query"
+ )
+
+ assert "content" in result
+ assert "metadata" in result
+ assert "Table of Contents" in result["content"]
+ assert "Introduction" in result["content"]
+ assert "Sources" in result["content"]
+
+ def test_format_final_report_metadata(self):
+ """Test final report metadata."""
+ mock_search_system = Mock()
+ mock_llm = Mock()
+ mock_search_system.model = mock_llm
+ mock_search_system.all_links_of_system = [
+ {"link": "url1"},
+ {"link": "url2"},
+ ]
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ sections = {"Section1": "Content"}
+ structure = [{"name": "Section1", "subsections": []}]
+
+ with patch(
+ "local_deep_research.report_generator.importlib.import_module"
+ ) as mock_import:
+ mock_utilities = Mock()
+ mock_utilities.search_utilities.format_links_to_markdown.return_value = ""
+ mock_import.return_value = mock_utilities
+
+ result = generator._format_final_report(
+ sections, structure, "test query"
+ )
+
+ assert result["metadata"]["initial_sources"] == 2
+ assert result["metadata"]["sections_researched"] == 1
+ assert result["metadata"]["query"] == "test query"
+ assert "generated_at" in result["metadata"]
+
+
+class TestGenerateReport:
+ """Tests for generate_report method."""
+
+ def test_generate_report_full_flow(self):
+ """Test full report generation flow."""
+ mock_search_system = Mock()
+ mock_llm = Mock()
+ mock_search_system.model = mock_llm
+ mock_search_system.max_iterations = 3
+ mock_search_system.all_links_of_system = []
+
+ # Mock LLM response for structure
+ mock_response = Mock()
+ mock_response.content = """
+STRUCTURE
+1. Introduction
+ - Overview | Provide overview
+END_STRUCTURE
+"""
+ mock_llm.invoke.return_value = mock_response
+
+ # Mock search results
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "Test content"
+ }
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ initial_findings = {"current_knowledge": "Initial research"}
+
+ with patch(
+ "local_deep_research.report_generator.importlib.import_module"
+ ) as mock_import:
+ mock_utilities = Mock()
+ mock_utilities.search_utilities.format_links_to_markdown.return_value = ""
+ mock_import.return_value = mock_utilities
+
+ result = generator.generate_report(initial_findings, "test query")
+
+ assert "content" in result
+ assert "metadata" in result
+
+
+class TestGenerateErrorReport:
+ """Tests for _generate_error_report method."""
+
+ def test_generate_error_report(self):
+ """Test error report generation."""
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ result = generator._generate_error_report(
+ "test query", "Something went wrong"
+ )
+
+ assert "ERROR REPORT" in result
+ assert "test query" in result
+ assert "Something went wrong" in result
+
+
+class TestGenerateSectionsDeprecated:
+ """Tests for deprecated _generate_sections method."""
+
+ def test_generate_sections_returns_empty(self):
+ """Test deprecated _generate_sections returns empty dict."""
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(search_system=mock_search_system)
+
+ result = generator._generate_sections({}, {}, [], "query")
+
+ assert result == {}
diff --git a/tests/core/test_search_system.py b/tests/core/test_search_system.py
new file mode 100644
index 0000000000..8538d92582
--- /dev/null
+++ b/tests/core/test_search_system.py
@@ -0,0 +1,631 @@
+"""
+Tests for search_system.py
+
+Tests cover:
+- AdvancedSearchSystem initialization
+- Strategy selection
+- Search execution
+- Progress callbacks
+"""
+
+from unittest.mock import Mock, patch
+
+
+class TestAdvancedSearchSystemInit:
+ """Tests for AdvancedSearchSystem initialization."""
+
+ def test_init_basic(self):
+ """Test basic initialization."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(llm=mock_llm, search=mock_search)
+
+ assert system.model == mock_llm
+ assert system.search == mock_search
+ assert system.max_iterations == 1 # default
+ assert system.questions_per_iteration == 3 # default
+
+ def test_init_with_custom_iterations(self):
+ """Test initialization with custom iterations."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm,
+ search=mock_search,
+ max_iterations=5,
+ questions_per_iteration=10,
+ )
+
+ assert system.max_iterations == 5
+ assert system.questions_per_iteration == 10
+
+ def test_init_iterations_from_settings_snapshot(self):
+ """Test iterations are read from settings snapshot."""
+ mock_llm = Mock()
+ mock_search = Mock()
+ settings = {
+ "search.iterations": {"value": 7},
+ "search.questions_per_iteration": 4,
+ }
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search, settings_snapshot=settings
+ )
+
+ assert system.max_iterations == 7
+ assert system.questions_per_iteration == 4
+
+ def test_init_programmatic_mode(self):
+ """Test programmatic mode initialization."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search, programmatic_mode=True
+ )
+
+ assert system.programmatic_mode is True
+
+
+class TestStrategySelection:
+ """Tests for strategy selection."""
+
+ def test_default_strategy(self):
+ """Test default strategy is source-based."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ AdvancedSearchSystem(llm=mock_llm, search=mock_search)
+
+ mock_create.assert_called_once()
+ call_kwargs = mock_create.call_args[1]
+ assert call_kwargs["strategy_name"] == "source-based"
+
+ def test_custom_strategy(self):
+ """Test custom strategy selection."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search, strategy_name="evidence"
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert call_kwargs["strategy_name"] == "evidence"
+
+ def test_contextual_followup_strategy(self):
+ """Test contextual followup strategy uses delegate."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.search_system.EnhancedContextualFollowUpStrategy"
+ ) as mock_followup:
+ mock_followup_strategy = Mock()
+ mock_followup.return_value = mock_followup_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ AdvancedSearchSystem(
+ llm=mock_llm,
+ search=mock_search,
+ strategy_name="enhanced-contextual-followup",
+ )
+
+ # Verify create_strategy was called for the delegate
+ mock_create.assert_called()
+
+
+class TestProgressCallbacks:
+ """Tests for progress callback handling."""
+
+ def test_set_progress_callback(self):
+ """Test setting progress callback."""
+ mock_llm = Mock()
+ mock_search = Mock()
+ mock_callback = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(llm=mock_llm, search=mock_search)
+
+ system.set_progress_callback(mock_callback)
+
+ assert system.progress_callback == mock_callback
+ mock_strategy.set_progress_callback.assert_called_with(
+ mock_callback
+ )
+
+ def test_progress_callback_called(self):
+ """Test progress callback is called internally."""
+ mock_llm = Mock()
+ mock_search = Mock()
+ mock_callback = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(llm=mock_llm, search=mock_search)
+ system.progress_callback = mock_callback
+
+ system._progress_callback("Test", 50, {})
+
+ mock_callback.assert_called_once_with("Test", 50, {})
+
+
+class TestAnalyzeTopic:
+ """Tests for analyze_topic method."""
+
+ def test_analyze_topic_basic(self):
+ """Test basic topic analysis."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = ["Q1"]
+ mock_strategy.all_links_of_system = [{"link": "url1"}]
+ mock_strategy.analyze_topic.return_value = {
+ "current_knowledge": "Result"
+ }
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+ ):
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search
+ )
+
+ result = system.analyze_topic("test query")
+
+ assert "current_knowledge" in result
+ assert result["query"] == "test query"
+ assert "search_system" in result
+ mock_strategy.analyze_topic.assert_called_once_with(
+ "test query"
+ )
+
+ def test_analyze_topic_generates_search_id(self):
+ """Test search ID is generated if not provided."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_strategy.analyze_topic.return_value = {}
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+ ):
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search
+ )
+
+ # Should not raise
+ result = system.analyze_topic("test")
+ assert isinstance(result, dict)
+
+ def test_analyze_topic_preserves_links(self):
+ """Test that links are preserved correctly."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ # Create a separate list object
+ mock_strategy.all_links_of_system = [
+ {"link": "url1"},
+ {"link": "url2"},
+ ]
+ mock_strategy.analyze_topic.return_value = {}
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+ ):
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search
+ )
+
+ result = system.analyze_topic("test")
+
+ assert "all_links_of_system" in result
+
+
+class TestPerformSearch:
+ """Tests for _perform_search method."""
+
+ def test_perform_search_extracts_settings(self):
+ """Test settings are extracted from snapshot."""
+ mock_llm = Mock()
+ mock_search = Mock()
+ settings = {
+ "llm.provider": {"value": "anthropic"},
+ "llm.model": {"value": "claude-3"},
+ "search.tool": {"value": "searxng"},
+ }
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_strategy.analyze_topic.return_value = {}
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+ ):
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm,
+ search=mock_search,
+ settings_snapshot=settings,
+ )
+ progress_calls = []
+ system.progress_callback = (
+ lambda m, p, md: progress_calls.append((m, p, md))
+ )
+
+ system._perform_search(
+ "test", "id123", True, False, "user1"
+ )
+
+ # Check progress was called with LLM info
+ assert any("anthropic" in str(c) for c in progress_calls)
+
+ def test_perform_search_handles_news_callback_error(self):
+ """Test news callback errors are handled gracefully."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_strategy.analyze_topic.return_value = {}
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+ ) as mock_callback:
+ mock_callback.side_effect = Exception("Callback error")
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search
+ )
+
+ # Should not raise despite callback error
+ result = system._perform_search(
+ "test", "id", True, False, "user"
+ )
+ assert isinstance(result, dict)
+
+
+class TestResearchContext:
+ """Tests for research context handling."""
+
+ def test_research_context_stored(self):
+ """Test research context is stored."""
+ mock_llm = Mock()
+ mock_search = Mock()
+ context = {"topic": "AI", "depth": "deep"}
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search, research_context=context
+ )
+
+ assert system.research_context == context
+
+ def test_research_id_stored(self):
+ """Test research ID is stored."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search, research_id="research-123"
+ )
+
+ assert system.research_id == "research-123"
+
+ def test_username_stored(self):
+ """Test username is stored."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ mock_create.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ) as mock_citation:
+ mock_citation.return_value = Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ )
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm, search=mock_search, username="testuser"
+ )
+
+ assert system.username == "testuser"
diff --git a/tests/search_engines/test_rate_limiting.py b/tests/search_engines/test_rate_limiting.py
new file mode 100644
index 0000000000..86c58b25b7
--- /dev/null
+++ b/tests/search_engines/test_rate_limiting.py
@@ -0,0 +1,82 @@
+"""
+Tests for web_search_engines/rate_limiting module
+
+Tests cover:
+- RateLimitError exception
+- Basic module exports
+"""
+
+import pytest
+
+
+class TestRateLimitError:
+ """Tests for RateLimitError exception."""
+
+ def test_rate_limit_error_exists(self):
+ """Test RateLimitError can be imported."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ assert RateLimitError is not None
+
+ def test_rate_limit_error_is_exception(self):
+ """Test RateLimitError is an exception class."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ assert issubclass(RateLimitError, Exception)
+
+ def test_rate_limit_error_can_be_raised(self):
+ """Test RateLimitError can be raised and caught."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ with pytest.raises(RateLimitError):
+ raise RateLimitError("Rate limit exceeded")
+
+ def test_rate_limit_error_message(self):
+ """Test RateLimitError stores message."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ try:
+ raise RateLimitError("Test message")
+ except RateLimitError as e:
+ assert "Test message" in str(e)
+
+
+class TestModuleExports:
+ """Tests for module exports."""
+
+ def test_get_tracker_exists(self):
+ """Test get_tracker function is exported."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ get_tracker,
+ )
+
+ assert get_tracker is not None
+ assert callable(get_tracker)
+
+
+class TestRateLimitExceptions:
+ """Tests for rate limiting exceptions module."""
+
+ def test_exceptions_module_exists(self):
+ """Test exceptions module can be imported."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ exceptions,
+ )
+
+ assert exceptions is not None
+
+ def test_rate_limit_error_in_exceptions(self):
+ """Test RateLimitError is in exceptions module."""
+ from local_deep_research.web_search_engines.rate_limiting.exceptions import (
+ RateLimitError,
+ )
+
+ assert RateLimitError is not None
diff --git a/tests/search_engines/test_search_engine_base.py b/tests/search_engines/test_search_engine_base.py
new file mode 100644
index 0000000000..82f28914a5
--- /dev/null
+++ b/tests/search_engines/test_search_engine_base.py
@@ -0,0 +1,249 @@
+"""
+Tests for web_search_engines/search_engine_base.py
+
+Tests cover:
+- BaseSearchEngine class attributes
+- AdaptiveWait strategy
+- Engine class loading
+- Search methods
+"""
+
+import pytest
+from unittest.mock import Mock
+
+
+class TestBaseSearchEngineAttributes:
+ """Tests for BaseSearchEngine class attributes."""
+
+ def test_is_public_default(self):
+ """Test default is_public attribute."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ assert BaseSearchEngine.is_public is False
+
+ def test_is_generic_default(self):
+ """Test default is_generic attribute."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ assert BaseSearchEngine.is_generic is False
+
+ def test_is_scientific_default(self):
+ """Test default is_scientific attribute."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ assert BaseSearchEngine.is_scientific is False
+
+ def test_is_local_default(self):
+ """Test default is_local attribute."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ assert BaseSearchEngine.is_local is False
+
+ def test_is_news_default(self):
+ """Test default is_news attribute."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ assert BaseSearchEngine.is_news is False
+
+ def test_is_code_default(self):
+ """Test default is_code attribute."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ assert BaseSearchEngine.is_code is False
+
+
+class TestAdaptiveWait:
+ """Tests for AdaptiveWait class."""
+
+ def test_adaptive_wait_init(self):
+ """Test AdaptiveWait initialization."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ AdaptiveWait,
+ )
+
+ def get_wait():
+ return 5.0
+
+ wait = AdaptiveWait(get_wait)
+ assert wait.get_wait_func == get_wait
+
+ def test_adaptive_wait_call(self):
+ """Test AdaptiveWait __call__ method."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ AdaptiveWait,
+ )
+
+ def get_wait():
+ return 2.5
+
+ wait = AdaptiveWait(get_wait)
+ mock_retry_state = Mock()
+
+ result = wait(mock_retry_state)
+
+ assert result == 2.5
+
+
+class TestLoadEngineClass:
+ """Tests for _load_engine_class method."""
+
+ def test_load_engine_class_missing_module_path(self):
+ """Test loading engine with missing module_path."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ config = {"class_name": "SomeClass"} # Missing module_path
+ success, engine_class, error_msg = BaseSearchEngine._load_engine_class(
+ "test_engine", config
+ )
+
+ assert success is False
+ assert engine_class is None
+ assert "Missing module_path" in error_msg
+
+ def test_load_engine_class_missing_class_name(self):
+ """Test loading engine with missing class_name."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ config = {"module_path": "some.module"} # Missing class_name
+ success, engine_class, error_msg = BaseSearchEngine._load_engine_class(
+ "test_engine", config
+ )
+
+ assert success is False
+ assert engine_class is None
+ assert "Missing" in error_msg
+
+ def test_load_engine_class_success(self):
+ """Test successful engine class loading."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ # Use an existing module and class
+ config = {
+ "module_path": "local_deep_research.web_search_engines.search_engine_base",
+ "class_name": "BaseSearchEngine",
+ }
+ success, engine_class, error_msg = BaseSearchEngine._load_engine_class(
+ "test_engine", config
+ )
+
+ assert success is True
+ assert engine_class is BaseSearchEngine
+ assert error_msg is None
+
+ def test_load_engine_class_relative_import(self):
+ """Test loading with relative import."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ config = {
+ "module_path": ".search_engine_base",
+ "class_name": "BaseSearchEngine",
+ }
+ success, engine_class, error_msg = BaseSearchEngine._load_engine_class(
+ "test_engine", config
+ )
+
+ assert success is True
+ assert engine_class is BaseSearchEngine
+
+ def test_load_engine_class_nonexistent_module(self):
+ """Test loading with nonexistent module."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ config = {
+ "module_path": "nonexistent.module.path",
+ "class_name": "SomeClass",
+ }
+ success, engine_class, error_msg = BaseSearchEngine._load_engine_class(
+ "test_engine", config
+ )
+
+ assert success is False
+ assert engine_class is None
+ assert error_msg is not None
+
+
+class TestConcreteSearchEngine:
+ """Tests using a concrete search engine implementation."""
+
+ @pytest.fixture
+ def concrete_engine_class(self):
+ """Create a concrete search engine for testing."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class ConcreteSearchEngine(BaseSearchEngine):
+ is_public = True
+ is_generic = True
+
+ def __init__(self, **kwargs):
+ self.llm = kwargs.get("llm")
+ self.max_results = kwargs.get("max_results", 10)
+
+ def _get_previews(self, query, num_results=None, *args, **kwargs):
+ return [
+ {"title": "Result 1", "link": "http://example.com/1"},
+ {"title": "Result 2", "link": "http://example.com/2"},
+ ]
+
+ def _get_full_content(self, relevant_items):
+ return [
+ {
+ "title": r["title"],
+ "link": r["link"],
+ "full_content": "content",
+ }
+ for r in relevant_items
+ ]
+
+ return ConcreteSearchEngine
+
+ def test_concrete_engine_class_attributes(self, concrete_engine_class):
+ """Test concrete engine class attributes."""
+ assert concrete_engine_class.is_public is True
+ assert concrete_engine_class.is_generic is True
+ assert concrete_engine_class.is_scientific is False
+
+ def test_concrete_engine_init(self, concrete_engine_class):
+ """Test concrete engine initialization."""
+ engine = concrete_engine_class(max_results=5)
+ assert engine.max_results == 5
+
+ def test_concrete_engine_get_previews(self, concrete_engine_class):
+ """Test concrete engine _get_previews."""
+ engine = concrete_engine_class()
+ results = engine._get_previews("test query")
+
+ assert len(results) == 2
+ assert results[0]["title"] == "Result 1"
+
+ def test_concrete_engine_get_full_content(self, concrete_engine_class):
+ """Test concrete engine _get_full_content."""
+ engine = concrete_engine_class()
+ items = [{"title": "Test", "link": "http://test.com"}]
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ assert "full_content" in results[0]