~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: add comprehensive tests for search engines and utilities (#1579)
LearningCircuita33452641a2e
diff --git a/tests/config/test_llm_config.py b/tests/config/test_llm_config.pyindex bd33897e23..3f3873d899 100644--- a/tests/config/test_llm_config.py+++ b/tests/config/test_llm_config.py@@ -553,3 +553,439 @@ class TestGetLlm:get_llm()except Exception:pass # Expected - testing normalization not actual LLM creation++ def test_invalid_provider_raises_error(self):+ """Should raise ValueError for invalid provider."""+ import pytest++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "test-model",+ "llm.temperature": 0.7,+ "llm.provider": "invalid_provider",+ }.get(key, default)++ with pytest.raises(ValueError, match="Invalid provider"):+ get_llm()++ def test_anthropic_provider_creates_chat_anthropic(self):+ """Should create ChatAnthropic when provider is anthropic."""+ from langchain_anthropic import ChatAnthropic++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "claude-3-sonnet",+ "llm.temperature": 0.7,+ "llm.provider": "anthropic",+ "llm.anthropic.api_key": "sk-ant-test",+ "llm.local_context_window_size": 4096,+ "llm.context_window_unrestricted": True,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 4096,+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ with patch.object(+ ChatAnthropic, "__init__", return_value=None+ ) as mock_init:+ get_llm(provider="anthropic")+ mock_init.assert_called_once()+ # Check it was called with model and api_key+ call_kwargs = mock_init.call_args.kwargs+ assert call_kwargs["model"] == "claude-3-sonnet"+ assert call_kwargs["anthropic_api_key"] == "sk-ant-test"++ def test_anthropic_without_api_key_returns_fallback(self):+ """Should return fallback model when anthropic API key not set."""+ from langchain_core.language_models import FakeListChatModel++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "claude-3-sonnet",+ "llm.temperature": 0.7,+ "llm.provider": "anthropic",+ "llm.anthropic.api_key": None,+ "llm.local_context_window_size": 4096,+ "llm.context_window_unrestricted": True,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 4096,+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ result = get_llm(provider="anthropic")+ # Returns FakeListChatModel directly (not wrapped) when no API key+ assert isinstance(result, FakeListChatModel)++ def test_openai_provider_creates_chat_openai(self):+ """Should create ChatOpenAI when provider is openai."""+ from langchain_openai import ChatOpenAI++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "gpt-4",+ "llm.temperature": 0.7,+ "llm.provider": "openai",+ "llm.openai.api_key": "sk-test",+ "llm.openai.api_base": None,+ "llm.openai.organization": None,+ "llm.streaming": None,+ "llm.max_retries": None,+ "llm.request_timeout": None,+ "llm.local_context_window_size": 4096,+ "llm.context_window_unrestricted": True,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 4096,+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ with patch.object(+ ChatOpenAI, "__init__", return_value=None+ ) as mock_init:+ get_llm(provider="openai")+ mock_init.assert_called_once()+ call_kwargs = mock_init.call_args.kwargs+ assert call_kwargs["model"] == "gpt-4"+ assert call_kwargs["api_key"] == "sk-test"++ def test_openai_without_api_key_returns_fallback(self):+ """Should return fallback model when openai API key not set."""+ from langchain_core.language_models import FakeListChatModel++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "gpt-4",+ "llm.temperature": 0.7,+ "llm.provider": "openai",+ "llm.openai.api_key": None,+ "llm.local_context_window_size": 4096,+ "llm.context_window_unrestricted": True,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 4096,+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ result = get_llm(provider="openai")+ # Returns FakeListChatModel directly (not wrapped) when no API key+ assert isinstance(result, FakeListChatModel)++ def test_openai_endpoint_creates_chat_openai(self):+ """Should create ChatOpenAI with custom endpoint when provider is openai_endpoint."""+ from langchain_openai import ChatOpenAI++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "custom-model",+ "llm.temperature": 0.7,+ "llm.provider": "openai_endpoint",+ "llm.openai_endpoint.api_key": "custom-key",+ "llm.openai_endpoint.url": "https://custom.api.com/v1",+ "llm.local_context_window_size": 4096,+ "llm.context_window_unrestricted": True,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 4096,+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ with patch.object(+ ChatOpenAI, "__init__", return_value=None+ ) as mock_init:+ get_llm(provider="openai_endpoint")+ mock_init.assert_called_once()+ call_kwargs = mock_init.call_args.kwargs+ assert call_kwargs["model"] == "custom-model"+ assert call_kwargs["api_key"] == "custom-key"+ assert "custom.api.com" in call_kwargs.get(+ "openai_api_base", ""+ )++ def test_lmstudio_creates_chat_openai(self):+ """Should create ChatOpenAI with LM Studio URL when provider is lmstudio."""+ from langchain_openai import ChatOpenAI++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "local-model",+ "llm.temperature": 0.7,+ "llm.provider": "lmstudio",+ "llm.lmstudio.url": "http://localhost:1234",+ "llm.local_context_window_size": 4096,+ "llm.context_window_unrestricted": False,+ "llm.context_window_size": 8192,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 4096,+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ with patch.object(+ ChatOpenAI, "__init__", return_value=None+ ) as mock_init:+ get_llm(provider="lmstudio")+ mock_init.assert_called_once()+ call_kwargs = mock_init.call_args.kwargs+ assert call_kwargs["model"] == "local-model"+ assert "localhost:1234" in call_kwargs.get("base_url", "")++ def test_custom_factory_function_is_called(self):+ """Should call factory function for custom registered LLM."""+ from langchain_core.language_models import BaseChatModel++ mock_llm = MagicMock(spec=BaseChatModel)+ mock_factory = MagicMock(return_value=mock_llm)++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=True,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_llm_from_registry",+ return_value=mock_factory,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "custom-model",+ "llm.temperature": 0.5,+ "llm.provider": "custom_provider",+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ get_llm(+ model_name="custom-model",+ temperature=0.5,+ provider="custom_provider",+ )++ mock_factory.assert_called_once()+ call_kwargs = mock_factory.call_args.kwargs+ assert call_kwargs["model_name"] == "custom-model"+ assert call_kwargs["temperature"] == 0.5++ def test_custom_factory_with_invalid_signature_raises(self):+ """Should raise TypeError when factory has invalid signature."""+ import pytest++ def bad_factory():+ return MagicMock()++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=True,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_llm_from_registry",+ return_value=bad_factory,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "model",+ "llm.temperature": 0.7,+ "llm.provider": "bad_factory",+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ with pytest.raises(TypeError, match="invalid signature"):+ get_llm(provider="bad_factory")++ def test_custom_factory_returning_non_basechatmodel_raises(self):+ """Should raise ValueError when factory returns non-BaseChatModel."""+ import pytest++ def bad_factory(+ model_name=None, temperature=None, settings_snapshot=None+ ):+ return "not a model"++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=True,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_llm_from_registry",+ return_value=bad_factory,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "model",+ "llm.temperature": 0.7,+ "llm.provider": "bad_factory",+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ with pytest.raises(+ ValueError, match="must return a BaseChatModel"+ ):+ get_llm(provider="bad_factory")++ def test_none_provider_returns_fallback(self):+ """Should return fallback model when provider is 'none'."""+ from langchain_core.language_models import FakeListChatModel++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "test-model",+ "llm.temperature": 0.7,+ "llm.provider": "none",+ "llm.local_context_window_size": 4096,+ "llm.context_window_unrestricted": True,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 4096,+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ result = get_llm(provider="none")+ assert hasattr(result, "base_llm")+ assert isinstance(result.base_llm, FakeListChatModel)++ def test_context_window_size_for_local_providers(self):+ """Should use local context window size for local providers."""+ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ calls = []++ def track_calls(key, default=None, **kwargs):+ calls.append(key)+ settings = {+ "llm.model": "test-model",+ "llm.temperature": 0.7,+ "llm.provider": "lmstudio",+ "llm.lmstudio.url": "http://localhost:1234",+ "llm.local_context_window_size": 2048, # Custom local size+ "llm.context_window_size": 128000,+ "llm.context_window_unrestricted": False,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 4096,+ "rate_limiting.llm_enabled": False,+ }+ return settings.get(key, default)++ mock_get.side_effect = track_calls++ from langchain_openai import ChatOpenAI++ with patch.object(ChatOpenAI, "__init__", return_value=None):+ get_llm(provider="lmstudio")+ # Should have checked local_context_window_size+ assert "llm.local_context_window_size" in calls++ def test_research_context_is_mutable_parameter(self):+ """Should accept research_context parameter."""++ research_context = {"existing": "value"}++ with patch(+ "local_deep_research.config.llm_config.is_llm_registered",+ return_value=False,+ ):+ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.side_effect = lambda key, default=None, **kwargs: {+ "llm.model": "test-model",+ "llm.temperature": 0.7,+ "llm.provider": "none", # Falls through to default+ "llm.local_context_window_size": 4096,+ "llm.context_window_unrestricted": True,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 4096,+ "rate_limiting.llm_enabled": False,+ }.get(key, default)++ # Should not fail when research_context is passed+ result = get_llm(+ provider="none", research_context=research_context+ )+ assert hasattr(result, "base_llm")+ # Original key should still be there+ assert research_context["existing"] == "value"+++class TestWrapperStringResponse:+ """Tests for wrapper handling string responses."""++ def test_wrapper_handles_string_response(self):+ """Should handle string response from LLM."""+ mock_llm = MagicMock()+ mock_llm.invoke.return_value = "<think>thought</think>answer"++ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=False,+ ):+ wrapper = wrap_llm_without_think_tags(mock_llm)+ result = wrapper.invoke("test")+ # Should remove think tags from string+ assert "answer" in result+ assert "<think>" not in result++ def test_wrapper_handles_invoke_exception(self):+ """Should propagate exceptions from LLM invoke."""+ import pytest++ mock_llm = MagicMock()+ mock_llm.invoke.side_effect = RuntimeError("LLM error")++ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=False,+ ):+ wrapper = wrap_llm_without_think_tags(mock_llm)+ with pytest.raises(RuntimeError, match="LLM error"):+ wrapper.invoke("test")diff --git a/tests/news/test_relevance_service.py b/tests/news/test_relevance_service.pyindex 9846b0cc52..4b91577c68 100644--- a/tests/news/test_relevance_service.py+++ b/tests/news/test_relevance_service.py@@ -170,3 +170,192 @@ class TestRelevanceService:result = service.filter_trending(cards, min_impact=7, limit=3)assert len(result) == 3++ def test_personalize_feed_with_prefs(self):+ """Test feed personalization with user preferences."""+ from src.local_deep_research.news.core.relevance_service import (+ RelevanceService,+ )++ service = RelevanceService()++ # Create cards with different categories+ cards = []+ for i, category in enumerate(["Technology", "Sports", "Politics"]):+ card = Mock()+ card.category = category+ card.impact_score = 5 + i+ card.topics = []+ card.interaction = {"viewed": False}+ cards.append(card)++ prefs = {+ "liked_categories": ["Technology"],+ "disliked_categories": ["Politics"],+ "impact_threshold": 5,+ }++ result = service.personalize_feed(cards, prefs)++ assert len(result) == 3+ # Technology card should be first (highest relevance)+ assert result[0].category == "Technology"+ # All cards should have relevance_score set+ for card in result:+ assert hasattr(card, "relevance_score")++ def test_personalize_feed_without_prefs(self):+ """Test feed personalization without user preferences."""+ from src.local_deep_research.news.core.relevance_service import (+ RelevanceService,+ )++ service = RelevanceService()++ cards = []+ for impact in [8, 5, 9]:+ card = Mock()+ card.impact_score = impact+ card.interaction = {}+ cards.append(card)++ result = service.personalize_feed(cards, None)++ assert len(result) == 3+ # Should be sorted by impact_score / 10+ assert result[0].impact_score == 9 # 0.9 relevance+ assert result[1].impact_score == 8 # 0.8 relevance+ assert result[2].impact_score == 5 # 0.5 relevance++ def test_personalize_feed_exclude_seen(self):+ """Test excluding seen cards from feed."""+ from src.local_deep_research.news.core.relevance_service import (+ RelevanceService,+ )++ service = RelevanceService()++ cards = []+ for i in range(3):+ card = Mock()+ card.impact_score = 7+ card.interaction = {"viewed": i == 1} # Middle card is viewed+ cards.append(card)++ # Include seen+ result_with_seen = service.personalize_feed(+ cards, None, include_seen=True+ )+ assert len(result_with_seen) == 3++ # Exclude seen+ result_without_seen = service.personalize_feed(+ cards, None, include_seen=False+ )+ assert len(result_without_seen) == 2++ def test_personalize_feed_empty(self):+ """Test personalization with empty card list."""+ from src.local_deep_research.news.core.relevance_service import (+ RelevanceService,+ )++ service = RelevanceService()++ result = service.personalize_feed([], None)++ assert len(result) == 0++ def test_calculate_relevance_topic_matching(self):+ """Test relevance boosting based on topic matching."""+ from src.local_deep_research.news.core.relevance_service import (+ RelevanceService,+ )++ service = RelevanceService()++ card = Mock()+ card.impact_score = 5+ card.topics = ["Artificial Intelligence", "Machine Learning"]++ prefs = {+ "liked_topics": ["artificial", "programming"],+ "impact_threshold": 5,+ }++ result = service.calculate_relevance(card, prefs)++ # Should have topic match bonus+ # Base 0.5 + impact match 0.1 + topic match 0.1 = 0.7+ assert result == 0.7++ def test_calculate_relevance_score_clamping(self):+ """Test that relevance score is clamped to [0, 1]."""+ from src.local_deep_research.news.core.relevance_service import (+ RelevanceService,+ )++ service = RelevanceService()++ # Card with everything liked+ card = Mock()+ card.category = "Technology"+ card.impact_score = 10+ card.topics = ["AI", "Tech"]++ prefs = {+ "liked_categories": ["Technology"],+ "disliked_categories": [],+ "impact_threshold": 3,+ "liked_topics": ["ai", "tech"],+ }++ result = service.calculate_relevance(card, prefs)++ # Should be clamped to 1.0+ assert result <= 1.0+ assert result >= 0.0++ def test_get_relevance_service_singleton(self):+ """Test that get_relevance_service returns singleton."""+ from src.local_deep_research.news.core.relevance_service import (+ get_relevance_service,+ RelevanceService,+ )++ service1 = get_relevance_service()+ service2 = get_relevance_service()++ assert service1 is service2+ assert isinstance(service1, RelevanceService)++ def test_filter_trending_empty_list(self):+ """Test filtering with empty card list."""+ from src.local_deep_research.news.core.relevance_service import (+ RelevanceService,+ )++ service = RelevanceService()++ result = service.filter_trending([], min_impact=7)++ assert len(result) == 0++ def test_filter_trending_no_matching_cards(self):+ """Test filtering when no cards meet minimum impact."""+ from src.local_deep_research.news.core.relevance_service import (+ RelevanceService,+ )++ service = RelevanceService()++ cards = []+ for impact in [3, 4, 5]:+ card = Mock()+ card.impact_score = impact+ card.interaction = {"views": 10, "votes_up": 1, "votes_down": 0}+ cards.append(card)++ result = service.filter_trending(cards, min_impact=7)++ assert len(result) == 0diff --git a/tests/search_engines/test_base_search_engine.py b/tests/search_engines/test_base_search_engine.pyindex 3d3a00642c..e29a351e0f 100644--- a/tests/search_engines/test_base_search_engine.py+++ b/tests/search_engines/test_base_search_engine.py@@ -2,8 +2,14 @@Tests for BaseSearchEngine."""+from unittest.mock import Mock+from src.local_deep_research.web_search_engines.search_engine_base import (BaseSearchEngine,+ AdaptiveWait,+)+from src.local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,)@@ -230,3 +236,580 @@ class TestSearchResultValidation:"""Result titles are not empty."""for result in mock_search_results:assert len(result["title"]) > 0+++class ConcreteSearchEngine(BaseSearchEngine):+ """Concrete implementation for testing."""++ is_public = True+ is_generic = True++ def __init__(self, **kwargs):+ super().__init__(**kwargs)+ self._mock_previews = []+ self._mock_full_content = []++ def _get_previews(self, query):+ return self._mock_previews++ def _get_full_content(self, relevant_items):+ return self._mock_full_content or relevant_items+++class TestAdaptiveWait:+ """Tests for AdaptiveWait class."""++ def test_adaptive_wait_calls_function(self):+ """AdaptiveWait calls the provided function."""+ mock_func = Mock(return_value=2.5)+ wait = AdaptiveWait(mock_func)+ mock_retry_state = Mock()++ result = wait(mock_retry_state)++ assert result == 2.5+ mock_func.assert_called_once()++ def test_adaptive_wait_with_different_values(self):+ """AdaptiveWait returns different values based on function."""+ call_count = [0]++ def variable_wait():+ call_count[0] += 1+ return call_count[0] * 1.0++ wait = AdaptiveWait(variable_wait)+ mock_retry_state = Mock()++ assert wait(mock_retry_state) == 1.0+ assert wait(mock_retry_state) == 2.0+ assert wait(mock_retry_state) == 3.0+++class TestBaseSearchEngineInit:+ """Tests for BaseSearchEngine initialization."""++ def test_init_default_values(self):+ """Test initialization with default values."""+ engine = ConcreteSearchEngine(programmatic_mode=True)++ assert engine.max_results == 10+ assert engine.max_filtered_results == 5+ assert engine.llm is None+ assert engine.search_snippets_only is True+ assert engine.programmatic_mode is True+ assert engine._preview_filters == []+ assert engine._content_filters == []++ def test_init_custom_values(self):+ """Test initialization with custom values."""+ mock_llm = Mock()+ engine = ConcreteSearchEngine(+ llm=mock_llm,+ max_results=20,+ max_filtered_results=10,+ search_snippets_only=False,+ programmatic_mode=True,+ )++ assert engine.max_results == 20+ assert engine.max_filtered_results == 10+ assert engine.llm is mock_llm+ assert engine.search_snippets_only is False++ def test_init_none_values_use_defaults(self):+ """Test that None values use defaults."""+ engine = ConcreteSearchEngine(+ max_results=None, max_filtered_results=None, programmatic_mode=True+ )++ assert engine.max_results == 10+ assert engine.max_filtered_results == 5++ def test_init_with_filters(self):+ """Test initialization with custom filters."""+ preview_filter = Mock()+ content_filter = Mock()+ engine = ConcreteSearchEngine(+ preview_filters=[preview_filter],+ content_filters=[content_filter],+ programmatic_mode=True,+ )++ assert len(engine._preview_filters) == 1+ assert len(engine._content_filters) == 1++ def test_init_with_settings_snapshot(self):+ """Test initialization with settings snapshot."""+ snapshot = {"key": "value"}+ engine = ConcreteSearchEngine(+ settings_snapshot=snapshot, programmatic_mode=True+ )++ assert engine.settings_snapshot == snapshot++ def test_init_engine_type_set(self):+ """Test that engine_type is set from class name."""+ engine = ConcreteSearchEngine(programmatic_mode=True)++ assert engine.engine_type == "ConcreteSearchEngine"+++class TestMaxResultsProperty:+ """Tests for max_results property."""++ def test_max_results_getter(self):+ """Test max_results getter."""+ engine = ConcreteSearchEngine(max_results=15, programmatic_mode=True)+ assert engine.max_results == 15++ def test_max_results_setter(self):+ """Test max_results setter."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine.max_results = 25+ assert engine.max_results == 25++ def test_max_results_setter_none_uses_default(self):+ """Test max_results setter with None uses default."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine.max_results = None+ assert engine.max_results == 10++ def test_max_results_minimum_is_one(self):+ """Test max_results has minimum of 1."""+ engine = ConcreteSearchEngine(max_results=0, programmatic_mode=True)+ assert engine.max_results >= 1++ engine.max_results = -5+ assert engine.max_results >= 1+++class TestMaxFilteredResultsProperty:+ """Tests for max_filtered_results property."""++ def test_max_filtered_results_getter(self):+ """Test max_filtered_results getter."""+ engine = ConcreteSearchEngine(+ max_filtered_results=8, programmatic_mode=True+ )+ assert engine.max_filtered_results == 8++ def test_max_filtered_results_setter(self):+ """Test max_filtered_results setter."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine.max_filtered_results = 12+ assert engine.max_filtered_results == 12++ def test_max_filtered_results_setter_none_uses_default(self):+ """Test max_filtered_results setter with None uses default."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine.max_filtered_results = None+ assert engine.max_filtered_results == 5+++class TestRunMethod:+ """Tests for BaseSearchEngine.run method."""++ def test_run_returns_empty_list_on_no_previews(self):+ """Test run returns empty list when no previews found."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine._mock_previews = []++ results = engine.run("test query")++ assert results == []++ def test_run_returns_previews_with_snippets_only(self):+ """Test run returns previews when search_snippets_only is True."""+ engine = ConcreteSearchEngine(+ search_snippets_only=True, programmatic_mode=True+ )+ engine._mock_previews = [+ {+ "title": "Test",+ "snippet": "Content",+ "link": "https://example.com",+ }+ ]++ results = engine.run("test query")++ assert len(results) == 1+ assert results[0]["title"] == "Test"++ def test_run_applies_preview_filters(self):+ """Test run applies preview filters."""+ mock_filter = Mock()+ mock_filter.filter_results.return_value = [+ {"title": "Filtered", "snippet": "Content"}+ ]++ engine = ConcreteSearchEngine(+ preview_filters=[mock_filter], programmatic_mode=True+ )+ engine._mock_previews = [+ {"title": "Original", "snippet": "Content"},+ {"title": "Also Original", "snippet": "More content"},+ ]++ results = engine.run("test query")++ mock_filter.filter_results.assert_called_once()+ assert len(results) == 1+ assert results[0]["title"] == "Filtered"++ def test_run_applies_content_filters(self):+ """Test run applies content filters."""+ mock_filter = Mock()+ mock_filter.filter_results.return_value = [+ {"title": "Content Filtered", "content": "Full content"}+ ]++ engine = ConcreteSearchEngine(+ content_filters=[mock_filter],+ search_snippets_only=False,+ programmatic_mode=True,+ )+ engine._mock_previews = [{"title": "Original", "snippet": "Content"}]+ engine._mock_full_content = [+ {"title": "Original", "content": "Full content"}+ ]++ results = engine.run("test query")++ mock_filter.filter_results.assert_called_once()+ assert len(results) == 1+ assert results[0]["title"] == "Content Filtered"++ def test_run_gets_full_content_when_not_snippets_only(self):+ """Test run gets full content when search_snippets_only is False."""+ engine = ConcreteSearchEngine(+ search_snippets_only=False, programmatic_mode=True+ )+ engine._mock_previews = [{"title": "Preview", "snippet": "Short"}]+ engine._mock_full_content = [+ {"title": "Preview", "content": "Full content"}+ ]++ results = engine.run("test query")++ assert len(results) == 1+ assert results[0]["content"] == "Full content"++ def test_run_handles_exception_gracefully(self):+ """Test run handles exceptions gracefully."""++ class FailingEngine(ConcreteSearchEngine):+ def _get_previews(self, query):+ raise ValueError("Test error")++ engine = FailingEngine(programmatic_mode=True)++ results = engine.run("test query")++ assert results == []++ def test_run_with_research_context(self):+ """Test run with research context parameter."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine._mock_previews = [{"title": "Test", "snippet": "Content"}]++ context = {"research_id": 123}+ results = engine.run("test query", research_context=context)++ assert len(results) == 1+++class TestInvokeMethod:+ """Tests for invoke method (LangChain compatibility)."""++ def test_invoke_calls_run(self):+ """Test invoke calls run method."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine._mock_previews = [{"title": "Test", "snippet": "Content"}]++ results = engine.invoke("test query")++ assert len(results) == 1+ assert results[0]["title"] == "Test"+++class TestFilterForRelevance:+ """Tests for _filter_for_relevance method."""++ def test_filter_no_llm_returns_all(self):+ """Test that no LLM returns all previews."""+ engine = ConcreteSearchEngine(llm=None, programmatic_mode=True)+ previews = [+ {"title": "A", "snippet": "Content A"},+ {"title": "B", "snippet": "Content B"},+ ]++ result = engine._filter_for_relevance(previews, "query")++ assert len(result) == 2++ def test_filter_single_preview_returns_all(self):+ """Test that single preview returns as-is."""+ mock_llm = Mock()+ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ previews = [{"title": "A", "snippet": "Content A"}]++ result = engine._filter_for_relevance(previews, "query")++ assert len(result) == 1+ mock_llm.invoke.assert_not_called()++ def test_filter_with_valid_llm_response(self):+ """Test filtering with valid LLM response."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(content="[0, 2]")++ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ previews = [+ {"title": "A", "snippet": "Content A", "url": "https://a.com"},+ {"title": "B", "snippet": "Content B", "url": "https://b.com"},+ {"title": "C", "snippet": "Content C", "url": "https://c.com"},+ ]++ result = engine._filter_for_relevance(previews, "query")++ assert len(result) == 2+ assert result[0]["title"] == "A"+ assert result[1]["title"] == "C"++ def test_filter_with_out_of_range_indices(self):+ """Test filtering skips out-of-range indices."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(+ content="[0, 10, 1]"+ ) # 10 is out of range++ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ previews = [+ {"title": "A", "snippet": "Content A", "url": "https://a.com"},+ {"title": "B", "snippet": "Content B", "url": "https://b.com"},+ ]++ result = engine._filter_for_relevance(previews, "query")++ assert len(result) == 2 # Only valid indices 0 and 1++ def test_filter_with_invalid_json_returns_top_results(self):+ """Test filtering with invalid JSON returns top results."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(content="not json")++ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ previews = [+ {"title": "A", "snippet": "Content A", "url": "https://a.com"},+ {"title": "B", "snippet": "Content B", "url": "https://b.com"},+ {"title": "C", "snippet": "Content C", "url": "https://c.com"},+ ]++ result = engine._filter_for_relevance(previews, "query")++ # Should return top results as fallback+ assert len(result) <= 5++ def test_filter_limits_to_max_filtered_results(self):+ """Test filtering limits results to max_filtered_results."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(+ content="[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"+ )++ engine = ConcreteSearchEngine(+ llm=mock_llm, max_filtered_results=3, programmatic_mode=True+ )+ previews = [+ {+ "title": str(i),+ "snippet": f"Content {i}",+ "url": f"https://{i}.com",+ }+ for i in range(10)+ ]++ result = engine._filter_for_relevance(previews, "query")++ assert len(result) == 3++ def test_filter_handles_llm_exception(self):+ """Test filtering handles LLM exceptions."""+ mock_llm = Mock()+ mock_llm.invoke.side_effect = Exception("LLM error")++ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ previews = [+ {"title": "A", "snippet": "Content A", "url": "https://a.com"},+ {"title": "B", "snippet": "Content B", "url": "https://b.com"},+ ]++ result = engine._filter_for_relevance(previews, "query")++ # Should return fallback (top results)+ assert len(result) <= 5++ def test_filter_handles_non_list_response(self):+ """Test filtering handles non-list JSON response."""+ mock_llm = Mock()+ # Response that has array brackets but parses to a dict+ mock_llm.invoke.return_value = Mock(content='[{"not": "list"}]')++ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ previews = [+ {"title": "A", "snippet": "Content A", "url": "https://a.com"},+ {"title": "B", "snippet": "Content B", "url": "https://b.com"},+ ]++ result = engine._filter_for_relevance(previews, "query")++ # When parsed array contains non-integers, should return empty list+ assert result == []++ def test_filter_handles_non_integer_indices(self):+ """Test filtering handles non-integer indices in response."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(content='["a", "b"]')++ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ previews = [+ {"title": "A", "snippet": "Content A", "url": "https://a.com"},+ {"title": "B", "snippet": "Content B", "url": "https://b.com"},+ ]++ result = engine._filter_for_relevance(previews, "query")++ # Should return empty since indices are not integers+ assert result == []++ def test_filter_truncates_long_snippets(self):+ """Test filtering truncates long snippets in prompt."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(content="[0]")++ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ long_snippet = "x" * 500 # Longer than 300 char limit+ previews = [+ {"title": "A", "snippet": long_snippet, "url": "https://a.com"},+ {"title": "B", "snippet": "Short", "url": "https://b.com"},+ ]++ result = engine._filter_for_relevance(previews, "query")++ # Should succeed - just checking it doesn't fail+ assert len(result) >= 0+++class TestRateLimiting:+ """Tests for rate limiting functionality."""++ def test_get_adaptive_wait(self):+ """Test _get_adaptive_wait returns tracker wait time."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine.rate_tracker = Mock()+ engine.rate_tracker.get_wait_time.return_value = 1.5++ wait_time = engine._get_adaptive_wait()++ assert wait_time == 1.5+ assert engine._last_wait_time == 1.5+ engine.rate_tracker.get_wait_time.assert_called_once_with(+ "ConcreteSearchEngine"+ )++ def test_record_retry_outcome_success(self):+ """Test _record_retry_outcome records successful outcome."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine.rate_tracker = Mock()+ engine._last_wait_time = 1.0+ engine._last_results_count = 5++ mock_outcome = Mock()+ mock_outcome.failed = False+ mock_retry_state = Mock()+ mock_retry_state.outcome = mock_outcome+ mock_retry_state.attempt_number = 1++ engine._record_retry_outcome(mock_retry_state)++ engine.rate_tracker.record_outcome.assert_called_once()+ # Check call was made with expected arguments+ call_args = engine.rate_tracker.record_outcome.call_args+ # Engine type is first positional arg+ assert call_args[0][0] == "ConcreteSearchEngine"+ # Wait time is second positional arg+ assert call_args[0][1] == 1.0++ def test_record_retry_outcome_failure(self):+ """Test _record_retry_outcome records failed outcome."""+ engine = ConcreteSearchEngine(programmatic_mode=True)+ engine.rate_tracker = Mock()+ engine._last_wait_time = 2.0++ mock_outcome = Mock()+ mock_outcome.failed = True+ mock_retry_state = Mock()+ mock_retry_state.outcome = mock_outcome+ mock_retry_state.attempt_number = 2++ engine._record_retry_outcome(mock_retry_state)++ engine.rate_tracker.record_outcome.assert_called_once()+ # Check call was made with expected arguments+ call_args = engine.rate_tracker.record_outcome.call_args+ # Engine type is first positional arg+ assert call_args[0][0] == "ConcreteSearchEngine"+ # Wait time is second positional arg+ assert call_args[0][1] == 2.0++ def test_run_with_rate_limit_error_disabled(self):+ """Test run handles RateLimitError when rate limiting disabled."""++ class RateLimitedEngine(ConcreteSearchEngine):+ def _get_previews(self, query):+ raise RateLimitError("Rate limited")++ engine = RateLimitedEngine(programmatic_mode=True)+ engine.rate_tracker.enabled = False++ results = engine.run("test query")++ assert results == []+++class TestLLMRelevanceFilter:+ """Tests for LLM relevance filtering behavior."""++ def test_llm_filter_disabled_by_default(self):+ """Test LLM filter is disabled by default."""+ mock_llm = Mock()+ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ engine._mock_previews = [+ {"title": "A", "snippet": "Content"},+ {"title": "B", "snippet": "Content"},+ ]++ # Without enable_llm_relevance_filter set, should return all previews+ results = engine.run("query")++ mock_llm.invoke.assert_not_called()+ assert len(results) == 2++ def test_llm_filter_enabled(self):+ """Test LLM filter when enabled."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(content="[0]")++ engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)+ engine.enable_llm_relevance_filter = True+ engine._mock_previews = [+ {"title": "A", "snippet": "Content A", "url": "https://a.com"},+ {"title": "B", "snippet": "Content B", "url": "https://b.com"},+ ]++ results = engine.run("query")++ mock_llm.invoke.assert_called_once()+ assert len(results) == 1diff --git a/tests/search_engines/test_search_engine_searxng.py b/tests/search_engines/test_search_engine_searxng.pyindex 14a0871310..61a96f38eb 100644--- a/tests/search_engines/test_search_engine_searxng.py+++ b/tests/search_engines/test_search_engine_searxng.py@@ -412,3 +412,526 @@ class TestSearXNGTimeRange:engine = SearXNGSearchEngine(time_range="year")assert engine.time_range == "year"+++class TestSearXNGValidSearchResult:+ """Tests for _is_valid_search_result method."""++ @pytest.fixture(autouse=True)+ def mock_safe_get(self, monkeypatch):+ """Mock safe_get to avoid HTTP requests."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.cookies = {}+ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ Mock(return_value=mock_response),+ )++ def test_valid_https_url(self):+ """Test valid HTTPS URL is accepted."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ assert engine._is_valid_search_result("https://example.com") is True++ def test_valid_http_url(self):+ """Test valid HTTP URL is accepted."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ assert engine._is_valid_search_result("http://example.com") is True++ def test_relative_url_rejected(self):+ """Test relative URL is rejected."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ assert engine._is_valid_search_result("/stats?engine=google") is False++ def test_empty_url_rejected(self):+ """Test empty URL is rejected."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ assert engine._is_valid_search_result("") is False+ assert engine._is_valid_search_result(None) is False++ def test_instance_url_rejected(self):+ """Test URLs pointing to instance itself are rejected."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine(instance_url="http://localhost:8080")+ assert (+ engine._is_valid_search_result(+ "http://localhost:8080/stats?engine=google"+ )+ is False+ )+ assert (+ engine._is_valid_search_result("http://localhost:8080/preferences")+ is False+ )++ def test_case_insensitive_scheme(self):+ """Test URL scheme check is case insensitive."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ assert engine._is_valid_search_result("HTTPS://example.com") is True+ assert engine._is_valid_search_result("HTTP://example.com") is True+++class TestSearXNGSearchResults:+ """Tests for SearXNG search result parsing."""++ @pytest.fixture+ def mock_html_response(self):+ """Mock HTML response with search results."""+ return """+ <html>+ <body>+ <div class="result-item">+ <h3 class="result-title"><a href="https://example.com/1">Result 1</a></h3>+ <p class="result-content">This is the first result snippet.</p>+ </div>+ <div class="result-item">+ <h3 class="result-title"><a href="https://example.com/2">Result 2</a></h3>+ <p class="result-content">This is the second result snippet.</p>+ </div>+ </body>+ </html>+ """++ def test_get_search_results_parses_html(+ self, monkeypatch, mock_html_response+ ):+ """Test HTML parsing of search results."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.cookies = {}+ mock_response.text = mock_html_response++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ Mock(return_value=mock_response),+ )++ engine = SearXNGSearchEngine()+ results = engine._get_search_results("test query")++ assert len(results) == 2+ assert results[0]["url"] == "https://example.com/1"+ assert results[0]["title"] == "Result 1"++ def test_get_search_results_unavailable(self, monkeypatch):+ """Test _get_search_results returns empty when unavailable."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.cookies = {}+ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ Mock(return_value=mock_response),+ )++ engine = SearXNGSearchEngine()+ engine.is_available = False++ results = engine._get_search_results("test")+ assert results == []++ def test_get_search_results_filters_invalid(self, monkeypatch):+ """Test that invalid search results are filtered out."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ # HTML with one valid result and one invalid (pointing to instance)+ html = """+ <html>+ <body>+ <div class="result-item">+ <h3 class="result-title"><a href="https://example.com">Valid</a></h3>+ <p class="result-content">Valid result.</p>+ </div>+ <div class="result-item">+ <h3 class="result-title"><a href="http://localhost:8080/stats?engine=google">Engine Error</a></h3>+ <p class="result-content">Engine failed.</p>+ </div>+ </body>+ </html>+ """+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.cookies = {}+ mock_response.text = html++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ Mock(return_value=mock_response),+ )++ engine = SearXNGSearchEngine()+ results = engine._get_search_results("test")++ # Should only have 1 valid result+ assert len(results) == 1+ assert results[0]["url"] == "https://example.com"++ def test_get_search_results_error_response(self, monkeypatch):+ """Test handling of error response from SearXNG."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ mock_init_response = Mock()+ mock_init_response.status_code = 200+ mock_init_response.cookies = {}++ mock_search_response = Mock()+ mock_search_response.status_code = 500++ call_count = [0]++ def mock_get(*args, **kwargs):+ call_count[0] += 1+ if call_count[0] <= 2: # Init calls+ return mock_init_response+ return mock_search_response++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ mock_get,+ )++ engine = SearXNGSearchEngine()+ results = engine._get_search_results("test")++ assert results == []++ def test_get_search_results_exception(self, monkeypatch):+ """Test handling of exception during search."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ mock_init_response = Mock()+ mock_init_response.status_code = 200+ mock_init_response.cookies = {}++ call_count = [0]++ def mock_get(*args, **kwargs):+ call_count[0] += 1+ if call_count[0] <= 2:+ return mock_init_response+ raise Exception("Network error")++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ mock_get,+ )++ engine = SearXNGSearchEngine()+ results = engine._get_search_results("test")++ assert results == []+++class TestSearXNGGetPreviews:+ """Tests for _get_previews method."""++ @pytest.fixture(autouse=True)+ def mock_safe_get(self, monkeypatch):+ """Mock safe_get to avoid HTTP requests."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.cookies = {}+ mock_response.text = ""+ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ Mock(return_value=mock_response),+ )++ def test_get_previews_formats_results(self, monkeypatch):+ """Test that previews are formatted correctly."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()++ # Mock _get_search_results+ mock_results = [+ {+ "title": "Title 1",+ "url": "https://example.com/1",+ "content": "Snippet 1",+ },+ {+ "title": "Title 2",+ "url": "https://example.com/2",+ "content": "Snippet 2",+ },+ ]+ engine._get_search_results = Mock(return_value=mock_results)++ previews = engine._get_previews("test")++ assert len(previews) == 2+ assert previews[0]["title"] == "Title 1"+ assert previews[0]["link"] == "https://example.com/1"+ assert previews[0]["snippet"] == "Snippet 1"+ assert previews[0]["id"] == "https://example.com/1"++ def test_get_previews_handles_empty_results(self, monkeypatch):+ """Test that empty results are handled."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ engine._get_search_results = Mock(return_value=[])++ previews = engine._get_previews("test")++ assert previews == []++ def test_get_previews_generates_id_when_no_url(self, monkeypatch):+ """Test that ID is generated when URL is missing."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ engine._get_search_results = Mock(+ return_value=[{"title": "Title", "url": "", "content": "Snippet"}]+ )++ previews = engine._get_previews("test")++ assert previews[0]["id"] == "searxng-result-0"+++class TestSearXNGGetFullContent:+ """Tests for _get_full_content method."""++ @pytest.fixture(autouse=True)+ def mock_safe_get(self, monkeypatch):+ """Mock safe_get to avoid HTTP requests."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.cookies = {}+ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ Mock(return_value=mock_response),+ )++ def test_get_full_content_unavailable(self):+ """Test _get_full_content returns items when unavailable."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ engine.is_available = False++ items = [{"title": "Test", "snippet": "Content"}]+ results = engine._get_full_content(items)++ assert results == items++ def test_get_full_content_exception(self, monkeypatch):+ """Test _get_full_content handles exceptions."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()++ # Mock full_search to raise exception+ engine.full_search = Mock()+ engine.full_search._get_full_content = Mock(+ side_effect=Exception("Error")+ )++ items = [{"title": "Test", "snippet": "Content"}]+ results = engine._get_full_content(items)++ # Should return original items on error+ assert results == items+++class TestSearXNGResultsMethod:+ """Tests for results method."""++ @pytest.fixture(autouse=True)+ def mock_safe_get(self, monkeypatch):+ """Mock safe_get to avoid HTTP requests."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.cookies = {}+ mock_response.text = ""+ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ Mock(return_value=mock_response),+ )++ def test_results_formats_output(self):+ """Test results method formats output correctly."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ engine._get_search_results = Mock(+ return_value=[+ {+ "title": "Title",+ "url": "https://example.com",+ "content": "Snippet",+ }+ ]+ )++ results = engine.results("test")++ assert len(results) == 1+ assert results[0]["title"] == "Title"+ assert results[0]["link"] == "https://example.com"+ assert results[0]["snippet"] == "Snippet"++ def test_results_respects_max_results_override(self):+ """Test results method respects max_results override."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine(max_results=10)+ original_max = engine.max_results++ engine._get_search_results = Mock(return_value=[])+ engine.results("test", max_results=50)++ # Should restore original max_results after call+ assert engine.max_results == original_max++ def test_results_restores_max_results_on_exception(self):+ """Test max_results is restored even on exception."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine(max_results=10)+ original_max = engine.max_results++ engine._get_search_results = Mock(side_effect=Exception("Error"))++ try:+ engine.results("test", max_results=50)+ except Exception:+ pass++ # Should restore original max_results even on error+ assert engine.max_results == original_max+++class TestSearXNGRateLimitMethod:+ """Tests for _respect_rate_limit method."""++ @pytest.fixture(autouse=True)+ def mock_safe_get(self, monkeypatch):+ """Mock safe_get to avoid HTTP requests."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.cookies = {}+ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ Mock(return_value=mock_response),+ )++ def test_respect_rate_limit_updates_time(self, monkeypatch):+ """Test that _respect_rate_limit updates last_request_time."""++ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine(delay_between_requests=0)+ engine.last_request_time = 0++ engine._respect_rate_limit()++ assert engine.last_request_time > 0++ def test_respect_rate_limit_waits_when_needed(self, monkeypatch):+ """Test that _respect_rate_limit waits when delay is needed."""+ import time++ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ sleep_called = []+ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.time.sleep",+ lambda x: sleep_called.append(x),+ )++ engine = SearXNGSearchEngine(delay_between_requests=1.0)+ engine.last_request_time = time.time()++ engine._respect_rate_limit()++ # Should have called sleep+ assert len(sleep_called) > 0+++class TestSearXNGInvokeMethod:+ """Tests for invoke method (LangChain compatibility)."""++ @pytest.fixture(autouse=True)+ def mock_safe_get(self, monkeypatch):+ """Mock safe_get to avoid HTTP requests."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.cookies = {}+ mock_response.text = ""+ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ Mock(return_value=mock_response),+ )++ def test_invoke_calls_run(self):+ """Test invoke method calls run."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ engine = SearXNGSearchEngine()+ engine.run = Mock(return_value=[{"title": "Test"}])++ result = engine.invoke("test query")++ engine.run.assert_called_once_with("test query")+ assert result == [{"title": "Test"}]diff --git a/tests/search_engines/test_search_engine_wikipedia.py b/tests/search_engines/test_search_engine_wikipedia.pyindex 6b0fd479d3..f6bb23f5c2 100644--- a/tests/search_engines/test_search_engine_wikipedia.py+++ b/tests/search_engines/test_search_engine_wikipedia.py@@ -218,3 +218,366 @@ class TestWikipediaSearchEngine:assert result["title"] == "Python"assert result["content"] == "Full content..."assert result["source"] == "Wikipedia"++ @patch("wikipedia.search")+ @patch("wikipedia.summary")+ def test_get_previews_page_error(self, mock_summary, mock_search):+ """Test handling of PageError during preview generation."""+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_search.return_value = ["Valid Page", "Invalid Page"]+ mock_summary.side_effect = [+ "Valid page content.",+ wikipedia.exceptions.PageError("Invalid Page"),+ ]++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()+ previews = engine._get_previews("test query")++ # Should skip the invalid page+ assert len(previews) == 1+ assert previews[0]["title"] == "Valid Page"++ @patch("wikipedia.search")+ @patch("wikipedia.summary")+ def test_get_previews_wikipedia_exception(self, mock_summary, mock_search):+ """Test handling of WikipediaException during preview generation."""+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_search.return_value = ["Page 1"]+ mock_summary.side_effect = wikipedia.exceptions.WikipediaException(+ "API error"+ )++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()+ previews = engine._get_previews("test query")++ # Should handle the exception and return empty+ assert previews == []++ @patch("wikipedia.search")+ @patch("wikipedia.summary")+ def test_get_previews_disambiguation_no_options(+ self, mock_summary, mock_search+ ):+ """Test handling of disambiguation error with no options."""+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_search.return_value = ["Ambiguous Term"]+ # Create disambiguation error with empty options+ disambiguation_error = wikipedia.exceptions.DisambiguationError(+ "Ambiguous Term", []+ )+ mock_summary.side_effect = disambiguation_error++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()+ previews = engine._get_previews("Ambiguous Term")++ # Should skip the term with no options+ assert len(previews) == 0++ @patch("wikipedia.search")+ @patch("wikipedia.summary")+ def test_get_previews_disambiguation_inner_error(+ self, mock_summary, mock_search+ ):+ """Test handling when disambiguation option also fails."""+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_search.return_value = ["Term"]+ disambiguation_error = wikipedia.exceptions.DisambiguationError(+ "Term", ["Option 1", "Option 2"]+ )+ # First call raises disambiguation, second also fails+ mock_summary.side_effect = [+ disambiguation_error,+ Exception("Inner error"),+ ]++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()+ previews = engine._get_previews("Term")++ # Should handle inner error gracefully+ assert len(previews) == 0++ @patch("wikipedia.search")+ def test_get_previews_search_exception(self, mock_search):+ """Test handling of exception during search."""+ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_search.side_effect = Exception("Network error")++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()+ previews = engine._get_previews("test query")++ assert previews == []++ @patch("wikipedia.page")+ def test_get_full_content_missing_id(self, mock_page):+ """Test full content retrieval with missing id."""+ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()++ # Item without id+ relevant_items = [+ {"title": "Some Title", "snippet": "Some snippet"}+ ]++ results = engine._get_full_content(relevant_items)++ # Should return item as-is+ assert len(results) == 1+ assert results[0]["title"] == "Some Title"+ mock_page.assert_not_called()++ @patch("wikipedia.page")+ def test_get_full_content_page_error(self, mock_page):+ """Test full content with PageError falls back to preview."""+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_page.side_effect = wikipedia.exceptions.PageError("Title")++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()++ relevant_items = [+ {"id": "Title", "title": "Title", "snippet": "Preview snippet"}+ ]++ results = engine._get_full_content(relevant_items)++ # Should fall back to preview item+ assert len(results) == 1+ assert results[0]["snippet"] == "Preview snippet"+ assert "content" not in results[0]++ @patch("wikipedia.page")+ def test_get_full_content_disambiguation_error(self, mock_page):+ """Test full content with DisambiguationError falls back to preview."""+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_page.side_effect = wikipedia.exceptions.DisambiguationError(+ "Title", ["Option 1"]+ )++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()++ relevant_items = [+ {"id": "Title", "title": "Title", "snippet": "Preview"}+ ]++ results = engine._get_full_content(relevant_items)++ # Should fall back to preview+ assert len(results) == 1+ assert "content" not in results[0]++ @patch("wikipedia.page")+ def test_get_full_content_unexpected_error(self, mock_page):+ """Test full content with unexpected error falls back to preview."""+ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_page.side_effect = RuntimeError("Unexpected error")++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()++ relevant_items = [+ {"id": "Title", "title": "Title", "snippet": "Preview"}+ ]++ results = engine._get_full_content(relevant_items)++ assert len(results) == 1+ assert results[0]["snippet"] == "Preview"++ @patch("wikipedia.summary")+ def test_get_summary_disambiguation(self, mock_summary):+ """Test get_summary handles disambiguation by using first option."""+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ disambiguation_error = wikipedia.exceptions.DisambiguationError(+ "Mercury", ["Mercury (planet)", "Mercury (element)"]+ )+ mock_summary.side_effect = [+ disambiguation_error,+ "Mercury is the closest planet to the Sun.",+ ]++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()+ result = engine.get_summary("Mercury")++ assert "planet" in result.lower()++ @patch("wikipedia.summary")+ def test_get_summary_disambiguation_no_options_raises(self, mock_summary):+ """Test get_summary raises when disambiguation has no options."""+ import pytest+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ disambiguation_error = wikipedia.exceptions.DisambiguationError(+ "Term", []+ )+ mock_summary.side_effect = disambiguation_error++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()++ with pytest.raises(wikipedia.exceptions.DisambiguationError):+ engine.get_summary("Term")++ @patch("wikipedia.page")+ @patch("wikipedia.summary")+ def test_get_page_disambiguation(self, mock_summary, mock_page):+ """Test get_page handles disambiguation recursively."""+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ disambiguation_error = wikipedia.exceptions.DisambiguationError(+ "Mercury", ["Mercury (planet)"]+ )++ mock_page_obj = Mock()+ mock_page_obj.title = "Mercury (planet)"+ mock_page_obj.url = "https://en.wikipedia.org/wiki/Mercury_(planet)"+ mock_page_obj.content = "Mercury is a planet."+ mock_page_obj.categories = []+ mock_page_obj.references = []+ mock_page_obj.links = []+ mock_page_obj.images = []+ mock_page_obj.sections = []++ mock_page.side_effect = [disambiguation_error, mock_page_obj]+ mock_summary.return_value = "Mercury is a planet."++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine(include_content=True)+ result = engine.get_page("Mercury")++ assert result["title"] == "Mercury (planet)"++ @patch("wikipedia.page")+ def test_get_page_disambiguation_no_options_raises(self, mock_page):+ """Test get_page raises when disambiguation has no options."""+ import pytest+ import wikipedia++ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ disambiguation_error = wikipedia.exceptions.DisambiguationError(+ "Term", []+ )+ mock_page.side_effect = disambiguation_error++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()++ with pytest.raises(wikipedia.exceptions.DisambiguationError):+ engine.get_page("Term")++ def test_get_page_without_content(self):+ """Test get_page with include_content=False."""+ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_page_obj = Mock()+ mock_page_obj.title = "Python"+ mock_page_obj.url = "https://en.wikipedia.org/wiki/Python"+ mock_page_obj.content = "Full content..."++ with patch("wikipedia.set_lang"):+ with patch("wikipedia.page", return_value=mock_page_obj):+ with patch("wikipedia.summary", return_value="Python summary"):+ engine = WikipediaSearchEngine(include_content=False)+ result = engine.get_page("Python")++ assert result["title"] == "Python"+ # Should not have content when include_content=False+ assert "content" not in result++ def test_get_summary_uses_default_sentences(self):+ """Test get_summary uses instance sentences when not specified."""+ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ with patch("wikipedia.set_lang"):+ with patch("wikipedia.summary", return_value="Summary") as mock:+ engine = WikipediaSearchEngine(sentences=7)+ engine.get_summary("Title")++ mock.assert_called_with(+ "Title", sentences=7, auto_suggest=False+ )++ @patch("wikipedia.search")+ @patch("wikipedia.summary")+ def test_get_previews_summary_none(self, mock_summary, mock_search):+ """Test preview skipped when summary returns None."""+ from src.local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ mock_search.return_value = ["Page 1", "Page 2"]+ mock_summary.side_effect = [None, "Valid summary"]++ with patch("wikipedia.set_lang"):+ engine = WikipediaSearchEngine()+ previews = engine._get_previews("query")++ # Should only include the page with valid summary+ assert len(previews) == 1+ assert previews[0]["snippet"] == "Valid summary"diff --git a/tests/test_citation_handler.py b/tests/test_citation_handler.pyindex 0badb39f23..61f7039f93 100644--- a/tests/test_citation_handler.py+++ b/tests/test_citation_handler.py@@ -192,3 +192,180 @@ def test_analyze_followup_no_fact_check(# LLM should only be called once (no fact check)assert citation_handler.llm.invoke.call_count == 1+++class TestCitationHandlerType:+ """Tests for citation handler type selection."""++ def test_default_handler_is_standard(self):+ """Should use StandardCitationHandler by default."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm)+ assert "StandardCitationHandler" in type(handler._handler).__name__++ def test_explicit_standard_handler(self):+ """Should use StandardCitationHandler when explicitly specified."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, handler_type="standard")+ assert "StandardCitationHandler" in type(handler._handler).__name__++ def test_forced_handler(self):+ """Should use ForcedAnswerCitationHandler for 'forced' type."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, handler_type="forced")+ assert "ForcedAnswerCitationHandler" in type(handler._handler).__name__++ def test_forced_answer_handler(self):+ """Should use ForcedAnswerCitationHandler for 'forced_answer' type."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, handler_type="forced_answer")+ assert "ForcedAnswerCitationHandler" in type(handler._handler).__name__++ def test_browsecomp_handler(self):+ """Should use ForcedAnswerCitationHandler for 'browsecomp' type."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, handler_type="browsecomp")+ assert "ForcedAnswerCitationHandler" in type(handler._handler).__name__++ def test_precision_handler(self):+ """Should use PrecisionExtractionHandler for 'precision' type."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, handler_type="precision")+ assert "PrecisionExtractionHandler" in type(handler._handler).__name__++ def test_precision_extraction_handler(self):+ """Should use PrecisionExtractionHandler for 'precision_extraction' type."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, handler_type="precision_extraction")+ assert "PrecisionExtractionHandler" in type(handler._handler).__name__++ def test_simpleqa_handler(self):+ """Should use PrecisionExtractionHandler for 'simpleqa' type."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, handler_type="simpleqa")+ assert "PrecisionExtractionHandler" in type(handler._handler).__name__++ def test_unknown_handler_falls_back_to_standard(self):+ """Should fall back to StandardCitationHandler for unknown type."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, handler_type="unknown_type")+ assert "StandardCitationHandler" in type(handler._handler).__name__++ def test_handler_type_from_settings_snapshot(self):+ """Should read handler type from settings snapshot."""+ mock_llm = Mock()+ settings = {"citation.handler_type": "forced"}+ handler = CitationHandler(mock_llm, settings_snapshot=settings)+ assert "ForcedAnswerCitationHandler" in type(handler._handler).__name__++ def test_handler_type_from_settings_snapshot_dict_format(self):+ """Should read handler type from settings snapshot with value dict."""+ mock_llm = Mock()+ settings = {+ "citation.handler_type": {"value": "precision", "type": "str"}+ }+ handler = CitationHandler(mock_llm, settings_snapshot=settings)+ assert "PrecisionExtractionHandler" in type(handler._handler).__name__++ def test_handler_type_case_insensitive(self):+ """Handler type should be case insensitive."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, handler_type="FORCED")+ assert "ForcedAnswerCitationHandler" in type(handler._handler).__name__++ def test_settings_snapshot_passed_to_handler(self):+ """Settings snapshot should be passed to the underlying handler."""+ mock_llm = Mock()+ settings = {"custom_key": "custom_value"}+ handler = CitationHandler(mock_llm, settings_snapshot=settings)+ assert handler.settings_snapshot == settings+ assert handler._handler.settings_snapshot == settings+++class TestCitationHandlerDelegation:+ """Tests for CitationHandler delegation to internal handler."""++ def test_exposes_create_documents_method(self):+ """Should expose _create_documents from internal handler."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm)+ assert callable(handler._create_documents)+ # Call it to verify it works+ result = handler._create_documents([])+ assert isinstance(result, list)++ def test_exposes_format_sources_method(self):+ """Should expose _format_sources from internal handler."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm)+ assert callable(handler._format_sources)++ def test_analyze_initial_delegates(self):+ """Should delegate analyze_initial to internal handler."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(content="Test response")+ handler = CitationHandler(mock_llm)+ result = handler.analyze_initial("query", [])+ assert "content" in result++ def test_analyze_followup_delegates(self):+ """Should delegate analyze_followup to internal handler."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(content="Test response")+ handler = CitationHandler(mock_llm)+ result = handler.analyze_followup("question", [], "previous", 0)+ assert "content" in result+++class TestCitationHandlerEdgeCases:+ """Tests for edge cases in CitationHandler."""++ def test_none_settings_snapshot_uses_empty_dict(self):+ """Should use empty dict when settings_snapshot is None."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, settings_snapshot=None)+ assert handler.settings_snapshot == {}++ def test_empty_settings_snapshot(self):+ """Should work with empty settings snapshot."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm, settings_snapshot={})+ assert handler.settings_snapshot == {}+ # Default handler type should be standard+ assert "StandardCitationHandler" in type(handler._handler).__name__++ def test_llm_stored_on_handler(self):+ """Should store LLM reference on handler."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm)+ assert handler.llm is mock_llm++ def test_create_documents_with_missing_fields(self):+ """Should handle search results with missing fields."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm)+ # Result with missing title+ results = [{"link": "https://example.com", "snippet": "content"}]+ docs = handler._create_documents(results)+ assert len(docs) == 1+ # Default title is "Source N" when missing+ assert docs[0].metadata["title"] == "Source 1"++ def test_create_documents_with_none_content(self):+ """Should handle search results with None content."""+ mock_llm = Mock()+ handler = CitationHandler(mock_llm)+ results = [{"title": "Title", "link": "https://example.com"}]+ docs = handler._create_documents(results)+ assert len(docs) == 1+ # Should have empty or default content+ assert docs[0].page_content is not None++ def test_analyze_initial_with_string_results(self):+ """Should handle string input gracefully."""+ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(content="Response")+ handler = CitationHandler(mock_llm)+ result = handler.analyze_initial("query", "not a list")+ assert "content" in result+ assert "documents" in resultdiff --git a/tests/utilities/test_search_cache.py b/tests/utilities/test_search_cache.pyindex e8fbad83f5..548e6a2f1c 100644--- a/tests/utilities/test_search_cache.py+++ b/tests/utilities/test_search_cache.py@@ -212,14 +212,17 @@ class TestSearchCachePutGet:"""Test that custom TTL is respected."""results = [{"title": "Test"}]- # Use very short TTL- cache.put("test query", results, ttl=1)+ # Use short TTL of 2 seconds+ cache.put("test query", results, ttl=2)# Should be available immediately- assert cache.get("test query") is not None+ retrieved = cache.get("test query")+ assert retrieved is not None, (+ "Cache should be available immediately after put"+ )# Wait for expiration- time.sleep(1.5)+ time.sleep(2.5)# Clear memory cache to force DB checkcache._memory_cache.clear()