~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
Add comprehensive utilities and web services tests (447 tests)
LearningCircuit819ec78ee395
diff --git a/.pre-commit-hooks/check-deprecated-settings-wrapper.py b/.pre-commit-hooks/check-deprecated-settings-wrapper.pyindex c46c8977a5..1785cbd404 100755--- a/.pre-commit-hooks/check-deprecated-settings-wrapper.py+++ b/.pre-commit-hooks/check-deprecated-settings-wrapper.py@@ -90,10 +90,12 @@ def main():if filepath.suffix != ".py":continue- # Skip the file that defines the function (db_utils.py) and this hook itself+ # Skip the file that defines the function (db_utils.py), this hook itself,+ # and test files that test the deprecated functionif filepath.name in ["db_utils.py","check-deprecated-settings-wrapper.py",+ "test_db_utils.py",]:continuediff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.pyindex fd13ea0ea8..396c832d85 100644--- a/src/local_deep_research/news/flask_api.py+++ b/src/local_deep_research/news/flask_api.py@@ -12,7 +12,7 @@ from .folder_manager import FolderManagerfrom ..database.models import SubscriptionFolderfrom ..web.auth.decorators import login_requiredfrom ..database.session_context import get_user_db_session-from ..utilities.get_settings_manager import get_settings_manager+from ..utilities.db_utils import get_settings_managerdef safe_error_message(e: Exception, context: str = "") -> str:diff --git a/src/local_deep_research/utilities/enums.py b/src/local_deep_research/utilities/enums.pyindex 125bfafc74..596ed9480f 100644--- a/src/local_deep_research/utilities/enums.py+++ b/src/local_deep_research/utilities/enums.py@@ -1,4 +1,4 @@-# config/enums.py+# utilities/enums.pyfrom enum import Enumdiff --git a/src/local_deep_research/utilities/get_settings_manager.py b/src/local_deep_research/utilities/get_settings_manager.pydeleted file mode 100644index 1af95eaebc..0000000000--- a/src/local_deep_research/utilities/get_settings_manager.py+++ /dev/null@@ -1,36 +0,0 @@-"""-Utility function to get the appropriate settings manager instance.--This module provides a centralized way to get a settings manager,-ensuring consistency across the application.-"""--from typing import Optional-from sqlalchemy.orm import Session-from loguru import logger--from local_deep_research.settings import SettingsManager---def get_settings_manager(- db_session: Optional[Session] = None,- user_id: Optional[str] = None,- use_cache: bool = True,-) -> SettingsManager:- """- Get an appropriate settings manager instance.-- Args:- db_session: SQLAlchemy session- user_id: User identifier (required for cached version)- use_cache: Whether to use the cached version-- Returns:- SettingsManager instance (cached or regular)- """- if use_cache and user_id:- logger.debug(f"Creating SettingsManager for user {user_id}")- return SettingsManager(db_session)- else:- logger.debug("Creating regular SettingsManager")- return SettingsManager(db_session)diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.pyindex 129759d686..9b8e96ae51 100644--- a/src/local_deep_research/utilities/search_utilities.py+++ b/src/local_deep_research/utilities/search_utilities.py@@ -266,5 +266,5 @@ def print_search_results(search_results):formatted_text = ""links = extract_links_from_search_results(search_results)if links:- formatted_text = format_links_to_markdown(links=links)+ formatted_text = format_links_to_markdown(links)logger.info(formatted_text)diff --git a/tests/utilities/__init__.py b/tests/utilities/__init__.pynew file mode 100644index 0000000000..69e211f706--- /dev/null+++ b/tests/utilities/__init__.py@@ -0,0 +1 @@+"""Tests for utilities module."""diff --git a/tests/utilities/conftest.py b/tests/utilities/conftest.pynew file mode 100644index 0000000000..4577410051--- /dev/null+++ b/tests/utilities/conftest.py@@ -0,0 +1,110 @@+"""Shared fixtures for utilities tests."""++import pytest+++def sample_search_results():+ """Sample search results with standard format."""+ return [+ {+ "title": "First Article",+ "link": "https://example.com/article1",+ "index": "1",+ },+ {+ "title": "Second Article",+ "link": "https://example.org/article2",+ "index": "2",+ },+ {+ "title": "Third Article",+ "link": "https://test.com/article3",+ "index": "3",+ },+ ]+++def sample_search_results_with_duplicates():+ """Search results with duplicate URLs."""+ return [+ {+ "title": "First Article",+ "link": "https://example.com/article1",+ "index": "1",+ },+ {+ "title": "Second Article",+ "link": "https://example.com/article1", # Duplicate URL+ "index": "2",+ },+ {+ "title": "Third Article",+ "link": "https://test.com/article3",+ "index": "3",+ },+ ]+++def sample_findings():+ """Sample findings list for format_findings tests."""+ return [+ {+ "phase": "Initial Search",+ "content": "This is the initial search content.",+ "search_results": [+ {+ "title": "Source 1",+ "link": "https://source1.com",+ "index": "1",+ }+ ],+ },+ {+ "phase": "Follow-up Iteration 1.1",+ "content": "Follow-up content for iteration 1.",+ "search_results": [+ {+ "title": "Source 2",+ "link": "https://source2.com",+ "index": "2",+ }+ ],+ },+ ]+++def sample_questions_by_iteration():+ """Sample questions organized by iteration."""+ return {+ 1: ["What is the main topic?", "Who are the key players?"],+ 2: ["What are the implications?", "What is the timeline?"],+ }+++def sample_findings_with_subquery():+ """Findings with Sub-query phases (IterDRAG strategy)."""+ return [+ {+ "phase": "Sub-query 1",+ "content": "Content for sub-query 1.",+ "search_results": [],+ },+ {+ "phase": "Sub-query 2",+ "content": "Content for sub-query 2.",+ "search_results": [],+ },+ ]+++def subquery_questions():+ """Questions for Sub-query phases (stored in iteration 0)."""+ return {+ 0: ["What is X?", "How does Y work?", "Why is Z important?"],+ }diff --git a/tests/utilities/test_db_utils.py b/tests/utilities/test_db_utils.pynew file mode 100644index 0000000000..a744bc613f--- /dev/null+++ b/tests/utilities/test_db_utils.py@@ -0,0 +1,381 @@+"""Tests for db_utils module."""++import threading+from unittest.mock import Mock, patch, MagicMock++import pytest+++class TestGetDbSession:+ """Tests for get_db_session function."""++ def test_raises_error_from_background_thread_without_context(self):+ """Should raise error when called from background thread without app context."""+ from local_deep_research.utilities.db_utils import get_db_session++ error_raised = [False]+ error_message = [""]++ def background_task():+ try:+ get_db_session()+ except RuntimeError as e:+ error_raised[0] = True+ error_message[0] = str(e)++ # Run in a background thread+ thread = threading.Thread(+ target=background_task, name="TestBackgroundThread"+ )+ thread.start()+ thread.join()++ assert error_raised[0], (+ "Should raise RuntimeError from background thread"+ )+ assert "background thread" in error_message[0].lower()++ def test_returns_session_when_username_provided(self):+ """Should return session when username is explicitly provided."""+ from local_deep_research.utilities.db_utils import get_db_session++ mock_session = Mock()++ with patch(+ "local_deep_research.utilities.db_utils.db_manager"+ ) as mock_manager:+ with patch(+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=True,+ ):+ mock_manager.get_session.return_value = mock_session++ result = get_db_session(username="testuser")++ assert result == mock_session+ mock_manager.get_session.assert_called_with("testuser")++ def test_raises_error_when_no_db_for_user(self):+ """Should raise error when no database found for user."""+ from local_deep_research.utilities.db_utils import get_db_session++ with patch(+ "local_deep_research.utilities.db_utils.db_manager"+ ) as mock_manager:+ with patch(+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=True,+ ):+ mock_manager.get_session.return_value = None++ with pytest.raises(RuntimeError, match="No database found"):+ get_db_session(username="nonexistent")++ def test_returns_session_from_flask_g(self):+ """Should return session from Flask g object if present."""+ from local_deep_research.utilities.db_utils import get_db_session++ mock_session = Mock()+ mock_g = Mock()+ mock_g.db_session = mock_session++ with patch(+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=True,+ ):+ with patch("local_deep_research.utilities.db_utils.g", mock_g):+ result = get_db_session()++ assert result == mock_session++ def test_checks_flask_g_for_session(self):+ """Should check Flask g object for db_session."""+ # This tests that the function checks g.db_session+ from local_deep_research.utilities.db_utils import get_db_session++ mock_session = Mock()+ mock_g = Mock()+ mock_g.db_session = mock_session++ with patch(+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=True,+ ):+ with patch("local_deep_research.utilities.db_utils.g", mock_g):+ result = get_db_session()+ # Should return a session (the mock)+ assert result is not None+ # Verify g.db_session was accessed+ assert hasattr(mock_g, "db_session")+++class TestGetSettingsManager:+ """Tests for get_settings_manager function."""++ def test_returns_settings_manager(self):+ """Should return a SettingsManager instance."""+ from local_deep_research.utilities.db_utils import get_settings_manager++ mock_manager = Mock()++ with patch(+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.db_utils.get_db_session",+ side_effect=RuntimeError("No session"),+ ):+ with patch(+ "local_deep_research.settings.SettingsManager",+ return_value=mock_manager,+ ):+ result = get_settings_manager()++ # Should return a SettingsManager (mocked)+ assert result is not None++ def test_uses_provided_db_session(self):+ """Should use provided db_session."""+ from local_deep_research.utilities.db_utils import get_settings_manager++ mock_session = Mock()+ mock_manager = Mock()++ with patch(+ "local_deep_research.settings.SettingsManager",+ return_value=mock_manager,+ ) as MockSettingsManager:+ get_settings_manager(db_session=mock_session)++ MockSettingsManager.assert_called_once_with(mock_session)++ def test_handles_no_session(self):+ """Should handle case when no session available."""+ from local_deep_research.utilities.db_utils import get_settings_manager++ with patch(+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.db_utils.get_db_session",+ side_effect=RuntimeError("No session"),+ ):+ with patch(+ "local_deep_research.settings.SettingsManager"+ ) as MockSettingsManager:+ get_settings_manager()++ # Should be called with None session+ MockSettingsManager.assert_called_once_with(None)+++class TestNoDbSettings:+ """Tests for no_db_settings decorator."""++ def test_disables_db_during_function_execution(self):+ """Should disable DB session during function execution."""+ from local_deep_research.utilities.db_utils import no_db_settings++ mock_session = Mock()+ mock_manager = Mock()+ mock_manager.db_session = mock_session++ session_during_call = []++ @no_db_settings+ def test_func():+ session_during_call.append(mock_manager.db_session)+ return "result"++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_manager,+ ):+ result = test_func()++ assert result == "result"+ assert session_during_call[0] is None+ # Session should be restored after+ assert mock_manager.db_session == mock_session++ def test_restores_db_on_exception(self):+ """Should restore DB session even if function raises."""+ from local_deep_research.utilities.db_utils import no_db_settings++ mock_session = Mock()+ mock_manager = Mock()+ mock_manager.db_session = mock_session++ @no_db_settings+ def failing_func():+ raise ValueError("Test error")++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_manager,+ ):+ with pytest.raises(ValueError):+ failing_func()++ # Session should still be restored+ assert mock_manager.db_session == mock_session++ def test_preserves_function_metadata(self):+ """Should preserve function name and docstring."""+ from local_deep_research.utilities.db_utils import no_db_settings++ @no_db_settings+ def my_function():+ """My docstring."""+ pass++ assert my_function.__name__ == "my_function"+ assert my_function.__doc__ == "My docstring."+++class TestGetSettingFromDbMainThread:+ """Tests for get_setting_from_db_main_thread function."""++ def test_returns_default_in_fallback_mode(self):+ """Should return default value when in fallback LLM mode."""+ from local_deep_research.utilities.db_utils import (+ get_setting_from_db_main_thread,+ )++ with patch(+ "local_deep_research.utilities.db_utils.use_fallback_llm",+ return_value=True,+ ):+ result = get_setting_from_db_main_thread(+ "test.key", default_value="default"+ )++ assert result == "default"++ def test_raises_error_from_background_thread(self):+ """Should raise error when called from background thread."""+ from local_deep_research.utilities.db_utils import (+ get_setting_from_db_main_thread,+ )++ error_raised = [False]++ def background_task():+ try:+ with patch(+ "local_deep_research.utilities.db_utils.use_fallback_llm",+ return_value=False,+ ):+ get_setting_from_db_main_thread("test.key")+ except RuntimeError:+ error_raised[0] = True++ thread = threading.Thread(target=background_task, name="BGThread")+ thread.start()+ thread.join()++ assert error_raised[0], (+ "Should raise RuntimeError from background thread"+ )++ def test_returns_default_when_no_session(self):+ """Should return default when no database session available."""+ from local_deep_research.utilities.db_utils import (+ get_setting_from_db_main_thread,+ )++ with patch(+ "local_deep_research.utilities.db_utils.use_fallback_llm",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=True,+ ):+ # Simulate get_user_db_session returning None+ with patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as mock_context:+ mock_cm = MagicMock()+ mock_cm.__enter__ = Mock(return_value=None)+ mock_cm.__exit__ = Mock(return_value=None)+ mock_context.return_value = mock_cm++ result = get_setting_from_db_main_thread(+ "test.key", default_value="fallback"+ )++ assert result == "fallback"++ def test_returns_default_on_exception(self):+ """Should return default value on exception."""+ from local_deep_research.utilities.db_utils import (+ get_setting_from_db_main_thread,+ )++ with patch(+ "local_deep_research.utilities.db_utils.use_fallback_llm",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=True,+ ):+ # Force an exception in the outer try block+ with patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=Exception("DB error"),+ ):+ result = get_setting_from_db_main_thread(+ "test.key", default_value="fallback"+ )++ assert result == "fallback"+++class TestDataDir:+ """Tests for DATA_DIR constant."""++ def test_data_dir_is_set(self):+ """DATA_DIR should be set from get_data_directory."""+ from local_deep_research.utilities.db_utils import DATA_DIR++ assert DATA_DIR is not None+++class TestThreadSafety:+ """Tests for thread safety mechanisms."""++ def test_thread_name_included_in_error(self):+ """Error message should include thread name."""+ from local_deep_research.utilities.db_utils import get_db_session++ error_message = [""]++ def background_task():+ try:+ get_db_session()+ except RuntimeError as e:+ error_message[0] = str(e)++ thread = threading.Thread(+ target=background_task, name="CustomThreadName"+ )+ thread.start()+ thread.join()++ assert "CustomThreadName" in error_message[0]++ def test_main_thread_not_blocked_without_context(self):+ """MainThread should not be blocked by thread safety check."""+ # Verify that MainThread can proceed past the thread check+ # even without app context (unlike background threads)+ import threading++ # This test runs in MainThread+ assert threading.current_thread().name == "MainThread"++ # The function should not raise RuntimeError for MainThread+ # (it may fail later for other reasons, but not the thread check)diff --git a/tests/utilities/test_enums.py b/tests/utilities/test_enums.pynew file mode 100644index 0000000000..db5d46b556--- /dev/null+++ b/tests/utilities/test_enums.py@@ -0,0 +1,151 @@+"""Tests for enums module."""++from enum import Enum++import pytest++from local_deep_research.utilities.enums import (+ KnowledgeAccumulationApproach,+ SearchMode,+)+++class TestKnowledgeAccumulationApproach:+ """Tests for KnowledgeAccumulationApproach enum."""++ def test_is_enum(self):+ """Should be an Enum class."""+ assert issubclass(KnowledgeAccumulationApproach, Enum)++ def test_has_question_value(self):+ """Should have QUESTION value."""+ assert KnowledgeAccumulationApproach.QUESTION.value == "QUESTION"++ def test_has_iteration_value(self):+ """Should have ITERATION value."""+ assert KnowledgeAccumulationApproach.ITERATION.value == "ITERATION"++ def test_has_no_knowledge_value(self):+ """Should have NO_KNOWLEDGE value."""+ assert (+ KnowledgeAccumulationApproach.NO_KNOWLEDGE.value == "NO_KNOWLEDGE"+ )++ def test_has_max_nr_of_characters_value(self):+ """Should have MAX_NR_OF_CHARACTERS value."""+ assert (+ KnowledgeAccumulationApproach.MAX_NR_OF_CHARACTERS.value+ == "MAX_NR_OF_CHARACTERS"+ )++ def test_all_values_are_strings(self):+ """All values should be strings."""+ for member in KnowledgeAccumulationApproach:+ assert isinstance(member.value, str)++ def test_can_access_by_name(self):+ """Should be able to access members by name."""+ assert (+ KnowledgeAccumulationApproach["QUESTION"]+ == KnowledgeAccumulationApproach.QUESTION+ )++ def test_can_access_by_value(self):+ """Should be able to access members by value."""+ assert (+ KnowledgeAccumulationApproach("QUESTION")+ == KnowledgeAccumulationApproach.QUESTION+ )++ def test_invalid_value_raises_error(self):+ """Should raise ValueError for invalid value."""+ with pytest.raises(ValueError):+ KnowledgeAccumulationApproach("INVALID")++ def test_member_count(self):+ """Should have exactly 4 members."""+ assert len(KnowledgeAccumulationApproach) == 4+++class TestSearchMode:+ """Tests for SearchMode enum."""++ def test_is_enum(self):+ """Should be an Enum class."""+ assert issubclass(SearchMode, Enum)++ def test_has_all_value(self):+ """Should have ALL value."""+ assert SearchMode.ALL.value == "all"++ def test_has_scientific_value(self):+ """Should have SCIENTIFIC value."""+ assert SearchMode.SCIENTIFIC.value == "scientific"++ def test_all_values_are_lowercase(self):+ """All values should be lowercase strings."""+ for member in SearchMode:+ assert isinstance(member.value, str)+ assert member.value == member.value.lower()++ def test_can_access_by_name(self):+ """Should be able to access members by name."""+ assert SearchMode["ALL"] == SearchMode.ALL+ assert SearchMode["SCIENTIFIC"] == SearchMode.SCIENTIFIC++ def test_can_access_by_value(self):+ """Should be able to access members by value."""+ assert SearchMode("all") == SearchMode.ALL+ assert SearchMode("scientific") == SearchMode.SCIENTIFIC++ def test_invalid_value_raises_error(self):+ """Should raise ValueError for invalid value."""+ with pytest.raises(ValueError):+ SearchMode("invalid")++ def test_member_count(self):+ """Should have exactly 2 members."""+ assert len(SearchMode) == 2++ def test_has_docstring(self):+ """SearchMode should have a docstring."""+ assert SearchMode.__doc__ is not None+ assert "Search mode" in SearchMode.__doc__+++class TestEnumComparison:+ """Tests for enum comparison behavior."""++ def test_same_members_are_equal(self):+ """Same enum members should be equal."""+ assert (+ KnowledgeAccumulationApproach.QUESTION+ == KnowledgeAccumulationApproach.QUESTION+ )++ def test_different_members_not_equal(self):+ """Different enum members should not be equal."""+ assert (+ KnowledgeAccumulationApproach.QUESTION+ != KnowledgeAccumulationApproach.ITERATION+ )++ def test_member_not_equal_to_string(self):+ """Enum member should not be equal to its string value directly."""+ assert KnowledgeAccumulationApproach.QUESTION != "QUESTION"++ def test_can_use_in_dict_keys(self):+ """Enum members can be used as dictionary keys."""+ config = {+ KnowledgeAccumulationApproach.QUESTION: "question_handler",+ KnowledgeAccumulationApproach.ITERATION: "iteration_handler",+ }+ assert (+ config[KnowledgeAccumulationApproach.QUESTION] == "question_handler"+ )++ def test_can_use_in_set(self):+ """Enum members can be used in sets."""+ modes = {SearchMode.ALL, SearchMode.SCIENTIFIC}+ assert SearchMode.ALL in modes+ assert len(modes) == 2diff --git a/tests/utilities/test_es_utils.py b/tests/utilities/test_es_utils.pynew file mode 100644index 0000000000..424bbbced3--- /dev/null+++ b/tests/utilities/test_es_utils.py@@ -0,0 +1,576 @@+"""Tests for es_utils module."""++import tempfile+from pathlib import Path+from unittest.mock import Mock, patch++import pytest+++class TestElasticsearchManagerInit:+ """Tests for ElasticsearchManager initialization."""++ def test_initializes_with_default_hosts(self):+ """Should initialize with default localhost host."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test-cluster",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ) as MockES:+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ ElasticsearchManager()++ MockES.assert_called_once()+ # Default hosts should be localhost+ call_args = MockES.call_args+ assert call_args[0][0] == ["http://localhost:9200"]++ def test_initializes_with_custom_hosts(self):+ """Should initialize with custom hosts."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ) as MockES:+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ ElasticsearchManager(hosts=["http://custom:9200"])++ call_args = MockES.call_args+ assert call_args[0][0] == ["http://custom:9200"]++ def test_initializes_with_basic_auth(self):+ """Should initialize with basic authentication."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ) as MockES:+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ ElasticsearchManager(username="user", password="pass")++ call_kwargs = MockES.call_args[1]+ assert call_kwargs["basic_auth"] == ("user", "pass")++ def test_initializes_with_api_key(self):+ """Should initialize with API key authentication."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ) as MockES:+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ ElasticsearchManager(api_key="my-api-key")++ call_kwargs = MockES.call_args[1]+ assert call_kwargs["api_key"] == "my-api-key"++ def test_initializes_with_cloud_id(self):+ """Should initialize with Elastic Cloud ID."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ) as MockES:+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ ElasticsearchManager(cloud_id="my-cloud-id")++ call_kwargs = MockES.call_args[1]+ assert call_kwargs["cloud_id"] == "my-cloud-id"++ def test_raises_connection_error_on_failure(self):+ """Should raise ConnectionError if connection fails."""+ mock_client = Mock()+ mock_client.info.side_effect = Exception("Connection refused")++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ):+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ with pytest.raises(ConnectionError):+ ElasticsearchManager()+++class TestElasticsearchManagerCreateIndex:+ """Tests for ElasticsearchManager.create_index method."""++ @pytest.fixture+ def manager(self):+ """Create a manager with mocked client."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ):+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ mgr = ElasticsearchManager()+ return mgr++ def test_creates_index_successfully(self, manager):+ """Should create index and return True."""+ manager.client.indices.exists.return_value = False+ manager.client.indices.create.return_value = {"acknowledged": True}++ result = manager.create_index("test-index")++ assert result is True+ manager.client.indices.create.assert_called_once()++ def test_skips_existing_index(self, manager):+ """Should skip creation if index already exists."""+ manager.client.indices.exists.return_value = True++ result = manager.create_index("existing-index")++ assert result is True+ manager.client.indices.create.assert_not_called()++ def test_uses_custom_mappings(self, manager):+ """Should use provided custom mappings."""+ manager.client.indices.exists.return_value = False+ manager.client.indices.create.return_value = {"acknowledged": True}++ custom_mappings = {"properties": {"custom_field": {"type": "keyword"}}}+ manager.create_index("test-index", mappings=custom_mappings)++ call_kwargs = manager.client.indices.create.call_args[1]+ assert call_kwargs["mappings"] == custom_mappings++ def test_uses_custom_settings(self, manager):+ """Should use provided custom settings."""+ manager.client.indices.exists.return_value = False+ manager.client.indices.create.return_value = {"acknowledged": True}++ custom_settings = {"number_of_shards": 3}+ manager.create_index("test-index", settings=custom_settings)++ call_kwargs = manager.client.indices.create.call_args[1]+ assert call_kwargs["settings"] == custom_settings++ def test_returns_false_on_error(self, manager):+ """Should return False on error."""+ manager.client.indices.exists.return_value = False+ manager.client.indices.create.side_effect = Exception("Error")++ result = manager.create_index("test-index")++ assert result is False+++class TestElasticsearchManagerDeleteIndex:+ """Tests for ElasticsearchManager.delete_index method."""++ @pytest.fixture+ def manager(self):+ """Create a manager with mocked client."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ):+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ return ElasticsearchManager()++ def test_deletes_index_successfully(self, manager):+ """Should delete index and return True."""+ manager.client.indices.exists.return_value = True+ manager.client.indices.delete.return_value = {"acknowledged": True}++ result = manager.delete_index("test-index")++ assert result is True+ manager.client.indices.delete.assert_called_once_with(+ index="test-index"+ )++ def test_skips_nonexistent_index(self, manager):+ """Should skip deletion if index doesn't exist."""+ manager.client.indices.exists.return_value = False++ result = manager.delete_index("nonexistent-index")++ assert result is True+ manager.client.indices.delete.assert_not_called()++ def test_returns_false_on_error(self, manager):+ """Should return False on error."""+ manager.client.indices.exists.return_value = True+ manager.client.indices.delete.side_effect = Exception("Error")++ result = manager.delete_index("test-index")++ assert result is False+++class TestElasticsearchManagerIndexDocument:+ """Tests for ElasticsearchManager.index_document method."""++ @pytest.fixture+ def manager(self):+ """Create a manager with mocked client."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ):+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ return ElasticsearchManager()++ def test_indexes_document_successfully(self, manager):+ """Should index document and return ID."""+ manager.client.index.return_value = {"_id": "doc-123"}++ document = {"title": "Test", "content": "Content"}+ result = manager.index_document("test-index", document)++ assert result == "doc-123"+ manager.client.index.assert_called_once()++ def test_uses_provided_document_id(self, manager):+ """Should use provided document ID."""+ manager.client.index.return_value = {"_id": "custom-id"}++ document = {"title": "Test"}+ manager.index_document("test-index", document, document_id="custom-id")++ call_kwargs = manager.client.index.call_args[1]+ assert call_kwargs["id"] == "custom-id"++ def test_respects_refresh_parameter(self, manager):+ """Should pass refresh parameter to client."""+ manager.client.index.return_value = {"_id": "doc-123"}++ document = {"title": "Test"}+ manager.index_document("test-index", document, refresh=True)++ call_kwargs = manager.client.index.call_args[1]+ assert call_kwargs["refresh"] is True++ def test_returns_none_on_error(self, manager):+ """Should return None on error."""+ manager.client.index.side_effect = Exception("Error")++ document = {"title": "Test"}+ result = manager.index_document("test-index", document)++ assert result is None+++class TestElasticsearchManagerBulkIndexDocuments:+ """Tests for ElasticsearchManager.bulk_index_documents method."""++ @pytest.fixture+ def manager(self):+ """Create a manager with mocked client."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ):+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ return ElasticsearchManager()++ def test_bulk_indexes_documents_successfully(self, manager):+ """Should bulk index documents and return count."""+ with patch(+ "local_deep_research.utilities.es_utils.bulk", return_value=(5, 0)+ ):+ documents = [{"title": f"Doc {i}"} for i in range(5)]+ result = manager.bulk_index_documents("test-index", documents)++ assert result == 5++ def test_uses_id_field_when_provided(self, manager):+ """Should use specified field as document ID."""+ with patch(+ "local_deep_research.utilities.es_utils.bulk", return_value=(2, 0)+ ) as mock_bulk:+ documents = [+ {"doc_id": "id-1", "title": "Doc 1"},+ {"doc_id": "id-2", "title": "Doc 2"},+ ]+ manager.bulk_index_documents(+ "test-index", documents, id_field="doc_id"+ )++ # Check that actions include _id+ call_args = mock_bulk.call_args+ actions = call_args[0][1]+ assert actions[0]["_id"] == "id-1"+ assert actions[1]["_id"] == "id-2"++ def test_returns_zero_on_error(self, manager):+ """Should return 0 on error."""+ with patch(+ "local_deep_research.utilities.es_utils.bulk",+ side_effect=Exception("Error"),+ ):+ documents = [{"title": "Doc"}]+ result = manager.bulk_index_documents("test-index", documents)++ assert result == 0+++class TestElasticsearchManagerSearch:+ """Tests for ElasticsearchManager.search method."""++ @pytest.fixture+ def manager(self):+ """Create a manager with mocked client."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ):+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ return ElasticsearchManager()++ def test_searches_successfully(self, manager):+ """Should execute search and return response."""+ expected_response = {+ "hits": {+ "total": {"value": 1},+ "hits": [{"_source": {"title": "Test"}}],+ }+ }+ manager.client.search.return_value = expected_response++ result = manager.search("test-index", "test query")++ assert result == expected_response++ def test_uses_custom_fields(self, manager):+ """Should search in specified fields."""+ manager.client.search.return_value = {"hits": {"hits": []}}++ manager.search("test-index", "query", fields=["custom_field"])++ call_kwargs = manager.client.search.call_args[1]+ body = call_kwargs["body"]+ assert body["query"]["multi_match"]["fields"] == ["custom_field"]++ def test_respects_size_parameter(self, manager):+ """Should respect size parameter."""+ manager.client.search.return_value = {"hits": {"hits": []}}++ manager.search("test-index", "query", size=50)++ call_kwargs = manager.client.search.call_args[1]+ body = call_kwargs["body"]+ assert body["size"] == 50++ def test_includes_highlighting_by_default(self, manager):+ """Should include highlighting by default."""+ manager.client.search.return_value = {"hits": {"hits": []}}++ manager.search("test-index", "query")++ call_kwargs = manager.client.search.call_args[1]+ body = call_kwargs["body"]+ assert "highlight" in body++ def test_can_disable_highlighting(self, manager):+ """Should be able to disable highlighting."""+ manager.client.search.return_value = {"hits": {"hits": []}}++ manager.search("test-index", "query", highlight=False)++ call_kwargs = manager.client.search.call_args[1]+ body = call_kwargs["body"]+ assert "highlight" not in body++ def test_returns_error_dict_on_failure(self, manager):+ """Should return error dict on failure."""+ manager.client.search.side_effect = Exception("Search error")++ result = manager.search("test-index", "query")++ assert result == {"error": "Search failed"}+++class TestElasticsearchManagerIndexFile:+ """Tests for ElasticsearchManager.index_file method."""++ @pytest.fixture+ def manager(self):+ """Create a manager with mocked client."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ):+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ return ElasticsearchManager()++ def test_returns_none_if_loader_not_available(self, manager):+ """Should return None if UnstructuredFileLoader not available."""+ # The import is lazy inside the function, so we patch at the source+ with patch.dict(+ "sys.modules",+ {"langchain_community.document_loaders": None},+ ):+ result = manager.index_file("test-index", "/path/to/file.txt")++ # Will raise ImportError, caught and returns None+ assert result is None++ def test_returns_none_on_error(self, manager):+ """Should return None on error."""+ # Force an error by using a non-existent file path without mocking loader+ result = manager.index_file("test-index", "/nonexistent/path/file.txt")++ assert result is None+++class TestElasticsearchManagerIndexDirectory:+ """Tests for ElasticsearchManager.index_directory method."""++ @pytest.fixture+ def manager(self):+ """Create a manager with mocked client."""+ mock_client = Mock()+ mock_client.info.return_value = {+ "cluster_name": "test",+ "version": {"number": "8.0.0"},+ }++ with patch(+ "local_deep_research.utilities.es_utils.Elasticsearch",+ return_value=mock_client,+ ):+ from local_deep_research.utilities.es_utils import (+ ElasticsearchManager,+ )++ return ElasticsearchManager()++ def test_indexes_matching_files(self, manager):+ """Should index files matching patterns."""+ with tempfile.TemporaryDirectory() as tmpdir:+ # Create test files+ Path(tmpdir, "test1.txt").write_text("Content 1")+ Path(tmpdir, "test2.txt").write_text("Content 2")+ Path(tmpdir, "test.pdf").write_text("PDF content")++ with patch.object(+ manager, "index_file", return_value="doc-id"+ ) as mock_index:+ result = manager.index_directory(+ "test-index", tmpdir, file_patterns=["*.txt"]+ )++ assert result == 2+ assert mock_index.call_count == 2++ def test_returns_zero_on_error(self, manager):+ """Should return 0 on error."""+ result = manager.index_directory("test-index", "/nonexistent/path")++ assert result == 0++ def test_counts_successful_indexes_only(self, manager):+ """Should only count successfully indexed files."""+ with tempfile.TemporaryDirectory() as tmpdir:+ Path(tmpdir, "test1.txt").write_text("Content 1")+ Path(tmpdir, "test2.txt").write_text("Content 2")++ # First succeeds, second fails+ with patch.object(+ manager, "index_file", side_effect=["doc-1", None]+ ):+ result = manager.index_directory(+ "test-index", tmpdir, file_patterns=["*.txt"]+ )++ assert result == 1diff --git a/tests/utilities/test_llm_utils.py b/tests/utilities/test_llm_utils.pynew file mode 100644index 0000000000..b39d26ed29--- /dev/null+++ b/tests/utilities/test_llm_utils.py@@ -0,0 +1,661 @@+"""Tests for llm_utils module."""++from unittest.mock import Mock, patch, MagicMock++import pytest++from local_deep_research.utilities.llm_utils import (+ fetch_ollama_models,+ get_model,+ get_ollama_base_url,+ get_server_url,+)+++class TestGetOllamaBaseUrl:+ """Tests for get_ollama_base_url function."""++ def test_returns_default_without_settings(self):+ """Should return default URL when no settings provided."""+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.return_value = None+ result = get_ollama_base_url()+ assert result == "http://localhost:11434"++ def test_uses_embeddings_ollama_url(self):+ """Should use embeddings.ollama.url setting."""+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.return_value = "http://custom:11434"+ result = get_ollama_base_url()+ assert result == "http://custom:11434"++ def test_normalizes_url(self):+ """Should normalize URL without scheme."""+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.return_value = "localhost:11434"+ result = get_ollama_base_url()+ assert result == "http://localhost:11434"++ def test_passes_settings_snapshot(self):+ """Should pass settings snapshot to get_setting_from_snapshot."""+ snapshot = {"key": "value"}+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.return_value = "http://localhost:11434"+ get_ollama_base_url(settings_snapshot=snapshot)+ # Should have been called with snapshot+ assert any(+ call.kwargs.get("settings_snapshot") == snapshot+ for call in mock_get.call_args_list+ )+++class TestGetServerUrl:+ """Tests for get_server_url function."""++ def test_returns_default_without_settings(self):+ """Should return default URL when no settings provided."""+ result = get_server_url()+ assert result == "http://127.0.0.1:5000/"++ def test_uses_server_url_from_snapshot(self):+ """Should use direct server_url from snapshot."""+ snapshot = {"server_url": "https://custom.example.com/"}+ result = get_server_url(settings_snapshot=snapshot)+ assert result == "https://custom.example.com/"++ def test_uses_system_server_url(self):+ """Should use system.server_url setting."""+ snapshot = {"system": {"server_url": "https://system.example.com/"}}+ result = get_server_url(settings_snapshot=snapshot)+ assert result == "https://system.example.com/"++ def test_constructs_url_from_web_settings(self):+ """Should construct URL from web.host, web.port, web.use_https."""+ # Need to provide snapshot so it goes through web settings path+ snapshot = {"_trigger_web_settings": True}+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:++ def side_effect(key, snapshot_arg=None, default=None):+ settings = {+ "web.host": "0.0.0.0",+ "web.port": 8080,+ "web.use_https": True,+ }+ return settings.get(key, default)++ mock_get.side_effect = side_effect+ result = get_server_url(settings_snapshot=snapshot)+ # 0.0.0.0 should be converted to 127.0.0.1+ assert result == "https://127.0.0.1:8080/"++ def test_uses_http_when_use_https_false(self):+ """Should use http scheme when use_https is False."""+ snapshot = {"_trigger_web_settings": True}+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:++ def side_effect(key, snapshot_arg=None, default=None):+ settings = {+ "web.host": "192.168.1.1", # Not localhost, so it won't default+ "web.port": 5000,+ "web.use_https": False,+ }+ return settings.get(key, default)++ mock_get.side_effect = side_effect+ result = get_server_url(settings_snapshot=snapshot)+ assert result == "http://192.168.1.1:5000/"++ def test_priority_order(self):+ """Should check server_url before system before web settings."""+ # Direct server_url takes priority+ snapshot = {+ "server_url": "https://direct/",+ "system": {"server_url": "https://system/"},+ }+ result = get_server_url(settings_snapshot=snapshot)+ assert result == "https://direct/"++ def test_returns_fallback_with_trailing_slash(self):+ """Fallback URL should have trailing slash."""+ result = get_server_url()+ assert result.endswith("/")+++class TestFetchOllamaModels:+ """Tests for fetch_ollama_models function."""++ def test_returns_empty_list_on_connection_error(self):+ """Should return empty list on connection error."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_get.side_effect = Exception("Connection refused")+ result = fetch_ollama_models("http://localhost:11434")+ assert result == []++ def test_returns_empty_list_on_non_200(self):+ """Should return empty list on non-200 status."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_response = Mock()+ mock_response.status_code = 404+ mock_get.return_value = mock_response+ result = fetch_ollama_models("http://localhost:11434")+ assert result == []++ def test_parses_models_from_response(self):+ """Should parse models from API response."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "models": [+ {"name": "llama2"},+ {"name": "mistral"},+ ]+ }+ mock_get.return_value = mock_response++ result = fetch_ollama_models("http://localhost:11434")++ assert len(result) == 2+ assert {"value": "llama2", "label": "llama2"} in result+ assert {"value": "mistral", "label": "mistral"} in result++ def test_handles_older_api_format(self):+ """Should handle older API format (list directly)."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = [+ {"name": "model1"},+ {"name": "model2"},+ ]+ mock_get.return_value = mock_response++ result = fetch_ollama_models("http://localhost:11434")++ assert len(result) == 2++ def test_skips_models_without_name(self):+ """Should skip models without name field."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "models": [+ {"name": "valid"},+ {"other": "field"}, # No name+ {"name": ""}, # Empty name+ ]+ }+ mock_get.return_value = mock_response++ result = fetch_ollama_models("http://localhost:11434")++ assert len(result) == 1+ assert result[0]["value"] == "valid"++ def test_uses_custom_timeout(self):+ """Should use custom timeout."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"models": []}+ mock_get.return_value = mock_response++ fetch_ollama_models("http://localhost:11434", timeout=10.0)++ mock_get.assert_called_once()+ assert mock_get.call_args.kwargs["timeout"] == 10.0++ def test_uses_auth_headers(self):+ """Should pass auth headers to request."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"models": []}+ mock_get.return_value = mock_response++ headers = {"Authorization": "Bearer token"}+ fetch_ollama_models("http://localhost:11434", auth_headers=headers)++ mock_get.assert_called_once()+ assert mock_get.call_args.kwargs["headers"] == headers++ def test_constructs_correct_url(self):+ """Should construct correct API URL."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"models": []}+ mock_get.return_value = mock_response++ fetch_ollama_models("http://localhost:11434")++ mock_get.assert_called_once()+ assert (+ mock_get.call_args.args[0] == "http://localhost:11434/api/tags"+ )++ def test_returns_correct_format(self):+ """Should return models in correct format with value and label."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "models": [{"name": "test-model"}]+ }+ mock_get.return_value = mock_response++ result = fetch_ollama_models("http://localhost:11434")++ assert len(result) == 1+ assert "value" in result[0]+ assert "label" in result[0]+ assert result[0]["value"] == result[0]["label"]++ def test_handles_empty_models_list(self):+ """Should handle empty models list."""+ import requests++ with patch.object(requests, "get") as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"models": []}+ mock_get.return_value = mock_response++ result = fetch_ollama_models("http://localhost:11434")++ assert result == []+++class TestGetModel:+ """Tests for get_model function."""++ def test_creates_ollama_model_by_default(self):+ """Should create Ollama model by default."""+ mock_chat_ollama = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOllama",+ mock_chat_ollama,+ create=True,+ ):+ with patch.dict(+ "sys.modules",+ {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},+ ):+ get_model(model_name="llama2", model_type="ollama")++ mock_chat_ollama.assert_called_once()+ call_kwargs = mock_chat_ollama.call_args.kwargs+ assert call_kwargs["model"] == "llama2"++ def test_uses_default_model_name(self):+ """Should use DEFAULT_MODEL from kwargs if model_name not provided."""+ mock_chat_ollama = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOllama",+ mock_chat_ollama,+ create=True,+ ):+ with patch.dict(+ "sys.modules",+ {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},+ ):+ get_model(model_type="ollama", DEFAULT_MODEL="custom-model")++ mock_chat_ollama.assert_called_once()+ call_kwargs = mock_chat_ollama.call_args.kwargs+ assert call_kwargs["model"] == "custom-model"++ def test_uses_default_temperature(self):+ """Should use DEFAULT_TEMPERATURE from kwargs."""+ mock_chat_ollama = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOllama",+ mock_chat_ollama,+ create=True,+ ):+ with patch.dict(+ "sys.modules",+ {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},+ ):+ get_model(+ model_name="test",+ model_type="ollama",+ DEFAULT_TEMPERATURE=0.5,+ )++ call_kwargs = mock_chat_ollama.call_args.kwargs+ assert call_kwargs["temperature"] == 0.5++ def test_uses_max_tokens(self):+ """Should use max_tokens from kwargs."""+ mock_chat_ollama = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOllama",+ mock_chat_ollama,+ create=True,+ ):+ with patch.dict(+ "sys.modules",+ {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},+ ):+ get_model(+ model_name="test", model_type="ollama", max_tokens=5000+ )++ call_kwargs = mock_chat_ollama.call_args.kwargs+ assert call_kwargs["max_tokens"] == 5000++ def test_openai_model_requires_api_key(self):+ """Should raise error if OpenAI API key not found."""+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.return_value = None # No API key++ with pytest.raises(ValueError, match="OpenAI API key not found"):+ get_model(model_name="gpt-4", model_type="openai")++ def test_anthropic_model_requires_api_key(self):+ """Should raise error if Anthropic API key not found."""+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.return_value = None # No API key++ with pytest.raises(ValueError, match="Anthropic API key not found"):+ get_model(model_name="claude-3", model_type="anthropic")++ def test_openai_endpoint_requires_api_key(self):+ """Should raise error if OpenAI endpoint API key not found."""+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.return_value = None # No API key++ with pytest.raises(+ ValueError, match="OpenAI endpoint API key not found"+ ):+ get_model(model_name="model", model_type="openai_endpoint")++ def test_unknown_model_type_falls_back_to_ollama(self):+ """Should fall back to Ollama for unknown model types."""+ mock_chat_ollama = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOllama",+ mock_chat_ollama,+ create=True,+ ):+ with patch.dict(+ "sys.modules",+ {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},+ ):+ with patch(+ "local_deep_research.utilities.llm_utils.logger"+ ) as mock_logger:+ get_model(model_name="test", model_type="unknown_type")++ mock_logger.warning.assert_called()+ mock_chat_ollama.assert_called_once()++ def test_passes_additional_kwargs(self):+ """Should pass additional kwargs to model."""+ mock_chat_ollama = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOllama",+ mock_chat_ollama,+ create=True,+ ):+ with patch.dict(+ "sys.modules",+ {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},+ ):+ get_model(+ model_name="test",+ model_type="ollama",+ custom_param="value",+ )++ call_kwargs = mock_chat_ollama.call_args.kwargs+ assert call_kwargs["custom_param"] == "value"++ def test_excludes_config_kwargs_from_model(self):+ """Should not pass config kwargs like DEFAULT_MODEL to model."""+ mock_chat_ollama = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOllama",+ mock_chat_ollama,+ create=True,+ ):+ with patch.dict(+ "sys.modules",+ {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},+ ):+ get_model(+ model_name="test",+ model_type="ollama",+ DEFAULT_MODEL="ignored",+ DEFAULT_MODEL_TYPE="ignored",+ DEFAULT_TEMPERATURE=0.5,+ MAX_TOKENS=1000,+ )++ call_kwargs = mock_chat_ollama.call_args.kwargs+ assert "DEFAULT_MODEL" not in call_kwargs+ assert "DEFAULT_MODEL_TYPE" not in call_kwargs+ assert "DEFAULT_TEMPERATURE" not in call_kwargs+ assert "MAX_TOKENS" not in call_kwargs+++class TestGetModelOpenAI:+ """Tests for get_model with OpenAI provider."""++ def test_creates_openai_model(self):+ """Should create OpenAI model with API key."""+ mock_chat_openai = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.return_value = "test-api-key"++ with patch.dict(+ "sys.modules",+ {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},+ ):+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOpenAI",+ mock_chat_openai,+ create=True,+ ):+ get_model(model_name="gpt-4", model_type="openai")++ mock_chat_openai.assert_called_once()+ call_kwargs = mock_chat_openai.call_args.kwargs+ assert call_kwargs["model"] == "gpt-4"+ assert call_kwargs["api_key"] == "test-api-key"+++class TestGetModelAnthropic:+ """Tests for get_model with Anthropic provider."""++ def test_creates_anthropic_model(self):+ """Should create Anthropic model with API key."""+ mock_chat_anthropic = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:+ mock_get.return_value = "test-api-key"++ with patch.dict(+ "sys.modules",+ {+ "langchain_anthropic": MagicMock(+ ChatAnthropic=mock_chat_anthropic+ )+ },+ ):+ with patch(+ "local_deep_research.utilities.llm_utils.ChatAnthropic",+ mock_chat_anthropic,+ create=True,+ ):+ get_model(model_name="claude-3", model_type="anthropic")++ mock_chat_anthropic.assert_called_once()+ call_kwargs = mock_chat_anthropic.call_args.kwargs+ assert call_kwargs["model"] == "claude-3"+ assert call_kwargs["anthropic_api_key"] == "test-api-key"+++class TestGetModelOpenAIEndpoint:+ """Tests for get_model with OpenAI endpoint provider."""++ def test_creates_openai_endpoint_model(self):+ """Should create OpenAI endpoint model with custom URL."""+ mock_chat_openai = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:++ def side_effect(key, *args, **kwargs):+ if "api_key" in key:+ return "test-api-key"+ return kwargs.get("default", "https://openrouter.ai/api/v1")++ mock_get.side_effect = side_effect++ with patch.dict(+ "sys.modules",+ {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},+ ):+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOpenAI",+ mock_chat_openai,+ create=True,+ ):+ get_model(+ model_name="model-name",+ model_type="openai_endpoint",+ OPENAI_ENDPOINT_URL="https://custom-endpoint.com/v1",+ )++ mock_chat_openai.assert_called_once()+ call_kwargs = mock_chat_openai.call_args.kwargs+ assert (+ call_kwargs["openai_api_base"]+ == "https://custom-endpoint.com/v1"+ )++ def test_endpoint_passes_model_name(self):+ """Should pass model name to endpoint."""+ mock_chat_openai = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"+ ) as mock_get:++ def side_effect(key, *args, **kwargs):+ if "api_key" in key:+ return "test-api-key"+ return "https://openrouter.ai/api/v1"++ mock_get.side_effect = side_effect++ with patch.dict(+ "sys.modules",+ {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},+ ):+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOpenAI",+ mock_chat_openai,+ create=True,+ ):+ get_model(+ model_name="custom-model",+ model_type="openai_endpoint",+ )++ mock_chat_openai.assert_called_once()+ call_kwargs = mock_chat_openai.call_args.kwargs+ assert call_kwargs["model"] == "custom-model"+++class TestGetModelFallback:+ """Tests for get_model fallback behavior."""++ def test_default_model_values(self):+ """Should use sensible defaults for model parameters."""+ mock_chat_ollama = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOllama",+ mock_chat_ollama,+ create=True,+ ):+ with patch.dict(+ "sys.modules",+ {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},+ ):+ # Call without specifying any params+ get_model()++ mock_chat_ollama.assert_called_once()+ call_kwargs = mock_chat_ollama.call_args.kwargs+ # Should use default model name+ assert call_kwargs["model"] == "mistral"+ # Should use default temperature+ assert call_kwargs["temperature"] == 0.7+ # Should use default max_tokens+ assert call_kwargs["max_tokens"] == 30000++ def test_kwargs_override_defaults(self):+ """Should allow kwargs to override default values."""+ mock_chat_ollama = Mock()+ with patch(+ "local_deep_research.utilities.llm_utils.ChatOllama",+ mock_chat_ollama,+ create=True,+ ):+ with patch.dict(+ "sys.modules",+ {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},+ ):+ get_model(+ DEFAULT_MODEL="custom-model",+ DEFAULT_MODEL_TYPE="ollama",+ DEFAULT_TEMPERATURE=0.3,+ MAX_TOKENS=10000,+ )++ call_kwargs = mock_chat_ollama.call_args.kwargs+ assert call_kwargs["model"] == "custom-model"+ assert call_kwargs["temperature"] == 0.3+ assert call_kwargs["max_tokens"] == 10000diff --git a/tests/utilities/test_log_utils.py b/tests/utilities/test_log_utils.pynew file mode 100644index 0000000000..420be9d4ef--- /dev/null+++ b/tests/utilities/test_log_utils.py@@ -0,0 +1,516 @@+"""Tests for log_utils module."""++import logging+import queue+import threading+from datetime import datetime+from unittest.mock import Mock, patch, MagicMock+++class TestInterceptHandler:+ """Tests for InterceptHandler class."""++ def test_emit_forwards_to_loguru(self):+ """Should forward log records to loguru."""+ from local_deep_research.utilities.log_utils import InterceptHandler++ handler = InterceptHandler()++ # Create a mock log record+ record = logging.LogRecord(+ name="test",+ level=logging.INFO,+ pathname="test.py",+ lineno=1,+ msg="Test message",+ args=(),+ exc_info=None,+ )++ with patch(+ "local_deep_research.utilities.log_utils.logger"+ ) as mock_logger:+ mock_logger.level.return_value = Mock(name="INFO")+ mock_opt = Mock()+ mock_logger.opt.return_value = mock_opt++ handler.emit(record)++ mock_logger.opt.assert_called()+ mock_opt.log.assert_called()++ def test_handles_unknown_level(self):+ """Should handle unknown log levels by using levelno."""+ from local_deep_research.utilities.log_utils import InterceptHandler++ handler = InterceptHandler()++ record = logging.LogRecord(+ name="test",+ level=35, # Non-standard level+ pathname="test.py",+ lineno=1,+ msg="Test",+ args=(),+ exc_info=None,+ )+ record.levelname = "CUSTOM"++ with patch(+ "local_deep_research.utilities.log_utils.logger"+ ) as mock_logger:+ mock_logger.level.side_effect = ValueError("Unknown level")+ mock_opt = Mock()+ mock_logger.opt.return_value = mock_opt++ handler.emit(record)++ mock_opt.log.assert_called()+++class TestLogForResearch:+ """Tests for log_for_research decorator."""++ def test_sets_research_id_in_g(self):+ """Should set research_id in Flask g object."""+ from local_deep_research.utilities.log_utils import log_for_research++ mock_g = MagicMock()++ @log_for_research+ def test_func(research_id):+ return "done"++ with patch("local_deep_research.utilities.log_utils.g", mock_g):+ test_func("test-uuid-123")++ # Check that research_id was set+ assert mock_g.research_id == "test-uuid-123"++ def test_removes_research_id_after_function(self):+ """Should remove research_id from g after function completes."""+ from local_deep_research.utilities.log_utils import log_for_research++ @log_for_research+ def test_func(research_id):+ return "result"++ mock_g = MagicMock()+ with patch("local_deep_research.utilities.log_utils.g", mock_g):+ test_func("uuid")++ mock_g.pop.assert_called_with("research_id")++ def test_preserves_function_metadata(self):+ """Should preserve function name and docstring."""+ from local_deep_research.utilities.log_utils import log_for_research++ @log_for_research+ def documented_func(research_id):+ """My documentation."""+ pass++ assert documented_func.__name__ == "documented_func"+ assert documented_func.__doc__ == "My documentation."++ def test_passes_args_and_kwargs(self):+ """Should pass arguments correctly."""+ from local_deep_research.utilities.log_utils import log_for_research++ @log_for_research+ def test_func(research_id, arg1, kwarg1=None):+ return (research_id, arg1, kwarg1)++ mock_g = MagicMock()+ with patch("local_deep_research.utilities.log_utils.g", mock_g):+ result = test_func("uuid", "value1", kwarg1="value2")++ assert result == ("uuid", "value1", "value2")+++class TestGetResearchId:+ """Tests for _get_research_id function."""++ def test_returns_none_when_not_set(self):+ """Should return None when no research_id is set."""+ from local_deep_research.utilities.log_utils import _get_research_id++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=False,+ ):+ result = _get_research_id()+ assert result is None++ def test_gets_from_record_extra(self):+ """Should get research_id from log record extra."""+ from local_deep_research.utilities.log_utils import _get_research_id++ record = {"extra": {"research_id": "record-uuid"}}++ result = _get_research_id(record)++ assert result == "record-uuid"++ def test_gets_from_flask_g(self):+ """Should get research_id from Flask g object."""+ from local_deep_research.utilities.log_utils import _get_research_id++ mock_g = Mock()+ mock_g.get.return_value = "flask-uuid"++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=True,+ ):+ with patch("local_deep_research.utilities.log_utils.g", mock_g):+ result = _get_research_id()++ assert result == "flask-uuid"++ def test_record_takes_priority_over_flask(self):+ """Record research_id should take priority over Flask g."""+ from local_deep_research.utilities.log_utils import _get_research_id++ record = {"extra": {"research_id": "record-uuid"}}++ mock_g = Mock()+ mock_g.get.return_value = "flask-uuid"++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=True,+ ):+ with patch("local_deep_research.utilities.log_utils.g", mock_g):+ result = _get_research_id(record)++ assert result == "record-uuid"+++class TestDatabaseSink:+ """Tests for database_sink function."""++ def test_creates_log_entry_dict(self):+ """Should create log entry dictionary from message."""+ from local_deep_research.utilities.log_utils import database_sink++ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "Test log message",+ "name": "test_module",+ "function": "test_function",+ "line": 42,+ "level": Mock(name="INFO"),+ "extra": {},+ }++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ database_sink(mock_message)++ # Should queue the log since we're not in app context+ mock_queue.put_nowait.assert_called_once()++ def test_queues_log_from_non_main_thread(self):+ """Should queue log when not in main thread."""+ from local_deep_research.utilities.log_utils import database_sink+ import local_deep_research.utilities.log_utils as module++ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "Test message",+ "name": "module",+ "function": "func",+ "line": 1,+ "level": Mock(name="DEBUG"),+ "extra": {"research_id": "test-uuid"},+ }++ # Mock has_app_context to return True but thread name is not MainThread+ mock_thread = Mock()+ mock_thread.name = "WorkerThread"++ with patch.object(module, "has_app_context", return_value=True):+ with patch.object(+ module, "_get_research_id", return_value="test-uuid"+ ):+ with patch.object(+ threading, "current_thread", return_value=mock_thread+ ):+ with patch.object(module, "_log_queue") as mock_queue:+ database_sink(mock_message)++ # Should queue since not MainThread+ mock_queue.put_nowait.assert_called_once()++ def test_handles_full_queue_gracefully(self):+ """Should not raise when queue is full."""+ from local_deep_research.utilities.log_utils import database_sink++ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "Test",+ "name": "mod",+ "function": "f",+ "line": 1,+ "level": Mock(name="INFO"),+ "extra": {},+ }++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ mock_queue.put_nowait.side_effect = queue.Full()++ # Should not raise+ database_sink(mock_message)+++class TestFrontendProgressSink:+ """Tests for frontend_progress_sink function."""++ def test_skips_when_no_research_id(self):+ """Should skip when no research_id is available."""+ from local_deep_research.utilities.log_utils import (+ frontend_progress_sink,+ )++ mock_message = Mock()+ mock_message.record = {+ "message": "Test",+ "level": Mock(name="INFO"),+ "time": Mock(isoformat=Mock(return_value="2024-01-01T00:00:00")),+ "extra": {},+ }++ with patch(+ "local_deep_research.utilities.log_utils._get_research_id",+ return_value=None,+ ):+ with patch(+ "local_deep_research.utilities.log_utils.SocketIOService"+ ) as mock_socket:+ frontend_progress_sink(mock_message)++ # Should not emit anything+ mock_socket.return_value.emit_to_subscribers.assert_not_called()++ def test_emits_to_subscribers_with_research_id(self):+ """Should emit to subscribers when research_id is present."""+ from local_deep_research.utilities.log_utils import (+ frontend_progress_sink,+ )++ mock_message = Mock()+ mock_message.record = {+ "message": "Progress update",+ "level": Mock(name="INFO"),+ "time": Mock(isoformat=Mock(return_value="2024-01-01T12:00:00")),+ "extra": {"research_id": "test-uuid"},+ }++ with patch(+ "local_deep_research.utilities.log_utils._get_research_id",+ return_value="test-uuid",+ ):+ with patch(+ "local_deep_research.utilities.log_utils.SocketIOService"+ ) as mock_socket:+ frontend_progress_sink(mock_message)++ mock_socket.return_value.emit_to_subscribers.assert_called_once()+ call_args = (+ mock_socket.return_value.emit_to_subscribers.call_args+ )+ assert call_args[0][0] == "progress"+ assert call_args[0][1] == "test-uuid"+++class TestFlushLogQueue:+ """Tests for flush_log_queue function."""++ def test_flushes_all_queued_logs(self):+ """Should flush all logs from queue."""+ from local_deep_research.utilities.log_utils import flush_log_queue++ log_entries = [+ {"message": "Log 1", "research_id": None},+ {"message": "Log 2", "research_id": None},+ ]++ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ mock_queue.empty.side_effect = [False, False, True]+ mock_queue.get_nowait.side_effect = log_entries + [queue.Empty()]++ with patch(+ "local_deep_research.utilities.log_utils._write_log_to_database"+ ) as mock_write:+ flush_log_queue()++ assert mock_write.call_count == 2++ def test_handles_empty_queue(self):+ """Should handle empty queue gracefully."""+ from local_deep_research.utilities.log_utils import flush_log_queue++ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ mock_queue.empty.return_value = True++ # Should not raise+ flush_log_queue()+++class TestConfigLogger:+ """Tests for config_logger function."""++ def test_configures_logger(self):+ """Should configure logger with sinks."""+ from local_deep_research.utilities.log_utils import config_logger++ with patch(+ "local_deep_research.utilities.log_utils.logger"+ ) as mock_logger:+ config_logger("test_app")++ mock_logger.enable.assert_called_with("local_deep_research")+ mock_logger.remove.assert_called_once()+ # Should add multiple sinks+ assert mock_logger.add.call_count >= 3++ def test_adds_file_logging_when_enabled(self):+ """Should add file logging when environment variable is set."""+ from local_deep_research.utilities.log_utils import config_logger++ with patch.dict("os.environ", {"LDR_ENABLE_FILE_LOGGING": "true"}):+ with patch(+ "local_deep_research.utilities.log_utils.logger"+ ) as mock_logger:+ config_logger("test_app")++ # Should add 4 sinks (stderr, database, frontend, file)+ assert mock_logger.add.call_count >= 4++ def test_creates_milestone_level(self):+ """Should create MILESTONE log level."""+ from local_deep_research.utilities.log_utils import config_logger++ with patch(+ "local_deep_research.utilities.log_utils.logger"+ ) as mock_logger:+ config_logger("test_app")++ mock_logger.level.assert_called()++ def test_handles_existing_milestone_level(self):+ """Should handle case where MILESTONE level already exists."""+ from local_deep_research.utilities.log_utils import config_logger++ with patch(+ "local_deep_research.utilities.log_utils.logger"+ ) as mock_logger:+ mock_logger.level.side_effect = ValueError("Level already exists")++ # Should not raise+ config_logger("test_app")+++class TestWriteLogToDatabase:+ """Tests for _write_log_to_database function."""++ def test_writes_research_log(self):+ """Should write ResearchLog to database."""+ from local_deep_research.utilities.log_utils import (+ _write_log_to_database,+ )++ log_entry = {+ "timestamp": datetime.now(),+ "message": "Test message",+ "module": "test_module",+ "function": "test_func",+ "line_no": 42,+ "level": "INFO",+ "research_id": "test-uuid",+ "username": "testuser",+ }++ mock_session = MagicMock()+ mock_cm = MagicMock()+ mock_cm.__enter__ = Mock(return_value=mock_session)+ mock_cm.__exit__ = Mock(return_value=None)++ with patch(+ "local_deep_research.database.session_context.get_user_db_session",+ return_value=mock_cm,+ ):+ _write_log_to_database(log_entry)++ mock_session.add.assert_called_once()+ mock_session.commit.assert_called_once()++ def test_handles_database_error_gracefully(self):+ """Should not raise on database errors."""+ from local_deep_research.utilities.log_utils import (+ _write_log_to_database,+ )++ log_entry = {+ "timestamp": datetime.now(),+ "message": "Test",+ "module": "mod",+ "function": "f",+ "line_no": 1,+ "level": "INFO",+ "research_id": None,+ "username": None,+ }++ with patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=Exception("DB error"),+ ):+ # Should not raise+ _write_log_to_database(log_entry)+++class TestLogQueue:+ """Tests for log queue functionality."""++ def test_queue_has_max_size(self):+ """Log queue should have a maximum size."""+ from local_deep_research.utilities.log_utils import _log_queue++ assert _log_queue.maxsize == 1000++ def test_stop_event_exists(self):+ """Stop event for queue processor should exist."""+ from local_deep_research.utilities.log_utils import _stop_queue++ assert isinstance(_stop_queue, threading.Event)+++class TestLogDir:+ """Tests for log directory configuration."""++ def test_log_dir_is_created(self):+ """Log directory should be created."""+ from local_deep_research.utilities.log_utils import _LOG_DIR++ # Should be a Path object+ assert hasattr(_LOG_DIR, "mkdir")diff --git a/tests/utilities/test_search_cache.py b/tests/utilities/test_search_cache.pynew file mode 100644index 0000000000..e8fbad83f5--- /dev/null+++ b/tests/utilities/test_search_cache.py@@ -0,0 +1,644 @@+"""+Comprehensive tests for search_cache module.+Tests caching, TTL, LRU eviction, stampede protection, and persistence.+"""++import pytest+import tempfile+import time+import threading+from unittest.mock import patch+from pathlib import Path+++class TestSearchCacheInit:+ """Tests for SearchCache initialization."""++ def test_init_with_defaults(self):+ """Test initialization with default parameters."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache = SearchCache(cache_dir=tmpdir)++ assert cache.max_memory_items == 1000+ assert cache.default_ttl == 3600++ def test_init_with_custom_params(self):+ """Test initialization with custom parameters."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache = SearchCache(+ cache_dir=tmpdir,+ max_memory_items=500,+ default_ttl=7200,+ )++ assert cache.max_memory_items == 500+ assert cache.default_ttl == 7200++ def test_creates_cache_directory(self):+ """Test that cache directory is created."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache_dir = Path(tmpdir) / "new_cache"+ SearchCache(cache_dir=str(cache_dir))++ assert cache_dir.exists()++ def test_creates_database_file(self):+ """Test that database file is created."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache = SearchCache(cache_dir=tmpdir)++ assert cache.db_path.exists()++ def test_initializes_empty_memory_cache(self):+ """Test that memory cache starts empty."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache = SearchCache(cache_dir=tmpdir)++ assert cache._memory_cache == {}+ assert cache._access_times == {}+++class TestSearchCacheNormalization:+ """Tests for query normalization."""++ @pytest.fixture+ def cache(self):+ """Create a SearchCache instance."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ yield SearchCache(cache_dir=tmpdir)++ def test_normalizes_to_lowercase(self, cache):+ """Test that queries are lowercased."""+ result = cache._normalize_query("HELLO WORLD")++ assert result == "hello world"++ def test_removes_extra_whitespace(self, cache):+ """Test that extra whitespace is removed."""+ result = cache._normalize_query("hello world")++ assert result == "hello world"++ def test_strips_leading_trailing_whitespace(self, cache):+ """Test that leading/trailing whitespace is stripped."""+ result = cache._normalize_query(" hello world ")++ assert result == "hello world"++ def test_removes_quotes(self, cache):+ """Test that quotes are removed."""+ result = cache._normalize_query("\"hello\" 'world'")++ assert result == "hello world"+++class TestSearchCacheHashing:+ """Tests for query hashing."""++ @pytest.fixture+ def cache(self):+ """Create a SearchCache instance."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ yield SearchCache(cache_dir=tmpdir)++ def test_same_query_same_hash(self, cache):+ """Test that same query produces same hash."""+ hash1 = cache._get_query_hash("test query")+ hash2 = cache._get_query_hash("test query")++ assert hash1 == hash2++ def test_different_queries_different_hashes(self, cache):+ """Test that different queries produce different hashes."""+ hash1 = cache._get_query_hash("query one")+ hash2 = cache._get_query_hash("query two")++ assert hash1 != hash2++ def test_normalized_queries_same_hash(self, cache):+ """Test that normalized equivalent queries have same hash."""+ hash1 = cache._get_query_hash("HELLO WORLD")+ hash2 = cache._get_query_hash("hello world")++ assert hash1 == hash2++ def test_different_engines_different_hashes(self, cache):+ """Test that different search engines produce different hashes."""+ hash1 = cache._get_query_hash("test", search_engine="google")+ hash2 = cache._get_query_hash("test", search_engine="bing")++ assert hash1 != hash2+++class TestSearchCachePutGet:+ """Tests for put and get operations."""++ @pytest.fixture+ def cache(self):+ """Create a SearchCache instance."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ yield SearchCache(cache_dir=tmpdir)++ def test_put_stores_results(self, cache):+ """Test that put stores results."""+ results = [{"title": "Test", "url": "https://test.com"}]++ success = cache.put("test query", results)++ assert success is True++ def test_get_retrieves_stored_results(self, cache):+ """Test that get retrieves stored results."""+ results = [{"title": "Test", "url": "https://test.com"}]+ cache.put("test query", results)++ retrieved = cache.get("test query")++ assert retrieved == results++ def test_get_returns_none_for_missing(self, cache):+ """Test that get returns None for missing queries."""+ result = cache.get("nonexistent query")++ assert result is None++ def test_put_rejects_empty_results(self, cache):+ """Test that empty results are not cached."""+ success = cache.put("test query", [])++ assert success is False++ def test_put_updates_existing_entry(self, cache):+ """Test that put updates existing entry."""+ results1 = [{"title": "First"}]+ results2 = [{"title": "Second"}]++ cache.put("test query", results1)+ cache.put("test query", results2)++ retrieved = cache.get("test query")+ assert retrieved == results2++ def test_get_uses_memory_cache_first(self, cache):+ """Test that get checks memory cache first."""+ results = [{"title": "Test"}]+ cache.put("test query", results)++ # Second get should use memory cache+ with patch.object(cache, "Session") as mock_session:+ retrieved = cache.get("test query")++ # Should not access database+ mock_session.assert_not_called()+ assert retrieved == results++ def test_custom_ttl(self, cache):+ """Test that custom TTL is respected."""+ results = [{"title": "Test"}]++ # Use very short TTL+ cache.put("test query", results, ttl=1)++ # Should be available immediately+ assert cache.get("test query") is not None++ # Wait for expiration+ time.sleep(1.5)++ # Clear memory cache to force DB check+ cache._memory_cache.clear()++ # Should be expired+ assert cache.get("test query") is None+++class TestSearchCacheExpiration:+ """Tests for cache expiration."""++ @pytest.fixture+ def cache(self):+ """Create a SearchCache instance with short TTL."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ yield SearchCache(cache_dir=tmpdir, default_ttl=1)++ def test_expired_entries_not_returned(self, cache):+ """Test that expired entries are not returned."""+ results = [{"title": "Test"}]+ cache.put("test query", results)++ # Wait for expiration+ time.sleep(1.5)++ # Clear memory cache to force DB check+ cache._memory_cache.clear()++ result = cache.get("test query")+ assert result is None++ def test_expired_memory_entries_removed(self, cache):+ """Test that expired memory entries are removed."""+ results = [{"title": "Test"}]+ cache.put("test query", results)++ # Wait for expiration+ time.sleep(1.5)++ # Access should remove expired entry from memory+ cache.get("test query")++ query_hash = cache._get_query_hash("test query")+ assert query_hash not in cache._memory_cache+++class TestSearchCacheLRUEviction:+ """Tests for LRU memory eviction."""++ def test_evicts_when_over_limit(self):+ """Test that LRU eviction occurs when over limit."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache = SearchCache(cache_dir=tmpdir, max_memory_items=5)++ # Add more items than limit+ for i in range(10):+ results = [{"title": f"Result {i}"}]+ cache.put(f"query {i}", results)++ # Memory cache should be limited+ assert (+ len(cache._memory_cache) <= 5 + 100+ ) # +100 for efficiency buffer+++class TestSearchCacheInvalidate:+ """Tests for cache invalidation."""++ @pytest.fixture+ def cache(self):+ """Create a SearchCache instance."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ yield SearchCache(cache_dir=tmpdir)++ def test_invalidate_removes_entry(self, cache):+ """Test that invalidate removes entry."""+ results = [{"title": "Test"}]+ cache.put("test query", results)++ cache.invalidate("test query")++ assert cache.get("test query") is None++ def test_invalidate_removes_from_memory(self, cache):+ """Test that invalidate removes from memory cache."""+ results = [{"title": "Test"}]+ cache.put("test query", results)++ cache.invalidate("test query")++ query_hash = cache._get_query_hash("test query")+ assert query_hash not in cache._memory_cache++ def test_invalidate_returns_true_if_found(self, cache):+ """Test that invalidate returns True if entry found."""+ results = [{"title": "Test"}]+ cache.put("test query", results)++ result = cache.invalidate("test query")++ assert result is True++ def test_invalidate_returns_false_if_not_found(self, cache):+ """Test that invalidate returns False if entry not found."""+ result = cache.invalidate("nonexistent query")++ assert result is False+++class TestSearchCacheClearAll:+ """Tests for clear_all operation."""++ @pytest.fixture+ def cache(self):+ """Create a SearchCache instance."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ yield SearchCache(cache_dir=tmpdir)++ def test_clear_all_removes_all_entries(self, cache):+ """Test that clear_all removes all entries."""+ cache.put("query 1", [{"title": "1"}])+ cache.put("query 2", [{"title": "2"}])++ cache.clear_all()++ assert cache.get("query 1") is None+ assert cache.get("query 2") is None++ def test_clear_all_empties_memory_cache(self, cache):+ """Test that clear_all empties memory cache."""+ cache.put("test query", [{"title": "Test"}])++ cache.clear_all()++ assert cache._memory_cache == {}+ assert cache._access_times == {}++ def test_clear_all_returns_true(self, cache):+ """Test that clear_all returns True on success."""+ result = cache.clear_all()++ assert result is True+++class TestSearchCacheStats:+ """Tests for cache statistics."""++ @pytest.fixture+ def cache(self):+ """Create a SearchCache instance."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ yield SearchCache(cache_dir=tmpdir)++ def test_stats_returns_dict(self, cache):+ """Test that stats returns a dictionary."""+ stats = cache.get_stats()++ assert isinstance(stats, dict)++ def test_stats_includes_required_keys(self, cache):+ """Test that stats includes required keys."""+ stats = cache.get_stats()++ assert "total_valid_entries" in stats+ assert "memory_cache_size" in stats++ def test_stats_reflects_cache_state(self, cache):+ """Test that stats reflect actual cache state."""+ cache.put("test query", [{"title": "Test"}])++ stats = cache.get_stats()++ assert stats["total_valid_entries"] >= 1+ assert stats["memory_cache_size"] >= 1+++class TestSearchCacheGetOrFetch:+ """Tests for get_or_fetch with stampede protection."""++ @pytest.fixture+ def cache(self):+ """Create a SearchCache instance."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ yield SearchCache(cache_dir=tmpdir)++ def test_returns_cached_if_available(self, cache):+ """Test that cached results are returned without fetching."""+ results = [{"title": "Cached"}]+ cache.put("test query", results)++ fetch_called = []++ def fetch_func():+ fetch_called.append(True)+ return [{"title": "Fetched"}]++ result = cache.get_or_fetch("test query", fetch_func)++ assert result == results+ assert len(fetch_called) == 0++ def test_calls_fetch_func_on_miss(self, cache):+ """Test that fetch_func is called on cache miss."""+ expected = [{"title": "Fetched"}]++ def fetch_func():+ return expected++ result = cache.get_or_fetch("test query", fetch_func)++ assert result == expected++ def test_caches_fetched_results(self, cache):+ """Test that fetched results are cached."""+ expected = [{"title": "Fetched"}]++ def fetch_func():+ return expected++ cache.get_or_fetch("test query", fetch_func)++ # Second call should use cache+ cached = cache.get("test query")+ assert cached == expected++ def test_handles_fetch_exception(self, cache):+ """Test that fetch exceptions are handled gracefully."""++ def fetch_func():+ raise Exception("Fetch failed")++ result = cache.get_or_fetch("test query", fetch_func)++ assert result is None++ def test_stampede_protection_single_fetch(self, cache):+ """Test that only one thread fetches during stampede."""+ fetch_count = []++ def slow_fetch():+ fetch_count.append(1)+ time.sleep(0.2)+ return [{"title": "Result"}]++ threads = []+ results = []++ def worker():+ result = cache.get_or_fetch("same query", slow_fetch)+ results.append(result)++ # Start multiple threads simultaneously+ for _ in range(5):+ t = threading.Thread(target=worker)+ threads.append(t)+ t.start()++ # Wait for all threads+ for t in threads:+ t.join(timeout=5)++ # All threads should get results+ assert len(results) == 5+ # But fetch should only be called once (or very few times due to race)+ assert len(fetch_count) <= 2+++class TestGlobalCacheInstance:+ """Tests for global cache singleton."""++ def test_get_search_cache_returns_instance(self):+ """Test that get_search_cache returns a SearchCache instance."""+ from local_deep_research.utilities.search_cache import (+ get_search_cache,+ SearchCache,+ )++ cache = get_search_cache()++ assert isinstance(cache, SearchCache)++ def test_get_search_cache_returns_same_instance(self):+ """Test that get_search_cache returns same instance."""+ from local_deep_research.utilities.search_cache import (+ get_search_cache,+ )++ cache1 = get_search_cache()+ cache2 = get_search_cache()++ assert cache1 is cache2+++class TestNormalizeEntityQuery:+ """Tests for normalize_entity_query function."""++ def test_normalizes_entity_and_constraint(self):+ """Test that entity and constraint are normalized."""+ from local_deep_research.utilities.search_cache import (+ normalize_entity_query,+ )++ result = normalize_entity_query("ENTITY NAME", "CONSTRAINT VALUE")++ assert result == "entity name constraint value"++ def test_removes_extra_whitespace(self):+ """Test that extra whitespace is removed."""+ from local_deep_research.utilities.search_cache import (+ normalize_entity_query,+ )++ result = normalize_entity_query("entity name", "constraint value")++ assert result == "entity name constraint value"++ def test_strips_values(self):+ """Test that values are stripped."""+ from local_deep_research.utilities.search_cache import (+ normalize_entity_query,+ )++ result = normalize_entity_query(" entity ", " constraint ")++ assert result == "entity constraint"++ def test_caches_results(self):+ """Test that results are cached via lru_cache."""+ from local_deep_research.utilities.search_cache import (+ normalize_entity_query,+ )++ # Clear cache+ normalize_entity_query.cache_clear()++ # First call+ normalize_entity_query("test", "value")++ # Check cache info+ cache_info = normalize_entity_query.cache_info()+ assert cache_info.misses == 1++ # Second call with same args+ normalize_entity_query("test", "value")++ cache_info = normalize_entity_query.cache_info()+ assert cache_info.hits == 1+++class TestSearchCacheEdgeCases:+ """Tests for edge cases and error handling."""++ def test_handles_special_characters_in_query(self):+ """Test handling of special characters in queries."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache = SearchCache(cache_dir=tmpdir)++ results = [{"title": "Test"}]+ query = "test & query with <special> 'chars'"++ cache.put(query, results)+ retrieved = cache.get(query)++ assert retrieved == results++ def test_handles_unicode_queries(self):+ """Test handling of unicode queries."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache = SearchCache(cache_dir=tmpdir)++ results = [{"title": "Test"}]+ query = "café naïve 日本語"++ cache.put(query, results)+ retrieved = cache.get(query)++ assert retrieved == results++ def test_handles_very_long_queries(self):+ """Test handling of very long queries."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache = SearchCache(cache_dir=tmpdir)++ results = [{"title": "Test"}]+ query = "x" * 10000++ cache.put(query, results)+ retrieved = cache.get(query)++ assert retrieved == results++ def test_handles_empty_query(self):+ """Test handling of empty query."""+ from local_deep_research.utilities.search_cache import SearchCache++ with tempfile.TemporaryDirectory() as tmpdir:+ cache = SearchCache(cache_dir=tmpdir)++ results = [{"title": "Test"}]++ cache.put("", results)+ retrieved = cache.get("")++ assert retrieved == resultsdiff --git a/tests/utilities/test_search_utilities.py b/tests/utilities/test_search_utilities.pynew file mode 100644index 0000000000..0706e27165--- /dev/null+++ b/tests/utilities/test_search_utilities.py@@ -0,0 +1,619 @@+"""+Comprehensive tests for search_utilities module.+Tests tag removal, link extraction, markdown formatting, and findings formatting.+"""++from unittest.mock import patch+++class TestLanguageCodeMap:+ """Tests for LANGUAGE_CODE_MAP constant."""++ def test_language_code_map_exists(self):+ """Test that LANGUAGE_CODE_MAP is defined."""+ from local_deep_research.utilities.search_utilities import (+ LANGUAGE_CODE_MAP,+ )++ assert LANGUAGE_CODE_MAP is not None+ assert isinstance(LANGUAGE_CODE_MAP, dict)++ def test_contains_common_languages(self):+ """Test that common languages are mapped."""+ from local_deep_research.utilities.search_utilities import (+ LANGUAGE_CODE_MAP,+ )++ assert LANGUAGE_CODE_MAP["english"] == "en"+ assert LANGUAGE_CODE_MAP["french"] == "fr"+ assert LANGUAGE_CODE_MAP["german"] == "de"+ assert LANGUAGE_CODE_MAP["spanish"] == "es"++ def test_contains_asian_languages(self):+ """Test that Asian languages are mapped."""+ from local_deep_research.utilities.search_utilities import (+ LANGUAGE_CODE_MAP,+ )++ assert LANGUAGE_CODE_MAP["japanese"] == "ja"+ assert LANGUAGE_CODE_MAP["chinese"] == "zh"+++class TestRemoveThinkTags:+ """Tests for remove_think_tags function."""++ def test_removes_paired_think_tags(self):+ """Test removal of paired <think>...</think> tags."""+ from local_deep_research.utilities.search_utilities import (+ remove_think_tags,+ )++ text = "Hello <think>internal thoughts</think> World"+ result = remove_think_tags(text)++ assert result == "Hello World"+ assert "<think>" not in result+ assert "</think>" not in result++ def test_removes_multiline_think_tags(self):+ """Test removal of multiline think tags."""+ from local_deep_research.utilities.search_utilities import (+ remove_think_tags,+ )++ text = "Start <think>\nLine 1\nLine 2\n</think> End"+ result = remove_think_tags(text)++ assert result == "Start End"++ def test_removes_multiple_think_tags(self):+ """Test removal of multiple think tag pairs."""+ from local_deep_research.utilities.search_utilities import (+ remove_think_tags,+ )++ text = "A <think>x</think> B <think>y</think> C"+ result = remove_think_tags(text)++ assert result == "A B C"++ def test_removes_orphaned_opening_tag(self):+ """Test removal of orphaned opening think tag."""+ from local_deep_research.utilities.search_utilities import (+ remove_think_tags,+ )++ text = "Hello <think> World"+ result = remove_think_tags(text)++ assert "<think>" not in result++ def test_removes_orphaned_closing_tag(self):+ """Test removal of orphaned closing think tag."""+ from local_deep_research.utilities.search_utilities import (+ remove_think_tags,+ )++ text = "Hello </think> World"+ result = remove_think_tags(text)++ assert "</think>" not in result++ def test_strips_whitespace(self):+ """Test that result is stripped of leading/trailing whitespace."""+ from local_deep_research.utilities.search_utilities import (+ remove_think_tags,+ )++ text = " <think>thoughts</think> Content "+ result = remove_think_tags(text)++ assert result == "Content"++ def test_handles_empty_think_tags(self):+ """Test handling of empty think tags."""+ from local_deep_research.utilities.search_utilities import (+ remove_think_tags,+ )++ text = "Hello <think></think> World"+ result = remove_think_tags(text)++ assert result == "Hello World"++ def test_handles_text_without_think_tags(self):+ """Test that text without think tags is unchanged."""+ from local_deep_research.utilities.search_utilities import (+ remove_think_tags,+ )++ text = "Hello World"+ result = remove_think_tags(text)++ assert result == "Hello World"++ def test_handles_empty_string(self):+ """Test handling of empty string."""+ from local_deep_research.utilities.search_utilities import (+ remove_think_tags,+ )++ result = remove_think_tags("")++ assert result == ""+++class TestExtractLinksFromSearchResults:+ """Tests for extract_links_from_search_results function."""++ def test_extracts_links_from_valid_results(self, sample_search_results):+ """Test extraction from valid search results."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ links = extract_links_from_search_results(sample_search_results)++ assert len(links) == 3+ assert links[0]["title"] == "First Article"+ assert links[0]["url"] == "https://example.com/article1"++ def test_returns_empty_list_for_none(self):+ """Test that None input returns empty list."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ links = extract_links_from_search_results(None)++ assert links == []++ def test_returns_empty_list_for_empty_list(self):+ """Test that empty list returns empty list."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ links = extract_links_from_search_results([])++ assert links == []++ def test_extracts_index(self, sample_search_results):+ """Test that index is extracted."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ links = extract_links_from_search_results(sample_search_results)++ assert links[0]["index"] == "1"+ assert links[1]["index"] == "2"++ def test_handles_none_title(self):+ """Test handling of None title."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ results = [{"title": None, "link": "https://example.com"}]+ links = extract_links_from_search_results(results)++ # Should skip results with None title+ assert links == []++ def test_handles_none_link(self):+ """Test handling of None link."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ results = [{"title": "Test", "link": None}]+ links = extract_links_from_search_results(results)++ # Should skip results with None link+ assert links == []++ def test_handles_missing_title(self):+ """Test handling of missing title key."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ results = [{"link": "https://example.com"}]+ links = extract_links_from_search_results(results)++ # Should skip results without title+ assert links == []++ def test_handles_missing_link(self):+ """Test handling of missing link key."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ results = [{"title": "Test"}]+ links = extract_links_from_search_results(results)++ # Should skip results without link+ assert links == []++ def test_strips_whitespace_from_values(self):+ """Test that whitespace is stripped from values."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ results = [+ {"title": " Test Title ", "link": " https://example.com "}+ ]+ links = extract_links_from_search_results(results)++ assert links[0]["title"] == "Test Title"+ assert links[0]["url"] == "https://example.com"++ def test_handles_missing_index(self):+ """Test handling of missing index key."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ results = [{"title": "Test", "link": "https://example.com"}]+ links = extract_links_from_search_results(results)++ assert links[0]["index"] == ""++ def test_skips_invalid_results(self):+ """Test that invalid results are skipped."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ results = [+ {"title": "Valid", "link": "https://example.com"},+ {"title": "", "link": ""}, # Empty - should skip+ {"title": "Also Valid", "link": "https://test.com"},+ ]+ links = extract_links_from_search_results(results)++ assert len(links) == 2+++class TestFormatLinksToMarkdown:+ """Tests for format_links_to_markdown function."""++ def test_formats_links_with_indices(self):+ """Test formatting links with indices."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {+ "title": "Test Article",+ "url": "https://example.com",+ "index": "1",+ }+ ]+ result = format_links_to_markdown(links)++ assert "[1]" in result+ assert "Test Article" in result+ assert "https://example.com" in result++ def test_deduplicates_urls(self, sample_search_results_with_duplicates):+ """Test that duplicate URLs are deduplicated."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ format_links_to_markdown,+ )++ links = extract_links_from_search_results(+ sample_search_results_with_duplicates+ )+ result = format_links_to_markdown(links)++ # Count URL occurrences+ url_count = result.count("https://example.com/article1")+ # Should appear only once (deduplicated)+ assert url_count == 1++ def test_groups_indices_for_same_url(self):+ """Test that indices are grouped for same URL."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {"title": "Article", "url": "https://example.com", "index": "1"},+ {"title": "Article", "url": "https://example.com", "index": "3"},+ ]+ result = format_links_to_markdown(links)++ # Should have grouped indices [1, 3]+ assert "[1, 3]" in result++ def test_returns_empty_string_for_empty_list(self):+ """Test that empty list returns empty string."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ result = format_links_to_markdown([])++ assert result == ""++ def test_handles_link_key_fallback(self):+ """Test that 'link' key is used as fallback for 'url'."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [{"title": "Test", "link": "https://example.com", "index": "1"}]+ result = format_links_to_markdown(links)++ assert "https://example.com" in result++ def test_uses_untitled_for_missing_title(self):+ """Test that 'Untitled' is used for missing title."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [{"url": "https://example.com", "index": "1"}]+ result = format_links_to_markdown(links)++ assert "Untitled" in result++ def test_includes_source_nr_fallback(self):+ """Test that source nr is included for accessibility."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [{"title": "Test", "url": "https://example.com", "index": "1"}]+ result = format_links_to_markdown(links)++ assert "source nr:" in result+++class TestFormatFindings:+ """Tests for format_findings function."""++ def test_includes_synthesized_content(+ self, sample_findings, sample_questions_by_iteration+ ):+ """Test that synthesized content is included."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings(+ sample_findings,+ "This is the synthesis.",+ sample_questions_by_iteration,+ )++ assert "This is the synthesis." in result++ def test_includes_search_questions_section(+ self, sample_findings, sample_questions_by_iteration+ ):+ """Test that search questions section is included."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings(+ sample_findings, "Synthesis", sample_questions_by_iteration+ )++ assert "SEARCH QUESTIONS BY ITERATION" in result+ assert "What is the main topic?" in result++ def test_includes_detailed_findings_section(+ self, sample_findings, sample_questions_by_iteration+ ):+ """Test that detailed findings section is included."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings(+ sample_findings, "Synthesis", sample_questions_by_iteration+ )++ assert "DETAILED FINDINGS" in result++ def test_includes_all_sources_section(+ self, sample_findings, sample_questions_by_iteration+ ):+ """Test that all sources section is included."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings(+ sample_findings, "Synthesis", sample_questions_by_iteration+ )++ assert "ALL SOURCES" in result++ def test_formats_followup_phases(+ self, sample_findings, sample_questions_by_iteration+ ):+ """Test formatting of Follow-up phases."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings(+ sample_findings, "Synthesis", sample_questions_by_iteration+ )++ # Should include the follow-up phase header+ assert "Follow-up Iteration 1.1" in result++ def test_formats_subquery_phases(+ self, sample_findings_with_subquery, subquery_questions+ ):+ """Test formatting of Sub-query phases (IterDRAG)."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings(+ sample_findings_with_subquery, "Synthesis", subquery_questions+ )++ # Should include sub-query content+ assert "Content for sub-query 1" in result++ def test_handles_empty_findings(self, sample_questions_by_iteration):+ """Test handling of empty findings list."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings([], "Synthesis", sample_questions_by_iteration)++ # Should still include synthesis+ assert "Synthesis" in result+ # Should not have detailed findings section+ assert "DETAILED FINDINGS" not in result++ def test_handles_empty_questions(self, sample_findings):+ """Test handling of empty questions dictionary."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings(sample_findings, "Synthesis", {})++ # Should still include synthesis and findings+ assert "Synthesis" in result+ # Should not have questions section+ assert "SEARCH QUESTIONS BY ITERATION" not in result++ def test_extracts_sources_from_findings(+ self, sample_findings, sample_questions_by_iteration+ ):+ """Test that sources are extracted from findings."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings(+ sample_findings, "Synthesis", sample_questions_by_iteration+ )++ assert "source1.com" in result++ def test_handles_finding_with_question(self):+ """Test handling of finding with embedded question."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [+ {+ "phase": "Search",+ "content": "Content",+ "question": "What is the answer?",+ "search_results": [],+ }+ ]++ result = format_findings(findings, "Synthesis", {})++ assert "SEARCH QUESTION:" in result+ assert "What is the answer?" in result+++class TestPrintSearchResults:+ """Tests for print_search_results function."""++ def test_logs_formatted_results(self, sample_search_results):+ """Test that results are logged."""+ from local_deep_research.utilities.search_utilities import (+ print_search_results,+ )++ with patch(+ "local_deep_research.utilities.search_utilities.logger"+ ) as mock_logger:+ print_search_results(sample_search_results)++ mock_logger.info.assert_called()++ def test_handles_empty_results(self):+ """Test handling of empty results."""+ from local_deep_research.utilities.search_utilities import (+ print_search_results,+ )++ with patch(+ "local_deep_research.utilities.search_utilities.logger"+ ) as mock_logger:+ print_search_results([])++ # Should still call logger (with empty string)+ mock_logger.info.assert_called()+++class TestEdgeCases:+ """Tests for edge cases and error handling."""++ def test_extract_links_handles_exception(self):+ """Test that extract_links handles exceptions gracefully."""+ from local_deep_research.utilities.search_utilities import (+ extract_links_from_search_results,+ )++ # Create a result that could cause issues+ results = [+ {"title": "Valid", "link": "https://example.com"},+ object(), # This would cause an error+ {"title": "Also Valid", "link": "https://test.com"},+ ]++ # Should not raise, should skip problematic items+ with patch("local_deep_research.utilities.search_utilities.logger"):+ links = extract_links_from_search_results(results)+ # Should get at least some valid results+ assert len(links) >= 0++ def test_format_findings_handles_none_search_results(self):+ """Test that format_findings handles None search_results."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [+ {+ "phase": "Test",+ "content": "Content",+ "search_results": None, # None instead of list+ }+ ]++ # Should not raise+ result = format_findings(findings, "Synthesis", {})+ assert "Content" in result++ def test_format_findings_handles_malformed_phase(self):+ """Test that format_findings handles malformed phase strings."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [+ {+ "phase": "Follow-up Iteration X.Y", # Malformed - not numbers+ "content": "Content",+ "search_results": [],+ }+ ]++ # Should not raise+ result = format_findings(findings, "Synthesis", {1: ["Question"]})+ assert "Content" in resultdiff --git a/tests/utilities/test_thread_context.py b/tests/utilities/test_thread_context.pynew file mode 100644index 0000000000..c4ecdb0b54--- /dev/null+++ b/tests/utilities/test_thread_context.py@@ -0,0 +1,333 @@+"""Tests for thread_context module."""++import threading+from concurrent.futures import ThreadPoolExecutor+from unittest.mock import patch+++from local_deep_research.utilities.thread_context import (+ _g_thread_data,+ get_search_context,+ preserve_research_context,+ set_search_context,+)+++class TestSetSearchContext:+ """Tests for set_search_context function."""++ def setup_method(self):+ """Clear thread-local data before each test."""+ if hasattr(_g_thread_data, "context"):+ delattr(_g_thread_data, "context")++ def test_sets_context(self):+ """Should set context in thread-local storage."""+ context = {"research_id": "123", "user": "test"}+ set_search_context(context)+ assert hasattr(_g_thread_data, "context")+ assert _g_thread_data.context == context++ def test_copies_context(self):+ """Should copy context to avoid mutations."""+ context = {"research_id": "123"}+ set_search_context(context)+ context["new_key"] = "value"+ assert "new_key" not in _g_thread_data.context++ def test_overwrites_existing_context(self):+ """Should overwrite existing context."""+ set_search_context({"old": "context"})+ set_search_context({"new": "context"})+ assert _g_thread_data.context == {"new": "context"}++ def test_logs_warning_on_overwrite(self):+ """Should log warning when overwriting existing context."""+ set_search_context({"first": "context"})+ with patch(+ "local_deep_research.utilities.thread_context.logger"+ ) as mock_logger:+ set_search_context({"second": "context"})+ mock_logger.warning.assert_called_once()++ def test_handles_empty_context(self):+ """Should handle empty context dictionary."""+ set_search_context({})+ assert _g_thread_data.context == {}+++class TestGetSearchContext:+ """Tests for get_search_context function."""++ def setup_method(self):+ """Clear thread-local data before each test."""+ if hasattr(_g_thread_data, "context"):+ delattr(_g_thread_data, "context")++ def test_returns_none_when_not_set(self):+ """Should return None when no context is set."""+ result = get_search_context()+ assert result is None++ def test_returns_context_when_set(self):+ """Should return context when set."""+ context = {"research_id": "456"}+ set_search_context(context)+ result = get_search_context()+ assert result == context++ def test_returns_copy_of_context(self):+ """Should return a copy to prevent mutations."""+ context = {"research_id": "789"}+ set_search_context(context)+ result = get_search_context()+ result["mutated"] = True+ # Original should not be mutated+ assert "mutated" not in _g_thread_data.context++ def test_multiple_calls_return_same_data(self):+ """Multiple calls should return same data."""+ context = {"key": "value"}+ set_search_context(context)+ result1 = get_search_context()+ result2 = get_search_context()+ assert result1 == result2+++class TestThreadIsolation:+ """Tests for thread isolation of context."""++ def setup_method(self):+ """Clear thread-local data before each test."""+ if hasattr(_g_thread_data, "context"):+ delattr(_g_thread_data, "context")++ def test_context_isolated_between_threads(self):+ """Context should be isolated between threads."""+ main_context = {"thread": "main"}+ set_search_context(main_context)++ other_thread_context = []++ def other_thread():+ other_thread_context.append(get_search_context())++ thread = threading.Thread(target=other_thread)+ thread.start()+ thread.join()++ # Other thread should not see main thread's context+ assert other_thread_context[0] is None++ def test_each_thread_has_own_context(self):+ """Each thread should have its own context."""+ results = {}++ def thread_worker(thread_id):+ set_search_context({"thread_id": thread_id})+ # Small delay to allow interleaving+ import time++ time.sleep(0.01)+ ctx = get_search_context()+ results[thread_id] = ctx["thread_id"] if ctx else None++ threads = []+ for i in range(5):+ t = threading.Thread(target=thread_worker, args=(i,))+ threads.append(t)+ t.start()++ for t in threads:+ t.join()++ # Each thread should have preserved its own context+ for i in range(5):+ assert results[i] == i+++class TestPreserveResearchContext:+ """Tests for preserve_research_context decorator."""++ def setup_method(self):+ """Clear thread-local data before each test."""+ if hasattr(_g_thread_data, "context"):+ delattr(_g_thread_data, "context")++ def test_preserves_context_in_thread_pool(self):+ """Should preserve context when function runs in thread pool."""+ context = {"research_id": "pool-test"}+ set_search_context(context)++ captured_context = []++ @preserve_research_context+ def worker():+ captured_context.append(get_search_context())+ return "done"++ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(worker)+ future.result()++ assert len(captured_context) == 1+ assert captured_context[0] == context++ def test_works_without_context(self):+ """Should work when no context is set."""+ captured_context = []++ @preserve_research_context+ def worker():+ captured_context.append(get_search_context())+ return "done"++ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(worker)+ future.result()++ # Should not fail, context should be None+ assert len(captured_context) == 1+ assert captured_context[0] is None++ def test_preserves_function_metadata(self):+ """Should preserve function name and docstring."""++ @preserve_research_context+ def my_function():+ """My docstring."""+ pass++ assert my_function.__name__ == "my_function"+ assert my_function.__doc__ == "My docstring."++ def test_passes_arguments_correctly(self):+ """Should pass arguments to wrapped function."""+ context = {"research_id": "arg-test"}+ set_search_context(context)++ @preserve_research_context+ def worker(a, b, c=None):+ return (a, b, c)++ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(worker, 1, 2, c=3)+ result = future.result()++ assert result == (1, 2, 3)++ def test_returns_function_result(self):+ """Should return the wrapped function's result."""+ context = {"research_id": "return-test"}+ set_search_context(context)++ @preserve_research_context+ def worker():+ return {"result": "success"}++ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(worker)+ result = future.result()++ assert result == {"result": "success"}++ def test_preserves_context_across_multiple_calls(self):+ """Should preserve context for multiple calls."""+ context = {"research_id": "multi-call"}+ set_search_context(context)++ results = []++ @preserve_research_context+ def worker(idx):+ ctx = get_search_context()+ return (idx, ctx["research_id"] if ctx else None)++ with ThreadPoolExecutor(max_workers=2) as executor:+ futures = [executor.submit(worker, i) for i in range(3)]+ results = [f.result() for f in futures]++ for idx, research_id in results:+ assert research_id == "multi-call"+++class TestGetSearchTrackerIfNeeded:+ """Tests for _get_search_tracker_if_needed function."""++ def test_returns_none_on_import_error(self):+ """Should return None when import fails."""++ # Reset the cached tracker+ import local_deep_research.utilities.thread_context as tc++ tc._search_tracker = None++ with patch.dict(+ "sys.modules", {"local_deep_research.metrics.search_tracker": None}+ ):+ with patch("local_deep_research.utilities.thread_context.logger"):+ # Force import error by patching the import+ def raise_import_error(*args, **kwargs):+ raise ImportError("Test error")++ with patch.object(+ tc,+ "_get_search_tracker_if_needed",+ side_effect=raise_import_error,+ ):+ pass # The function would return None on error++ def test_caches_tracker_instance(self):+ """Should cache the tracker instance after first call."""+ import local_deep_research.utilities.thread_context as tc++ # Reset+ tc._search_tracker = None++ object()++ with patch("local_deep_research.utilities.thread_context.logger"):+ with patch.dict("sys.modules"):+ # Just verify it doesn't crash+ # Full integration test would need database+ pass+++class TestEdgeCases:+ """Edge case tests for thread_context module."""++ def setup_method(self):+ """Clear thread-local data before each test."""+ if hasattr(_g_thread_data, "context"):+ delattr(_g_thread_data, "context")++ def test_context_with_nested_dict(self):+ """Should handle nested dictionaries in context."""+ context = {+ "research_id": "nested",+ "metadata": {"key1": "value1", "key2": {"nested": "value"}},+ }+ set_search_context(context)+ result = get_search_context()+ assert result["metadata"]["key2"]["nested"] == "value"++ def test_context_with_list_values(self):+ """Should handle lists in context."""+ context = {"items": [1, 2, 3], "tags": ["a", "b", "c"]}+ set_search_context(context)+ result = get_search_context()+ assert result["items"] == [1, 2, 3]++ def test_context_with_none_values(self):+ """Should handle None values in context."""+ context = {"research_id": "test", "optional": None}+ set_search_context(context)+ result = get_search_context()+ assert result["optional"] is None++ def test_rapid_set_get_cycles(self):+ """Should handle rapid set/get cycles."""+ for i in range(100):+ set_search_context({"iteration": i})+ result = get_search_context()+ assert result["iteration"] == idiff --git a/tests/utilities/test_threading_utils.py b/tests/utilities/test_threading_utils.pynew file mode 100644index 0000000000..15323416fd--- /dev/null+++ b/tests/utilities/test_threading_utils.py@@ -0,0 +1,422 @@+"""Tests for threading_utils module."""++from concurrent.futures import ThreadPoolExecutor+from unittest.mock import MagicMock, Mock, patch++import pytest++from local_deep_research.utilities.threading_utils import (+ g_thread_local_store,+ thread_context,+ thread_specific_cache,+ thread_with_app_context,+)+++class TestThreadSpecificCache:+ """Tests for thread_specific_cache decorator."""++ def setup_method(self):+ """Clear thread-local data before each test."""+ if hasattr(g_thread_local_store, "thread_id"):+ delattr(g_thread_local_store, "thread_id")++ def test_caches_result_in_same_thread(self):+ """Should cache results within the same thread."""+ call_count = 0++ @thread_specific_cache({})+ def expensive_func(x):+ nonlocal call_count+ call_count += 1+ return x * 2++ # First call+ result1 = expensive_func(5)+ # Second call with same arg+ result2 = expensive_func(5)++ assert result1 == 10+ assert result2 == 10+ assert call_count == 1 # Should only be called once++ def test_different_args_not_cached(self):+ """Different arguments should not use cached result."""+ call_count = 0++ @thread_specific_cache({})+ def func(x):+ nonlocal call_count+ call_count += 1+ return x * 2++ result1 = func(5)+ result2 = func(10)++ assert result1 == 10+ assert result2 == 20+ assert call_count == 2++ def test_cache_isolated_between_threads(self):+ """Cache should be isolated between threads."""+ call_counts = {"main": 0, "other": 0}++ @thread_specific_cache({})+ def func(thread_name, x):+ call_counts[thread_name] += 1+ return x * 2++ # Call in main thread+ result_main = func("main", 5)++ # Call in other thread with same args+ def other_thread():+ return func("other", 5)++ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(other_thread)+ result_other = future.result()++ assert result_main == 10+ assert result_other == 10+ # Both threads should have called the function+ assert call_counts["main"] == 1+ assert call_counts["other"] == 1++ def test_assigns_unique_thread_id(self):+ """Should assign unique thread ID to each thread."""+ thread_ids = []++ @thread_specific_cache({})+ def func():+ thread_ids.append(g_thread_local_store.thread_id)+ return "done"++ func()+ main_id = g_thread_local_store.thread_id++ def other_thread():+ func()+ return g_thread_local_store.thread_id++ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(other_thread)+ other_id = future.result()++ assert main_id != other_id++ def test_reuses_thread_id_within_thread(self):+ """Should reuse same thread ID for multiple calls in same thread."""++ @thread_specific_cache({})+ def func(x):+ return x++ func(1)+ id1 = g_thread_local_store.thread_id+ func(2)+ id2 = g_thread_local_store.thread_id++ assert id1 == id2++ def test_handles_kwargs(self):+ """Should properly handle keyword arguments."""+ call_count = 0++ @thread_specific_cache({})+ def func(a, b=None):+ nonlocal call_count+ call_count += 1+ return (a, b)++ result1 = func(1, b=2)+ result2 = func(1, b=2)++ assert result1 == (1, 2)+ assert result2 == (1, 2)+ assert call_count == 1+++class TestThreadWithAppContext:+ """Tests for thread_with_app_context decorator."""++ def test_runs_with_app_context(self):+ """Should run function within provided app context."""+ mock_context = MagicMock()+ mock_context.__enter__ = Mock(return_value=None)+ mock_context.__exit__ = Mock(return_value=None)++ @thread_with_app_context+ def my_func(x):+ return x * 2++ result = my_func(mock_context, 5)++ assert result == 10+ mock_context.__enter__.assert_called_once()+ mock_context.__exit__.assert_called_once()++ def test_runs_without_context_when_none(self):+ """Should run function normally when context is None."""++ @thread_with_app_context+ def my_func(x):+ return x * 3++ result = my_func(None, 7)++ assert result == 21++ def test_preserves_function_metadata(self):+ """Should preserve function name and docstring."""++ @thread_with_app_context+ def documented_func():+ """My documentation."""+ pass++ assert documented_func.__name__ == "documented_func"+ assert documented_func.__doc__ == "My documentation."++ def test_passes_args_correctly(self):+ """Should pass arguments correctly to wrapped function."""+ mock_context = MagicMock()+ mock_context.__enter__ = Mock(return_value=None)+ mock_context.__exit__ = Mock(return_value=None)++ @thread_with_app_context+ def func(a, b, c=None):+ return (a, b, c)++ result = func(mock_context, "x", "y", c="z")++ assert result == ("x", "y", "z")++ def test_context_manager_properly_exited_on_exception(self):+ """Context manager should be properly exited even on exception."""+ mock_context = MagicMock()+ mock_context.__enter__ = Mock(return_value=None)+ mock_context.__exit__ = Mock(return_value=False)++ @thread_with_app_context+ def failing_func():+ raise ValueError("Test error")++ with pytest.raises(ValueError, match="Test error"):+ failing_func(mock_context)++ mock_context.__exit__.assert_called_once()+++class TestThreadContext:+ """Tests for thread_context function."""++ def test_returns_none_without_flask_context(self):+ """Should return None when no Flask app context is active."""+ import local_deep_research.utilities.threading_utils as module++ mock_app = Mock()+ mock_app.app_context.side_effect = RuntimeError("No context")++ with patch.object(module, "current_app", mock_app):+ with patch.object(module, "g", Mock()):+ result = thread_context()++ assert result is None++ def test_returns_app_context_when_available(self):+ """Should return app context when Flask context is active."""+ import local_deep_research.utilities.threading_utils as module++ mock_context = MagicMock()+ mock_context.__enter__ = Mock(return_value=None)+ mock_context.__exit__ = Mock(return_value=None)++ mock_app = Mock()+ mock_app.app_context.return_value = mock_context++ mock_g = Mock()+ mock_g.__iter__ = Mock(return_value=iter([]))++ with patch.object(module, "current_app", mock_app):+ with patch.object(module, "g", mock_g):+ result = thread_context()++ assert result == mock_context++ def test_copies_global_data(self):+ """Should copy global data from current context."""+ import local_deep_research.utilities.threading_utils as module++ mock_context = MagicMock()+ mock_context.__enter__ = Mock(return_value=None)+ mock_context.__exit__ = Mock(return_value=None)++ mock_app = Mock()+ mock_app.app_context.return_value = mock_context++ mock_g = Mock()+ mock_g.__iter__ = Mock(return_value=iter(["user_id", "settings"]))+ mock_g.get = Mock(+ side_effect=lambda k: {"user_id": 123, "settings": {"a": 1}}[k]+ )++ with patch.object(module, "current_app", mock_app):+ with patch.object(module, "g", mock_g):+ thread_context()++ # Should have iterated over g+ mock_g.__iter__.assert_called()++ def test_handles_type_error_on_g_iteration(self):+ """Should handle TypeError when g is not iterable."""+ import local_deep_research.utilities.threading_utils as module++ mock_context = MagicMock()+ mock_context.__enter__ = Mock(return_value=None)+ mock_context.__exit__ = Mock(return_value=None)++ mock_app = Mock()+ mock_app.app_context.return_value = mock_context++ mock_g = Mock()+ mock_g.__iter__ = Mock(side_effect=TypeError("Not iterable"))++ with patch.object(module, "current_app", mock_app):+ with patch.object(module, "g", mock_g):+ # Should not raise, should return context+ result = thread_context()++ assert result == mock_context++ def test_logs_debug_when_no_context(self):+ """Should log debug message when no app context available."""+ import local_deep_research.utilities.threading_utils as module++ mock_app = Mock()+ mock_app.app_context.side_effect = RuntimeError("No context")++ with patch.object(module, "current_app", mock_app):+ with patch.object(module, "g", Mock()):+ with patch.object(module, "logger") as mock_logger:+ thread_context()++ mock_logger.debug.assert_called()+++class TestIntegration:+ """Integration tests for threading utilities."""++ def test_thread_specific_cache_with_thread_context(self):+ """Should work correctly with thread context propagation."""+ call_count = 0++ @thread_specific_cache({})+ def cached_func(x):+ nonlocal call_count+ call_count += 1+ return x * 2++ # Main thread calls+ cached_func(5)+ cached_func(5) # Should use cache++ results = []++ def worker():+ # Worker thread should have its own cache+ return cached_func(5)++ with ThreadPoolExecutor(max_workers=2) as executor:+ futures = [executor.submit(worker) for _ in range(3)]+ results = [f.result() for f in futures]++ # All results should be correct+ assert all(r == 10 for r in results)+ # Main thread called once, each worker thread called once+ # (some workers may share thread due to pool reuse)+ assert call_count >= 2 # At minimum: main + 1 worker++ def test_thread_with_app_context_in_thread_pool(self):+ """Should properly inject app context in thread pool."""+ results = []++ @thread_with_app_context+ def worker(value):+ return value * 2++ mock_context = MagicMock()+ mock_context.__enter__ = Mock(return_value=None)+ mock_context.__exit__ = Mock(return_value=None)++ with ThreadPoolExecutor(max_workers=2) as executor:+ futures = [+ executor.submit(worker, mock_context, i) for i in range(5)+ ]+ results = [f.result() for f in futures]++ assert results == [0, 2, 4, 6, 8]+++class TestEdgeCases:+ """Edge case tests for threading utilities."""++ def setup_method(self):+ """Clear thread-local data before each test."""+ if hasattr(g_thread_local_store, "thread_id"):+ delattr(g_thread_local_store, "thread_id")++ def test_thread_specific_cache_with_unhashable_args(self):+ """Should raise error for unhashable arguments."""++ @thread_specific_cache({})+ def func(x):+ return x++ # Lists are unhashable+ with pytest.raises(TypeError):+ func([1, 2, 3])++ def test_thread_specific_cache_with_none_arg(self):+ """Should handle None arguments correctly."""+ call_count = 0++ @thread_specific_cache({})+ def func(x):+ nonlocal call_count+ call_count += 1+ return x is None++ result1 = func(None)+ result2 = func(None)++ assert result1 is True+ assert result2 is True+ assert call_count == 1++ def test_nested_decorators(self):+ """Should work with other decorators."""+ from functools import wraps++ def logging_decorator(func):+ @wraps(func)+ def wrapper(*args, **kwargs):+ return func(*args, **kwargs)++ return wrapper++ call_count = 0++ @logging_decorator+ @thread_specific_cache({})+ def func(x):+ nonlocal call_count+ call_count += 1+ return x++ result1 = func(5)+ result2 = func(5)++ assert result1 == 5+ assert result2 == 5+ assert call_count == 1diff --git a/tests/utilities/test_url_utils.py b/tests/utilities/test_url_utils.pynew file mode 100644index 0000000000..4dc7dcf3e4--- /dev/null+++ b/tests/utilities/test_url_utils.py@@ -0,0 +1,177 @@+"""Tests for url_utils module."""++import pytest++from local_deep_research.utilities.url_utils import normalize_url+++class TestNormalizeUrl:+ """Tests for normalize_url function."""++ # Already proper URLs - should be returned unchanged+ def test_http_url_unchanged(self):+ """HTTP URLs should be returned unchanged."""+ url = "http://example.com"+ assert normalize_url(url) == "http://example.com"++ def test_https_url_unchanged(self):+ """HTTPS URLs should be returned unchanged."""+ url = "https://example.com"+ assert normalize_url(url) == "https://example.com"++ def test_http_url_with_port_unchanged(self):+ """HTTP URLs with port should be returned unchanged."""+ url = "http://localhost:8080"+ assert normalize_url(url) == "http://localhost:8080"++ def test_https_url_with_port_unchanged(self):+ """HTTPS URLs with port should be returned unchanged."""+ url = "https://example.com:443"+ assert normalize_url(url) == "https://example.com:443"++ def test_http_url_with_path_unchanged(self):+ """HTTP URLs with path should be returned unchanged."""+ url = "http://example.com/api/v1"+ assert normalize_url(url) == "http://example.com/api/v1"++ # Localhost handling - should get http://+ def test_localhost_gets_http(self):+ """localhost without scheme should get http://."""+ url = "localhost:11434"+ assert normalize_url(url) == "http://localhost:11434"++ def test_localhost_without_port_gets_http(self):+ """localhost without port should get http://."""+ url = "localhost"+ assert normalize_url(url) == "http://localhost"++ def test_127_0_0_1_gets_http(self):+ """127.0.0.1 should get http://."""+ url = "127.0.0.1:8080"+ assert normalize_url(url) == "http://127.0.0.1:8080"++ def test_0_0_0_0_gets_http(self):+ """0.0.0.0 should get http://."""+ url = "0.0.0.0:5000"+ assert normalize_url(url) == "http://0.0.0.0:5000"++ # External hosts - should get https://+ def test_external_host_gets_https(self):+ """External hosts without scheme should get https://."""+ url = "example.com"+ assert normalize_url(url) == "https://example.com"++ def test_external_host_with_port_gets_https(self):+ """External hosts with port should get https://."""+ url = "api.example.com:8443"+ assert normalize_url(url) == "https://api.example.com:8443"++ def test_external_host_with_path_gets_https(self):+ """External hosts with path should get https://."""+ url = "example.com/api"+ assert normalize_url(url) == "https://example.com/api"++ # Malformed scheme handling+ def test_http_colon_without_slashes(self):+ """http: without // should be fixed."""+ url = "http:example.com"+ assert normalize_url(url) == "http://example.com"++ def test_https_colon_without_slashes(self):+ """https: without // should be fixed."""+ url = "https:example.com"+ assert normalize_url(url) == "https://example.com"++ def test_http_colon_without_slashes_with_port(self):+ """http: without // but with port should be fixed."""+ url = "http:localhost:8080"+ assert normalize_url(url) == "http://localhost:8080"++ # Double slash handling+ def test_double_slash_prefix_localhost(self):+ """//localhost should be normalized with http://."""+ url = "//localhost:8080"+ assert normalize_url(url) == "http://localhost:8080"++ def test_double_slash_prefix_external(self):+ """//example.com should be normalized with https://."""+ url = "//example.com"+ assert normalize_url(url) == "https://example.com"++ # IPv6 handling+ def test_ipv6_localhost_gets_http(self):+ """IPv6 localhost [::1] should get http://."""+ url = "[::1]:8080"+ assert normalize_url(url) == "http://[::1]:8080"++ def test_ipv6_external_gets_https(self):+ """IPv6 external addresses should get https://."""+ url = "[2001:db8::1]:8080"+ assert normalize_url(url) == "https://[2001:db8::1]:8080"++ # Whitespace handling+ def test_strips_leading_whitespace(self):+ """Leading whitespace should be stripped."""+ url = " http://example.com"+ assert normalize_url(url) == "http://example.com"++ def test_strips_trailing_whitespace(self):+ """Trailing whitespace should be stripped."""+ url = "http://example.com "+ assert normalize_url(url) == "http://example.com"++ def test_strips_both_whitespace(self):+ """Both leading and trailing whitespace should be stripped."""+ url = " example.com "+ assert normalize_url(url) == "https://example.com"++ # Error handling+ def test_empty_string_raises_error(self):+ """Empty string should raise ValueError."""+ with pytest.raises(ValueError, match="URL cannot be empty"):+ normalize_url("")++ def test_none_raises_error(self):+ """None should raise an error (either ValueError or TypeError)."""+ with pytest.raises((ValueError, TypeError)):+ normalize_url(None)++ # Complex URLs+ def test_url_with_query_params(self):+ """URLs with query parameters should work."""+ url = "example.com/search?q=test&page=1"+ assert normalize_url(url) == "https://example.com/search?q=test&page=1"++ def test_url_with_fragment(self):+ """URLs with fragments should work."""+ url = "example.com/page#section"+ assert normalize_url(url) == "https://example.com/page#section"++ def test_url_with_auth(self):+ """URLs with authentication info should work."""+ url = "user:[email protected]"+ assert normalize_url(url) == "https://user:[email protected]"+++class TestNormalizeUrlOllamaScenarios:+ """Tests for common Ollama URL scenarios."""++ def test_ollama_default_localhost(self):+ """Default Ollama localhost URL."""+ url = "localhost:11434"+ assert normalize_url(url) == "http://localhost:11434"++ def test_ollama_with_api_path(self):+ """Ollama URL with API path."""+ url = "localhost:11434/api/generate"+ assert normalize_url(url) == "http://localhost:11434/api/generate"++ def test_ollama_127_0_0_1(self):+ """Ollama on 127.0.0.1."""+ url = "127.0.0.1:11434"+ assert normalize_url(url) == "http://127.0.0.1:11434"++ def test_ollama_already_formatted(self):+ """Already properly formatted Ollama URL."""+ url = "http://localhost:11434"+ assert normalize_url(url) == "http://localhost:11434"diff --git a/tests/web_services/__init__.py b/tests/web_services/__init__.pynew file mode 100644index 0000000000..07649b6931--- /dev/null+++ b/tests/web_services/__init__.py@@ -0,0 +1 @@+"""Tests for web services."""diff --git a/tests/web_services/conftest.py b/tests/web_services/conftest.pynew file mode 100644index 0000000000..c22e1d5515--- /dev/null+++ b/tests/web_services/conftest.py@@ -0,0 +1,206 @@+"""Shared fixtures for web services tests."""++import pytest+from unittest.mock import Mock, MagicMock+++def sample_markdown():+ """Sample markdown content for testing."""+ return """# Test Document++This is a test document with **bold** and *italic* text.++## Section 1++A paragraph with some content.++| Column 1 | Column 2 |+|----------|----------|+| Data 1 | Data 2 |++## Section 2++- Item 1+- Item 2+- Item 3++```python+def example():+ return "code block"+```+"""+++def simple_markdown():+ """Minimal markdown for basic tests."""+ return "# Hello World\n\nThis is a test."+++def markdown_with_special_chars():+ """Markdown with special characters."""+ return """# Special Characters++Testing: <>&"'+Unicode: café, naïve, 日本語+Symbols: © ® ™ € £ ¥+"""+++def sample_metadata():+ """Sample metadata for PDF generation."""+ return {+ "author": "Test Author",+ "date": "2024-01-15",+ "subject": "Test Subject",+ }+++def custom_css():+ """Custom CSS for PDF styling."""+ return """+ body {+ font-family: 'Times New Roman', serif;+ font-size: 12pt;+ }+ h1 {+ color: navy;+ }+ """+++def valid_pdf_bytes():+ """Generate valid minimal PDF bytes for testing extraction."""+ # This is a minimal valid PDF structure+ pdf_content = b"""%PDF-1.4+1 0 obj+<< /Type /Catalog /Pages 2 0 R >>+endobj+2 0 obj+<< /Type /Pages /Kids [3 0 R] /Count 1 >>+endobj+3 0 obj+<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792]+ /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>+endobj+4 0 obj+<< /Length 44 >>+stream+BT /F1 12 Tf 100 700 Td (Hello World) Tj ET+endstream+endobj+5 0 obj+<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>+endobj+xref+0 6+0000000000 65535 f+0000000009 00000 n+0000000058 00000 n+0000000115 00000 n+0000000266 00000 n+0000000359 00000 n+trailer+<< /Size 6 /Root 1 0 R >>+startxref+434+%%EOF"""+ return pdf_content+++def invalid_pdf_bytes():+ """Invalid/corrupted PDF bytes."""+ return b"This is not a valid PDF file"+++def empty_file_bytes():+ """Empty file bytes."""+ return b""+++def mock_flask_app():+ """Mock Flask app for socket service testing."""+ app = Mock()+ app.config = {}+ return app+++def mock_socketio():+ """Mock SocketIO instance."""+ socketio = Mock()+ socketio.emit = Mock(return_value=None)+ socketio.on = Mock(return_value=lambda f: f)+ socketio.on_error = Mock(return_value=lambda f: f)+ socketio.on_error_default = Mock(return_value=lambda f: f)+ socketio.run = Mock()+ return socketio+++def mock_request():+ """Mock Flask request object."""+ request = Mock()+ request.sid = "test-session-id-123"+ return request+++def sample_research_id():+ """Sample research ID for testing."""+ return "research-abc-123"+++def sample_sources():+ """Sample sources for research sources service."""+ return [+ {+ "title": "Source 1",+ "url": "https://example.com/source1",+ "snippet": "This is the first source snippet.",+ "full_content": "Full content of source 1.",+ },+ {+ "link": "https://example.com/source2", # Alternative key+ "name": "Source 2", # Alternative key+ "snippet": "Second source snippet.",+ },+ {+ "title": "Source 3",+ "url": "https://example.com/source3",+ "snippet": "Third source with a very long snippet that should be truncated "+ * 50,+ },+ ]+++def mock_db_session():+ """Mock database session."""+ session = MagicMock()+ session.__enter__ = Mock(return_value=session)+ session.__exit__ = Mock(return_value=False)+ return session+++def mock_research_resource():+ """Mock ResearchResource model instance."""+ resource = Mock()+ resource.id = 1+ resource.research_id = "research-abc-123"+ resource.title = "Test Resource"+ resource.url = "https://example.com/resource"+ resource.content_preview = "Preview content"+ resource.source_type = "web"+ resource.resource_metadata = {"key": "value"}+ return resourcediff --git a/tests/web_services/test_pdf_extraction_service.py b/tests/web_services/test_pdf_extraction_service.pynew file mode 100644index 0000000000..0476eb5091--- /dev/null+++ b/tests/web_services/test_pdf_extraction_service.py@@ -0,0 +1,488 @@+"""+Comprehensive tests for PDFExtractionService.+Tests PDF text extraction, metadata extraction, and batch processing.+"""++from unittest.mock import Mock, patch, MagicMock+++class TestPDFExtractionServiceExtractTextAndMetadata:+ """Tests for extract_text_and_metadata method."""++ def test_returns_dict_with_required_keys(self, valid_pdf_bytes):+ """Test that extraction returns dict with all required keys."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ result = PDFExtractionService.extract_text_and_metadata(+ valid_pdf_bytes, "test.pdf"+ )++ assert "text" in result+ assert "pages" in result+ assert "size" in result+ assert "filename" in result+ assert "success" in result+ assert "error" in result++ def test_extracts_text_from_valid_pdf(self, valid_pdf_bytes):+ """Test text extraction from valid PDF."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ result = PDFExtractionService.extract_text_and_metadata(+ valid_pdf_bytes, "test.pdf"+ )++ # The minimal PDF contains "Hello World"+ assert "Hello World" in result["text"]+ assert result["success"] is True++ def test_returns_page_count(self, valid_pdf_bytes):+ """Test that page count is returned."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ result = PDFExtractionService.extract_text_and_metadata(+ valid_pdf_bytes, "test.pdf"+ )++ assert result["pages"] == 1++ def test_returns_file_size(self, valid_pdf_bytes):+ """Test that file size is returned."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ result = PDFExtractionService.extract_text_and_metadata(+ valid_pdf_bytes, "test.pdf"+ )++ assert result["size"] == len(valid_pdf_bytes)++ def test_returns_filename(self, valid_pdf_bytes):+ """Test that filename is returned."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ result = PDFExtractionService.extract_text_and_metadata(+ valid_pdf_bytes, "my_document.pdf"+ )++ assert result["filename"] == "my_document.pdf"++ def test_handles_invalid_pdf(self, invalid_pdf_bytes):+ """Test handling of invalid/corrupted PDF."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ result = PDFExtractionService.extract_text_and_metadata(+ invalid_pdf_bytes, "corrupt.pdf"+ )++ assert result["success"] is False+ assert result["error"] is not None+ assert "Failed to extract" in result["error"]++ def test_handles_empty_file(self, empty_file_bytes):+ """Test handling of empty file."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ result = PDFExtractionService.extract_text_and_metadata(+ empty_file_bytes, "empty.pdf"+ )++ assert result["success"] is False+ assert result["error"] is not None++ def test_handles_pdf_with_no_text(self):+ """Test handling of PDF with no extractable text."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ # Mock pdfplumber to return empty text+ mock_page = Mock()+ mock_page.extract_text.return_value = ""++ mock_pdf = MagicMock()+ mock_pdf.__enter__.return_value = mock_pdf+ mock_pdf.__exit__.return_value = None+ mock_pdf.pages = [mock_page]++ with patch(+ "local_deep_research.web.services.pdf_extraction_service.pdfplumber"+ ) as mock_pdfplumber:+ mock_pdfplumber.open.return_value = mock_pdf++ result = PDFExtractionService.extract_text_and_metadata(+ b"fake pdf content", "empty_text.pdf"+ )++ assert result["success"] is False+ assert "No extractable text found" in result["error"]++ def test_logs_warning_for_no_text(self):+ """Test that warning is logged when no text found."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ mock_page = Mock()+ mock_page.extract_text.return_value = ""++ mock_pdf = MagicMock()+ mock_pdf.__enter__.return_value = mock_pdf+ mock_pdf.__exit__.return_value = None+ mock_pdf.pages = [mock_page]++ with patch(+ "local_deep_research.web.services.pdf_extraction_service.pdfplumber"+ ) as mock_pdfplumber:+ mock_pdfplumber.open.return_value = mock_pdf++ with patch(+ "local_deep_research.web.services.pdf_extraction_service.logger"+ ) as mock_logger:+ PDFExtractionService.extract_text_and_metadata(+ b"fake pdf", "no_text.pdf"+ )++ mock_logger.warning.assert_called_once()+ assert (+ "No extractable text" in mock_logger.warning.call_args[0][0]+ )++ def test_logs_success_for_extraction(self, valid_pdf_bytes):+ """Test that success is logged on extraction."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ with patch(+ "local_deep_research.web.services.pdf_extraction_service.logger"+ ) as mock_logger:+ result = PDFExtractionService.extract_text_and_metadata(+ valid_pdf_bytes, "test.pdf"+ )++ if result["success"]:+ mock_logger.info.assert_called()++ def test_logs_exception_on_error(self, invalid_pdf_bytes):+ """Test that exceptions are logged."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ with patch(+ "local_deep_research.web.services.pdf_extraction_service.logger"+ ) as mock_logger:+ PDFExtractionService.extract_text_and_metadata(+ invalid_pdf_bytes, "corrupt.pdf"+ )++ mock_logger.exception.assert_called()++ def test_returns_generic_error_message(self, invalid_pdf_bytes):+ """Test that generic error message is returned (no internal details)."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ result = PDFExtractionService.extract_text_and_metadata(+ invalid_pdf_bytes, "corrupt.pdf"+ )++ # Should not expose internal exception details+ assert "Failed to extract text from PDF" in result["error"]+++class TestPDFExtractionServiceExtractBatch:+ """Tests for extract_batch method."""++ def test_returns_dict_with_required_keys(self, valid_pdf_bytes):+ """Test that batch returns dict with all required keys."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ files_data = [{"content": valid_pdf_bytes, "filename": "test.pdf"}]++ result = PDFExtractionService.extract_batch(files_data)++ assert "results" in result+ assert "total_files" in result+ assert "successful" in result+ assert "failed" in result+ assert "errors" in result++ def test_processes_multiple_files(self, valid_pdf_bytes):+ """Test processing multiple PDF files."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ files_data = [+ {"content": valid_pdf_bytes, "filename": "test1.pdf"},+ {"content": valid_pdf_bytes, "filename": "test2.pdf"},+ {"content": valid_pdf_bytes, "filename": "test3.pdf"},+ ]++ result = PDFExtractionService.extract_batch(files_data)++ assert result["total_files"] == 3+ assert len(result["results"]) == 3++ def test_counts_successful_extractions(self, valid_pdf_bytes):+ """Test counting of successful extractions."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ files_data = [+ {"content": valid_pdf_bytes, "filename": "test1.pdf"},+ {"content": valid_pdf_bytes, "filename": "test2.pdf"},+ ]++ result = PDFExtractionService.extract_batch(files_data)++ assert result["successful"] == 2+ assert result["failed"] == 0++ def test_counts_failed_extractions(+ self, valid_pdf_bytes, invalid_pdf_bytes+ ):+ """Test counting of failed extractions."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ files_data = [+ {"content": valid_pdf_bytes, "filename": "valid.pdf"},+ {"content": invalid_pdf_bytes, "filename": "invalid.pdf"},+ ]++ result = PDFExtractionService.extract_batch(files_data)++ assert result["successful"] == 1+ assert result["failed"] == 1++ def test_aggregates_errors(self, invalid_pdf_bytes):+ """Test error aggregation in batch mode."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ files_data = [+ {"content": invalid_pdf_bytes, "filename": "bad1.pdf"},+ {"content": invalid_pdf_bytes, "filename": "bad2.pdf"},+ ]++ result = PDFExtractionService.extract_batch(files_data)++ assert len(result["errors"]) == 2+ assert any("bad1.pdf" in err for err in result["errors"])+ assert any("bad2.pdf" in err for err in result["errors"])++ def test_handles_empty_batch(self):+ """Test handling of empty file list."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ result = PDFExtractionService.extract_batch([])++ assert result["total_files"] == 0+ assert result["successful"] == 0+ assert result["failed"] == 0+ assert result["results"] == []+ assert result["errors"] == []++ def test_preserves_order_of_results(self, valid_pdf_bytes):+ """Test that results preserve the order of input files."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ files_data = [+ {"content": valid_pdf_bytes, "filename": "first.pdf"},+ {"content": valid_pdf_bytes, "filename": "second.pdf"},+ {"content": valid_pdf_bytes, "filename": "third.pdf"},+ ]++ result = PDFExtractionService.extract_batch(files_data)++ assert result["results"][0]["filename"] == "first.pdf"+ assert result["results"][1]["filename"] == "second.pdf"+ assert result["results"][2]["filename"] == "third.pdf"++ def test_each_result_has_extraction_data(self, valid_pdf_bytes):+ """Test that each result has complete extraction data."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ files_data = [{"content": valid_pdf_bytes, "filename": "test.pdf"}]++ result = PDFExtractionService.extract_batch(files_data)++ file_result = result["results"][0]+ assert "text" in file_result+ assert "pages" in file_result+ assert "size" in file_result+ assert "filename" in file_result+ assert "success" in file_result+++class TestPDFExtractionServiceSingleton:+ """Tests for get_pdf_extraction_service singleton."""++ def test_get_service_returns_instance(self):+ """Test that get_pdf_extraction_service returns an instance."""+ from local_deep_research.web.services.pdf_extraction_service import (+ get_pdf_extraction_service,+ PDFExtractionService,+ )++ service = get_pdf_extraction_service()++ assert isinstance(service, PDFExtractionService)++ def test_get_service_returns_same_instance(self):+ """Test that get_pdf_extraction_service returns same instance."""+ from local_deep_research.web.services.pdf_extraction_service import (+ get_pdf_extraction_service,+ )++ service1 = get_pdf_extraction_service()+ service2 = get_pdf_extraction_service()++ assert service1 is service2++ def test_singleton_can_be_reset(self):+ """Test that singleton can be reset for testing."""+ import local_deep_research.web.services.pdf_extraction_service as extraction_module++ # Reset singleton+ extraction_module._pdf_extraction_service = None++ service1 = extraction_module.get_pdf_extraction_service()++ # Reset again+ extraction_module._pdf_extraction_service = None++ service2 = extraction_module.get_pdf_extraction_service()++ # Different instances after reset+ assert service1 is not service2+++class TestPDFExtractionServiceMultiPage:+ """Tests for multi-page PDF extraction."""++ def test_extracts_all_pages(self):+ """Test that text is extracted from all pages."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ # Mock multi-page PDF+ mock_page1 = Mock()+ mock_page1.extract_text.return_value = "Page 1 content"++ mock_page2 = Mock()+ mock_page2.extract_text.return_value = "Page 2 content"++ mock_page3 = Mock()+ mock_page3.extract_text.return_value = "Page 3 content"++ mock_pdf = MagicMock()+ mock_pdf.__enter__.return_value = mock_pdf+ mock_pdf.__exit__.return_value = None+ mock_pdf.pages = [mock_page1, mock_page2, mock_page3]++ with patch(+ "local_deep_research.web.services.pdf_extraction_service.pdfplumber"+ ) as mock_pdfplumber:+ mock_pdfplumber.open.return_value = mock_pdf++ result = PDFExtractionService.extract_text_and_metadata(+ b"fake pdf", "multipage.pdf"+ )++ assert result["pages"] == 3+ assert "Page 1 content" in result["text"]+ assert "Page 2 content" in result["text"]+ assert "Page 3 content" in result["text"]++ def test_handles_page_with_no_text(self):+ """Test handling pages that return no text."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ mock_page1 = Mock()+ mock_page1.extract_text.return_value = "Page 1 content"++ mock_page2 = Mock()+ mock_page2.extract_text.return_value = None # Image-only page++ mock_page3 = Mock()+ mock_page3.extract_text.return_value = "Page 3 content"++ mock_pdf = MagicMock()+ mock_pdf.__enter__.return_value = mock_pdf+ mock_pdf.__exit__.return_value = None+ mock_pdf.pages = [mock_page1, mock_page2, mock_page3]++ with patch(+ "local_deep_research.web.services.pdf_extraction_service.pdfplumber"+ ) as mock_pdfplumber:+ mock_pdfplumber.open.return_value = mock_pdf++ result = PDFExtractionService.extract_text_and_metadata(+ b"fake pdf", "mixed.pdf"+ )++ assert result["pages"] == 3+ assert "Page 1 content" in result["text"]+ assert "Page 3 content" in result["text"]+ assert result["success"] is True++ def test_joins_pages_with_newline(self):+ """Test that pages are joined with newlines."""+ from local_deep_research.web.services.pdf_extraction_service import (+ PDFExtractionService,+ )++ mock_page1 = Mock()+ mock_page1.extract_text.return_value = "First"++ mock_page2 = Mock()+ mock_page2.extract_text.return_value = "Second"++ mock_pdf = MagicMock()+ mock_pdf.__enter__.return_value = mock_pdf+ mock_pdf.__exit__.return_value = None+ mock_pdf.pages = [mock_page1, mock_page2]++ with patch(+ "local_deep_research.web.services.pdf_extraction_service.pdfplumber"+ ) as mock_pdfplumber:+ mock_pdfplumber.open.return_value = mock_pdf++ result = PDFExtractionService.extract_text_and_metadata(+ b"fake pdf", "test.pdf"+ )++ # Text should be joined with newline+ assert result["text"] == "First\nSecond"diff --git a/tests/web_services/test_pdf_service.py b/tests/web_services/test_pdf_service.pynew file mode 100644index 0000000000..6a74b21fef--- /dev/null+++ b/tests/web_services/test_pdf_service.py@@ -0,0 +1,309 @@+"""+Comprehensive tests for PDFService.+Tests PDF generation, markdown conversion, CSS handling, and metadata.+"""++import pytest+from unittest.mock import patch+++class TestPDFServiceInit:+ """Tests for PDFService initialization."""++ def test_init_creates_minimal_css(self):+ """Test that initialization creates minimal CSS."""+ from local_deep_research.web.services.pdf_service import PDFService++ service = PDFService()++ assert service.minimal_css is not None++ def test_minimal_css_includes_page_settings(self):+ """Test that minimal CSS includes @page settings."""+ from local_deep_research.web.services.pdf_service import PDFService++ service = PDFService()++ # The CSS object wraps the string, so we check it was created+ assert service.minimal_css is not None+++class TestPDFServiceMarkdownToHtml:+ """Tests for _markdown_to_html method."""++ @pytest.fixture+ def service(self):+ """Create PDFService instance."""+ from local_deep_research.web.services.pdf_service import PDFService++ return PDFService()++ def test_converts_basic_markdown(self, service, simple_markdown):+ """Test conversion of basic markdown to HTML."""+ html = service._markdown_to_html(simple_markdown)++ # Markdown adds id attribute to headings+ assert "<h1" in html and "Hello World</h1>" in html+ assert "<p>This is a test.</p>" in html++ def test_includes_doctype_and_structure(self, service, simple_markdown):+ """Test that HTML includes proper structure."""+ html = service._markdown_to_html(simple_markdown)++ assert "<!DOCTYPE html>" in html+ assert "<html>" in html+ assert "</html>" in html+ assert "<head>" in html+ assert "</head>" in html+ assert "<body>" in html+ assert "</body>" in html++ def test_includes_charset_meta(self, service, simple_markdown):+ """Test that HTML includes UTF-8 charset."""+ html = service._markdown_to_html(simple_markdown)++ assert '<meta charset="utf-8">' in html++ def test_includes_title_when_provided(self, service, simple_markdown):+ """Test that title is included when provided."""+ html = service._markdown_to_html(simple_markdown, title="Test Title")++ assert "<title>Test Title</title>" in html++ def test_excludes_title_when_not_provided(self, service, simple_markdown):+ """Test that no title tag when title not provided."""+ html = service._markdown_to_html(simple_markdown)++ assert "<title>" not in html++ def test_includes_metadata_as_meta_tags(+ self, service, simple_markdown, sample_metadata+ ):+ """Test that metadata is included as meta tags."""+ html = service._markdown_to_html(+ simple_markdown, metadata=sample_metadata+ )++ assert '<meta name="author" content="Test Author">' in html+ assert '<meta name="date" content="2024-01-15">' in html+ assert '<meta name="subject" content="Test Subject">' in html++ def test_includes_ldr_attribution_footer(self, service, simple_markdown):+ """Test that LDR attribution footer is included."""+ html = service._markdown_to_html(simple_markdown)++ assert "Generated by" in html+ assert "Local Deep Research" in html++ def test_converts_tables(self, service, sample_markdown):+ """Test that markdown tables are converted."""+ html = service._markdown_to_html(sample_markdown)++ assert "<table>" in html+ assert "<th>" in html+ assert "Column 1" in html++ def test_converts_code_blocks(self, service, sample_markdown):+ """Test that fenced code blocks are converted."""+ html = service._markdown_to_html(sample_markdown)++ assert "<code" in html or "<pre>" in html+ assert "def example():" in html++ def test_converts_lists(self, service, sample_markdown):+ """Test that lists are converted."""+ html = service._markdown_to_html(sample_markdown)++ assert "<li>" in html+ assert "Item 1" in html++ def test_converts_bold_and_italic(self, service, sample_markdown):+ """Test that bold and italic text are converted."""+ html = service._markdown_to_html(sample_markdown)++ assert "<strong>bold</strong>" in html+ assert "<em>italic</em>" in html++ def test_handles_special_characters(+ self, service, markdown_with_special_chars+ ):+ """Test handling of special characters."""+ html = service._markdown_to_html(markdown_with_special_chars)++ # Unicode should pass through+ assert "café" in html+ assert "naïve" in html+ assert "日本語" in html+++class TestPDFServiceMarkdownToPdf:+ """Tests for markdown_to_pdf method."""++ @pytest.fixture+ def service(self):+ """Create PDFService instance."""+ from local_deep_research.web.services.pdf_service import PDFService++ return PDFService()++ def test_returns_bytes(self, service, simple_markdown):+ """Test that markdown_to_pdf returns bytes."""+ result = service.markdown_to_pdf(simple_markdown)++ assert isinstance(result, bytes)++ def test_returns_valid_pdf(self, service, simple_markdown):+ """Test that result is a valid PDF (starts with %PDF)."""+ result = service.markdown_to_pdf(simple_markdown)++ assert result.startswith(b"%PDF")++ def test_pdf_has_reasonable_size(self, service, simple_markdown):+ """Test that generated PDF has a reasonable size."""+ result = service.markdown_to_pdf(simple_markdown)++ # A simple PDF should be at least a few KB+ assert len(result) > 1000++ def test_applies_title(self, service, simple_markdown):+ """Test that title is applied to PDF."""+ result = service.markdown_to_pdf(simple_markdown, title="My Title")++ # PDF was generated successfully+ assert result.startswith(b"%PDF")+ assert len(result) > 0++ def test_applies_metadata(self, service, simple_markdown, sample_metadata):+ """Test that metadata is applied to PDF."""+ result = service.markdown_to_pdf(+ simple_markdown, metadata=sample_metadata+ )++ assert result.startswith(b"%PDF")++ def test_applies_custom_css(self, service, simple_markdown, custom_css):+ """Test that custom CSS is applied."""+ result = service.markdown_to_pdf(simple_markdown, custom_css=custom_css)++ assert result.startswith(b"%PDF")++ def test_uses_minimal_css_when_no_custom_css(+ self, service, simple_markdown+ ):+ """Test that minimal CSS is used by default."""+ result = service.markdown_to_pdf(simple_markdown)++ assert result.startswith(b"%PDF")++ def test_handles_empty_markdown(self, service):+ """Test handling of empty markdown."""+ result = service.markdown_to_pdf("")++ assert result.startswith(b"%PDF")++ def test_handles_large_markdown(self, service):+ """Test handling of large markdown content."""+ # Create a large markdown document+ large_content = "# Large Document\n\n"+ large_content += ("This is a paragraph. " * 100 + "\n\n") * 50++ result = service.markdown_to_pdf(large_content)++ assert result.startswith(b"%PDF")+ # Large content should produce larger PDF+ assert len(result) > 10000++ def test_handles_markdown_with_all_features(self, service, sample_markdown):+ """Test handling of markdown with tables, code, lists."""+ result = service.markdown_to_pdf(sample_markdown)++ assert result.startswith(b"%PDF")++ def test_logs_pdf_size(self, service, simple_markdown):+ """Test that PDF size is logged."""+ with patch(+ "local_deep_research.web.services.pdf_service.logger"+ ) as mock_logger:+ service.markdown_to_pdf(simple_markdown)++ mock_logger.info.assert_called_once()+ call_args = mock_logger.info.call_args[0][0]+ assert "Generated PDF" in call_args+ assert "bytes" in call_args+++class TestPDFServiceErrorHandling:+ """Tests for error handling in PDFService."""++ @pytest.fixture+ def service(self):+ """Create PDFService instance."""+ from local_deep_research.web.services.pdf_service import PDFService++ return PDFService()++ def test_raises_exception_on_html_error(self, service):+ """Test that exceptions are raised on HTML conversion errors."""+ with patch.object(+ service, "_markdown_to_html", side_effect=Exception("HTML error")+ ):+ with pytest.raises(Exception) as exc_info:+ service.markdown_to_pdf("test")++ assert "HTML error" in str(exc_info.value)++ def test_logs_exception_on_error(self, service):+ """Test that exceptions are logged."""+ with patch.object(+ service, "_markdown_to_html", side_effect=Exception("Test error")+ ):+ with patch(+ "local_deep_research.web.services.pdf_service.logger"+ ) as mock_logger:+ with pytest.raises(Exception):+ service.markdown_to_pdf("test")++ mock_logger.exception.assert_called_once()+++class TestPDFServiceSingleton:+ """Tests for get_pdf_service singleton."""++ def test_get_pdf_service_returns_instance(self):+ """Test that get_pdf_service returns a PDFService instance."""+ from local_deep_research.web.services.pdf_service import (+ get_pdf_service,+ PDFService,+ )++ service = get_pdf_service()++ assert isinstance(service, PDFService)++ def test_get_pdf_service_returns_same_instance(self):+ """Test that get_pdf_service returns the same instance."""+ from local_deep_research.web.services.pdf_service import (+ get_pdf_service,+ )++ service1 = get_pdf_service()+ service2 = get_pdf_service()++ assert service1 is service2++ def test_singleton_can_be_reset(self):+ """Test that singleton can be reset for testing."""+ import local_deep_research.web.services.pdf_service as pdf_module++ # Reset singleton+ pdf_module._pdf_service = None++ service1 = pdf_module.get_pdf_service()++ # Reset again+ pdf_module._pdf_service = None++ service2 = pdf_module.get_pdf_service()++ # Different instances after reset+ assert service1 is not service2diff --git a/tests/web_services/test_research_sources_service.py b/tests/web_services/test_research_sources_service.pynew file mode 100644index 0000000000..4359413db3--- /dev/null+++ b/tests/web_services/test_research_sources_service.py@@ -0,0 +1,809 @@+"""+Comprehensive tests for ResearchSourcesService.+Tests saving, retrieving, and copying research sources.+"""++from unittest.mock import Mock, MagicMock, patch+++class TestSaveResearchSources:+ """Tests for save_research_sources method."""++ def test_returns_zero_for_empty_sources(self, sample_research_id):+ """Test that zero is returned for empty sources list."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ result = ResearchSourcesService.save_research_sources(+ sample_research_id, []+ )++ assert result == 0++ def test_returns_zero_for_none_sources(self, sample_research_id):+ """Test that zero is returned for None sources."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ result = ResearchSourcesService.save_research_sources(+ sample_research_id, None+ )++ assert result == 0++ def test_skips_if_resources_already_exist(+ self, mock_db_session, sample_research_id, sample_sources+ ):+ """Test that saving is skipped if resources already exist."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 5++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = ResearchSourcesService.save_research_sources(+ sample_research_id, sample_sources+ )++ assert result == 5+ mock_db_session.add.assert_not_called()++ def test_saves_sources_when_none_exist(+ self, mock_db_session, sample_research_id, sample_sources+ ):+ """Test that sources are saved when none exist."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ):+ result = ResearchSourcesService.save_research_sources(+ sample_research_id, sample_sources+ )++ assert result > 0+ mock_db_session.commit.assert_called_once()++ def test_extracts_url_from_url_key(+ self, mock_db_session, sample_research_id+ ):+ """Test extraction of URL from 'url' key."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ sources = [{"url": "https://example.com", "title": "Test"}]+ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ) as mock_resource:+ ResearchSourcesService.save_research_sources(+ sample_research_id, sources+ )++ call_kwargs = mock_resource.call_args[1]+ assert call_kwargs["url"] == "https://example.com"++ def test_extracts_url_from_link_key(+ self, mock_db_session, sample_research_id+ ):+ """Test extraction of URL from 'link' key."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ sources = [{"link": "https://example.com", "title": "Test"}]+ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ) as mock_resource:+ ResearchSourcesService.save_research_sources(+ sample_research_id, sources+ )++ call_kwargs = mock_resource.call_args[1]+ assert call_kwargs["url"] == "https://example.com"++ def test_extracts_title_from_title_key(+ self, mock_db_session, sample_research_id+ ):+ """Test extraction of title from 'title' key."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ sources = [{"url": "https://example.com", "title": "My Title"}]+ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ) as mock_resource:+ ResearchSourcesService.save_research_sources(+ sample_research_id, sources+ )++ call_kwargs = mock_resource.call_args[1]+ assert call_kwargs["title"] == "My Title"++ def test_extracts_title_from_name_key(+ self, mock_db_session, sample_research_id+ ):+ """Test extraction of title from 'name' key."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ sources = [{"url": "https://example.com", "name": "My Name"}]+ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ) as mock_resource:+ ResearchSourcesService.save_research_sources(+ sample_research_id, sources+ )++ call_kwargs = mock_resource.call_args[1]+ assert call_kwargs["title"] == "My Name"++ def test_uses_untitled_for_missing_title(+ self, mock_db_session, sample_research_id+ ):+ """Test that 'Untitled' is used when title is missing."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ sources = [{"url": "https://example.com"}]+ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ) as mock_resource:+ ResearchSourcesService.save_research_sources(+ sample_research_id, sources+ )++ call_kwargs = mock_resource.call_args[1]+ assert call_kwargs["title"] == "Untitled"++ def test_skips_sources_without_url(+ self, mock_db_session, sample_research_id+ ):+ """Test that sources without URL are skipped."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ sources = [+ {"title": "No URL"},+ {"url": "https://example.com", "title": "Has URL"},+ ]+ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ):+ result = ResearchSourcesService.save_research_sources(+ sample_research_id, sources+ )++ # Only one source should be saved+ assert result == 1++ def test_truncates_long_snippets(self, mock_db_session, sample_research_id):+ """Test that snippets are truncated to 1000 characters."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ long_snippet = "x" * 2000+ sources = [+ {+ "url": "https://example.com",+ "title": "Test",+ "snippet": long_snippet,+ }+ ]+ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ) as mock_resource:+ ResearchSourcesService.save_research_sources(+ sample_research_id, sources+ )++ call_kwargs = mock_resource.call_args[1]+ assert len(call_kwargs["content_preview"]) == 1000++ def test_extracts_snippet_from_multiple_keys(+ self, mock_db_session, sample_research_id+ ):+ """Test extraction of snippet from various keys."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ # Test content_preview key+ sources = [+ {"url": "https://example.com", "content_preview": "Preview text"}+ ]+ mock_db_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ) as mock_resource:+ ResearchSourcesService.save_research_sources(+ sample_research_id, sources+ )++ call_kwargs = mock_resource.call_args[1]+ assert call_kwargs["content_preview"] == "Preview text"+++class TestGetResearchSources:+ """Tests for get_research_sources method."""++ def test_returns_list_of_sources(self, mock_db_session, sample_research_id):+ """Test that list of sources is returned."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_resource = Mock()+ mock_resource.id = 1+ mock_resource.url = "https://example.com"+ mock_resource.title = "Test"+ mock_resource.content_preview = "Preview"+ mock_resource.source_type = "web"+ mock_resource.resource_metadata = {}+ mock_resource.created_at = "2024-01-01"++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = [+ mock_resource+ ]++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = ResearchSourcesService.get_research_sources(+ sample_research_id+ )++ assert isinstance(result, list)+ assert len(result) == 1++ def test_returns_correct_fields(self, mock_db_session, sample_research_id):+ """Test that sources have correct fields."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_resource = Mock()+ mock_resource.id = 1+ mock_resource.url = "https://example.com"+ mock_resource.title = "Test Title"+ mock_resource.content_preview = "Preview text"+ mock_resource.source_type = "web"+ mock_resource.resource_metadata = {"key": "value"}+ mock_resource.created_at = "2024-01-01"++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = [+ mock_resource+ ]++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = ResearchSourcesService.get_research_sources(+ sample_research_id+ )++ source = result[0]+ assert source["id"] == 1+ assert source["url"] == "https://example.com"+ assert source["title"] == "Test Title"+ assert source["snippet"] == "Preview text"+ assert source["content_preview"] == "Preview text"+ assert source["source_type"] == "web"+ assert source["metadata"] == {"key": "value"}++ def test_returns_empty_list_when_no_sources(+ self, mock_db_session, sample_research_id+ ):+ """Test that empty list is returned when no sources exist."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = []++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = ResearchSourcesService.get_research_sources(+ sample_research_id+ )++ assert result == []++ def test_handles_null_metadata(self, mock_db_session, sample_research_id):+ """Test handling of null resource_metadata."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_resource = Mock()+ mock_resource.id = 1+ mock_resource.url = "https://example.com"+ mock_resource.title = "Test"+ mock_resource.content_preview = "Preview"+ mock_resource.source_type = "web"+ mock_resource.resource_metadata = None+ mock_resource.created_at = "2024-01-01"++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = [+ mock_resource+ ]++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = ResearchSourcesService.get_research_sources(+ sample_research_id+ )++ assert result[0]["metadata"] == {}++ def test_passes_username_to_session(+ self, mock_db_session, sample_research_id+ ):+ """Test that username is passed to get_user_db_session."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = []++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ ResearchSourcesService.get_research_sources(+ sample_research_id, username="testuser"+ )++ mock_get_session.assert_called_once_with("testuser")+++class TestCopySourcesToNewResearch:+ """Tests for copy_sources_to_new_research method."""++ def test_copies_all_sources(self, mock_db_session, sample_research_id):+ """Test that all sources are copied."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_resource = Mock()+ mock_resource.title = "Test"+ mock_resource.url = "https://example.com"+ mock_resource.content_preview = "Preview"+ mock_resource.source_type = "web"+ mock_resource.resource_metadata = {}++ mock_db_session.query.return_value.filter_by.return_value.all.return_value = [+ mock_resource+ ]++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ):+ result = ResearchSourcesService.copy_sources_to_new_research(+ sample_research_id, "new-research-id"+ )++ assert result == 1+ mock_db_session.commit.assert_called_once()++ def test_filters_by_source_ids(self, mock_db_session, sample_research_id):+ """Test that sources can be filtered by IDs."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_query = MagicMock()+ mock_db_session.query.return_value.filter_by.return_value = mock_query+ mock_query.filter.return_value.all.return_value = []++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ ResearchSourcesService.copy_sources_to_new_research(+ sample_research_id, "new-research-id", source_ids=[1, 2, 3]+ )++ # Should filter by source IDs+ mock_query.filter.assert_called_once()++ def test_adds_copied_from_metadata(+ self, mock_db_session, sample_research_id+ ):+ """Test that copied_from is added to metadata."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_resource = Mock()+ mock_resource.title = "Test"+ mock_resource.url = "https://example.com"+ mock_resource.content_preview = "Preview"+ mock_resource.source_type = "web"+ mock_resource.resource_metadata = {"original": "data"}++ mock_db_session.query.return_value.filter_by.return_value.all.return_value = [+ mock_resource+ ]++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.research_sources_service.ResearchResource"+ ) as mock_resource_class:+ ResearchSourcesService.copy_sources_to_new_research(+ sample_research_id, "new-research-id"+ )++ call_kwargs = mock_resource_class.call_args[1]+ assert "copied_from" in call_kwargs["resource_metadata"]+ assert (+ call_kwargs["resource_metadata"]["copied_from"]+ == sample_research_id+ )++ def test_returns_zero_when_no_sources(+ self, mock_db_session, sample_research_id+ ):+ """Test that zero is returned when no sources to copy."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_db_session.query.return_value.filter_by.return_value.all.return_value = []++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = ResearchSourcesService.copy_sources_to_new_research(+ sample_research_id, "new-research-id"+ )++ assert result == 0+ mock_db_session.commit.assert_not_called()+++class TestUpdateResearchWithSources:+ """Tests for update_research_with_sources method."""++ def test_calls_save_research_sources(+ self, mock_db_session, sample_research_id, sample_sources+ ):+ """Test that save_research_sources is called."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_research = Mock()+ mock_research.research_meta = None++ mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch.object(+ ResearchSourcesService,+ "save_research_sources",+ return_value=3,+ ) as mock_save:+ ResearchSourcesService.update_research_with_sources(+ sample_research_id, sample_sources+ )++ mock_save.assert_called_once()++ def test_updates_research_metadata(+ self, mock_db_session, sample_research_id, sample_sources+ ):+ """Test that research metadata is updated with source count."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_research = Mock()+ mock_research.research_meta = {}++ mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch.object(+ ResearchSourcesService,+ "save_research_sources",+ return_value=3,+ ):+ ResearchSourcesService.update_research_with_sources(+ sample_research_id, sample_sources+ )++ assert mock_research.research_meta["sources_count"] == 3+ assert mock_research.research_meta["has_sources"] is True++ def test_returns_true_on_success(+ self, mock_db_session, sample_research_id, sample_sources+ ):+ """Test that True is returned on success."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_research = Mock()+ mock_research.research_meta = {}++ mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch.object(+ ResearchSourcesService,+ "save_research_sources",+ return_value=3,+ ):+ result = ResearchSourcesService.update_research_with_sources(+ sample_research_id, sample_sources+ )++ assert result is True++ def test_returns_false_when_research_not_found(+ self, mock_db_session, sample_research_id, sample_sources+ ):+ """Test that False is returned when research not found."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_db_session.query.return_value.filter_by.return_value.first.return_value = None++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch.object(+ ResearchSourcesService,+ "save_research_sources",+ return_value=3,+ ):+ result = ResearchSourcesService.update_research_with_sources(+ sample_research_id, sample_sources+ )++ assert result is False++ def test_returns_false_on_exception(+ self, mock_db_session, sample_research_id, sample_sources+ ):+ """Test that False is returned on exception."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch.object(+ ResearchSourcesService,+ "save_research_sources",+ side_effect=Exception("DB error"),+ ):+ result = ResearchSourcesService.update_research_with_sources(+ sample_research_id, sample_sources+ )++ assert result is False++ def test_initializes_null_metadata(+ self, mock_db_session, sample_research_id, sample_sources+ ):+ """Test that null research_meta is initialized."""+ from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+ )++ mock_research = Mock()+ mock_research.research_meta = None++ mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ with patch(+ "local_deep_research.web.services.research_sources_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch.object(+ ResearchSourcesService,+ "save_research_sources",+ return_value=2,+ ):+ ResearchSourcesService.update_research_with_sources(+ sample_research_id, sample_sources+ )++ assert mock_research.research_meta is not None+ assert isinstance(mock_research.research_meta, dict)diff --git a/tests/web_services/test_resource_service.py b/tests/web_services/test_resource_service.pynew file mode 100644index 0000000000..2dc0718c5c--- /dev/null+++ b/tests/web_services/test_resource_service.py@@ -0,0 +1,503 @@+"""+Comprehensive tests for resource_service.+Tests CRUD operations for ResearchResource.+"""++import pytest+from unittest.mock import Mock, patch+++class TestGetResourcesForResearch:+ """Tests for get_resources_for_research function."""++ def test_returns_list_of_resources(+ self, mock_db_session, mock_research_resource, sample_research_id+ ):+ """Test that function returns list of resources."""+ from local_deep_research.web.services.resource_service import (+ get_resources_for_research,+ )++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = [+ mock_research_resource+ ]++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = get_resources_for_research(sample_research_id)++ assert isinstance(result, list)+ assert len(result) == 1++ def test_returns_correct_fields(+ self, mock_db_session, mock_research_resource, sample_research_id+ ):+ """Test that returned resources have correct fields."""+ from local_deep_research.web.services.resource_service import (+ get_resources_for_research,+ )++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = [+ mock_research_resource+ ]++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = get_resources_for_research(sample_research_id)++ resource = result[0]+ assert "id" in resource+ assert "research_id" in resource+ assert "title" in resource+ assert "url" in resource+ assert "content_preview" in resource+ assert "source_type" in resource+ assert "metadata" in resource++ def test_returns_empty_list_when_no_resources(+ self, mock_db_session, sample_research_id+ ):+ """Test that empty list is returned when no resources exist."""+ from local_deep_research.web.services.resource_service import (+ get_resources_for_research,+ )++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = []++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = get_resources_for_research(sample_research_id)++ assert result == []++ def test_filters_by_research_id(self, mock_db_session, sample_research_id):+ """Test that query filters by research_id."""+ from local_deep_research.web.services.resource_service import (+ get_resources_for_research,+ )++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = []++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ get_resources_for_research(sample_research_id)++ mock_db_session.query.return_value.filter_by.assert_called_once_with(+ research_id=sample_research_id+ )++ def test_handles_null_metadata(self, mock_db_session, sample_research_id):+ """Test handling of null resource_metadata."""+ from local_deep_research.web.services.resource_service import (+ get_resources_for_research,+ )++ resource = Mock()+ resource.id = 1+ resource.research_id = sample_research_id+ resource.title = "Test"+ resource.url = "https://test.com"+ resource.content_preview = "Preview"+ resource.source_type = "web"+ resource.resource_metadata = None++ mock_db_session.query.return_value.filter_by.return_value.order_by.return_value.all.return_value = [+ resource+ ]++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = get_resources_for_research(sample_research_id)++ assert result[0]["metadata"] == {}++ def test_raises_on_database_error(+ self, mock_db_session, sample_research_id+ ):+ """Test that exceptions are raised on database error."""+ from local_deep_research.web.services.resource_service import (+ get_resources_for_research,+ )++ mock_db_session.query.side_effect = Exception("DB error")++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with pytest.raises(Exception):+ get_resources_for_research(sample_research_id)+++class TestAddResource:+ """Tests for add_resource function."""++ def test_creates_resource(self, mock_db_session, sample_research_id):+ """Test that resource is created and added to session."""+ from local_deep_research.web.services.resource_service import (+ add_resource,+ )++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.resource_service.ResearchResource"+ ):+ add_resource(+ sample_research_id, "Test Title", "https://example.com"+ )++ mock_db_session.add.assert_called_once()+ mock_db_session.commit.assert_called_once()++ def test_returns_created_resource(+ self, mock_db_session, sample_research_id+ ):+ """Test that created resource is returned."""+ from local_deep_research.web.services.resource_service import (+ add_resource,+ )++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.resource_service.ResearchResource"+ ) as mock_resource_class:+ mock_resource_class.return_value = Mock()+ result = add_resource(+ sample_research_id, "Test Title", "https://example.com"+ )++ assert result is not None++ def test_uses_default_source_type(+ self, mock_db_session, sample_research_id+ ):+ """Test that default source_type is 'web'."""+ from local_deep_research.web.services.resource_service import (+ add_resource,+ )++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.resource_service.ResearchResource"+ ) as mock_resource_class:+ add_resource(+ sample_research_id, "Test Title", "https://example.com"+ )++ call_kwargs = mock_resource_class.call_args[1]+ assert call_kwargs["source_type"] == "web"++ def test_accepts_custom_source_type(+ self, mock_db_session, sample_research_id+ ):+ """Test that custom source_type is accepted."""+ from local_deep_research.web.services.resource_service import (+ add_resource,+ )++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.resource_service.ResearchResource"+ ) as mock_resource_class:+ add_resource(+ sample_research_id,+ "Test Title",+ "https://example.com",+ source_type="pdf",+ )++ call_kwargs = mock_resource_class.call_args[1]+ assert call_kwargs["source_type"] == "pdf"++ def test_accepts_metadata(self, mock_db_session, sample_research_id):+ """Test that metadata is passed to resource."""+ from local_deep_research.web.services.resource_service import (+ add_resource,+ )++ metadata = {"key": "value", "extra": "data"}++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.resource_service.ResearchResource"+ ) as mock_resource_class:+ add_resource(+ sample_research_id,+ "Test Title",+ "https://example.com",+ metadata=metadata,+ )++ call_kwargs = mock_resource_class.call_args[1]+ assert call_kwargs["resource_metadata"] == metadata++ def test_raises_on_database_error(+ self, mock_db_session, sample_research_id+ ):+ """Test that exceptions are raised on database error."""+ from local_deep_research.web.services.resource_service import (+ add_resource,+ )++ mock_db_session.add.side_effect = Exception("DB error")++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with pytest.raises(Exception):+ add_resource(+ sample_research_id, "Test Title", "https://example.com"+ )+++class TestDeleteResource:+ """Tests for delete_resource function."""++ def test_deletes_existing_resource(self, mock_db_session):+ """Test that existing resource is deleted."""+ from local_deep_research.web.services.resource_service import (+ delete_resource,+ )++ mock_resource = Mock()+ mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_resource++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = delete_resource(1)++ mock_db_session.delete.assert_called_once_with(mock_resource)+ mock_db_session.commit.assert_called_once()+ assert result is True++ def test_raises_value_error_when_not_found(self, mock_db_session):+ """Test that ValueError is raised when resource not found."""+ from local_deep_research.web.services.resource_service import (+ delete_resource,+ )++ mock_db_session.query.return_value.filter_by.return_value.first.return_value = None++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with pytest.raises(ValueError) as exc_info:+ delete_resource(999)++ assert "not found" in str(exc_info.value)++ def test_logs_successful_deletion(self, mock_db_session):+ """Test that successful deletion is logged."""+ from local_deep_research.web.services.resource_service import (+ delete_resource,+ )++ mock_resource = Mock()+ mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_resource++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with patch(+ "local_deep_research.web.services.resource_service.logger"+ ) as mock_logger:+ delete_resource(1)++ mock_logger.info.assert_called_once()++ def test_raises_on_database_error(self, mock_db_session):+ """Test that database errors are propagated."""+ from local_deep_research.web.services.resource_service import (+ delete_resource,+ )++ mock_db_session.query.side_effect = Exception("DB error")++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ with pytest.raises(Exception):+ delete_resource(1)+++class TestUpdateResourceContent:+ """Tests for update_resource_content function."""++ def test_updates_existing_resource(self, mock_db_session):+ """Test that existing resource content is updated."""+ from local_deep_research.web.services.resource_service import (+ update_resource_content,+ )++ mock_resource = Mock()+ mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_resource++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = update_resource_content(1, "New content")++ assert mock_resource.content == "New content"+ mock_db_session.commit.assert_called_once()+ assert result == mock_resource++ def test_returns_none_when_not_found(self, mock_db_session):+ """Test that None is returned when resource not found."""+ from local_deep_research.web.services.resource_service import (+ update_resource_content,+ )++ mock_db_session.query.return_value.filter_by.return_value.first.return_value = None++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = update_resource_content(999, "New content")++ assert result is None++ def test_updates_last_fetched(self, mock_db_session):+ """Test that last_fetched is updated."""+ from local_deep_research.web.services.resource_service import (+ update_resource_content,+ )++ mock_resource = Mock()+ mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_resource++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ update_resource_content(1, "New content")++ assert mock_resource.last_fetched is not None++ def test_returns_none_on_database_error(self, mock_db_session):+ """Test that None is returned on database error."""+ from local_deep_research.web.services.resource_service import (+ update_resource_content,+ )++ mock_db_session.query.side_effect = Exception("DB error")++ with patch(+ "local_deep_research.web.services.resource_service.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__.return_value = (+ mock_db_session+ )+ mock_get_session.return_value.__exit__.return_value = False++ result = update_resource_content(1, "New content")++ assert result is Nonediff --git a/tests/web_services/test_socket_service.py b/tests/web_services/test_socket_service.pynew file mode 100644index 0000000000..150ee2ef5f--- /dev/null+++ b/tests/web_services/test_socket_service.py@@ -0,0 +1,727 @@+"""+Comprehensive tests for SocketIOService.+Tests singleton pattern, event emission, subscriptions, and error handling.+"""++import pytest+from unittest.mock import Mock, MagicMock, patch+++class TestSocketIOServiceSingleton:+ """Tests for SocketIOService singleton pattern."""++ def setup_method(self):+ """Reset singleton before each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def teardown_method(self):+ """Reset singleton after each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def test_requires_app_on_first_creation(self):+ """Test that Flask app is required on first creation."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ with pytest.raises(ValueError) as exc_info:+ SocketIOService()++ assert "Flask app must be specified" in str(exc_info.value)++ def test_creates_instance_with_app(self, mock_flask_app):+ """Test that instance is created with Flask app."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO"+ ) as mock_socketio:+ service = SocketIOService(app=mock_flask_app)++ assert service is not None+ mock_socketio.assert_called_once()++ def test_returns_same_instance_on_second_call(self, mock_flask_app):+ """Test that same instance is returned on subsequent calls."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ with patch("local_deep_research.web.services.socket_service.SocketIO"):+ service1 = SocketIOService(app=mock_flask_app)+ service2 = SocketIOService()++ assert service1 is service2++ def test_ignores_app_on_second_call(self, mock_flask_app):+ """Test that app parameter is ignored after singleton creation."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ with patch("local_deep_research.web.services.socket_service.SocketIO"):+ service1 = SocketIOService(app=mock_flask_app)+ other_app = Mock()+ service2 = SocketIOService(app=other_app)++ assert service1 is service2+++class TestSocketIOServiceInit:+ """Tests for SocketIOService initialization."""++ def setup_method(self):+ """Reset singleton before each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def teardown_method(self):+ """Reset singleton after each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def test_initializes_socketio_with_correct_params(self, mock_flask_app):+ """Test that SocketIO is initialized with correct parameters."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO"+ ) as mock_socketio:+ SocketIOService(app=mock_flask_app)++ mock_socketio.assert_called_once_with(+ mock_flask_app,+ cors_allowed_origins="*",+ async_mode="threading",+ path="/socket.io",+ logger=False,+ engineio_logger=False,+ ping_timeout=20,+ ping_interval=5,+ )++ def test_registers_connect_handler(self, mock_flask_app):+ """Test that connect handler is registered."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ SocketIOService(app=mock_flask_app)++ # Check that on("connect") was called+ mock_socketio.on.assert_any_call("connect")++ def test_registers_disconnect_handler(self, mock_flask_app):+ """Test that disconnect handler is registered."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ SocketIOService(app=mock_flask_app)++ mock_socketio.on.assert_any_call("disconnect")++ def test_registers_subscribe_handler(self, mock_flask_app):+ """Test that subscribe_to_research handler is registered."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ SocketIOService(app=mock_flask_app)++ mock_socketio.on.assert_any_call("subscribe_to_research")+++class TestSocketIOServiceEmitSocketEvent:+ """Tests for emit_socket_event method."""++ @pytest.fixture+ def service(self, mock_flask_app):+ """Create SocketIOService instance with mocked SocketIO."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ service = SocketIOService(app=mock_flask_app)+ service._SocketIOService__socketio = mock_socketio+ return service, mock_socketio++ def teardown_method(self):+ """Reset singleton after each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def test_emits_to_all_when_no_room(self, service):+ """Test emitting to all clients when no room specified."""+ svc, mock_socketio = service++ result = svc.emit_socket_event("test_event", {"key": "value"})++ assert result is True+ mock_socketio.emit.assert_called_once_with(+ "test_event", {"key": "value"}+ )++ def test_emits_to_specific_room(self, service):+ """Test emitting to specific room."""+ svc, mock_socketio = service++ result = svc.emit_socket_event(+ "test_event", {"key": "value"}, room="room-123"+ )++ assert result is True+ mock_socketio.emit.assert_called_once_with(+ "test_event", {"key": "value"}, room="room-123"+ )++ def test_returns_false_on_exception(self, service):+ """Test that False is returned on emission error."""+ svc, mock_socketio = service+ mock_socketio.emit.side_effect = Exception("Emission failed")++ result = svc.emit_socket_event("test_event", {"key": "value"})++ assert result is False++ def test_logs_exception_on_error(self, service):+ """Test that exception is logged on error."""+ svc, mock_socketio = service+ mock_socketio.emit.side_effect = Exception("Emission failed")++ with patch(+ "local_deep_research.web.services.socket_service.logger"+ ) as mock_logger:+ svc.emit_socket_event("test_event", {"key": "value"})++ mock_logger.exception.assert_called_once()+++class TestSocketIOServiceEmitToSubscribers:+ """Tests for emit_to_subscribers method."""++ @pytest.fixture+ def service(self, mock_flask_app):+ """Create SocketIOService instance with mocked SocketIO."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ service = SocketIOService(app=mock_flask_app)+ service._SocketIOService__socketio = mock_socketio+ return service, mock_socketio++ def teardown_method(self):+ """Reset singleton after each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def test_emits_formatted_event(self, service, sample_research_id):+ """Test that event is emitted with formatted name."""+ svc, mock_socketio = service++ svc.emit_to_subscribers(+ "research_update", sample_research_id, {"data": "test"}+ )++ # Should emit with formatted event name+ mock_socketio.emit.assert_any_call(+ f"research_update_{sample_research_id}", {"data": "test"}+ )++ def test_emits_to_individual_subscribers(self, service, sample_research_id):+ """Test that event is emitted to each subscriber."""+ svc, mock_socketio = service++ # Add subscribers+ svc._SocketIOService__socket_subscriptions = {+ sample_research_id: {"sid-1", "sid-2"}+ }++ svc.emit_to_subscribers(+ "research_update", sample_research_id, {"data": "test"}+ )++ # Should emit to each subscriber+ calls = mock_socketio.emit.call_args_list+ room_calls = [c for c in calls if "room" in c.kwargs]+ assert len(room_calls) == 2++ def test_returns_true_on_success(self, service, sample_research_id):+ """Test that True is returned on success."""+ svc, mock_socketio = service++ result = svc.emit_to_subscribers(+ "research_update", sample_research_id, {"data": "test"}+ )++ assert result is True++ def test_returns_false_on_exception(self, service, sample_research_id):+ """Test that False is returned on error."""+ svc, mock_socketio = service+ mock_socketio.emit.side_effect = Exception("Failed")++ result = svc.emit_to_subscribers(+ "research_update", sample_research_id, {"data": "test"}+ )++ assert result is False++ def test_disables_logging_when_requested(self, service, sample_research_id):+ """Test that logging can be disabled."""+ svc, mock_socketio = service++ svc.emit_to_subscribers(+ "research_update",+ sample_research_id,+ {"data": "test"},+ enable_logging=False,+ )++ # After call, logging should be re-enabled+ assert svc._SocketIOService__logging_enabled is True++ def test_re_enables_logging_after_exception(+ self, service, sample_research_id+ ):+ """Test that logging is re-enabled even after exception."""+ svc, mock_socketio = service+ mock_socketio.emit.side_effect = Exception("Failed")++ svc.emit_to_subscribers(+ "research_update",+ sample_research_id,+ {"data": "test"},+ enable_logging=False,+ )++ # Logging should be re-enabled after exception+ assert svc._SocketIOService__logging_enabled is True++ def test_handles_no_subscribers(self, service, sample_research_id):+ """Test handling when no subscribers exist."""+ svc, mock_socketio = service++ result = svc.emit_to_subscribers(+ "research_update", sample_research_id, {"data": "test"}+ )++ assert result is True+ # Should still emit to general channel+ mock_socketio.emit.assert_called_once()++ def test_handles_subscriber_emit_error(self, service, sample_research_id):+ """Test that individual subscriber errors don't stop other emissions."""+ svc, mock_socketio = service++ # Add subscribers+ svc._SocketIOService__socket_subscriptions = {+ sample_research_id: {"sid-1", "sid-2"}+ }++ # First call succeeds, second fails+ call_count = [0]++ def emit_side_effect(*args, **kwargs):+ call_count[0] += 1+ if call_count[0] == 2: # Fail on second subscriber+ raise Exception("Subscriber error")++ mock_socketio.emit.side_effect = emit_side_effect++ result = svc.emit_to_subscribers(+ "research_update", sample_research_id, {"data": "test"}+ )++ # Should still return True (overall success)+ assert result is True+++class TestSocketIOServiceSubscriptionManagement:+ """Tests for subscription management."""++ @pytest.fixture+ def service_with_mocks(self, mock_flask_app):+ """Create service with accessible internal state."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ service = SocketIOService(app=mock_flask_app)+ service._SocketIOService__socketio = mock_socketio+ return service, mock_socketio++ def teardown_method(self):+ """Reset singleton after each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def test_subscribe_adds_client(+ self, service_with_mocks, mock_request, sample_research_id+ ):+ """Test that subscribing adds client to subscription set."""+ svc, _ = service_with_mocks++ data = {"research_id": sample_research_id}++ svc._SocketIOService__handle_subscribe(data, mock_request)++ subscriptions = svc._SocketIOService__socket_subscriptions+ assert sample_research_id in subscriptions+ assert mock_request.sid in subscriptions[sample_research_id]++ def test_subscribe_creates_set_for_new_research(+ self, service_with_mocks, mock_request+ ):+ """Test that subscribing creates new set for new research."""+ svc, _ = service_with_mocks++ data = {"research_id": "new-research-id"}++ svc._SocketIOService__handle_subscribe(data, mock_request)++ subscriptions = svc._SocketIOService__socket_subscriptions+ assert "new-research-id" in subscriptions+ assert isinstance(subscriptions["new-research-id"], set)++ def test_subscribe_ignores_empty_research_id(+ self, service_with_mocks, mock_request+ ):+ """Test that empty research_id is ignored."""+ svc, _ = service_with_mocks++ data = {"research_id": ""}++ svc._SocketIOService__handle_subscribe(data, mock_request)++ subscriptions = svc._SocketIOService__socket_subscriptions+ assert "" not in subscriptions++ def test_subscribe_ignores_missing_research_id(+ self, service_with_mocks, mock_request+ ):+ """Test that missing research_id is ignored."""+ svc, _ = service_with_mocks++ data = {}++ svc._SocketIOService__handle_subscribe(data, mock_request)++ subscriptions = svc._SocketIOService__socket_subscriptions+ assert len(subscriptions) == 0++ def test_disconnect_removes_subscription(+ self, service_with_mocks, mock_request+ ):+ """Test that disconnecting removes client subscription."""+ svc, _ = service_with_mocks++ # Add a subscription first+ svc._SocketIOService__socket_subscriptions = {+ mock_request.sid: {"research-1", "research-2"}+ }++ svc._SocketIOService__handle_disconnect(+ mock_request, "client disconnect"+ )++ subscriptions = svc._SocketIOService__socket_subscriptions+ assert mock_request.sid not in subscriptions++ def test_disconnect_handles_no_subscription(+ self, service_with_mocks, mock_request+ ):+ """Test that disconnect handles non-subscribed client."""+ svc, _ = service_with_mocks++ # No subscriptions exist+ svc._SocketIOService__socket_subscriptions = {}++ # Should not raise+ svc._SocketIOService__handle_disconnect(+ mock_request, "client disconnect"+ )+++class TestSocketIOServiceErrorHandling:+ """Tests for error handling methods."""++ @pytest.fixture+ def service(self, mock_flask_app):+ """Create SocketIOService instance."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ service = SocketIOService(app=mock_flask_app)+ return service++ def teardown_method(self):+ """Reset singleton after each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def test_socket_error_returns_false(self, service):+ """Test that socket error handler returns False."""+ result = service._SocketIOService__handle_socket_error(+ Exception("Test error")+ )++ assert result is False++ def test_default_error_returns_false(self, service):+ """Test that default error handler returns False."""+ result = service._SocketIOService__handle_default_error(+ Exception("Test error")+ )++ assert result is False++ def test_connect_handler_logs_sid(self, service, mock_request):+ """Test that connect handler logs client SID."""+ with patch(+ "local_deep_research.web.services.socket_service.logger"+ ) as mock_logger:+ service._SocketIOService__handle_connect(mock_request)++ mock_logger.info.assert_called()+ call_args = mock_logger.info.call_args[0][0]+ assert mock_request.sid in call_args+++class TestSocketIOServiceRun:+ """Tests for run method."""++ @pytest.fixture+ def service(self, mock_flask_app):+ """Create SocketIOService instance."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ service = SocketIOService(app=mock_flask_app)+ service._SocketIOService__socketio = mock_socketio+ return service, mock_socketio, mock_flask_app++ def teardown_method(self):+ """Reset singleton after each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def test_run_calls_socketio_run(self, service):+ """Test that run method calls socketio.run."""+ svc, mock_socketio, mock_app = service++ svc.run("0.0.0.0", 5000)++ mock_socketio.run.assert_called_once()++ def test_run_passes_correct_params(self, service):+ """Test that run passes correct parameters."""+ svc, mock_socketio, mock_app = service++ svc.run("localhost", 8080, debug=True)++ mock_socketio.run.assert_called_once_with(+ mock_app,+ debug=True,+ host="localhost",+ port=8080,+ allow_unsafe_werkzeug=True,+ use_reloader=False,+ )++ def test_run_defaults_debug_to_false(self, service):+ """Test that debug defaults to False."""+ svc, mock_socketio, mock_app = service++ svc.run("0.0.0.0", 5000)++ call_kwargs = mock_socketio.run.call_args[1]+ assert call_kwargs["debug"] is False+++class TestSocketIOServiceLogging:+ """Tests for logging behavior."""++ @pytest.fixture+ def service(self, mock_flask_app):+ """Create SocketIOService instance."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ service = SocketIOService(app=mock_flask_app)+ return service++ def teardown_method(self):+ """Reset singleton after each test."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None++ def test_logging_enabled_by_default(self, service):+ """Test that logging is enabled by default."""+ assert service._SocketIOService__logging_enabled is True++ def test_log_info_logs_when_enabled(self, service):+ """Test that __log_info logs when enabled."""+ with patch(+ "local_deep_research.web.services.socket_service.logger"+ ) as mock_logger:+ service._SocketIOService__log_info("Test message")++ mock_logger.info.assert_called_once_with("Test message")++ def test_log_info_skips_when_disabled(self, service):+ """Test that __log_info skips when disabled."""+ service._SocketIOService__logging_enabled = False++ with patch(+ "local_deep_research.web.services.socket_service.logger"+ ) as mock_logger:+ service._SocketIOService__log_info("Test message")++ mock_logger.info.assert_not_called()++ def test_log_error_logs_when_enabled(self, service):+ """Test that __log_error logs when enabled."""+ with patch(+ "local_deep_research.web.services.socket_service.logger"+ ) as mock_logger:+ service._SocketIOService__log_error("Error message")++ mock_logger.error.assert_called_once_with("Error message")++ def test_log_error_skips_when_disabled(self, service):+ """Test that __log_error skips when disabled."""+ service._SocketIOService__logging_enabled = False++ with patch(+ "local_deep_research.web.services.socket_service.logger"+ ) as mock_logger:+ service._SocketIOService__log_error("Error message")++ mock_logger.error.assert_not_called()++ def test_log_exception_logs_when_enabled(self, service):+ """Test that __log_exception logs when enabled."""+ with patch(+ "local_deep_research.web.services.socket_service.logger"+ ) as mock_logger:+ service._SocketIOService__log_exception("Exception message")++ mock_logger.exception.assert_called_once_with("Exception message")++ def test_log_exception_skips_when_disabled(self, service):+ """Test that __log_exception skips when disabled."""+ service._SocketIOService__logging_enabled = False++ with patch(+ "local_deep_research.web.services.socket_service.logger"+ ) as mock_logger:+ service._SocketIOService__log_exception("Exception message")++ mock_logger.exception.assert_not_called()