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: rewrite test_search_system.py with fixture-based tests (#2437)

LearningCircuitbc46ee06e52d
diff --git a/tests/core/test_search_system.py b/tests/core/test_search_system.py
index 8538d92582..b1def2d8c2 100644
--- a/tests/core/test_search_system.py
+++ b/tests/core/test_search_system.py
@@ -1,631 +1,420 @@
"""
-Tests for search_system.py
+Tests for search_system.py - AdvancedSearchSystem class.
Tests cover:
-- AdvancedSearchSystem initialization
-- Strategy selection
-- Search execution
-- Progress callbacks
+- __init__ settings extraction, defaults, factory wiring, follow-up delegation, logging
+- set_progress_callback forwarding to strategy
+- analyze_topic search_id generation and delegation
+- _perform_search settings extraction, progress callbacks, result assembly
+- Duplicate link avoidance (id check)
+- NewsSearchCallback error resilience
"""
-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,
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+# ---------------------------------------------------------------------------
+# Helpers / fixtures
+# ---------------------------------------------------------------------------
+
+
+def _make_strategy_mock():
+ """Return a MagicMock that behaves like a strategy returned by create_strategy."""
+ strategy = MagicMock()
+ strategy.analyze_topic.return_value = {"current_knowledge": "test"}
+ strategy.questions_by_iteration = []
+ strategy.all_links_of_system = []
+ strategy.set_progress_callback = MagicMock()
+ return strategy
+
+
+# Patch paths: top-level imports can be patched on search_system directly,
+# but create_strategy and NewsSearchCallback are lazily imported inside method
+# bodies, so they must be patched at their source modules.
+PATCH_CITATION = "local_deep_research.search_system.CitationHandler"
+PATCH_QUESTION_GEN = (
+ "local_deep_research.search_system.StandardQuestionGenerator"
+)
+PATCH_FINDINGS = "local_deep_research.search_system.FindingsRepository"
+PATCH_CREATE_STRATEGY = (
+ "local_deep_research.search_system_factory.create_strategy"
+)
+PATCH_ENHANCED_FOLLOWUP = (
+ "local_deep_research.search_system.EnhancedContextualFollowUpStrategy"
+)
+PATCH_NEWS_CALLBACK = (
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+)
+
+
+def mock_deps():
+ """Patch CitationHandler, StandardQuestionGenerator, FindingsRepository,
+ and create_strategy so that AdvancedSearchSystem can be instantiated
+ without real dependencies. Yields a dict of mock objects."""
+ with (
+ patch(PATCH_CITATION) as m_citation,
+ patch(PATCH_QUESTION_GEN) as m_qgen,
+ patch(PATCH_FINDINGS) as m_findings,
+ patch(PATCH_CREATE_STRATEGY) as m_create,
+ ):
+ strategy = _make_strategy_mock()
+ m_create.return_value = strategy
+
+ yield {
+ "citation": m_citation,
+ "question_gen": m_qgen,
+ "findings": m_findings,
+ "create_strategy": m_create,
+ "strategy": strategy,
}
- 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, {})
+
+def mock_model():
+ return MagicMock(name="BaseChatModel")
+
+
+def mock_search():
+ return MagicMock(name="BaseSearchEngine")
+
+
+def _build_system(mock_model, mock_search, mock_deps, **kwargs):
+ """Convenience: build an AdvancedSearchSystem with the standard mocks."""
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ return AdvancedSearchSystem(llm=mock_model, search=mock_search, **kwargs)
+
+
+# ===================================================================
+# __init__ tests
+# ===================================================================
+
+
+class TestInit:
+ """Tests for AdvancedSearchSystem.__init__."""
+
+ def test_settings_snapshot_defaults_to_empty_dict(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(
+ mock_model, mock_search, mock_deps, settings_snapshot=None
+ )
+ assert system.settings_snapshot == {}
+
+ # -- max_iterations -------------------------------------------------
+
+ def test_max_iterations_default_is_one(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(mock_model, mock_search, mock_deps)
+ assert system.max_iterations == 1
+
+ def test_max_iterations_from_settings_plain_value(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(
+ mock_model,
+ mock_search,
+ mock_deps,
+ settings_snapshot={"search.iterations": 5},
+ )
+ assert system.max_iterations == 5
+
+ def test_max_iterations_extracts_value_from_dict(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(
+ mock_model,
+ mock_search,
+ mock_deps,
+ settings_snapshot={"search.iterations": {"value": 8}},
+ )
+ assert system.max_iterations == 8
+
+ def test_max_iterations_explicit_overrides_snapshot(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(
+ mock_model,
+ mock_search,
+ mock_deps,
+ max_iterations=12,
+ settings_snapshot={"search.iterations": {"value": 8}},
+ )
+ assert system.max_iterations == 12
+
+ # -- questions_per_iteration ----------------------------------------
+
+ def test_questions_per_iteration_default_is_three(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(mock_model, mock_search, mock_deps)
+ assert system.questions_per_iteration == 3
+
+ def test_questions_per_iteration_from_settings_dict(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(
+ mock_model,
+ mock_search,
+ mock_deps,
+ settings_snapshot={"search.questions_per_iteration": {"value": 7}},
+ )
+ assert system.questions_per_iteration == 7
+
+ # -- strategy creation via factory ----------------------------------
+
+ def test_calls_create_strategy_factory(
+ self, mock_model, mock_search, mock_deps
+ ):
+ _build_system(mock_model, mock_search, mock_deps)
+ mock_deps["create_strategy"].assert_called_once()
+
+ # -- enhanced-contextual-followup strategy --------------------------
+
+ def test_enhanced_contextual_followup_creates_delegate(
+ self, mock_model, mock_search, mock_deps
+ ):
+ with patch(PATCH_ENHANCED_FOLLOWUP) as m_followup:
+ m_followup.return_value = _make_strategy_mock()
+ system = _build_system(
+ mock_model,
+ mock_search,
+ mock_deps,
+ strategy_name="enhanced-contextual-followup",
+ )
+ # create_strategy should have been called for the delegate
+ mock_deps["create_strategy"].assert_called_once()
+ delegate_kwargs = mock_deps["create_strategy"].call_args[1]
+ assert delegate_kwargs["strategy_name"] == "source-based"
+ # EnhancedContextualFollowUpStrategy should have been instantiated
+ m_followup.assert_called_once()
+ assert system.strategy is m_followup.return_value
+
+ # -- programmatic_mode warning --------------------------------------
+
+ def test_programmatic_mode_logs_warning(
+ self, mock_model, mock_search, mock_deps
+ ):
+ with patch("local_deep_research.search_system.logger") as m_logger:
+ _build_system(
+ mock_model, mock_search, mock_deps, programmatic_mode=True
+ )
+ m_logger.warning.assert_called_once()
+ assert (
+ "programmatic mode" in m_logger.warning.call_args[0][0].lower()
+ )
+
+
+# ===================================================================
+# set_progress_callback tests
+# ===================================================================
+
+
+class TestSetProgressCallback:
+ """Tests for set_progress_callback."""
+
+ def test_forwards_callback_to_strategy(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(mock_model, mock_search, mock_deps)
+ cb = MagicMock(name="my_callback")
+ system.set_progress_callback(cb)
+ mock_deps["strategy"].set_progress_callback.assert_called_with(cb)
+
+
+# ===================================================================
+# analyze_topic tests
+# ===================================================================
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
+ """Tests for analyze_topic."""
+
+ def test_generates_search_id_when_not_provided(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(mock_model, mock_search, mock_deps)
+ with patch.object(system, "_perform_search", return_value={}) as m_ps:
+ system.analyze_topic("quantum computing")
+ # search_id (2nd positional arg) should be a non-empty string
+ search_id = m_ps.call_args[0][1]
+ assert isinstance(search_id, str) and len(search_id) > 0
+
+ def test_passes_explicit_search_id(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(mock_model, mock_search, mock_deps)
+ with patch.object(system, "_perform_search", return_value={}) as m_ps:
+ system.analyze_topic("q", search_id="my-id-99")
+ assert m_ps.call_args[0][1] == "my-id-99"
+
+ def test_returns_perform_search_result(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(mock_model, mock_search, mock_deps)
+ expected = {"current_knowledge": "deep"}
+ with patch.object(system, "_perform_search", return_value=expected):
+ result = system.analyze_topic("topic")
+ assert result is expected
+
+
+# ===================================================================
+# _perform_search tests
+# ===================================================================
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"
+ """Tests for _perform_search."""
+
+ def _run_perform_search(
+ self,
+ mock_model,
+ mock_search,
+ mock_deps,
+ settings=None,
+ query="test q",
+ ):
+ system = _build_system(
+ mock_model,
+ mock_search,
+ mock_deps,
+ settings_snapshot=settings or {},
+ )
+ progress_calls = []
+ system.progress_callback = lambda m, p, md: progress_calls.append(
+ (m, p, md)
+ )
+ with patch(PATCH_NEWS_CALLBACK):
+ result = system._perform_search(
+ query, "sid-1", True, False, "user1"
+ )
+ return system, result, progress_calls
+
+ def test_extracts_llm_provider_from_settings(
+ self, mock_model, mock_search, mock_deps
+ ):
+ settings = {"llm.provider": {"value": "anthropic"}}
+ _, _, calls = self._run_perform_search(
+ mock_model, mock_search, mock_deps, settings=settings
+ )
+ assert any("anthropic" in str(c) for c in calls)
+
+ def test_extracts_llm_model_from_settings(
+ self, mock_model, mock_search, mock_deps
+ ):
+ settings = {"llm.model": "claude-3-opus"}
+ _, _, calls = self._run_perform_search(
+ mock_model, mock_search, mock_deps, settings=settings
+ )
+ assert any("claude-3-opus" in str(c) for c in calls)
+
+ def test_extracts_search_tool_from_settings(
+ self, mock_model, mock_search, mock_deps
+ ):
+ settings = {"search.tool": {"value": "google"}}
+ _, _, calls = self._run_perform_search(
+ mock_model, mock_search, mock_deps, settings=settings
+ )
+ assert any("google" in str(c) for c in calls)
+
+ def test_calls_progress_callback_with_setup_info(
+ self, mock_model, mock_search, mock_deps
+ ):
+ _, _, calls = self._run_perform_search(
+ mock_model, mock_search, mock_deps
+ )
+ # At least two calls: one for LLM info, one for search tool info
+ assert len(calls) >= 2
+ phases = [c[2].get("phase") for c in calls]
+ assert "setup" in phases
+
+ def test_calls_strategy_analyze_topic(
+ self, mock_model, mock_search, mock_deps
+ ):
+ self._run_perform_search(
+ mock_model, mock_search, mock_deps, query="my query"
+ )
+ mock_deps["strategy"].analyze_topic.assert_called_once_with("my query")
+
+ def test_updates_questions_by_iteration(
+ self, mock_model, mock_search, mock_deps
+ ):
+ mock_deps["strategy"].questions_by_iteration = ["q1", "q2"]
+ system, result, _ = self._run_perform_search(
+ mock_model, mock_search, mock_deps
+ )
+ assert system.questions_by_iteration == ["q1", "q2"]
+ assert result["questions_by_iteration"] == ["q1", "q2"]
+
+ def test_result_contains_search_system(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system, result, _ = self._run_perform_search(
+ mock_model, mock_search, mock_deps
+ )
+ assert result["search_system"] is system
+
+ def test_result_contains_all_links_of_system(
+ self, mock_model, mock_search, mock_deps
+ ):
+ mock_deps["strategy"].all_links_of_system = [{"url": "http://a.com"}]
+ _, result, _ = self._run_perform_search(
+ mock_model, mock_search, mock_deps
+ )
+ assert "all_links_of_system" in result
+
+ def test_result_contains_query(self, mock_model, mock_search, mock_deps):
+ _, result, _ = self._run_perform_search(
+ mock_model, mock_search, mock_deps, query="deep research"
+ )
+ assert result["query"] == "deep research"
+
+ def test_avoids_duplicate_links_when_same_object(
+ self, mock_model, mock_search, mock_deps
+ ):
+ """When strategy.all_links_of_system is the SAME object as
+ system.all_links_of_system, no extend should happen (id check)."""
+ system = _build_system(mock_model, mock_search, mock_deps)
+ # Make the strategy share the exact same list object
+ mock_deps["strategy"].all_links_of_system = system.all_links_of_system
+ system.all_links_of_system.extend(
+ [{"url": "http://a.com"}, {"url": "http://b.com"}]
+ )
+
+ system.progress_callback = lambda m, p, md: None
+ with patch(PATCH_NEWS_CALLBACK):
+ system._perform_search("q", "sid", True, False, "u")
+
+ # If id-check were removed, self-extend would double to 4
+ assert len(system.all_links_of_system) == 2
+
+ def test_extends_links_when_different_objects(
+ self, mock_model, mock_search, mock_deps
+ ):
+ """When strategy.all_links_of_system is a different object,
+ the links should be extended."""
+ system = _build_system(mock_model, mock_search, mock_deps)
+ strategy_links = [{"url": "http://new.com"}]
+ mock_deps["strategy"].all_links_of_system = strategy_links
+
+ system.progress_callback = lambda m, p, md: None
+ with patch(PATCH_NEWS_CALLBACK):
+ system._perform_search("q", "sid", True, False, "u")
+
+ assert {"url": "http://new.com"} in system.all_links_of_system
+
+ def test_news_callback_error_does_not_break_search(
+ self, mock_model, mock_search, mock_deps
+ ):
+ system = _build_system(mock_model, mock_search, mock_deps)
+ system.progress_callback = lambda m, p, md: None
+
+ with patch(PATCH_NEWS_CALLBACK, side_effect=Exception("boom")):
+ # Should not raise
+ result = system._perform_search("q", "sid", True, False, "u")
+ assert isinstance(result, dict)