Skip to content

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

Add tests for domain_classifier, llm, research_scheduler, text_processing (69 tests)

LearningCircuitb1c87bf22e08
diff --git a/tests/domain_classifier/__init__.py b/tests/domain_classifier/__init__.py
new file mode 100644
index 0000000000..80bd1dbb28
--- /dev/null
+++ b/tests/domain_classifier/__init__.py
@@ -0,0 +1 @@
+"""Tests for domain_classifier module."""
diff --git a/tests/domain_classifier/conftest.py b/tests/domain_classifier/conftest.py
new file mode 100644
index 0000000000..7314aec9dd
--- /dev/null
+++ b/tests/domain_classifier/conftest.py
@@ -0,0 +1,84 @@
+"""Fixtures for domain_classifier module tests."""
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock
+
+import pytest
+
+
+def mock_session():
+ """Mock SQLAlchemy session."""
+ session = MagicMock()
+ return session
+
+
+def mock_llm():
+ """Mock LLM instance."""
+ llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = '{"category": "News & Media", "subcategory": "Tech News", "confidence": 0.9, "reasoning": "Tech news website"}'
+ llm.invoke.return_value = mock_response
+ return llm
+
+
+def mock_research_resource():
+ """Mock ResearchResource."""
+ resource = MagicMock()
+ resource.title = "Test Article"
+ resource.url = "https://example.com/test"
+ resource.content_preview = "This is a test preview content for the article."
+ return resource
+
+
+def mock_domain_classification():
+ """Mock DomainClassification."""
+ classification = MagicMock()
+ classification.id = 1
+ classification.domain = "example.com"
+ classification.category = "News & Media"
+ classification.subcategory = "Tech News"
+ classification.confidence = 0.9
+ classification.reasoning = "Tech news website"
+ classification.sample_titles = '["Test Article"]'
+ classification.sample_count = 1
+ classification.created_at = datetime(
+ 2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc
+ )
+ classification.updated_at = datetime(
+ 2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc
+ )
+ # Configure to_dict to return an actual dict
+ classification.to_dict.return_value = {
+ "id": 1,
+ "domain": "example.com",
+ "category": "News & Media",
+ "subcategory": "Tech News",
+ "confidence": 0.9,
+ "reasoning": "Tech news website",
+ "sample_titles": '["Test Article"]',
+ "sample_count": 1,
+ "created_at": "2024-01-01T10:00:00+00:00",
+ "updated_at": "2024-01-01T10:00:00+00:00",
+ }
+ return classification
+
+
+def sample_samples():
+ """Sample resource data."""
+ return [
+ {
+ "title": "Article 1",
+ "url": "https://example.com/1",
+ "preview": "Preview 1",
+ },
+ {
+ "title": "Article 2",
+ "url": "https://example.com/2",
+ "preview": "Preview 2",
+ },
+ ]
diff --git a/tests/domain_classifier/test_classifier.py b/tests/domain_classifier/test_classifier.py
new file mode 100644
index 0000000000..c331ef646d
--- /dev/null
+++ b/tests/domain_classifier/test_classifier.py
@@ -0,0 +1,338 @@
+"""Tests for domain classifier."""
+
+from unittest.mock import MagicMock, patch
+
+
+from local_deep_research.domain_classifier.classifier import (
+ DOMAIN_CATEGORIES,
+ DomainClassifier,
+)
+
+
+class TestDomainCategories:
+ """Tests for DOMAIN_CATEGORIES constant."""
+
+ def test_has_expected_main_categories(self):
+ """Should have all expected main categories."""
+ expected = [
+ "Academic & Research",
+ "News & Media",
+ "Reference & Documentation",
+ "Social & Community",
+ "Business & Commerce",
+ "Technology",
+ "Government & Organization",
+ "Entertainment & Lifestyle",
+ "Professional & Industry",
+ "Other",
+ ]
+ for category in expected:
+ assert category in DOMAIN_CATEGORIES
+
+ def test_each_category_has_subcategories(self):
+ """Should have subcategories for each main category."""
+ for category, subcategories in DOMAIN_CATEGORIES.items():
+ assert isinstance(subcategories, list)
+ assert len(subcategories) > 0
+
+ def test_other_includes_unknown(self):
+ """Other category should include Unknown subcategory."""
+ assert "Unknown" in DOMAIN_CATEGORIES["Other"]
+
+
+class TestDomainClassifierInit:
+ """Tests for DomainClassifier initialization."""
+
+ def test_stores_username(self):
+ """Should store username."""
+ classifier = DomainClassifier(username="testuser")
+ assert classifier.username == "testuser"
+
+ def test_stores_settings_snapshot(self):
+ """Should store settings snapshot."""
+ snapshot = {"key": "value"}
+ classifier = DomainClassifier(
+ username="testuser", settings_snapshot=snapshot
+ )
+ assert classifier.settings_snapshot == snapshot
+
+ def test_llm_initially_none(self):
+ """Should have LLM as None initially."""
+ classifier = DomainClassifier(username="testuser")
+ assert classifier.llm is None
+
+
+class TestGetLlm:
+ """Tests for _get_llm method."""
+
+ def test_creates_llm_on_first_call(self):
+ """Should create LLM on first call."""
+ mock_llm = MagicMock()
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_llm",
+ return_value=mock_llm,
+ ):
+ result = classifier._get_llm()
+
+ assert result is mock_llm
+ assert classifier.llm is mock_llm
+
+ def test_reuses_existing_llm(self):
+ """Should reuse existing LLM on subsequent calls."""
+ mock_llm = MagicMock()
+ classifier = DomainClassifier(username="testuser")
+ classifier.llm = mock_llm
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_llm"
+ ) as mock_get:
+ result = classifier._get_llm()
+
+ mock_get.assert_not_called()
+ assert result is mock_llm
+
+ def test_passes_settings_snapshot(self):
+ """Should pass settings snapshot to get_llm."""
+ snapshot = {"key": "value"}
+ classifier = DomainClassifier(
+ username="testuser", settings_snapshot=snapshot
+ )
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_llm"
+ ) as mock_get:
+ classifier._get_llm()
+
+ mock_get.assert_called_once_with(settings_snapshot=snapshot)
+
+
+class TestBuildClassificationPrompt:
+ """Tests for _build_classification_prompt method."""
+
+ def test_includes_domain(self):
+ """Should include domain in prompt."""
+ classifier = DomainClassifier(username="testuser")
+ samples = []
+ prompt = classifier._build_classification_prompt("example.com", samples)
+ assert "example.com" in prompt
+
+ def test_includes_categories(self, sample_samples):
+ """Should include categories in prompt."""
+ classifier = DomainClassifier(username="testuser")
+ prompt = classifier._build_classification_prompt(
+ "example.com", sample_samples
+ )
+ assert "News & Media" in prompt
+ assert "Technology" in prompt
+
+ def test_includes_samples(self, sample_samples):
+ """Should include samples in prompt."""
+ classifier = DomainClassifier(username="testuser")
+ prompt = classifier._build_classification_prompt(
+ "example.com", sample_samples
+ )
+ assert "Article 1" in prompt
+ assert "Article 2" in prompt
+
+ def test_handles_empty_samples(self):
+ """Should handle empty samples."""
+ classifier = DomainClassifier(username="testuser")
+ prompt = classifier._build_classification_prompt("example.com", [])
+ assert "No samples available" in prompt
+
+ def test_requests_json_response(self, sample_samples):
+ """Should request JSON response format."""
+ classifier = DomainClassifier(username="testuser")
+ prompt = classifier._build_classification_prompt(
+ "example.com", sample_samples
+ )
+ assert "JSON" in prompt
+ assert "category" in prompt
+ assert "subcategory" in prompt
+ assert "confidence" in prompt
+
+
+class TestClassifyDomain:
+ """Tests for classify_domain method."""
+
+ def test_returns_existing_classification(self, mock_domain_classification):
+ """Should return existing classification without reclassifying."""
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_user_db_session"
+ ) as mock_session_ctx:
+ mock_session = MagicMock()
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_session_ctx.return_value.__exit__ = MagicMock(
+ return_value=None
+ )
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_domain_classification
+
+ result = classifier.classify_domain("example.com")
+
+ assert result is mock_domain_classification
+
+ def test_returns_none_on_error(self):
+ """Should return None on error."""
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_user_db_session"
+ ) as mock_session_ctx:
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ side_effect=Exception("DB error")
+ )
+
+ result = classifier.classify_domain("example.com")
+
+ assert result is None
+
+
+class TestGetClassification:
+ """Tests for get_classification method."""
+
+ def test_returns_classification_when_exists(
+ self, mock_domain_classification
+ ):
+ """Should return classification when exists."""
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_user_db_session"
+ ) as mock_session_ctx:
+ mock_session = MagicMock()
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_session_ctx.return_value.__exit__ = MagicMock(
+ return_value=None
+ )
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_domain_classification
+
+ result = classifier.get_classification("example.com")
+
+ assert result is mock_domain_classification
+
+ def test_returns_none_when_not_found(self):
+ """Should return None when not found."""
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_user_db_session"
+ ) as mock_session_ctx:
+ mock_session = MagicMock()
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_session_ctx.return_value.__exit__ = MagicMock(
+ return_value=None
+ )
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ result = classifier.get_classification("unknown.com")
+
+ assert result is None
+
+ def test_returns_none_on_error(self):
+ """Should return None on error."""
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_user_db_session"
+ ) as mock_session_ctx:
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ side_effect=Exception("DB error")
+ )
+
+ result = classifier.get_classification("example.com")
+
+ assert result is None
+
+
+class TestGetAllClassifications:
+ """Tests for get_all_classifications method."""
+
+ def test_returns_list_of_classifications(self, mock_domain_classification):
+ """Should return list of classifications."""
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_user_db_session"
+ ) as mock_session_ctx:
+ mock_session = MagicMock()
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_session_ctx.return_value.__exit__ = MagicMock(
+ return_value=None
+ )
+ mock_session.query.return_value.order_by.return_value.all.return_value = [
+ mock_domain_classification
+ ]
+
+ result = classifier.get_all_classifications()
+
+ assert len(result) == 1
+ assert result[0] is mock_domain_classification
+
+ def test_returns_empty_list_on_error(self):
+ """Should return empty list on error."""
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_user_db_session"
+ ) as mock_session_ctx:
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ side_effect=Exception("DB error")
+ )
+
+ result = classifier.get_all_classifications()
+
+ assert result == []
+
+
+class TestGetCategoriesSummary:
+ """Tests for get_categories_summary method."""
+
+ def test_returns_summary_dict(self, mock_domain_classification):
+ """Should return summary dictionary."""
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_user_db_session"
+ ) as mock_session_ctx:
+ mock_session = MagicMock()
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_session_ctx.return_value.__exit__ = MagicMock(
+ return_value=None
+ )
+ mock_session.query.return_value.all.return_value = [
+ mock_domain_classification
+ ]
+
+ result = classifier.get_categories_summary()
+
+ assert "News & Media" in result
+ assert result["News & Media"]["count"] == 1
+
+ def test_returns_empty_dict_on_error(self):
+ """Should return empty dict on error."""
+ classifier = DomainClassifier(username="testuser")
+
+ with patch(
+ "local_deep_research.domain_classifier.classifier.get_user_db_session"
+ ) as mock_session_ctx:
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ side_effect=Exception("DB error")
+ )
+
+ result = classifier.get_categories_summary()
+
+ assert result == {}
diff --git a/tests/domain_classifier/test_models.py b/tests/domain_classifier/test_models.py
new file mode 100644
index 0000000000..213e085bdc
--- /dev/null
+++ b/tests/domain_classifier/test_models.py
@@ -0,0 +1,88 @@
+"""Tests for domain classifier models."""
+
+from unittest.mock import MagicMock
+
+
+class TestDomainClassificationModel:
+ """Tests for DomainClassification model."""
+
+ def test_to_dict_returns_dict(self, mock_domain_classification):
+ """Should return dictionary representation."""
+ result = mock_domain_classification.to_dict()
+ assert isinstance(result, dict)
+
+ def test_to_dict_has_expected_keys(self, mock_domain_classification):
+ """Should have all expected keys."""
+ # Set up to_dict to return a dict
+ mock_domain_classification.to_dict = lambda: {
+ "id": mock_domain_classification.id,
+ "domain": mock_domain_classification.domain,
+ "category": mock_domain_classification.category,
+ "subcategory": mock_domain_classification.subcategory,
+ "confidence": mock_domain_classification.confidence,
+ "reasoning": mock_domain_classification.reasoning,
+ "sample_titles": mock_domain_classification.sample_titles,
+ "sample_count": mock_domain_classification.sample_count,
+ "created_at": mock_domain_classification.created_at.isoformat()
+ if mock_domain_classification.created_at
+ else None,
+ "updated_at": mock_domain_classification.updated_at.isoformat()
+ if mock_domain_classification.updated_at
+ else None,
+ }
+
+ result = mock_domain_classification.to_dict()
+
+ expected_keys = [
+ "id",
+ "domain",
+ "category",
+ "subcategory",
+ "confidence",
+ "reasoning",
+ "sample_titles",
+ "sample_count",
+ "created_at",
+ "updated_at",
+ ]
+ for key in expected_keys:
+ assert key in result
+
+ def test_to_dict_formats_timestamps(self, mock_domain_classification):
+ """Should format timestamps as ISO format strings."""
+ mock_domain_classification.to_dict = lambda: {
+ "created_at": mock_domain_classification.created_at.isoformat()
+ if mock_domain_classification.created_at
+ else None,
+ "updated_at": mock_domain_classification.updated_at.isoformat()
+ if mock_domain_classification.updated_at
+ else None,
+ }
+
+ result = mock_domain_classification.to_dict()
+
+ assert "T" in result["created_at"] # ISO format contains T
+ assert "T" in result["updated_at"]
+
+ def test_to_dict_handles_none_timestamps(self):
+ """Should handle None timestamps."""
+ classification = MagicMock()
+ classification.id = 1
+ classification.domain = "test.com"
+ classification.category = "Other"
+ classification.subcategory = "Unknown"
+ classification.confidence = 0.5
+ classification.reasoning = None
+ classification.sample_titles = None
+ classification.sample_count = 0
+ classification.created_at = None
+ classification.updated_at = None
+ classification.to_dict = lambda: {
+ "created_at": None,
+ "updated_at": None,
+ }
+
+ result = classification.to_dict()
+
+ assert result["created_at"] is None
+ assert result["updated_at"] is None
diff --git a/tests/llm/__init__.py b/tests/llm/__init__.py
new file mode 100644
index 0000000000..a8ba13ab86
--- /dev/null
+++ b/tests/llm/__init__.py
@@ -0,0 +1 @@
+"""Tests for llm module."""
diff --git a/tests/llm/test_llm_registry.py b/tests/llm/test_llm_registry.py
new file mode 100644
index 0000000000..8736f179d5
--- /dev/null
+++ b/tests/llm/test_llm_registry.py
@@ -0,0 +1,195 @@
+"""Tests for LLM registry module."""
+
+from unittest.mock import MagicMock
+
+import pytest
+
+from local_deep_research.llm.llm_registry import (
+ LLMRegistry,
+ register_llm,
+ unregister_llm,
+ get_llm_from_registry,
+ is_llm_registered,
+ list_registered_llms,
+ clear_llm_registry,
+ _llm_registry,
+)
+
+
+class TestLLMRegistry:
+ """Tests for LLMRegistry class."""
+
+ @pytest.fixture(autouse=True)
+ def clean_registry(self):
+ """Clean registry before each test."""
+ _llm_registry.clear()
+ yield
+ _llm_registry.clear()
+
+ def test_register_stores_llm(self):
+ """Should store LLM in registry."""
+ registry = LLMRegistry()
+ mock_llm = MagicMock()
+
+ registry.register("test", mock_llm)
+
+ assert registry.get("test") is mock_llm
+
+ def test_register_normalizes_name_to_lowercase(self):
+ """Should normalize name to lowercase."""
+ registry = LLMRegistry()
+ mock_llm = MagicMock()
+
+ registry.register("TestLLM", mock_llm)
+
+ assert registry.get("testllm") is mock_llm
+ assert registry.get("TestLLM") is mock_llm
+ assert registry.get("TESTLLM") is mock_llm
+
+ def test_register_overwrites_existing(self):
+ """Should overwrite existing LLM with same name."""
+ registry = LLMRegistry()
+ llm1 = MagicMock()
+ llm2 = MagicMock()
+
+ registry.register("test", llm1)
+ registry.register("test", llm2)
+
+ assert registry.get("test") is llm2
+
+ def test_unregister_removes_llm(self):
+ """Should remove LLM from registry."""
+ registry = LLMRegistry()
+ mock_llm = MagicMock()
+ registry.register("test", mock_llm)
+
+ registry.unregister("test")
+
+ assert registry.get("test") is None
+
+ def test_unregister_case_insensitive(self):
+ """Should unregister case-insensitively."""
+ registry = LLMRegistry()
+ mock_llm = MagicMock()
+ registry.register("TestLLM", mock_llm)
+
+ registry.unregister("TESTLLM")
+
+ assert registry.get("testllm") is None
+
+ def test_unregister_nonexistent_no_error(self):
+ """Should not raise error for nonexistent LLM."""
+ registry = LLMRegistry()
+ registry.unregister("nonexistent") # Should not raise
+
+ def test_get_returns_none_for_nonexistent(self):
+ """Should return None for nonexistent LLM."""
+ registry = LLMRegistry()
+ assert registry.get("nonexistent") is None
+
+ def test_is_registered_returns_true_when_exists(self):
+ """Should return True when LLM is registered."""
+ registry = LLMRegistry()
+ registry.register("test", MagicMock())
+
+ assert registry.is_registered("test") is True
+ assert registry.is_registered("TEST") is True
+
+ def test_is_registered_returns_false_when_not_exists(self):
+ """Should return False when LLM not registered."""
+ registry = LLMRegistry()
+ assert registry.is_registered("nonexistent") is False
+
+ def test_list_registered_returns_names(self):
+ """Should return list of registered names."""
+ registry = LLMRegistry()
+ registry.register("llm1", MagicMock())
+ registry.register("LLM2", MagicMock())
+
+ names = registry.list_registered()
+
+ assert "llm1" in names
+ assert "llm2" in names # Normalized to lowercase
+
+ def test_list_registered_returns_empty_when_empty(self):
+ """Should return empty list when no LLMs registered."""
+ registry = LLMRegistry()
+ assert registry.list_registered() == []
+
+ def test_clear_removes_all(self):
+ """Should remove all registered LLMs."""
+ registry = LLMRegistry()
+ registry.register("llm1", MagicMock())
+ registry.register("llm2", MagicMock())
+
+ registry.clear()
+
+ assert registry.list_registered() == []
+
+
+class TestGlobalRegistryFunctions:
+ """Tests for global registry functions."""
+
+ @pytest.fixture(autouse=True)
+ def clean_registry(self):
+ """Clean registry before each test."""
+ clear_llm_registry()
+ yield
+ clear_llm_registry()
+
+ def test_register_llm_adds_to_global_registry(self):
+ """Should add LLM to global registry."""
+ mock_llm = MagicMock()
+
+ register_llm("global_test", mock_llm)
+
+ assert get_llm_from_registry("global_test") is mock_llm
+
+ def test_unregister_llm_removes_from_global_registry(self):
+ """Should remove LLM from global registry."""
+ mock_llm = MagicMock()
+ register_llm("to_remove", mock_llm)
+
+ unregister_llm("to_remove")
+
+ assert get_llm_from_registry("to_remove") is None
+
+ def test_get_llm_from_registry_returns_none_for_nonexistent(self):
+ """Should return None for nonexistent LLM."""
+ assert get_llm_from_registry("nonexistent") is None
+
+ def test_is_llm_registered_checks_global_registry(self):
+ """Should check global registry."""
+ register_llm("check_test", MagicMock())
+
+ assert is_llm_registered("check_test") is True
+ assert is_llm_registered("not_registered") is False
+
+ def test_list_registered_llms_returns_global_list(self):
+ """Should return list from global registry."""
+ register_llm("list_test1", MagicMock())
+ register_llm("list_test2", MagicMock())
+
+ names = list_registered_llms()
+
+ assert "list_test1" in names
+ assert "list_test2" in names
+
+ def test_clear_llm_registry_clears_global_registry(self):
+ """Should clear global registry."""
+ register_llm("clear_test", MagicMock())
+
+ clear_llm_registry()
+
+ assert list_registered_llms() == []
+
+ def test_register_factory_function(self):
+ """Should accept factory function."""
+
+ def factory_fn(model_name, temperature, settings_snapshot):
+ return MagicMock()
+
+ register_llm("factory_test", factory_fn)
+
+ result = get_llm_from_registry("factory_test")
+ assert callable(result)
diff --git a/tests/research_scheduler/__init__.py b/tests/research_scheduler/__init__.py
new file mode 100644
index 0000000000..2d4e0988e6
--- /dev/null
+++ b/tests/research_scheduler/__init__.py
@@ -0,0 +1 @@
+"""Tests for research_scheduler module."""
diff --git a/tests/research_scheduler/conftest.py b/tests/research_scheduler/conftest.py
new file mode 100644
index 0000000000..b340423823
--- /dev/null
+++ b/tests/research_scheduler/conftest.py
@@ -0,0 +1,36 @@
+"""Fixtures for research_scheduler tests."""
+
+from unittest.mock import MagicMock
+
+import pytest
+
+
+def mock_news_scheduler():
+ """Mock NewsScheduler instance."""
+ scheduler = MagicMock()
+ scheduler.get_document_scheduler_status.return_value = {
+ "is_running": True,
+ "last_run_time": "2024-01-01T10:00:00",
+ "next_run_time": "2024-01-01T11:00:00",
+ "total_processed": 100,
+ "currently_processing": 2,
+ "processing_ids": ["id1", "id2"],
+ "settings": {"interval": 60},
+ }
+ scheduler.trigger_document_processing.return_value = True
+ return scheduler
+
+
+def sample_status():
+ """Sample scheduler status."""
+ return {
+ "is_running": True,
+ "last_run_time": "2024-01-01T10:00:00",
+ "next_run_time": "2024-01-01T11:00:00",
+ "total_processed": 100,
+ "currently_processing": 2,
+ "processing_ids": ["id1", "id2"],
+ "settings": {"interval": 60},
+ }
diff --git a/tests/research_scheduler/test_document_scheduler.py b/tests/research_scheduler/test_document_scheduler.py
new file mode 100644
index 0000000000..9c4f7eefa3
--- /dev/null
+++ b/tests/research_scheduler/test_document_scheduler.py
@@ -0,0 +1,139 @@
+"""Tests for document_scheduler module."""
+
+from unittest.mock import MagicMock, patch
+
+
+from local_deep_research.research_scheduler.document_scheduler import (
+ DocumentSchedulerUtil,
+ get_document_scheduler,
+)
+
+
+class TestDocumentSchedulerUtilInit:
+ """Tests for DocumentSchedulerUtil initialization."""
+
+ def test_initializes_successfully(self):
+ """Should initialize without error."""
+ scheduler = DocumentSchedulerUtil()
+ assert scheduler is not None
+
+
+class TestGetStatus:
+ """Tests for get_status method."""
+
+ def test_returns_status_from_news_scheduler(
+ self, mock_news_scheduler, sample_status
+ ):
+ """Should return status from news scheduler."""
+ scheduler = DocumentSchedulerUtil()
+
+ with patch(
+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler",
+ return_value=mock_news_scheduler,
+ ):
+ result = scheduler.get_status("testuser")
+
+ mock_news_scheduler.get_document_scheduler_status.assert_called_once_with(
+ "testuser"
+ )
+ assert result["is_running"] is True
+ assert result["total_processed"] == 100
+
+ def test_returns_error_status_on_exception(self):
+ """Should return error status on exception."""
+ scheduler = DocumentSchedulerUtil()
+
+ with patch(
+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler",
+ side_effect=Exception("Connection error"),
+ ):
+ result = scheduler.get_status("testuser")
+
+ assert result["error"] == "Failed to get scheduler status"
+ assert result["is_running"] is False
+ assert result["total_processed"] == 0
+
+
+class TestTriggerManualRun:
+ """Tests for trigger_manual_run method."""
+
+ def test_returns_success_when_trigger_succeeds(self, mock_news_scheduler):
+ """Should return success when trigger succeeds."""
+ scheduler = DocumentSchedulerUtil()
+
+ with patch(
+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler",
+ return_value=mock_news_scheduler,
+ ):
+ success, message = scheduler.trigger_manual_run("testuser")
+
+ assert success is True
+ assert "successfully" in message
+ mock_news_scheduler.trigger_document_processing.assert_called_once_with(
+ "testuser"
+ )
+
+ def test_returns_failure_when_trigger_fails(self):
+ """Should return failure when trigger fails."""
+ scheduler = DocumentSchedulerUtil()
+ mock_scheduler = MagicMock()
+ mock_scheduler.trigger_document_processing.return_value = False
+
+ with patch(
+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler",
+ return_value=mock_scheduler,
+ ):
+ success, message = scheduler.trigger_manual_run("testuser")
+
+ assert success is False
+ assert "Failed" in message or "disabled" in message
+
+ def test_returns_failure_on_exception(self):
+ """Should return failure on exception."""
+ scheduler = DocumentSchedulerUtil()
+
+ with patch(
+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler",
+ side_effect=Exception("Connection error"),
+ ):
+ success, message = scheduler.trigger_manual_run("testuser")
+
+ assert success is False
+ assert "Failed" in message
+
+
+class TestGetDocumentScheduler:
+ """Tests for get_document_scheduler function."""
+
+ def test_returns_singleton_instance(self):
+ """Should return singleton instance."""
+ # Reset singleton
+ import local_deep_research.research_scheduler.document_scheduler as mod
+
+ mod._scheduler_util_instance = None
+
+ instance1 = get_document_scheduler()
+ instance2 = get_document_scheduler()
+
+ assert instance1 is instance2
+
+ def test_creates_new_instance_when_none(self):
+ """Should create new instance when none exists."""
+ import local_deep_research.research_scheduler.document_scheduler as mod
+
+ mod._scheduler_util_instance = None
+
+ instance = get_document_scheduler()
+
+ assert isinstance(instance, DocumentSchedulerUtil)
+
+ def test_returns_existing_instance(self):
+ """Should return existing instance."""
+ existing = DocumentSchedulerUtil()
+ import local_deep_research.research_scheduler.document_scheduler as mod
+
+ mod._scheduler_util_instance = existing
+
+ instance = get_document_scheduler()
+
+ assert instance is existing
diff --git a/tests/research_scheduler/test_routes.py b/tests/research_scheduler/test_routes.py
new file mode 100644
index 0000000000..0b57c7ac15
--- /dev/null
+++ b/tests/research_scheduler/test_routes.py
@@ -0,0 +1,40 @@
+"""Tests for research_scheduler routes."""
+
+from unittest.mock import patch
+
+
+from local_deep_research.research_scheduler.routes import (
+ get_current_username,
+ scheduler_bp,
+)
+
+
+class TestGetCurrentUsername:
+ """Tests for get_current_username function."""
+
+ def test_returns_username_from_session(self):
+ """Should return username from session."""
+ with patch(
+ "local_deep_research.research_scheduler.routes.session",
+ {"username": "testuser"},
+ ):
+ result = get_current_username()
+ assert result == "testuser"
+
+ def test_returns_none_when_no_username(self):
+ """Should return None when no username in session."""
+ with patch("local_deep_research.research_scheduler.routes.session", {}):
+ result = get_current_username()
+ assert result is None
+
+
+class TestSchedulerBlueprint:
+ """Tests for scheduler blueprint configuration."""
+
+ def test_blueprint_name(self):
+ """Should have correct blueprint name."""
+ assert scheduler_bp.name == "document_scheduler"
+
+ def test_blueprint_exists(self):
+ """Should have valid blueprint."""
+ assert scheduler_bp is not None
diff --git a/tests/text_processing/__init__.py b/tests/text_processing/__init__.py
new file mode 100644
index 0000000000..8ffc4b1780
--- /dev/null
+++ b/tests/text_processing/__init__.py
@@ -0,0 +1 @@
+"""Tests for text_processing module."""
diff --git a/tests/text_processing/test_text_cleaner.py b/tests/text_processing/test_text_cleaner.py
new file mode 100644
index 0000000000..5eb23f01bc
--- /dev/null
+++ b/tests/text_processing/test_text_cleaner.py
@@ -0,0 +1,77 @@
+"""Tests for text_cleaner module."""
+
+from local_deep_research.text_processing.text_cleaner import remove_surrogates
+
+
+class TestRemoveSurrogates:
+ """Tests for remove_surrogates function."""
+
+ def test_returns_none_for_none_input(self):
+ """Should return None for None input."""
+ result = remove_surrogates(None)
+ assert result is None
+
+ def test_returns_empty_string_for_empty_input(self):
+ """Should return empty string for empty input."""
+ result = remove_surrogates("")
+ assert result == ""
+
+ def test_returns_normal_text_unchanged(self):
+ """Should return normal text unchanged."""
+ text = "Hello, World! This is normal text."
+ result = remove_surrogates(text)
+ assert result == text
+
+ def test_handles_unicode_text(self):
+ """Should handle valid Unicode text."""
+ text = "Hello, World! Test text"
+ result = remove_surrogates(text)
+ assert result == text
+
+ def test_removes_surrogate_characters(self):
+ """Should remove/replace surrogate characters."""
+ # Surrogate characters are in range U+D800 to U+DFFF
+ text_with_surrogate = "Hello\ud800World"
+ result = remove_surrogates(text_with_surrogate)
+ # Result should be encodable as UTF-8
+ result.encode("utf-8") # Should not raise
+ # Surrogate should be replaced
+ assert "\ud800" not in result
+
+ def test_handles_mixed_valid_and_invalid(self):
+ """Should handle text with both valid and invalid characters."""
+ text = "Valid text\ud800more valid"
+ result = remove_surrogates(text)
+ # Should preserve valid parts
+ assert "Valid text" in result
+ assert "more valid" in result
+ # Should be encodable
+ result.encode("utf-8")
+
+ def test_preserves_newlines(self):
+ """Should preserve newlines and whitespace."""
+ text = "Line 1\nLine 2\r\nLine 3\tTabbed"
+ result = remove_surrogates(text)
+ assert "\n" in result
+ assert "\t" in result
+
+ def test_handles_special_characters(self):
+ """Should handle special characters correctly."""
+ text = "<html>&nbsp;test'\"quote</html>"
+ result = remove_surrogates(text)
+ assert result == text
+
+ def test_handles_long_text(self):
+ """Should handle long text efficiently."""
+ text = "A" * 10000
+ result = remove_surrogates(text)
+ assert len(result) == 10000
+
+ def test_handles_consecutive_surrogates(self):
+ """Should handle multiple consecutive surrogate characters."""
+ text = "Start\ud800\ud801\ud802End"
+ result = remove_surrogates(text)
+ # Should be encodable
+ result.encode("utf-8")
+ assert "Start" in result
+ assert "End" in result