Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

test: add 244 tests for 6 untested modules (Phase 5)

LearningCircuit31efa4b58337
diff --git a/tests/news/core/__init__.py b/tests/news/core/__init__.py
new file mode 100644
index 0000000000..c01fbce31e
--- /dev/null
+++ b/tests/news/core/__init__.py
@@ -0,0 +1 @@
+# Tests for news core
diff --git a/tests/news/core/test_storage.py b/tests/news/core/test_storage.py
new file mode 100644
index 0000000000..65dc6ef9f0
--- /dev/null
+++ b/tests/news/core/test_storage.py
@@ -0,0 +1,726 @@
+"""
+Tests for news/core/storage.py
+
+Tests cover:
+- BaseStorage abstract interface
+- CardStorage abstract interface
+- SubscriptionStorage abstract interface
+- RatingStorage abstract interface
+- PreferenceStorage abstract interface
+- SearchHistoryStorage abstract interface
+- NewsItemStorage abstract interface
+- generate_id() utility method
+"""
+
+import pytest
+from abc import ABC
+
+
+class TestBaseStorage:
+ """Tests for BaseStorage abstract interface."""
+
+ def test_cannot_instantiate_directly(self):
+ """Test that BaseStorage cannot be instantiated directly."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ with pytest.raises(TypeError):
+ BaseStorage()
+
+ def test_is_abstract_base_class(self):
+ """Test that BaseStorage is an ABC."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ assert issubclass(BaseStorage, ABC)
+
+ def test_defines_create_abstract_method(self):
+ """Test that create is an abstract method."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ assert hasattr(BaseStorage, "create")
+ assert (
+ getattr(BaseStorage.create, "__isabstractmethod__", False) is True
+ )
+
+ def test_defines_get_abstract_method(self):
+ """Test that get is an abstract method."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ assert hasattr(BaseStorage, "get")
+ assert getattr(BaseStorage.get, "__isabstractmethod__", False) is True
+
+ def test_defines_update_abstract_method(self):
+ """Test that update is an abstract method."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ assert hasattr(BaseStorage, "update")
+ assert (
+ getattr(BaseStorage.update, "__isabstractmethod__", False) is True
+ )
+
+ def test_defines_delete_abstract_method(self):
+ """Test that delete is an abstract method."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ assert hasattr(BaseStorage, "delete")
+ assert (
+ getattr(BaseStorage.delete, "__isabstractmethod__", False) is True
+ )
+
+ def test_defines_list_abstract_method(self):
+ """Test that list is an abstract method."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ assert hasattr(BaseStorage, "list")
+ assert getattr(BaseStorage.list, "__isabstractmethod__", False) is True
+
+ def test_generate_id_is_concrete(self):
+ """Test that generate_id is a concrete method."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ assert hasattr(BaseStorage, "generate_id")
+ assert (
+ getattr(BaseStorage.generate_id, "__isabstractmethod__", False)
+ is False
+ )
+
+ def test_generate_id_returns_uuid_string(self):
+ """Test that generate_id returns a valid UUID string."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ # Create a concrete implementation to test generate_id
+ class ConcreteStorage(BaseStorage):
+ def create(self, data):
+ return "id"
+
+ def get(self, id):
+ return None
+
+ def update(self, id, data):
+ return True
+
+ def delete(self, id):
+ return True
+
+ def list(self, filters=None, limit=100, offset=0):
+ return []
+
+ storage = ConcreteStorage()
+ result = storage.generate_id()
+
+ assert isinstance(result, str)
+ assert len(result) == 36 # UUID format: 8-4-4-4-12 with dashes
+ assert result.count("-") == 4
+
+ def test_generate_id_returns_unique_values(self):
+ """Test that generate_id returns unique values."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ class ConcreteStorage(BaseStorage):
+ def create(self, data):
+ return "id"
+
+ def get(self, id):
+ return None
+
+ def update(self, id, data):
+ return True
+
+ def delete(self, id):
+ return True
+
+ def list(self, filters=None, limit=100, offset=0):
+ return []
+
+ storage = ConcreteStorage()
+ ids = [storage.generate_id() for _ in range(100)]
+
+ # All IDs should be unique
+ assert len(set(ids)) == 100
+
+
+class TestCardStorage:
+ """Tests for CardStorage abstract interface."""
+
+ def test_cannot_instantiate_directly(self):
+ """Test that CardStorage cannot be instantiated directly."""
+ from local_deep_research.news.core.storage import CardStorage
+
+ with pytest.raises(TypeError):
+ CardStorage()
+
+ def test_inherits_from_base_storage(self):
+ """Test that CardStorage inherits from BaseStorage."""
+ from local_deep_research.news.core.storage import (
+ CardStorage,
+ BaseStorage,
+ )
+
+ assert issubclass(CardStorage, BaseStorage)
+
+ def test_defines_get_by_user_abstract_method(self):
+ """Test that get_by_user is an abstract method."""
+ from local_deep_research.news.core.storage import CardStorage
+
+ assert hasattr(CardStorage, "get_by_user")
+ assert (
+ getattr(CardStorage.get_by_user, "__isabstractmethod__", False)
+ is True
+ )
+
+ def test_defines_get_latest_version_abstract_method(self):
+ """Test that get_latest_version is an abstract method."""
+ from local_deep_research.news.core.storage import CardStorage
+
+ assert hasattr(CardStorage, "get_latest_version")
+ assert (
+ getattr(
+ CardStorage.get_latest_version, "__isabstractmethod__", False
+ )
+ is True
+ )
+
+ def test_defines_add_version_abstract_method(self):
+ """Test that add_version is an abstract method."""
+ from local_deep_research.news.core.storage import CardStorage
+
+ assert hasattr(CardStorage, "add_version")
+ assert (
+ getattr(CardStorage.add_version, "__isabstractmethod__", False)
+ is True
+ )
+
+ def test_defines_update_latest_info_abstract_method(self):
+ """Test that update_latest_info is an abstract method."""
+ from local_deep_research.news.core.storage import CardStorage
+
+ assert hasattr(CardStorage, "update_latest_info")
+ assert (
+ getattr(
+ CardStorage.update_latest_info, "__isabstractmethod__", False
+ )
+ is True
+ )
+
+ def test_defines_archive_card_abstract_method(self):
+ """Test that archive_card is an abstract method."""
+ from local_deep_research.news.core.storage import CardStorage
+
+ assert hasattr(CardStorage, "archive_card")
+ assert (
+ getattr(CardStorage.archive_card, "__isabstractmethod__", False)
+ is True
+ )
+
+ def test_defines_pin_card_abstract_method(self):
+ """Test that pin_card is an abstract method."""
+ from local_deep_research.news.core.storage import CardStorage
+
+ assert hasattr(CardStorage, "pin_card")
+ assert (
+ getattr(CardStorage.pin_card, "__isabstractmethod__", False) is True
+ )
+
+
+class TestSubscriptionStorage:
+ """Tests for SubscriptionStorage abstract interface."""
+
+ def test_cannot_instantiate_directly(self):
+ """Test that SubscriptionStorage cannot be instantiated directly."""
+ from local_deep_research.news.core.storage import SubscriptionStorage
+
+ with pytest.raises(TypeError):
+ SubscriptionStorage()
+
+ def test_inherits_from_base_storage(self):
+ """Test that SubscriptionStorage inherits from BaseStorage."""
+ from local_deep_research.news.core.storage import (
+ SubscriptionStorage,
+ BaseStorage,
+ )
+
+ assert issubclass(SubscriptionStorage, BaseStorage)
+
+ def test_defines_get_active_subscriptions_abstract_method(self):
+ """Test that get_active_subscriptions is an abstract method."""
+ from local_deep_research.news.core.storage import SubscriptionStorage
+
+ assert hasattr(SubscriptionStorage, "get_active_subscriptions")
+ assert (
+ getattr(
+ SubscriptionStorage.get_active_subscriptions,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_get_due_subscriptions_abstract_method(self):
+ """Test that get_due_subscriptions is an abstract method."""
+ from local_deep_research.news.core.storage import SubscriptionStorage
+
+ assert hasattr(SubscriptionStorage, "get_due_subscriptions")
+ assert (
+ getattr(
+ SubscriptionStorage.get_due_subscriptions,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_update_refresh_time_abstract_method(self):
+ """Test that update_refresh_time is an abstract method."""
+ from local_deep_research.news.core.storage import SubscriptionStorage
+
+ assert hasattr(SubscriptionStorage, "update_refresh_time")
+ assert (
+ getattr(
+ SubscriptionStorage.update_refresh_time,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_increment_stats_abstract_method(self):
+ """Test that increment_stats is an abstract method."""
+ from local_deep_research.news.core.storage import SubscriptionStorage
+
+ assert hasattr(SubscriptionStorage, "increment_stats")
+ assert (
+ getattr(
+ SubscriptionStorage.increment_stats,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_pause_subscription_abstract_method(self):
+ """Test that pause_subscription is an abstract method."""
+ from local_deep_research.news.core.storage import SubscriptionStorage
+
+ assert hasattr(SubscriptionStorage, "pause_subscription")
+ assert (
+ getattr(
+ SubscriptionStorage.pause_subscription,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_resume_subscription_abstract_method(self):
+ """Test that resume_subscription is an abstract method."""
+ from local_deep_research.news.core.storage import SubscriptionStorage
+
+ assert hasattr(SubscriptionStorage, "resume_subscription")
+ assert (
+ getattr(
+ SubscriptionStorage.resume_subscription,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_expire_subscription_abstract_method(self):
+ """Test that expire_subscription is an abstract method."""
+ from local_deep_research.news.core.storage import SubscriptionStorage
+
+ assert hasattr(SubscriptionStorage, "expire_subscription")
+ assert (
+ getattr(
+ SubscriptionStorage.expire_subscription,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+
+class TestRatingStorage:
+ """Tests for RatingStorage abstract interface."""
+
+ def test_cannot_instantiate_directly(self):
+ """Test that RatingStorage cannot be instantiated directly."""
+ from local_deep_research.news.core.storage import RatingStorage
+
+ with pytest.raises(TypeError):
+ RatingStorage()
+
+ def test_inherits_from_base_storage(self):
+ """Test that RatingStorage inherits from BaseStorage."""
+ from local_deep_research.news.core.storage import (
+ RatingStorage,
+ BaseStorage,
+ )
+
+ assert issubclass(RatingStorage, BaseStorage)
+
+ def test_defines_get_user_rating_abstract_method(self):
+ """Test that get_user_rating is an abstract method."""
+ from local_deep_research.news.core.storage import RatingStorage
+
+ assert hasattr(RatingStorage, "get_user_rating")
+ assert (
+ getattr(
+ RatingStorage.get_user_rating, "__isabstractmethod__", False
+ )
+ is True
+ )
+
+ def test_defines_upsert_rating_abstract_method(self):
+ """Test that upsert_rating is an abstract method."""
+ from local_deep_research.news.core.storage import RatingStorage
+
+ assert hasattr(RatingStorage, "upsert_rating")
+ assert (
+ getattr(RatingStorage.upsert_rating, "__isabstractmethod__", False)
+ is True
+ )
+
+ def test_defines_get_ratings_summary_abstract_method(self):
+ """Test that get_ratings_summary is an abstract method."""
+ from local_deep_research.news.core.storage import RatingStorage
+
+ assert hasattr(RatingStorage, "get_ratings_summary")
+ assert (
+ getattr(
+ RatingStorage.get_ratings_summary, "__isabstractmethod__", False
+ )
+ is True
+ )
+
+ def test_defines_get_user_ratings_abstract_method(self):
+ """Test that get_user_ratings is an abstract method."""
+ from local_deep_research.news.core.storage import RatingStorage
+
+ assert hasattr(RatingStorage, "get_user_ratings")
+ assert (
+ getattr(
+ RatingStorage.get_user_ratings, "__isabstractmethod__", False
+ )
+ is True
+ )
+
+
+class TestPreferenceStorage:
+ """Tests for PreferenceStorage abstract interface."""
+
+ def test_cannot_instantiate_directly(self):
+ """Test that PreferenceStorage cannot be instantiated directly."""
+ from local_deep_research.news.core.storage import PreferenceStorage
+
+ with pytest.raises(TypeError):
+ PreferenceStorage()
+
+ def test_inherits_from_base_storage(self):
+ """Test that PreferenceStorage inherits from BaseStorage."""
+ from local_deep_research.news.core.storage import (
+ PreferenceStorage,
+ BaseStorage,
+ )
+
+ assert issubclass(PreferenceStorage, BaseStorage)
+
+ def test_defines_get_user_preferences_abstract_method(self):
+ """Test that get_user_preferences is an abstract method."""
+ from local_deep_research.news.core.storage import PreferenceStorage
+
+ assert hasattr(PreferenceStorage, "get_user_preferences")
+ assert (
+ getattr(
+ PreferenceStorage.get_user_preferences,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_upsert_preferences_abstract_method(self):
+ """Test that upsert_preferences is an abstract method."""
+ from local_deep_research.news.core.storage import PreferenceStorage
+
+ assert hasattr(PreferenceStorage, "upsert_preferences")
+ assert (
+ getattr(
+ PreferenceStorage.upsert_preferences,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_add_liked_item_abstract_method(self):
+ """Test that add_liked_item is an abstract method."""
+ from local_deep_research.news.core.storage import PreferenceStorage
+
+ assert hasattr(PreferenceStorage, "add_liked_item")
+ assert (
+ getattr(
+ PreferenceStorage.add_liked_item, "__isabstractmethod__", False
+ )
+ is True
+ )
+
+ def test_defines_add_disliked_item_abstract_method(self):
+ """Test that add_disliked_item is an abstract method."""
+ from local_deep_research.news.core.storage import PreferenceStorage
+
+ assert hasattr(PreferenceStorage, "add_disliked_item")
+ assert (
+ getattr(
+ PreferenceStorage.add_disliked_item,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_update_preference_embedding_abstract_method(self):
+ """Test that update_preference_embedding is an abstract method."""
+ from local_deep_research.news.core.storage import PreferenceStorage
+
+ assert hasattr(PreferenceStorage, "update_preference_embedding")
+ assert (
+ getattr(
+ PreferenceStorage.update_preference_embedding,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+
+class TestSearchHistoryStorage:
+ """Tests for SearchHistoryStorage abstract interface."""
+
+ def test_cannot_instantiate_directly(self):
+ """Test that SearchHistoryStorage cannot be instantiated directly."""
+ from local_deep_research.news.core.storage import SearchHistoryStorage
+
+ with pytest.raises(TypeError):
+ SearchHistoryStorage()
+
+ def test_inherits_from_base_storage(self):
+ """Test that SearchHistoryStorage inherits from BaseStorage."""
+ from local_deep_research.news.core.storage import (
+ SearchHistoryStorage,
+ BaseStorage,
+ )
+
+ assert issubclass(SearchHistoryStorage, BaseStorage)
+
+ def test_defines_record_search_abstract_method(self):
+ """Test that record_search is an abstract method."""
+ from local_deep_research.news.core.storage import SearchHistoryStorage
+
+ assert hasattr(SearchHistoryStorage, "record_search")
+ assert (
+ getattr(
+ SearchHistoryStorage.record_search,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_get_recent_searches_abstract_method(self):
+ """Test that get_recent_searches is an abstract method."""
+ from local_deep_research.news.core.storage import SearchHistoryStorage
+
+ assert hasattr(SearchHistoryStorage, "get_recent_searches")
+ assert (
+ getattr(
+ SearchHistoryStorage.get_recent_searches,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_link_to_subscription_abstract_method(self):
+ """Test that link_to_subscription is an abstract method."""
+ from local_deep_research.news.core.storage import SearchHistoryStorage
+
+ assert hasattr(SearchHistoryStorage, "link_to_subscription")
+ assert (
+ getattr(
+ SearchHistoryStorage.link_to_subscription,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+ def test_defines_get_popular_searches_abstract_method(self):
+ """Test that get_popular_searches is an abstract method."""
+ from local_deep_research.news.core.storage import SearchHistoryStorage
+
+ assert hasattr(SearchHistoryStorage, "get_popular_searches")
+ assert (
+ getattr(
+ SearchHistoryStorage.get_popular_searches,
+ "__isabstractmethod__",
+ False,
+ )
+ is True
+ )
+
+
+class TestNewsItemStorage:
+ """Tests for NewsItemStorage abstract interface."""
+
+ def test_cannot_instantiate_directly(self):
+ """Test that NewsItemStorage cannot be instantiated directly."""
+ from local_deep_research.news.core.storage import NewsItemStorage
+
+ with pytest.raises(TypeError):
+ NewsItemStorage()
+
+ def test_inherits_from_base_storage(self):
+ """Test that NewsItemStorage inherits from BaseStorage."""
+ from local_deep_research.news.core.storage import (
+ NewsItemStorage,
+ BaseStorage,
+ )
+
+ assert issubclass(NewsItemStorage, BaseStorage)
+
+ def test_defines_get_recent_abstract_method(self):
+ """Test that get_recent is an abstract method."""
+ from local_deep_research.news.core.storage import NewsItemStorage
+
+ assert hasattr(NewsItemStorage, "get_recent")
+ assert (
+ getattr(NewsItemStorage.get_recent, "__isabstractmethod__", False)
+ is True
+ )
+
+ def test_defines_store_batch_abstract_method(self):
+ """Test that store_batch is an abstract method."""
+ from local_deep_research.news.core.storage import NewsItemStorage
+
+ assert hasattr(NewsItemStorage, "store_batch")
+ assert (
+ getattr(NewsItemStorage.store_batch, "__isabstractmethod__", False)
+ is True
+ )
+
+ def test_defines_update_votes_abstract_method(self):
+ """Test that update_votes is an abstract method."""
+ from local_deep_research.news.core.storage import NewsItemStorage
+
+ assert hasattr(NewsItemStorage, "update_votes")
+ assert (
+ getattr(NewsItemStorage.update_votes, "__isabstractmethod__", False)
+ is True
+ )
+
+ def test_defines_get_by_category_abstract_method(self):
+ """Test that get_by_category is an abstract method."""
+ from local_deep_research.news.core.storage import NewsItemStorage
+
+ assert hasattr(NewsItemStorage, "get_by_category")
+ assert (
+ getattr(
+ NewsItemStorage.get_by_category, "__isabstractmethod__", False
+ )
+ is True
+ )
+
+ def test_defines_cleanup_old_items_abstract_method(self):
+ """Test that cleanup_old_items is an abstract method."""
+ from local_deep_research.news.core.storage import NewsItemStorage
+
+ assert hasattr(NewsItemStorage, "cleanup_old_items")
+ assert (
+ getattr(
+ NewsItemStorage.cleanup_old_items, "__isabstractmethod__", False
+ )
+ is True
+ )
+
+
+class TestConcreteImplementation:
+ """Tests for concrete implementation of BaseStorage."""
+
+ def test_can_create_concrete_subclass(self):
+ """Test that we can create a concrete subclass of BaseStorage."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ class ConcreteStorage(BaseStorage):
+ def create(self, data):
+ return self.generate_id()
+
+ def get(self, id):
+ return {"id": id}
+
+ def update(self, id, data):
+ return True
+
+ def delete(self, id):
+ return True
+
+ def list(self, filters=None, limit=100, offset=0):
+ return []
+
+ storage = ConcreteStorage()
+
+ # Should be able to call methods
+ created_id = storage.create({})
+ assert isinstance(created_id, str)
+
+ retrieved = storage.get("test-id")
+ assert retrieved == {"id": "test-id"}
+
+ updated = storage.update("test-id", {"name": "Test"})
+ assert updated is True
+
+ deleted = storage.delete("test-id")
+ assert deleted is True
+
+ listed = storage.list()
+ assert listed == []
+
+ def test_concrete_subclass_must_implement_all_methods(self):
+ """Test that concrete subclass must implement all abstract methods."""
+ from local_deep_research.news.core.storage import BaseStorage
+
+ # Missing some methods
+ class IncompleteStorage(BaseStorage):
+ def create(self, data):
+ return "id"
+
+ def get(self, id):
+ return None
+
+ # Missing update, delete, list
+
+ with pytest.raises(TypeError):
+ IncompleteStorage()
+
+
+class TestModuleImports:
+ """Tests for module imports."""
+
+ def test_all_classes_importable(self):
+ """Test that all storage classes can be imported."""
+ from local_deep_research.news.core.storage import (
+ BaseStorage,
+ CardStorage,
+ SubscriptionStorage,
+ RatingStorage,
+ PreferenceStorage,
+ SearchHistoryStorage,
+ NewsItemStorage,
+ )
+
+ assert BaseStorage is not None
+ assert CardStorage is not None
+ assert SubscriptionStorage is not None
+ assert RatingStorage is not None
+ assert PreferenceStorage is not None
+ assert SearchHistoryStorage is not None
+ assert NewsItemStorage is not None
diff --git a/tests/news/rating_system/__init__.py b/tests/news/rating_system/__init__.py
new file mode 100644
index 0000000000..e7ddb9971a
--- /dev/null
+++ b/tests/news/rating_system/__init__.py
@@ -0,0 +1 @@
+# Tests for rating system
diff --git a/tests/news/rating_system/test_storage.py b/tests/news/rating_system/test_storage.py
new file mode 100644
index 0000000000..12fe8b0c8f
--- /dev/null
+++ b/tests/news/rating_system/test_storage.py
@@ -0,0 +1,649 @@
+"""
+Tests for news/rating_system/storage.py
+
+Tests cover:
+- SQLRatingStorage initialization
+- create() - rating creation
+- get() - rating retrieval
+- update() - rating modification
+- delete() - rating removal
+- list() - rating listing with filters
+- get_user_rating() - user-specific rating retrieval
+- upsert_rating() - create or update rating
+- get_ratings_summary() - aggregated ratings
+- get_user_ratings() - all user ratings
+- _get_rating_distribution() - rating distribution helper
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+
+class TestSQLRatingStorageInitialization:
+ """Tests for SQLRatingStorage initialization."""
+
+ def test_initialization_with_valid_session(self):
+ """Test initialization with a valid session."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+
+ assert storage._session is mock_session
+
+ def test_initialization_without_session_raises_error(self):
+ """Test that initialization without session raises ValueError."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ with pytest.raises(ValueError, match="Session is required"):
+ SQLRatingStorage(None)
+
+ def test_session_property(self):
+ """Test session property returns correct session."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+
+ assert storage.session is mock_session
+
+
+class TestCreate:
+ """Tests for create() method."""
+
+ @patch("local_deep_research.news.rating_system.storage.UserRating")
+ def test_create_rating_success(self, mock_model_class):
+ """Test successful rating creation."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_rating = MagicMock()
+ mock_rating.id = 123
+ mock_model_class.return_value = mock_rating
+
+ storage = SQLRatingStorage(mock_session)
+
+ data = {
+ "user_id": "user123",
+ "item_id": "item456",
+ "item_type": "card",
+ "rating_value": "up",
+ }
+
+ result = storage.create(data)
+
+ assert result == "123"
+ mock_session.add.assert_called_once()
+ mock_session.commit.assert_called_once()
+
+ @patch("local_deep_research.news.rating_system.storage.UserRating")
+ def test_create_rating_with_default_item_type(self, mock_model_class):
+ """Test rating creation uses default item_type."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_rating = MagicMock()
+ mock_rating.id = 1
+ mock_model_class.return_value = mock_rating
+
+ storage = SQLRatingStorage(mock_session)
+
+ data = {
+ "user_id": "user123",
+ "item_id": "item456",
+ # No item_type provided
+ }
+
+ storage.create(data)
+
+ # Check that item_type was passed as "card" (default)
+ mock_model_class.assert_called_once()
+ call_kwargs = mock_model_class.call_args[1]
+ assert call_kwargs.get("item_type") == "card"
+
+
+class TestGet:
+ """Tests for get() method."""
+
+ def test_get_existing_rating(self):
+ """Test getting an existing rating."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_rating = MagicMock()
+ mock_rating.id = 123
+ mock_rating.user_id = "user123"
+ mock_rating.item_id = "item456"
+ mock_rating.item_type = "card"
+ mock_rating.relevance_vote = "up"
+ mock_rating.quality_rating = 4
+ mock_rating.created_at = None
+ mock_rating.updated_at = None
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_rating
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.get("123")
+
+ assert result is not None
+ assert result["id"] == 123
+ assert result["user_id"] == "user123"
+ assert result["item_id"] == "item456"
+
+ def test_get_nonexistent_rating(self):
+ """Test getting a nonexistent rating returns None."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.get("999")
+
+ assert result is None
+
+
+class TestUpdate:
+ """Tests for update() method."""
+
+ def test_update_existing_rating(self):
+ """Test updating an existing rating."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_rating = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_rating
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.update("123", {"rating_value": "down"})
+
+ assert result is True
+ mock_session.commit.assert_called_once()
+
+ def test_update_nonexistent_rating(self):
+ """Test updating a nonexistent rating returns False."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.update("999", {"rating_value": "down"})
+
+ assert result is False
+
+
+class TestDelete:
+ """Tests for delete() method."""
+
+ def test_delete_existing_rating(self):
+ """Test deleting an existing rating."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_rating = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_rating
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.delete("123")
+
+ assert result is True
+ mock_session.delete.assert_called_once_with(mock_rating)
+ mock_session.commit.assert_called_once()
+
+ def test_delete_nonexistent_rating(self):
+ """Test deleting a nonexistent rating returns False."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.delete("999")
+
+ assert result is False
+
+
+class TestList:
+ """Tests for list() method."""
+
+ def test_list_all_ratings(self):
+ """Test listing all ratings."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_rating = MagicMock()
+ mock_rating.id = 1
+ mock_rating.user_id = "user123"
+ mock_rating.item_id = "item456"
+ mock_rating.item_type = "card"
+ mock_rating.relevance_vote = "up"
+ mock_rating.quality_rating = None
+ mock_rating.created_at = None
+ mock_rating.updated_at = None
+
+ mock_query = MagicMock()
+ mock_query.order_by.return_value.limit.return_value.offset.return_value.all.return_value = [
+ mock_rating
+ ]
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.list()
+
+ assert len(result) == 1
+ assert result[0]["id"] == 1
+
+ def test_list_with_user_filter(self):
+ """Test listing ratings with user filter."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.order_by.return_value.limit.return_value.offset.return_value.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ storage.list(filters={"user_id": "user123"})
+
+ mock_query.filter_by.assert_called_with(user_id="user123")
+
+ def test_list_with_item_filter(self):
+ """Test listing ratings with item filter."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.order_by.return_value.limit.return_value.offset.return_value.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ storage.list(filters={"item_id": "item456"})
+
+ mock_query.filter_by.assert_called_with(item_id="item456")
+
+ def test_list_with_pagination(self):
+ """Test listing ratings with pagination."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.order_by.return_value.limit.return_value.offset.return_value.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ storage.list(limit=50, offset=10)
+
+ mock_query.order_by.return_value.limit.assert_called_once_with(50)
+ mock_query.order_by.return_value.limit.return_value.offset.assert_called_once_with(
+ 10
+ )
+
+
+class TestGetUserRating:
+ """Tests for get_user_rating() method."""
+
+ @patch("local_deep_research.news.rating_system.storage.UserRating")
+ def test_get_user_rating_found(self, mock_user_rating_class):
+ """Test getting existing user rating."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_rating = MagicMock()
+ mock_rating.to_dict.return_value = {
+ "id": 1,
+ "user_id": "user123",
+ "item_id": "item456",
+ "rating_value": "up",
+ }
+
+ # Set up mock for UserRating attributes
+ mock_user_rating_class.card_id = MagicMock()
+ mock_user_rating_class.news_item_id = MagicMock()
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.filter.return_value.first.return_value = mock_rating
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.get_user_rating("user123", "item456", "relevance")
+
+ assert result is not None
+ assert result["user_id"] == "user123"
+
+ @patch("local_deep_research.news.rating_system.storage.UserRating")
+ def test_get_user_rating_not_found(self, mock_user_rating_class):
+ """Test getting nonexistent user rating."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ # Set up mock for UserRating attributes
+ mock_user_rating_class.card_id = MagicMock()
+ mock_user_rating_class.news_item_id = MagicMock()
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.filter.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.get_user_rating("user123", "item456", "relevance")
+
+ assert result is None
+
+
+class TestUpsertRating:
+ """Tests for upsert_rating() method."""
+
+ def test_upsert_creates_new_rating(self):
+ """Test upsert creates new rating when none exists."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ storage = SQLRatingStorage(mock_session)
+ storage.get_user_rating = MagicMock(return_value=None)
+ storage.create = MagicMock(return_value="new-id-123")
+
+ result = storage.upsert_rating(
+ "user123", "item456", "relevance", "up", "card"
+ )
+
+ assert result == "new-id-123"
+ storage.create.assert_called_once()
+
+ def test_upsert_updates_existing_rating(self):
+ """Test upsert updates existing rating."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ storage = SQLRatingStorage(mock_session)
+ storage.get_user_rating = MagicMock(return_value={"id": 123})
+ storage.update = MagicMock(return_value=True)
+
+ result = storage.upsert_rating(
+ "user123", "item456", "relevance", "down", "card"
+ )
+
+ assert result == "123"
+ storage.update.assert_called_once_with("123", {"rating_value": "down"})
+
+
+class TestGetRatingsSummary:
+ """Tests for get_ratings_summary() method."""
+
+ def test_get_ratings_summary_for_card(self):
+ """Test getting ratings summary for a card."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ # Mock quality ratings
+ mock_quality_rating = MagicMock()
+ mock_quality_rating.rating_value = "4"
+
+ # Mock relevance ratings
+ mock_relevance_up = MagicMock()
+ mock_relevance_up.rating_value = "up"
+ mock_relevance_down = MagicMock()
+ mock_relevance_down.rating_value = "down"
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.all.side_effect = [
+ [mock_quality_rating], # Quality ratings
+ [mock_relevance_up, mock_relevance_down], # Relevance ratings
+ ]
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.get_ratings_summary("item456", "card")
+
+ assert result["item_id"] == "item456"
+ assert result["item_type"] == "card"
+ assert "quality" in result
+ assert "relevance" in result
+
+ def test_get_ratings_summary_empty(self):
+ """Test getting ratings summary when no ratings exist."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ storage = SQLRatingStorage(mock_session)
+ result = storage.get_ratings_summary("item456", "card")
+
+ assert result["quality"]["count"] == 0
+ assert result["quality"]["average"] == 0
+ assert result["relevance"]["up_votes"] == 0
+ assert result["relevance"]["down_votes"] == 0
+
+
+class TestGetUserRatings:
+ """Tests for get_user_ratings() method."""
+
+ def test_get_user_ratings_all(self):
+ """Test getting all ratings for a user."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+ storage.list = MagicMock(return_value=[{"id": 1}, {"id": 2}])
+
+ result = storage.get_user_ratings("user123")
+
+ assert len(result) == 2
+ storage.list.assert_called_once_with({"user_id": "user123"}, 100)
+
+ def test_get_user_ratings_with_type(self):
+ """Test getting user ratings filtered by type."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+ storage.list = MagicMock(return_value=[])
+
+ storage.get_user_ratings("user123", rating_type="relevance", limit=50)
+
+ storage.list.assert_called_once_with(
+ {"user_id": "user123", "rating_type": "relevance"}, 50
+ )
+
+
+class TestGetRatingDistribution:
+ """Tests for _get_rating_distribution() helper."""
+
+ def test_distribution_empty_list(self):
+ """Test distribution with empty list."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+
+ result = storage._get_rating_distribution([])
+
+ assert result == {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
+
+ def test_distribution_all_same_value(self):
+ """Test distribution with all same values."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+
+ result = storage._get_rating_distribution([5, 5, 5])
+
+ assert result == {1: 0, 2: 0, 3: 0, 4: 0, 5: 3}
+
+ def test_distribution_varied_values(self):
+ """Test distribution with varied values."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+
+ result = storage._get_rating_distribution([1, 2, 3, 3, 4, 5, 5])
+
+ assert result == {1: 1, 2: 1, 3: 2, 4: 1, 5: 2}
+
+ def test_distribution_ignores_out_of_range(self):
+ """Test distribution ignores values outside 1-5."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+
+ result = storage._get_rating_distribution([0, 1, 3, 6, 10])
+
+ assert result == {1: 1, 2: 0, 3: 1, 4: 0, 5: 0}
+
+
+class TestInheritance:
+ """Tests for RatingStorage inheritance."""
+
+ def test_inherits_from_rating_storage(self):
+ """Test that SQLRatingStorage inherits from RatingStorage."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+ from local_deep_research.news.core.storage import RatingStorage
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+
+ assert isinstance(storage, RatingStorage)
+
+ def test_has_generate_id_method(self):
+ """Test that storage has generate_id method from BaseStorage."""
+ from local_deep_research.news.rating_system.storage import (
+ SQLRatingStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLRatingStorage(mock_session)
+
+ assert hasattr(storage, "generate_id")
+ assert callable(storage.generate_id)
diff --git a/tests/news/subscription_manager/__init__.py b/tests/news/subscription_manager/__init__.py
index 50ec32fdd1..bc0a84088e 100644
--- a/tests/news/subscription_manager/__init__.py
+++ b/tests/news/subscription_manager/__init__.py
@@ -1 +1 @@
-# Subscription manager tests
+# Tests for subscription manager
diff --git a/tests/news/subscription_manager/test_storage.py b/tests/news/subscription_manager/test_storage.py
new file mode 100644
index 0000000000..3fce755e90
--- /dev/null
+++ b/tests/news/subscription_manager/test_storage.py
@@ -0,0 +1,812 @@
+"""
+Tests for news/subscription_manager/storage.py
+
+Tests cover:
+- SQLSubscriptionStorage initialization
+- create() - new subscription creation
+- get() - subscription retrieval
+- update() - subscription modification
+- delete() - subscription removal
+- list() - subscription listing with filters
+- get_active_subscriptions() - active subscription retrieval
+- get_due_subscriptions() - due subscription retrieval
+- update_refresh_time() - refresh time updates
+- increment_stats() - stats updates
+- pause_subscription() / resume_subscription() / expire_subscription()
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+from datetime import datetime, timezone, timedelta
+
+
+class TestSQLSubscriptionStorageInitialization:
+ """Tests for SQLSubscriptionStorage initialization."""
+
+ def test_initialization_with_valid_session(self):
+ """Test initialization with a valid session."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLSubscriptionStorage(mock_session)
+
+ assert storage._session is mock_session
+
+ def test_initialization_without_session_raises_error(self):
+ """Test that initialization without session raises ValueError."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ with pytest.raises(ValueError, match="Session is required"):
+ SQLSubscriptionStorage(None)
+
+ def test_session_property(self):
+ """Test session property returns correct session."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLSubscriptionStorage(mock_session)
+
+ assert storage.session is mock_session
+
+
+class TestCreate:
+ """Tests for create() method."""
+
+ @patch(
+ "local_deep_research.news.subscription_manager.storage.NewsSubscription"
+ )
+ def test_create_subscription_with_all_fields(self, mock_model_class):
+ """Test creating subscription with all fields."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ # Mock context manager
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_model_class.return_value = MagicMock()
+
+ storage = SQLSubscriptionStorage(mock_session)
+ storage.generate_id = MagicMock(return_value="test-id-123")
+
+ data = {
+ "user_id": "user123",
+ "subscription_type": "topic",
+ "query_or_topic": "AI news",
+ "refresh_interval_minutes": 60,
+ "name": "My AI Subscription",
+ }
+
+ result = storage.create(data)
+
+ assert result == "test-id-123"
+ mock_session.add.assert_called_once()
+ mock_session.commit.assert_called_once()
+
+ @patch(
+ "local_deep_research.news.subscription_manager.storage.NewsSubscription"
+ )
+ def test_create_subscription_with_provided_id(self, mock_model_class):
+ """Test creating subscription with provided ID."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_model_class.return_value = MagicMock()
+
+ storage = SQLSubscriptionStorage(mock_session)
+
+ data = {
+ "id": "provided-id-456",
+ "user_id": "user123",
+ "subscription_type": "topic",
+ "query_or_topic": "Tech news",
+ "refresh_interval_minutes": 30,
+ }
+
+ result = storage.create(data)
+
+ assert result == "provided-id-456"
+
+
+class TestGet:
+ """Tests for get() method."""
+
+ def test_get_existing_subscription(self):
+ """Test getting an existing subscription."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ # Create mock subscription
+ mock_subscription = MagicMock()
+ mock_subscription.id = "sub-123"
+ mock_subscription.user_id = "user123"
+ mock_subscription.name = "Test Subscription"
+ mock_subscription.subscription_type = "topic"
+ mock_subscription.query_or_topic = "AI news"
+ mock_subscription.refresh_interval_minutes = 60
+ mock_subscription.created_at = datetime.now(timezone.utc)
+ mock_subscription.updated_at = datetime.now(timezone.utc)
+ mock_subscription.last_refresh = None
+ mock_subscription.next_refresh = datetime.now(timezone.utc)
+ mock_subscription.expires_at = None
+ mock_subscription.source_type = None
+ mock_subscription.source_id = None
+ mock_subscription.created_from = None
+ mock_subscription.folder = None
+ mock_subscription.folder_id = None
+ mock_subscription.notes = None
+ mock_subscription.status = "active"
+ mock_subscription.refresh_count = 0
+ mock_subscription.results_count = 0
+ mock_subscription.last_error = None
+ mock_subscription.error_count = 0
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.get("sub-123")
+
+ assert result is not None
+ assert result["id"] == "sub-123"
+ assert result["user_id"] == "user123"
+ assert result["name"] == "Test Subscription"
+
+ def test_get_nonexistent_subscription(self):
+ """Test getting a nonexistent subscription returns None."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.get("nonexistent-id")
+
+ assert result is None
+
+
+class TestUpdate:
+ """Tests for update() method."""
+
+ def test_update_existing_subscription(self):
+ """Test updating an existing subscription."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_subscription = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.update("sub-123", {"name": "Updated Name"})
+
+ assert result is True
+ assert mock_subscription.name == "Updated Name"
+ mock_session.commit.assert_called_once()
+
+ def test_update_nonexistent_subscription(self):
+ """Test updating a nonexistent subscription returns False."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.update("nonexistent-id", {"name": "New Name"})
+
+ assert result is False
+
+ def test_update_refresh_interval_recalculates_next_refresh(self):
+ """Test that updating refresh_interval_minutes recalculates next_refresh."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_subscription = MagicMock()
+ mock_subscription.next_refresh = datetime.now(timezone.utc)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ storage.update("sub-123", {"refresh_interval_minutes": 120})
+
+ # next_refresh should be updated
+ assert mock_subscription.next_refresh is not None
+
+
+class TestDelete:
+ """Tests for delete() method."""
+
+ def test_delete_existing_subscription(self):
+ """Test deleting an existing subscription."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_subscription = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.delete("sub-123")
+
+ assert result is True
+ mock_session.delete.assert_called_once_with(mock_subscription)
+ mock_session.commit.assert_called_once()
+
+ def test_delete_nonexistent_subscription(self):
+ """Test deleting a nonexistent subscription returns False."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.delete("nonexistent-id")
+
+ assert result is False
+
+
+class TestList:
+ """Tests for list() method."""
+
+ def test_list_all_subscriptions(self):
+ """Test listing all subscriptions."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_sub1 = MagicMock()
+ mock_sub1.id = "sub-1"
+ mock_sub1.user_id = "user1"
+ mock_sub1.name = "Sub 1"
+ mock_sub1.subscription_type = "topic"
+ mock_sub1.query_or_topic = "Topic 1"
+ mock_sub1.refresh_interval_minutes = 60
+ mock_sub1.created_at = datetime.now(timezone.utc)
+ mock_sub1.updated_at = datetime.now(timezone.utc)
+ mock_sub1.last_refresh = None
+ mock_sub1.next_refresh = datetime.now(timezone.utc)
+ mock_sub1.status = "active"
+ mock_sub1.folder = None
+ mock_sub1.notes = None
+
+ mock_query = MagicMock()
+ mock_query.limit.return_value.offset.return_value.all.return_value = [
+ mock_sub1
+ ]
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.list()
+
+ assert len(result) == 1
+ assert result[0]["id"] == "sub-1"
+
+ def test_list_with_user_filter(self):
+ """Test listing subscriptions with user filter."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.limit.return_value.offset.return_value.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ storage.list(filters={"user_id": "user123"})
+
+ mock_query.filter_by.assert_called_once_with(user_id="user123")
+
+ def test_list_with_pagination(self):
+ """Test listing subscriptions with pagination."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.limit.return_value.offset.return_value.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ storage.list(limit=50, offset=10)
+
+ mock_query.limit.assert_called_once_with(50)
+ mock_query.limit.return_value.offset.assert_called_once_with(10)
+
+
+class TestGetActiveSubscriptions:
+ """Tests for get_active_subscriptions() method."""
+
+ def test_get_active_subscriptions_all_users(self):
+ """Test getting active subscriptions for all users."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+ from local_deep_research.database.models.news import SubscriptionStatus
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_sub = MagicMock()
+ mock_sub.to_dict.return_value = {"id": "sub-1", "status": "active"}
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.all.return_value = [mock_sub]
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.get_active_subscriptions()
+
+ assert len(result) == 1
+ mock_query.filter_by.assert_called_once_with(
+ status=SubscriptionStatus.ACTIVE
+ )
+
+ def test_get_active_subscriptions_for_user(self):
+ """Test getting active subscriptions for specific user."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.filter_by.return_value.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ storage.get_active_subscriptions(user_id="user123")
+
+ # Should filter by user_id after filtering by status
+ assert mock_query.filter_by.call_count >= 1
+
+
+class TestGetDueSubscriptions:
+ """Tests for get_due_subscriptions() method."""
+
+ def test_get_due_subscriptions(self):
+ """Test getting subscriptions due for refresh."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_sub = MagicMock()
+ mock_sub.to_dict.return_value = {
+ "id": "sub-1",
+ "next_refresh": datetime.now(timezone.utc),
+ }
+
+ mock_query = MagicMock()
+ mock_query.filter.return_value.limit.return_value.all.return_value = [
+ mock_sub
+ ]
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.get_due_subscriptions()
+
+ assert len(result) == 1
+
+ def test_get_due_subscriptions_with_limit(self):
+ """Test getting due subscriptions with limit."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter.return_value.limit.return_value.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ storage.get_due_subscriptions(limit=50)
+
+ mock_query.filter.return_value.limit.assert_called_once_with(50)
+
+
+class TestUpdateRefreshTime:
+ """Tests for update_refresh_time() method."""
+
+ def test_update_refresh_time_success(self):
+ """Test successful refresh time update."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_subscription = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ now = datetime.now(timezone.utc)
+ next_refresh = now + timedelta(hours=1)
+
+ result = storage.update_refresh_time("sub-123", now, next_refresh)
+
+ assert result is True
+ assert mock_subscription.last_refresh == now
+ assert mock_subscription.next_refresh == next_refresh
+ mock_session.commit.assert_called_once()
+
+ def test_update_refresh_time_not_found(self):
+ """Test refresh time update for nonexistent subscription."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ now = datetime.now(timezone.utc)
+
+ result = storage.update_refresh_time("nonexistent", now, now)
+
+ assert result is False
+
+
+class TestIncrementStats:
+ """Tests for increment_stats() method."""
+
+ def test_increment_stats_success(self):
+ """Test successful stats increment."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_subscription = MagicMock()
+ mock_subscription.refresh_count = 5
+ mock_subscription.results_count = 50
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.increment_stats("sub-123", 10)
+
+ assert result is True
+ assert mock_subscription.refresh_count == 6
+ assert mock_subscription.results_count == 10
+ mock_session.commit.assert_called_once()
+
+ def test_increment_stats_not_found(self):
+ """Test stats increment for nonexistent subscription."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.increment_stats("nonexistent", 10)
+
+ assert result is False
+
+
+class TestPauseSubscription:
+ """Tests for pause_subscription() method."""
+
+ def test_pause_subscription_success(self):
+ """Test successful subscription pause."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+ from local_deep_research.database.models.news import SubscriptionStatus
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_subscription = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.pause_subscription("sub-123")
+
+ assert result is True
+ assert mock_subscription.status == SubscriptionStatus.PAUSED
+ mock_session.commit.assert_called_once()
+
+ def test_pause_subscription_not_found(self):
+ """Test pausing nonexistent subscription."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.pause_subscription("nonexistent")
+
+ assert result is False
+
+
+class TestResumeSubscription:
+ """Tests for resume_subscription() method."""
+
+ def test_resume_subscription_success(self):
+ """Test successful subscription resume."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+ from local_deep_research.database.models.news import SubscriptionStatus
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_subscription = MagicMock()
+ mock_subscription.status = SubscriptionStatus.PAUSED
+ mock_subscription.refresh_interval_minutes = 60
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.resume_subscription("sub-123")
+
+ assert result is True
+ assert mock_subscription.status == SubscriptionStatus.ACTIVE
+ mock_session.commit.assert_called_once()
+
+ def test_resume_subscription_not_paused(self):
+ """Test resuming a subscription that's not paused returns False."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+ from local_deep_research.database.models.news import SubscriptionStatus
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_subscription = MagicMock()
+ mock_subscription.status = SubscriptionStatus.ACTIVE # Not paused
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.resume_subscription("sub-123")
+
+ assert result is False
+
+
+class TestExpireSubscription:
+ """Tests for expire_subscription() method."""
+
+ def test_expire_subscription_success(self):
+ """Test successful subscription expiration."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+ from local_deep_research.database.models.news import SubscriptionStatus
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_subscription = MagicMock()
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = mock_subscription
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.expire_subscription("sub-123")
+
+ assert result is True
+ assert mock_subscription.status == SubscriptionStatus.EXPIRED
+ assert mock_subscription.expires_at is not None
+ mock_session.commit.assert_called_once()
+
+ def test_expire_subscription_not_found(self):
+ """Test expiring nonexistent subscription."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.expire_subscription("nonexistent")
+
+ assert result is False
+
+
+class TestInheritance:
+ """Tests for SubscriptionStorage inheritance."""
+
+ def test_inherits_from_subscription_storage(self):
+ """Test that SQLSubscriptionStorage inherits from SubscriptionStorage."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+ from local_deep_research.news.core.storage import SubscriptionStorage
+
+ mock_session = MagicMock()
+ storage = SQLSubscriptionStorage(mock_session)
+
+ assert isinstance(storage, SubscriptionStorage)
+
+ def test_has_generate_id_method(self):
+ """Test that storage has generate_id method."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ storage = SQLSubscriptionStorage(mock_session)
+
+ assert hasattr(storage, "generate_id")
+ assert callable(storage.generate_id)
+
+
+class TestEdgeCases:
+ """Edge case tests."""
+
+ def test_empty_filters_in_list(self):
+ """Test list with empty filters dict."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_query = MagicMock()
+ mock_query.limit.return_value.offset.return_value.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ storage = SQLSubscriptionStorage(mock_session)
+ result = storage.list(filters={})
+
+ assert result == []
+
+ @patch(
+ "local_deep_research.news.subscription_manager.storage.NewsSubscription"
+ )
+ def test_default_values_in_create(self, mock_model_class):
+ """Test that default values are applied in create."""
+ from local_deep_research.news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+
+ mock_session = MagicMock()
+ mock_session.__enter__ = MagicMock(return_value=mock_session)
+ mock_session.__exit__ = MagicMock(return_value=False)
+
+ mock_model_class.return_value = MagicMock()
+
+ storage = SQLSubscriptionStorage(mock_session)
+ storage.generate_id = MagicMock(return_value="gen-id")
+
+ # Minimal required fields
+ data = {
+ "user_id": "user123",
+ "subscription_type": "topic",
+ "query_or_topic": "Test",
+ "refresh_interval_minutes": 60,
+ }
+
+ result = storage.create(data)
+
+ # Should succeed with minimal data
+ assert result == "gen-id"
diff --git a/tests/research_library/deletion/routes/__init__.py b/tests/research_library/deletion/routes/__init__.py
new file mode 100644
index 0000000000..63add5e757
--- /dev/null
+++ b/tests/research_library/deletion/routes/__init__.py
@@ -0,0 +1 @@
+# Tests for deletion routes
diff --git a/tests/research_library/deletion/routes/test_delete_routes.py b/tests/research_library/deletion/routes/test_delete_routes.py
new file mode 100644
index 0000000000..f03a772a74
--- /dev/null
+++ b/tests/research_library/deletion/routes/test_delete_routes.py
@@ -0,0 +1,709 @@
+"""
+Tests for research_library/deletion/routes/delete_routes.py
+
+Tests cover:
+- DELETE /document/<id> - single document deletion
+- DELETE /document/<id>/blob - blob only deletion
+- GET /document/<id>/preview - document deletion preview
+- DELETE /collection/<id>/document/<id> - remove from collection
+- DELETE /collections/<id> - collection deletion
+- DELETE /collections/<id>/index - collection index deletion
+- GET /collections/<id>/preview - collection deletion preview
+- DELETE /documents/bulk - bulk document deletion
+- DELETE /documents/blobs - bulk blob deletion
+- DELETE /collection/<id>/documents/bulk - bulk removal from collection
+- POST /documents/preview - bulk deletion preview
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+from flask import Flask
+
+
+class TestDeleteBlueprintImport:
+ """Tests for blueprint import and registration."""
+
+ def test_blueprint_exists(self):
+ """Test that delete blueprint exists."""
+ from local_deep_research.research_library.deletion.routes.delete_routes import (
+ delete_bp,
+ )
+
+ assert delete_bp is not None
+ assert delete_bp.name == "delete"
+ assert delete_bp.url_prefix == "/library/api"
+
+
+class TestDeleteDocumentEndpoint:
+ """Tests for DELETE /document/<id> endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_delete_document_service_called_correctly(self, mock_service_class):
+ """Test that DocumentDeletionService is called with correct arguments."""
+ mock_service = MagicMock()
+ mock_service.delete_document.return_value = {"deleted": True}
+ mock_service_class.return_value = mock_service
+
+ # Just verify the service mock setup works
+ service = mock_service_class("testuser")
+ result = service.delete_document("doc123")
+
+ mock_service.delete_document.assert_called_once_with("doc123")
+ assert result["deleted"] is True
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_delete_document_not_found_returns_false(self, mock_service_class):
+ """Test document deletion when document not found."""
+ mock_service = MagicMock()
+ mock_service.delete_document.return_value = {
+ "deleted": False,
+ "error": "Document not found",
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.delete_document("nonexistent")
+
+ assert result["deleted"] is False
+ assert "error" in result
+
+
+class TestDeleteDocumentBlobEndpoint:
+ """Tests for DELETE /document/<id>/blob endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_delete_blob_service_called_correctly(self, mock_service_class):
+ """Test that delete_blob_only is called correctly."""
+ mock_service = MagicMock()
+ mock_service.delete_blob_only.return_value = {
+ "deleted": True,
+ "bytes_freed": 2048,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.delete_blob_only("doc123")
+
+ mock_service.delete_blob_only.assert_called_once_with("doc123")
+ assert result["deleted"] is True
+ assert result["bytes_freed"] == 2048
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_delete_blob_not_found(self, mock_service_class):
+ """Test blob deletion when document not found."""
+ mock_service = MagicMock()
+ mock_service.delete_blob_only.return_value = {
+ "deleted": False,
+ "error": "Document not found",
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.delete_blob_only("nonexistent")
+
+ assert result["deleted"] is False
+
+
+class TestDocumentDeletionPreviewEndpoint:
+ """Tests for GET /document/<id>/preview endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_preview_service_called_correctly(self, mock_service_class):
+ """Test that get_deletion_preview is called correctly."""
+ mock_service = MagicMock()
+ mock_service.get_deletion_preview.return_value = {
+ "found": True,
+ "title": "Test Document",
+ "chunks_count": 15,
+ "blob_size": 4096,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.get_deletion_preview("doc123")
+
+ mock_service.get_deletion_preview.assert_called_once_with("doc123")
+ assert result["found"] is True
+ assert result["title"] == "Test Document"
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_preview_not_found(self, mock_service_class):
+ """Test preview for nonexistent document."""
+ mock_service = MagicMock()
+ mock_service.get_deletion_preview.return_value = {"found": False}
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.get_deletion_preview("nonexistent")
+
+ assert result["found"] is False
+
+
+class TestRemoveDocumentFromCollectionEndpoint:
+ """Tests for DELETE /collection/<coll_id>/document/<doc_id> endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_remove_from_collection_success(self, mock_service_class):
+ """Test successful removal from collection."""
+ mock_service = MagicMock()
+ mock_service.remove_from_collection.return_value = {
+ "unlinked": True,
+ "document_deleted": False,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.remove_from_collection("doc123", "coll123")
+
+ mock_service.remove_from_collection.assert_called_once_with(
+ "doc123", "coll123"
+ )
+ assert result["unlinked"] is True
+ assert result["document_deleted"] is False
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_remove_orphan_document_deleted(self, mock_service_class):
+ """Test that orphaned document is deleted."""
+ mock_service = MagicMock()
+ mock_service.remove_from_collection.return_value = {
+ "unlinked": True,
+ "document_deleted": True,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.remove_from_collection("doc123", "coll123")
+
+ assert result["unlinked"] is True
+ assert result["document_deleted"] is True
+
+
+class TestDeleteCollectionEndpoint:
+ """Tests for DELETE /collections/<id> endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.CollectionDeletionService"
+ )
+ def test_delete_collection_success(self, mock_service_class):
+ """Test successful collection deletion."""
+ mock_service = MagicMock()
+ mock_service.delete_collection.return_value = {
+ "deleted": True,
+ "documents_unlinked": 5,
+ "chunks_deleted": 150,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.delete_collection("coll123")
+
+ mock_service.delete_collection.assert_called_once_with("coll123")
+ assert result["deleted"] is True
+ assert result["documents_unlinked"] == 5
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.CollectionDeletionService"
+ )
+ def test_delete_collection_not_found(self, mock_service_class):
+ """Test collection deletion when not found."""
+ mock_service = MagicMock()
+ mock_service.delete_collection.return_value = {
+ "deleted": False,
+ "error": "Collection not found",
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.delete_collection("nonexistent")
+
+ assert result["deleted"] is False
+
+
+class TestDeleteCollectionIndexEndpoint:
+ """Tests for DELETE /collections/<id>/index endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.CollectionDeletionService"
+ )
+ def test_delete_index_success(self, mock_service_class):
+ """Test successful index deletion."""
+ mock_service = MagicMock()
+ mock_service.delete_collection_index_only.return_value = {
+ "deleted": True,
+ "chunks_deleted": 200,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.delete_collection_index_only("coll123")
+
+ mock_service.delete_collection_index_only.assert_called_once_with(
+ "coll123"
+ )
+ assert result["deleted"] is True
+ assert result["chunks_deleted"] == 200
+
+
+class TestCollectionDeletionPreviewEndpoint:
+ """Tests for GET /collections/<id>/preview endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.CollectionDeletionService"
+ )
+ def test_collection_preview_success(self, mock_service_class):
+ """Test successful collection preview."""
+ mock_service = MagicMock()
+ mock_service.get_deletion_preview.return_value = {
+ "found": True,
+ "name": "Test Collection",
+ "document_count": 10,
+ "chunk_count": 500,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.get_deletion_preview("coll123")
+
+ assert result["found"] is True
+ assert result["name"] == "Test Collection"
+
+
+class TestBulkDeleteDocumentsEndpoint:
+ """Tests for DELETE /documents/bulk endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.BulkDeletionService"
+ )
+ def test_bulk_delete_success(self, mock_service_class):
+ """Test successful bulk deletion."""
+ mock_service = MagicMock()
+ mock_service.delete_documents.return_value = {
+ "deleted": 3,
+ "failed": 0,
+ "total_chunks_deleted": 50,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.delete_documents(["doc1", "doc2", "doc3"])
+
+ mock_service.delete_documents.assert_called_once_with(
+ ["doc1", "doc2", "doc3"]
+ )
+ assert result["deleted"] == 3
+ assert result["failed"] == 0
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.BulkDeletionService"
+ )
+ def test_bulk_delete_partial_failure(self, mock_service_class):
+ """Test bulk deletion with partial failures."""
+ mock_service = MagicMock()
+ mock_service.delete_documents.return_value = {
+ "deleted": 2,
+ "failed": 1,
+ "errors": [{"id": "doc3", "error": "Not found"}],
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.delete_documents(["doc1", "doc2", "doc3"])
+
+ assert result["deleted"] == 2
+ assert result["failed"] == 1
+
+
+class TestBulkDeleteBlobsEndpoint:
+ """Tests for DELETE /documents/blobs endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.BulkDeletionService"
+ )
+ def test_bulk_delete_blobs_success(self, mock_service_class):
+ """Test successful bulk blob deletion."""
+ mock_service = MagicMock()
+ mock_service.delete_blobs.return_value = {
+ "deleted": 2,
+ "failed": 0,
+ "bytes_freed": 8192,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.delete_blobs(["doc1", "doc2"])
+
+ mock_service.delete_blobs.assert_called_once_with(["doc1", "doc2"])
+ assert result["deleted"] == 2
+ assert result["bytes_freed"] == 8192
+
+
+class TestBulkRemoveFromCollectionEndpoint:
+ """Tests for DELETE /collection/<id>/documents/bulk endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.BulkDeletionService"
+ )
+ def test_bulk_remove_success(self, mock_service_class):
+ """Test successful bulk removal from collection."""
+ mock_service = MagicMock()
+ mock_service.remove_documents_from_collection.return_value = {
+ "unlinked": 3,
+ "documents_deleted": 1,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.remove_documents_from_collection(
+ ["doc1", "doc2", "doc3"], "coll123"
+ )
+
+ mock_service.remove_documents_from_collection.assert_called_once_with(
+ ["doc1", "doc2", "doc3"], "coll123"
+ )
+ assert result["unlinked"] == 3
+ assert result["documents_deleted"] == 1
+
+
+class TestBulkDeletionPreviewEndpoint:
+ """Tests for POST /documents/preview endpoint."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.BulkDeletionService"
+ )
+ def test_bulk_preview_success(self, mock_service_class):
+ """Test successful bulk preview."""
+ mock_service = MagicMock()
+ mock_service.get_bulk_preview.return_value = {
+ "document_count": 3,
+ "total_chunks": 75,
+ "total_blob_size": 12288,
+ }
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+ result = service.get_bulk_preview(["doc1", "doc2", "doc3"], "delete")
+
+ mock_service.get_bulk_preview.assert_called_once_with(
+ ["doc1", "doc2", "doc3"], "delete"
+ )
+ assert result["document_count"] == 3
+ assert result["total_chunks"] == 75
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.BulkDeletionService"
+ )
+ def test_bulk_preview_delete_blobs_operation(self, mock_service_class):
+ """Test bulk preview with delete_blobs operation."""
+ mock_service = MagicMock()
+ mock_service.get_bulk_preview.return_value = {
+ "document_count": 2,
+ "total_blob_size": 4096,
+ }
+ mock_service_class.return_value = mock_service
+
+ _service = mock_service_class("testuser")
+ _result = _service.get_bulk_preview(["doc1", "doc2"], "delete_blobs")
+
+ mock_service.get_bulk_preview.assert_called_once_with(
+ ["doc1", "doc2"], "delete_blobs"
+ )
+
+
+class TestRequestValidation:
+ """Tests for request validation logic."""
+
+ def test_document_ids_must_be_list(self):
+ """Test that document_ids must be a list."""
+ # Simulate the validation logic from the route
+ data = {"document_ids": "not-a-list"}
+ is_valid = (
+ isinstance(data.get("document_ids"), list) and data["document_ids"]
+ )
+ assert is_valid is False
+
+ def test_document_ids_cannot_be_empty(self):
+ """Test that document_ids cannot be empty."""
+ data = {"document_ids": []}
+ is_valid = (
+ isinstance(data.get("document_ids"), list)
+ and len(data["document_ids"]) > 0
+ )
+ assert is_valid is False
+
+ def test_document_ids_required(self):
+ """Test that document_ids field is required."""
+ data = {}
+ has_document_ids = "document_ids" in data
+ assert has_document_ids is False
+
+ def test_valid_document_ids(self):
+ """Test valid document_ids format."""
+ data = {"document_ids": ["doc1", "doc2", "doc3"]}
+ is_valid = (
+ isinstance(data.get("document_ids"), list)
+ and len(data["document_ids"]) > 0
+ )
+ assert is_valid is True
+
+
+class TestErrorHandling:
+ """Tests for error handling patterns."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_service_exception_handling(self, mock_service_class):
+ """Test that service exceptions are handled."""
+ mock_service = MagicMock()
+ mock_service.delete_document.side_effect = Exception("Database error")
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+
+ with pytest.raises(Exception) as exc_info:
+ service.delete_document("doc123")
+
+ assert "Database error" in str(exc_info.value)
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.CollectionDeletionService"
+ )
+ def test_collection_service_exception(self, mock_service_class):
+ """Test collection service exception handling."""
+ mock_service = MagicMock()
+ mock_service.delete_collection.side_effect = ValueError(
+ "Invalid collection"
+ )
+ mock_service_class.return_value = mock_service
+
+ service = mock_service_class("testuser")
+
+ with pytest.raises(ValueError) as exc_info:
+ service.delete_collection("coll123")
+
+ assert "Invalid collection" in str(exc_info.value)
+
+
+class TestResponseFormats:
+ """Tests for response format consistency."""
+
+ def test_delete_success_response_format(self):
+ """Test successful deletion response format."""
+ response = {
+ "deleted": True,
+ "document_id": "doc123",
+ "chunks_deleted": 10,
+ }
+ assert "deleted" in response
+ assert response["deleted"] is True
+
+ def test_delete_failure_response_format(self):
+ """Test failed deletion response format."""
+ response = {
+ "deleted": False,
+ "error": "Document not found",
+ }
+ assert "deleted" in response
+ assert response["deleted"] is False
+ assert "error" in response
+
+ def test_preview_response_format(self):
+ """Test preview response format."""
+ response = {
+ "found": True,
+ "title": "Test Document",
+ "chunks_count": 15,
+ "blob_size": 4096,
+ }
+ assert "found" in response
+ assert response["found"] is True
+
+ def test_bulk_response_format(self):
+ """Test bulk operation response format."""
+ response = {
+ "deleted": 3,
+ "failed": 0,
+ "total_chunks_deleted": 50,
+ }
+ assert "deleted" in response
+ assert "failed" in response
+
+
+class TestServiceIntegration:
+ """Tests for service integration patterns."""
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.DocumentDeletionService"
+ )
+ def test_service_created_with_username(self, mock_service_class):
+ """Test that services are created with username."""
+ mock_service = MagicMock()
+ mock_service_class.return_value = mock_service
+
+ # Simulate how the route creates the service
+ username = "testuser"
+ _service = mock_service_class(username)
+
+ mock_service_class.assert_called_once_with(username)
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.CollectionDeletionService"
+ )
+ def test_collection_service_created_with_username(self, mock_service_class):
+ """Test that collection services are created with username."""
+ mock_service = MagicMock()
+ mock_service_class.return_value = mock_service
+
+ username = "testuser"
+ _service = mock_service_class(username)
+
+ mock_service_class.assert_called_once_with(username)
+
+ @patch(
+ "local_deep_research.research_library.deletion.routes.delete_routes.BulkDeletionService"
+ )
+ def test_bulk_service_created_with_username(self, mock_service_class):
+ """Test that bulk services are created with username."""
+ mock_service = MagicMock()
+ mock_service_class.return_value = mock_service
+
+ username = "testuser"
+ _service = mock_service_class(username)
+
+ mock_service_class.assert_called_once_with(username)
+
+
+class TestEdgeCases:
+ """Edge case tests."""
+
+ def test_uuid_format_document_id(self):
+ """Test UUID format document ID is valid."""
+ import uuid
+
+ doc_id = str(uuid.uuid4())
+ assert len(doc_id) == 36 # Standard UUID format
+
+ def test_empty_string_document_id(self):
+ """Test that empty string ID is invalid."""
+ doc_id = ""
+ is_valid = bool(doc_id)
+ assert is_valid is False
+
+ def test_whitespace_only_document_id(self):
+ """Test that whitespace-only ID is invalid."""
+ doc_id = " "
+ is_valid = bool(doc_id.strip())
+ assert is_valid is False
+
+ def test_very_long_document_id(self):
+ """Test handling of very long document ID."""
+ doc_id = "a" * 1000
+ # Should still be valid string
+ assert isinstance(doc_id, str)
+ assert len(doc_id) == 1000
+
+ def test_special_characters_in_id(self):
+ """Test special characters in document ID."""
+ special_ids = [
+ "doc-123",
+ "doc_123",
+ "doc.123",
+ "doc:123",
+ ]
+ for doc_id in special_ids:
+ assert isinstance(doc_id, str)
+
+ def test_unicode_document_id(self):
+ """Test unicode characters in document ID."""
+ doc_id = "文档123"
+ assert isinstance(doc_id, str)
+ assert len(doc_id) == 5
+
+
+class TestHandleApiErrorIntegration:
+ """Tests for handle_api_error helper."""
+
+ def test_handle_api_error_imported(self):
+ """Test that handle_api_error is available."""
+ from local_deep_research.research_library.utils import handle_api_error
+
+ assert callable(handle_api_error)
+
+ def test_handle_api_error_returns_tuple(self):
+ """Test that handle_api_error returns proper format."""
+ from flask import Flask
+ from local_deep_research.research_library.utils import handle_api_error
+
+ app = Flask(__name__)
+ with app.app_context():
+ result = handle_api_error("test operation", Exception("Test error"))
+
+ # Should return a tuple (response, status_code)
+ assert isinstance(result, tuple)
+ assert len(result) == 2
+ assert result[1] == 500 # Default status code
+
+
+class TestDeleteRoutesModuleImport:
+ """Tests for module imports."""
+
+ def test_all_services_importable(self):
+ """Test that all deletion services are importable."""
+ from local_deep_research.research_library.deletion.services.document_deletion import (
+ DocumentDeletionService,
+ )
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+ )
+ from local_deep_research.research_library.deletion.services.bulk_deletion import (
+ BulkDeletionService,
+ )
+
+ assert DocumentDeletionService is not None
+ assert CollectionDeletionService is not None
+ assert BulkDeletionService is not None
+
+ def test_blueprint_routes_registered(self):
+ """Test that all routes are registered on the blueprint."""
+ from local_deep_research.research_library.deletion.routes.delete_routes import (
+ delete_bp,
+ )
+
+ # Get all registered rules
+ app = Flask(__name__)
+ app.register_blueprint(delete_bp)
+
+ rules = [rule.rule for rule in app.url_map.iter_rules()]
+
+ expected_routes = [
+ "/library/api/document/<string:document_id>",
+ "/library/api/document/<string:document_id>/blob",
+ "/library/api/document/<string:document_id>/preview",
+ "/library/api/collection/<string:collection_id>/document/<string:document_id>",
+ "/library/api/collections/<string:collection_id>",
+ "/library/api/collections/<string:collection_id>/index",
+ "/library/api/collections/<string:collection_id>/preview",
+ "/library/api/documents/bulk",
+ "/library/api/documents/blobs",
+ "/library/api/collection/<string:collection_id>/documents/bulk",
+ "/library/api/documents/preview",
+ ]
+
+ for expected in expected_routes:
+ assert expected in rules, f"Expected route {expected} not found"
diff --git a/tests/research_library/downloaders/test_pubmed.py b/tests/research_library/downloaders/test_pubmed.py
new file mode 100644
index 0000000000..183ee61da3
--- /dev/null
+++ b/tests/research_library/downloaders/test_pubmed.py
@@ -0,0 +1,994 @@
+"""
+Tests for research_library/downloaders/pubmed.py
+
+Tests cover:
+- PubMedDownloader initialization
+- can_handle() URL detection
+- download() methods
+- download_with_result() methods
+- PDF download methods
+- Text download methods
+- Rate limiting
+- PMC ID extraction
+- Europe PMC API integration
+- Error handling
+"""
+
+from unittest.mock import MagicMock, patch
+import time
+
+
+class TestPubMedDownloaderInitialization:
+ """Tests for PubMedDownloader initialization."""
+
+ def test_default_initialization(self):
+ """Test default initialization parameters."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert downloader.timeout == 30
+ assert downloader.rate_limit_delay == 1.0
+ assert downloader.last_request_time == 0
+
+ def test_custom_timeout(self):
+ """Test initialization with custom timeout."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader(timeout=60)
+
+ assert downloader.timeout == 60
+
+ def test_custom_rate_limit(self):
+ """Test initialization with custom rate limit."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader(rate_limit_delay=2.0)
+
+ assert downloader.rate_limit_delay == 2.0
+
+
+class TestCanHandle:
+ """Tests for can_handle() URL detection."""
+
+ def test_can_handle_pubmed_url(self):
+ """Test PubMed main site URL detection."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert (
+ downloader.can_handle("https://pubmed.ncbi.nlm.nih.gov/12345678")
+ is True
+ )
+ assert (
+ downloader.can_handle("https://pubmed.ncbi.nlm.nih.gov/12345678/")
+ is True
+ )
+
+ def test_can_handle_pmc_url(self):
+ """Test PMC URL detection."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert (
+ downloader.can_handle(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC1234567"
+ )
+ is True
+ )
+ assert (
+ downloader.can_handle(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC1234567/"
+ )
+ is True
+ )
+
+ def test_can_handle_europe_pmc_url(self):
+ """Test Europe PMC URL detection."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert (
+ downloader.can_handle("https://europepmc.org/article/PMC/1234567")
+ is True
+ )
+ assert (
+ downloader.can_handle(
+ "https://www.europepmc.org/article/PMC/1234567"
+ )
+ is True
+ )
+
+ def test_cannot_handle_generic_url(self):
+ """Test that generic URLs are not handled."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert downloader.can_handle("https://google.com") is False
+ assert downloader.can_handle("https://arxiv.org/abs/1234") is False
+ assert downloader.can_handle("https://nature.com/article/123") is False
+
+ def test_cannot_handle_empty_url(self):
+ """Test that empty URL returns False."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert downloader.can_handle("") is False
+
+ def test_cannot_handle_invalid_url(self):
+ """Test that invalid URL returns False."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert downloader.can_handle("not a valid url") is False
+
+ def test_cannot_handle_ncbi_without_pmc(self):
+ """Test that NCBI URLs without /pmc are not handled."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ # ncbi.nlm.nih.gov without /pmc should return False
+ assert (
+ downloader.can_handle("https://ncbi.nlm.nih.gov/gene/12345")
+ is False
+ )
+
+
+class TestDownload:
+ """Tests for download() method."""
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_apply_rate_limit",
+ )
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_download_pdf_content",
+ )
+ def test_download_pdf_success(self, mock_download_pdf, mock_rate_limit):
+ """Test successful PDF download."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+ from local_deep_research.research_library.downloaders.base import (
+ ContentType,
+ )
+
+ mock_download_pdf.return_value = b"%PDF-1.4 content"
+
+ downloader = PubMedDownloader()
+ result = downloader.download(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678", ContentType.PDF
+ )
+
+ assert result == b"%PDF-1.4 content"
+ mock_rate_limit.assert_called_once()
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_apply_rate_limit",
+ )
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_download_text",
+ )
+ def test_download_text_success(self, mock_download_text, mock_rate_limit):
+ """Test successful text download."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+ from local_deep_research.research_library.downloaders.base import (
+ ContentType,
+ )
+
+ mock_download_text.return_value = b"Article text content"
+
+ downloader = PubMedDownloader()
+ result = downloader.download(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678", ContentType.TEXT
+ )
+
+ assert result == b"Article text content"
+
+
+class TestDownloadWithResult:
+ """Tests for download_with_result() method."""
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_apply_rate_limit",
+ )
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_download_text",
+ )
+ def test_download_text_with_result_success(
+ self, mock_download_text, mock_rate_limit
+ ):
+ """Test successful text download returns success result."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+ from local_deep_research.research_library.downloaders.base import (
+ ContentType,
+ )
+
+ mock_download_text.return_value = b"Article text content"
+
+ downloader = PubMedDownloader()
+ result = downloader.download_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678", ContentType.TEXT
+ )
+
+ assert result.is_success is True
+ assert result.content == b"Article text content"
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_apply_rate_limit",
+ )
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_download_text",
+ )
+ def test_download_text_with_result_failure(
+ self, mock_download_text, mock_rate_limit
+ ):
+ """Test failed text download returns skip reason."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+ from local_deep_research.research_library.downloaders.base import (
+ ContentType,
+ )
+
+ mock_download_text.return_value = None
+
+ downloader = PubMedDownloader()
+ result = downloader.download_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678", ContentType.TEXT
+ )
+
+ assert result.is_success is False
+ assert "subscription" in result.skip_reason.lower()
+
+
+class TestApplyRateLimit:
+ """Tests for _apply_rate_limit() method."""
+
+ def test_no_delay_on_first_request(self):
+ """Test that first request doesn't delay."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader(rate_limit_delay=1.0)
+ downloader.last_request_time = 0
+
+ start_time = time.time()
+ downloader._apply_rate_limit()
+ elapsed = time.time() - start_time
+
+ # Should be nearly instant (no delay)
+ assert elapsed < 0.1
+
+ def test_delay_on_rapid_requests(self):
+ """Test that rapid requests are rate limited."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader(rate_limit_delay=0.2)
+
+ # First request
+ downloader._apply_rate_limit()
+
+ # Second request immediately after
+ start_time = time.time()
+ downloader._apply_rate_limit()
+ elapsed = time.time() - start_time
+
+ # Should have delayed close to rate_limit_delay
+ assert elapsed >= 0.15 # Allow some tolerance
+
+ def test_no_delay_after_waiting(self):
+ """Test that there's no delay if enough time has passed."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader(rate_limit_delay=0.1)
+
+ # Set last request time to well in the past
+ downloader.last_request_time = time.time() - 10
+
+ start_time = time.time()
+ downloader._apply_rate_limit()
+ elapsed = time.time() - start_time
+
+ # Should be nearly instant
+ assert elapsed < 0.05
+
+
+class TestGetPmcIdFromPmid:
+ """Tests for _get_pmc_id_from_pmid() method."""
+
+ @patch("requests.Session.get")
+ def test_get_pmc_id_success(self, mock_get):
+ """Test successful PMC ID retrieval."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ # Mock NCBI E-utilities response
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "linksets": [{"linksetdbs": [{"dbto": "pmc", "links": [7654321]}]}]
+ }
+ mock_get.return_value = mock_response
+
+ downloader = PubMedDownloader()
+ result = downloader._get_pmc_id_from_pmid("12345678")
+
+ assert result == "PMC7654321"
+
+ @patch("requests.Session.get")
+ def test_get_pmc_id_no_link(self, mock_get):
+ """Test when no PMC link exists."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ # Mock response with no PMC links
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"linksets": [{}]}
+ mock_get.return_value = mock_response
+
+ downloader = PubMedDownloader()
+ result = downloader._get_pmc_id_from_pmid("12345678")
+
+ assert result is None
+
+ @patch("requests.Session.get")
+ def test_get_pmc_id_api_error(self, mock_get):
+ """Test PMC ID retrieval when API fails."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_get.side_effect = Exception("Network error")
+
+ downloader = PubMedDownloader()
+ result = downloader._get_pmc_id_from_pmid("12345678")
+
+ assert result is None
+
+
+class TestDownloadViaMethods:
+ """Tests for _download_via_* methods."""
+
+ @patch("requests.Session.get")
+ def test_download_via_europe_pmc_success(self, mock_get):
+ """Test successful download from Europe PMC."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.content = b"%PDF-1.4 Europe PMC content"
+ mock_response.headers = {"Content-Type": "application/pdf"}
+ mock_get.return_value = mock_response
+
+ downloader = PubMedDownloader()
+ result = downloader._download_via_europe_pmc("PMC1234567")
+
+ assert result == b"%PDF-1.4 Europe PMC content"
+
+ @patch("requests.Session.get")
+ def test_download_via_europe_pmc_failure(self, mock_get):
+ """Test failed download from Europe PMC."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_response = MagicMock()
+ mock_response.status_code = 404
+ mock_get.return_value = mock_response
+
+ downloader = PubMedDownloader()
+ result = downloader._download_via_europe_pmc("PMC1234567")
+
+ assert result is None
+
+ @patch("requests.Session.get")
+ def test_download_via_ncbi_pmc_success(self, mock_get):
+ """Test successful download from NCBI PMC."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.content = b"%PDF-1.4 NCBI PMC content"
+ mock_response.headers = {"Content-Type": "application/pdf"}
+ mock_get.return_value = mock_response
+
+ downloader = PubMedDownloader()
+ result = downloader._download_via_ncbi_pmc("PMC1234567")
+
+ assert result == b"%PDF-1.4 NCBI PMC content"
+
+
+class TestDownloadPmcDirect:
+ """Tests for _download_pmc_direct() method."""
+
+ def test_extract_pmc_id_from_url(self):
+ """Test PMC ID extraction from URL."""
+ import re
+
+ url = "https://ncbi.nlm.nih.gov/pmc/articles/PMC7654321"
+ pmc_match = re.search(r"(PMC\d+)", url)
+
+ assert pmc_match is not None
+ assert pmc_match.group(1) == "PMC7654321"
+
+ def test_pmc_id_not_found(self):
+ """Test when PMC ID is not in URL."""
+ import re
+
+ url = "https://ncbi.nlm.nih.gov/pmc/articles/"
+ pmc_match = re.search(r"(PMC\d+)", url)
+
+ assert pmc_match is None
+
+
+class TestDownloadPubmed:
+ """Tests for _download_pubmed() method."""
+
+ def test_extract_pmid_from_url(self):
+ """Test PMID extraction from URL."""
+ import re
+
+ url = "https://pubmed.ncbi.nlm.nih.gov/12345678/"
+ pmid_match = re.search(r"/(\d+)/?", url)
+
+ assert pmid_match is not None
+ assert pmid_match.group(1) == "12345678"
+
+ def test_pmid_not_found(self):
+ """Test when PMID is not in URL."""
+ import re
+
+ url = "https://pubmed.ncbi.nlm.nih.gov/"
+ pmid_match = re.search(r"/(\d+)/?", url)
+
+ assert pmid_match is None
+
+
+class TestTryEuropePmcApi:
+ """Tests for _try_europe_pmc_api() method."""
+
+ @patch("requests.Session.get")
+ def test_api_returns_open_access(self, mock_get):
+ """Test API returns open access article."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ # First call - API search
+ api_response = MagicMock()
+ api_response.status_code = 200
+ api_response.json.return_value = {
+ "resultList": {
+ "result": [
+ {
+ "isOpenAccess": "Y",
+ "hasPDF": "Y",
+ "pmcid": "PMC7654321",
+ }
+ ]
+ }
+ }
+
+ # Second call - PDF download
+ pdf_response = MagicMock()
+ pdf_response.status_code = 200
+ pdf_response.content = b"%PDF-1.4 content"
+ pdf_response.headers = {"Content-Type": "application/pdf"}
+
+ mock_get.side_effect = [api_response, pdf_response]
+
+ downloader = PubMedDownloader()
+ result = downloader._try_europe_pmc_api("12345678")
+
+ assert result == b"%PDF-1.4 content"
+
+ @patch("requests.Session.get")
+ def test_api_returns_no_results(self, mock_get):
+ """Test API returns no results."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"resultList": {"result": []}}
+ mock_get.return_value = mock_response
+
+ downloader = PubMedDownloader()
+ result = downloader._try_europe_pmc_api("12345678")
+
+ assert result is None
+
+ @patch("requests.Session.get")
+ def test_api_returns_non_open_access(self, mock_get):
+ """Test API returns non-open access article."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "resultList": {
+ "result": [
+ {
+ "isOpenAccess": "N",
+ "hasPDF": "N",
+ }
+ ]
+ }
+ }
+ mock_get.return_value = mock_response
+
+ downloader = PubMedDownloader()
+ result = downloader._try_europe_pmc_api("12345678")
+
+ assert result is None
+
+
+class TestDownloadPdfWithResult:
+ """Tests for _download_pdf_with_result() method."""
+
+ def test_invalid_pmc_url_format(self):
+ """Test invalid PMC URL format returns error result."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+ downloader._apply_rate_limit = MagicMock() # Skip rate limiting
+
+ result = downloader._download_pdf_with_result(
+ "https://ncbi.nlm.nih.gov/pmc/articles/"
+ )
+
+ # Should return skip reason about invalid format
+ assert result.is_success is False
+ assert result.skip_reason is not None
+
+ def test_invalid_pubmed_url_format(self):
+ """Test invalid PubMed URL format returns error result."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+ downloader._apply_rate_limit = MagicMock()
+
+ result = downloader._download_pdf_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/"
+ )
+
+ assert result.is_success is False
+ assert result.skip_reason is not None
+
+
+class TestFetchTextFromEuropePmc:
+ """Tests for _fetch_text_from_europe_pmc() method."""
+
+ @patch("requests.Session.get")
+ def test_fetch_text_success(self, mock_get):
+ """Test successful text fetch from Europe PMC."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ # First call - metadata
+ meta_response = MagicMock()
+ meta_response.status_code = 200
+ meta_response.json.return_value = {
+ "resultList": {
+ "result": [
+ {
+ "isOpenAccess": "Y",
+ "pmcid": "PMC7654321",
+ }
+ ]
+ }
+ }
+
+ # Second call - full text XML
+ xml_response = MagicMock()
+ xml_response.status_code = 200
+ xml_response.text = (
+ "<article><body><p>Article text content</p></body></article>"
+ )
+
+ mock_get.side_effect = [meta_response, xml_response]
+
+ downloader = PubMedDownloader()
+ result = downloader._fetch_text_from_europe_pmc("12345678", None)
+
+ assert result is not None
+ assert "Article text content" in result
+
+ @patch("requests.Session.get")
+ def test_fetch_text_no_open_access(self, mock_get):
+ """Test text fetch when article is not open access."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "resultList": {
+ "result": [
+ {
+ "isOpenAccess": "N",
+ }
+ ]
+ }
+ }
+ mock_get.return_value = mock_response
+
+ downloader = PubMedDownloader()
+ result = downloader._fetch_text_from_europe_pmc("12345678", None)
+
+ assert result is None
+
+ def test_fetch_text_no_identifiers(self):
+ """Test text fetch with no identifiers."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+ result = downloader._fetch_text_from_europe_pmc(None, None)
+
+ assert result is None
+
+
+class TestDownloadText:
+ """Tests for _download_text() method."""
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_fetch_text_from_europe_pmc",
+ )
+ def test_download_text_from_pubmed_url(self, mock_fetch_text):
+ """Test text download from PubMed URL."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_fetch_text.return_value = "Full article text"
+
+ downloader = PubMedDownloader()
+ result = downloader._download_text(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678/"
+ )
+
+ assert result == b"Full article text"
+ mock_fetch_text.assert_called_once()
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_fetch_text_from_europe_pmc",
+ )
+ def test_download_text_from_pmc_url(self, mock_fetch_text):
+ """Test text download from PMC URL."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_fetch_text.return_value = "PMC article text"
+
+ downloader = PubMedDownloader()
+ result = downloader._download_text(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC7654321/"
+ )
+
+ assert result == b"PMC article text"
+
+
+class TestDownloadPdfContent:
+ """Tests for _download_pdf_content() method."""
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_download_pmc_direct",
+ )
+ def test_routes_pmc_url_correctly(self, mock_download_pmc):
+ """Test that PMC URLs are routed to _download_pmc_direct."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_download_pmc.return_value = b"%PDF-1.4 content"
+
+ downloader = PubMedDownloader()
+ result = downloader._download_pdf_content(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC7654321"
+ )
+
+ mock_download_pmc.assert_called_once()
+ assert result == b"%PDF-1.4 content"
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_download_pubmed",
+ )
+ def test_routes_pubmed_url_correctly(self, mock_download_pubmed):
+ """Test that PubMed URLs are routed to _download_pubmed."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_download_pubmed.return_value = b"%PDF-1.4 content"
+
+ downloader = PubMedDownloader()
+ result = downloader._download_pdf_content(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678"
+ )
+
+ mock_download_pubmed.assert_called_once()
+ assert result == b"%PDF-1.4 content"
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_download_europe_pmc",
+ )
+ def test_routes_europe_pmc_url_correctly(self, mock_download_europe):
+ """Test that Europe PMC URLs are routed correctly."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_download_europe.return_value = b"%PDF-1.4 content"
+
+ downloader = PubMedDownloader()
+ result = downloader._download_pdf_content(
+ "https://europepmc.org/article/PMC/7654321"
+ )
+
+ mock_download_europe.assert_called_once()
+ assert result == b"%PDF-1.4 content"
+
+
+class TestDownloadEuropePmc:
+ """Tests for _download_europe_pmc() method."""
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_download_via_europe_pmc",
+ )
+ def test_extracts_pmc_id_and_downloads(self, mock_download):
+ """Test PMC ID extraction and download."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ mock_download.return_value = b"%PDF-1.4 content"
+
+ downloader = PubMedDownloader()
+ result = downloader._download_europe_pmc(
+ "https://europepmc.org/article/PMC7654321"
+ )
+
+ mock_download.assert_called_once_with("PMC7654321")
+ assert result == b"%PDF-1.4 content"
+
+ @patch.object(
+ __import__(
+ "local_deep_research.research_library.downloaders.pubmed",
+ fromlist=["PubMedDownloader"],
+ ).PubMedDownloader,
+ "_download_via_europe_pmc",
+ )
+ def test_returns_none_when_no_pmc_id(self, mock_download):
+ """Test returns None when PMC ID not found."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+ result = downloader._download_europe_pmc(
+ "https://europepmc.org/article/invalid"
+ )
+
+ mock_download.assert_not_called()
+ assert result is None
+
+
+class TestEdgeCases:
+ """Edge case tests."""
+
+ def test_url_with_query_parameters(self):
+ """Test URL with query parameters."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ # Should still handle URLs with query params
+ assert (
+ downloader.can_handle(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678?from=home"
+ )
+ is True
+ )
+
+ def test_url_with_fragment(self):
+ """Test URL with fragment."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert (
+ downloader.can_handle(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678#abstract"
+ )
+ is True
+ )
+
+ def test_http_url(self):
+ """Test HTTP (non-HTTPS) URL."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ # Should handle HTTP URLs too
+ assert (
+ downloader.can_handle("http://pubmed.ncbi.nlm.nih.gov/12345678")
+ is True
+ )
+
+ def test_url_parsing_exception(self):
+ """Test URL that causes parsing exception."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ # Invalid URL should return False without raising
+ result = downloader.can_handle("://invalid")
+ assert result is False
+
+
+class TestBaseDownloaderInheritance:
+ """Tests for BaseDownloader inheritance."""
+
+ def test_inherits_from_base_downloader(self):
+ """Test that PubMedDownloader inherits from BaseDownloader."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+ from local_deep_research.research_library.downloaders.base import (
+ BaseDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert isinstance(downloader, BaseDownloader)
+
+ def test_has_session_attribute(self):
+ """Test that downloader has session attribute."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert hasattr(downloader, "session")
+
+ def test_has_download_pdf_method(self):
+ """Test that downloader has _download_pdf method from base."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert hasattr(downloader, "_download_pdf")
+ assert callable(downloader._download_pdf)
+
+ def test_has_extract_text_from_pdf_method(self):
+ """Test that downloader has extract_text_from_pdf method from base."""
+ from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+ )
+
+ downloader = PubMedDownloader()
+
+ assert hasattr(downloader, "extract_text_from_pdf")
+ assert callable(downloader.extract_text_from_pdf)
diff --git a/tests/web_search_engines/test_search_engines_config.py b/tests/web_search_engines/test_search_engines_config.py
new file mode 100644
index 0000000000..a0fac428cd
--- /dev/null
+++ b/tests/web_search_engines/test_search_engines_config.py
@@ -0,0 +1,713 @@
+"""
+Tests for search_engines_config module.
+
+Tests the configuration loading and processing for search engines:
+- _get_setting() - settings retrieval with fallbacks
+- _extract_per_engine_config() - nested config extraction
+- search_config() - full search engine configuration
+- default_search_engine() - default engine retrieval
+- local_search_engines() - local engine listing
+"""
+
+from unittest.mock import MagicMock, patch
+
+
+class TestGetSetting:
+ """Tests for _get_setting function."""
+
+ def test_returns_value_from_snapshot(self):
+ """Should return value from settings snapshot when available."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _get_setting,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engines_config.get_setting_from_snapshot",
+ return_value="snapshot_value",
+ ):
+ result = _get_setting(
+ "test.key",
+ "default_value",
+ settings_snapshot={"test.key": "snapshot_value"},
+ )
+ assert result == "snapshot_value"
+
+ def test_returns_value_from_db_session(self):
+ """Should return value from db session when snapshot not available."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _get_setting,
+ )
+
+ mock_session = MagicMock()
+ mock_settings_manager = MagicMock()
+ mock_settings_manager.get_setting.return_value = "db_value"
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engines_config.get_settings_manager",
+ return_value=mock_settings_manager,
+ ):
+ result = _get_setting(
+ "test.key",
+ "default_value",
+ db_session=mock_session,
+ )
+ assert result == "db_value"
+
+ def test_returns_default_when_no_source_available(self):
+ """Should return default value when no settings source available."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _get_setting,
+ )
+
+ result = _get_setting("test.key", "default_value")
+ assert result == "default_value"
+
+ def test_prefers_snapshot_over_db_session(self):
+ """Should prefer settings snapshot over database session."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _get_setting,
+ )
+
+ mock_session = MagicMock()
+ mock_settings_manager = MagicMock()
+ mock_settings_manager.get_setting.return_value = "db_value"
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engines_config.get_setting_from_snapshot",
+ return_value="snapshot_value",
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engines_config.get_settings_manager",
+ return_value=mock_settings_manager,
+ ),
+ ):
+ result = _get_setting(
+ "test.key",
+ "default_value",
+ db_session=mock_session,
+ settings_snapshot={"test.key": "snapshot_value"},
+ )
+ assert result == "snapshot_value"
+
+ def test_handles_snapshot_exception(self):
+ """Should fall back to db_session when snapshot raises exception."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _get_setting,
+ )
+
+ mock_session = MagicMock()
+ mock_settings_manager = MagicMock()
+ mock_settings_manager.get_setting.return_value = "db_value"
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engines_config.get_setting_from_snapshot",
+ side_effect=Exception("Snapshot error"),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engines_config.get_settings_manager",
+ return_value=mock_settings_manager,
+ ),
+ ):
+ result = _get_setting(
+ "test.key",
+ "default_value",
+ db_session=mock_session,
+ settings_snapshot={"test.key": "value"},
+ )
+ assert result == "db_value"
+
+ def test_handles_db_session_exception(self):
+ """Should return default when db_session raises exception."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _get_setting,
+ )
+
+ mock_session = MagicMock()
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engines_config.get_settings_manager",
+ side_effect=Exception("DB error"),
+ ):
+ result = _get_setting(
+ "test.key",
+ "default_value",
+ db_session=mock_session,
+ )
+ assert result == "default_value"
+
+ def test_passes_username_to_settings_manager(self):
+ """Should pass username to settings manager."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _get_setting,
+ )
+
+ mock_session = MagicMock()
+ mock_settings_manager = MagicMock()
+ mock_settings_manager.get_setting.return_value = "value"
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engines_config.get_settings_manager",
+ return_value=mock_settings_manager,
+ ) as mock_get_sm:
+ _get_setting(
+ "test.key",
+ "default",
+ db_session=mock_session,
+ username="testuser",
+ )
+ mock_get_sm.assert_called_once_with(mock_session, "testuser")
+
+
+class TestExtractPerEngineConfig:
+ """Tests for _extract_per_engine_config function."""
+
+ def test_extracts_simple_flat_config(self):
+ """Should return flat config as-is for non-dotted keys."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _extract_per_engine_config,
+ )
+
+ raw_config = {"key1": "value1", "key2": "value2"}
+ result = _extract_per_engine_config(raw_config)
+ assert result == {"key1": "value1", "key2": "value2"}
+
+ def test_extracts_single_level_nested_config(self):
+ """Should convert single dotted keys to nested dict."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _extract_per_engine_config,
+ )
+
+ raw_config = {
+ "engine1.param1": "value1",
+ "engine1.param2": "value2",
+ }
+ result = _extract_per_engine_config(raw_config)
+ assert "engine1" in result
+ assert result["engine1"]["param1"] == "value1"
+ assert result["engine1"]["param2"] == "value2"
+
+ def test_extracts_multiple_engines(self):
+ """Should extract configs for multiple engines."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _extract_per_engine_config,
+ )
+
+ raw_config = {
+ "duckduckgo.api_key": "key1",
+ "google.api_key": "key2",
+ "google.cx": "cx123",
+ }
+ result = _extract_per_engine_config(raw_config)
+ assert result["duckduckgo"]["api_key"] == "key1"
+ assert result["google"]["api_key"] == "key2"
+ assert result["google"]["cx"] == "cx123"
+
+ def test_extracts_deeply_nested_config(self):
+ """Should recursively extract deeply nested configs."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _extract_per_engine_config,
+ )
+
+ raw_config = {
+ "engine.nested.param1": "value1",
+ "engine.nested.param2": "value2",
+ }
+ result = _extract_per_engine_config(raw_config)
+ assert result["engine"]["nested"]["param1"] == "value1"
+ assert result["engine"]["nested"]["param2"] == "value2"
+
+ def test_handles_empty_config(self):
+ """Should return empty dict for empty input."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _extract_per_engine_config,
+ )
+
+ result = _extract_per_engine_config({})
+ assert result == {}
+
+ def test_mixes_flat_and_nested(self):
+ """Should handle mix of flat and nested keys."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ _extract_per_engine_config,
+ )
+
+ raw_config = {
+ "simple_key": "simple_value",
+ "engine.param": "nested_value",
+ }
+ result = _extract_per_engine_config(raw_config)
+ assert result["simple_key"] == "simple_value"
+ assert result["engine"]["param"] == "nested_value"
+
+
+class TestSearchConfig:
+ """Tests for search_config function."""
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_returns_dict_of_search_engines(
+ self, mock_get_setting, mock_registry
+ ):
+ """Should return dict containing search engine configs."""
+ mock_get_setting.return_value = {}
+ mock_registry.list_registered.return_value = []
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ assert isinstance(result, dict)
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_includes_auto_config(self, mock_get_setting, mock_registry):
+ """Should include 'auto' key in result."""
+ mock_get_setting.return_value = {}
+ mock_registry.list_registered.return_value = []
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ assert "auto" in result
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_adds_meta_alias_for_auto(self, mock_get_setting, mock_registry):
+ """Should add 'meta' as alias for 'auto'."""
+ mock_get_setting.return_value = {}
+ mock_registry.list_registered.return_value = []
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ assert "meta" in result
+ assert result["meta"] == result["auto"]
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_includes_registered_retrievers(
+ self, mock_get_setting, mock_registry
+ ):
+ """Should include registered retrievers as search engines."""
+ mock_get_setting.return_value = {}
+ mock_registry.list_registered.return_value = ["custom_retriever"]
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ assert "custom_retriever" in result
+ assert result["custom_retriever"]["is_retriever"] is True
+ assert (
+ result["custom_retriever"]["class_name"] == "RetrieverSearchEngine"
+ )
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_processes_local_collections(self, mock_get_setting, mock_registry):
+ """Should process local collection configurations."""
+ mock_registry.list_registered.return_value = []
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.local":
+ return {
+ "my_docs.enabled": True,
+ "my_docs.paths": '["./docs"]',
+ }
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ assert "my_docs" in result
+ assert result["my_docs"]["requires_llm"] is True
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_skips_disabled_local_collections(
+ self, mock_get_setting, mock_registry
+ ):
+ """Should skip disabled local collections."""
+ mock_registry.list_registered.return_value = []
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.local":
+ return {
+ "disabled_docs.enabled": False,
+ "disabled_docs.paths": '["./docs"]',
+ }
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ assert "disabled_docs" not in result
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_parses_json_paths_for_local_collection(
+ self, mock_get_setting, mock_registry
+ ):
+ """Should parse JSON array for local collection paths."""
+ mock_registry.list_registered.return_value = []
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.local":
+ return {
+ "my_docs.enabled": True,
+ "my_docs.paths": '["./path1", "./path2"]',
+ }
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ assert result["my_docs"]["default_params"]["paths"] == [
+ "./path1",
+ "./path2",
+ ]
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_handles_invalid_json_paths(self, mock_get_setting, mock_registry):
+ """Should handle invalid JSON in paths gracefully."""
+ mock_registry.list_registered.return_value = []
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.local":
+ return {
+ "my_docs.enabled": True,
+ "my_docs.paths": "invalid json",
+ }
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ # Should set to empty list on JSON error
+ assert result["my_docs"]["default_params"]["paths"] == []
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_adds_library_search_engine_when_enabled(
+ self, mock_get_setting, mock_registry
+ ):
+ """Should add library search engine when enabled."""
+ mock_registry.list_registered.return_value = []
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.library.enabled":
+ return True
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ assert "library" in result
+ assert result["library"]["class_name"] == "LibraryRAGSearchEngine"
+
+ @patch(
+ "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_skips_library_when_disabled(self, mock_get_setting, mock_registry):
+ """Should skip library search engine when disabled."""
+ mock_registry.list_registered.return_value = []
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.library.enabled":
+ return False
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ result = search_config()
+ assert "library" not in result
+
+
+class TestDefaultSearchEngine:
+ """Tests for default_search_engine function."""
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_returns_configured_default(self, mock_get_setting):
+ """Should return configured default search engine."""
+ mock_get_setting.return_value = "google"
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ default_search_engine,
+ )
+
+ result = default_search_engine()
+ assert result == "google"
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_returns_wikipedia_as_default(self, mock_get_setting):
+ """Should return 'wikipedia' as default when not configured."""
+ mock_get_setting.return_value = "wikipedia"
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ default_search_engine,
+ )
+
+ result = default_search_engine()
+ assert result == "wikipedia"
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_uses_correct_setting_key(self, mock_get_setting):
+ """Should query the correct setting key."""
+ mock_get_setting.return_value = "duckduckgo"
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ default_search_engine,
+ )
+
+ default_search_engine()
+ mock_get_setting.assert_called_once()
+ call_args = mock_get_setting.call_args
+ assert call_args[0][0] == "search.engine.DEFAULT_SEARCH_ENGINE"
+ assert call_args[0][1] == "wikipedia"
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_passes_db_session(self, mock_get_setting):
+ """Should pass db_session to _get_setting."""
+ mock_get_setting.return_value = "searxng"
+ mock_session = MagicMock()
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ default_search_engine,
+ )
+
+ default_search_engine(db_session=mock_session)
+ call_kwargs = mock_get_setting.call_args[1]
+ assert call_kwargs["db_session"] is mock_session
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_passes_settings_snapshot(self, mock_get_setting):
+ """Should pass settings_snapshot to _get_setting."""
+ mock_get_setting.return_value = "brave"
+ snapshot = {"search.engine.DEFAULT_SEARCH_ENGINE": "brave"}
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ default_search_engine,
+ )
+
+ default_search_engine(settings_snapshot=snapshot)
+ call_kwargs = mock_get_setting.call_args[1]
+ assert call_kwargs["settings_snapshot"] is snapshot
+
+
+class TestLocalSearchEngines:
+ """Tests for local_search_engines function."""
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_returns_list_of_enabled_collections(self, mock_get_setting):
+ """Should return list of enabled local collection names."""
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.local":
+ return {
+ "docs1.enabled": True,
+ "docs2.enabled": True,
+ }
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ local_search_engines,
+ )
+
+ result = local_search_engines()
+ assert isinstance(result, list)
+ assert "docs1" in result
+ assert "docs2" in result
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_excludes_disabled_collections(self, mock_get_setting):
+ """Should exclude disabled collections."""
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.local":
+ return {
+ "enabled_docs.enabled": True,
+ "disabled_docs.enabled": False,
+ }
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ local_search_engines,
+ )
+
+ result = local_search_engines()
+ assert "enabled_docs" in result
+ assert "disabled_docs" not in result
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_excludes_local_all_collection(self, mock_get_setting):
+ """Should exclude the 'local_all' collection."""
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.local":
+ return {
+ "local_all.enabled": True,
+ "my_docs.enabled": True,
+ }
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ local_search_engines,
+ )
+
+ result = local_search_engines()
+ assert "local_all" not in result
+ assert "my_docs" in result
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_returns_empty_list_when_no_local_engines(self, mock_get_setting):
+ """Should return empty list when no local engines configured."""
+ mock_get_setting.return_value = {}
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ local_search_engines,
+ )
+
+ result = local_search_engines()
+ assert result == []
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_treats_missing_enabled_as_true(self, mock_get_setting):
+ """Should treat missing 'enabled' field as True (default enabled)."""
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.engine.local":
+ return {
+ "implicit_enabled.paths": '["./docs"]',
+ }
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ local_search_engines,
+ )
+
+ result = local_search_engines()
+ assert "implicit_enabled" in result
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_passes_all_parameters_to_get_setting(self, mock_get_setting):
+ """Should pass username, db_session, and settings_snapshot."""
+ mock_get_setting.return_value = {}
+ mock_session = MagicMock()
+ snapshot = {"test": "value"}
+
+ from local_deep_research.web_search_engines.search_engines_config import (
+ local_search_engines,
+ )
+
+ local_search_engines(
+ username="testuser",
+ db_session=mock_session,
+ settings_snapshot=snapshot,
+ )
+
+ call_kwargs = mock_get_setting.call_args[1]
+ assert call_kwargs["username"] == "testuser"
+ assert call_kwargs["db_session"] is mock_session
+ assert call_kwargs["settings_snapshot"] is snapshot