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 132 high-value tests across 10 under-tested modules (round 5) (#2569)

LearningCircuit0107cd9fa210
diff --git a/tests/content_fetcher/test_url_classifier_pdf.py b/tests/content_fetcher/test_url_classifier_pdf.py
new file mode 100644
index 0000000000..b7d259bf33
--- /dev/null
+++ b/tests/content_fetcher/test_url_classifier_pdf.py
@@ -0,0 +1,88 @@
+"""Tests for URLClassifier._is_pdf_url method."""
+
+from local_deep_research.content_fetcher.url_classifier import URLClassifier
+
+
+class TestIsPdfUrl:
+ """Tests for _is_pdf_url()."""
+
+ def test_pdf_extension(self):
+ assert URLClassifier._is_pdf_url("https://example.com/doc.pdf") is True
+
+ def test_pdf_extension_case_insensitive(self):
+ assert URLClassifier._is_pdf_url("https://example.com/doc.PDF") is True
+
+ def test_pdf_in_path(self):
+ assert (
+ URLClassifier._is_pdf_url("https://example.com/pdf/document")
+ is True
+ )
+
+ def test_html_url(self):
+ assert (
+ URLClassifier._is_pdf_url("https://example.com/page.html") is False
+ )
+
+ def test_no_extension(self):
+ assert (
+ URLClassifier._is_pdf_url("https://example.com/article/123")
+ is False
+ )
+
+ def test_arxiv_pdf_not_treated_as_generic_pdf(self):
+ """arXiv PDFs should use specialized downloader, not generic PDF."""
+ assert (
+ URLClassifier._is_pdf_url("https://arxiv.org/pdf/2301.12345")
+ is False
+ )
+
+ def test_biorxiv_pdf_not_treated_as_generic_pdf(self):
+ assert (
+ URLClassifier._is_pdf_url(
+ "https://www.biorxiv.org/content/10.1101/2024.01.01.pdf"
+ )
+ is False
+ )
+
+ def test_medrxiv_pdf_not_treated_as_generic_pdf(self):
+ assert (
+ URLClassifier._is_pdf_url(
+ "https://www.medrxiv.org/content/10.1101/2024.01.01.pdf"
+ )
+ is False
+ )
+
+ def test_ncbi_pdf_not_treated_as_generic_pdf(self):
+ assert (
+ URLClassifier._is_pdf_url(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC123/pdf/"
+ )
+ is False
+ )
+
+ def test_semanticscholar_not_treated_as_generic_pdf(self):
+ assert (
+ URLClassifier._is_pdf_url(
+ "https://pdfs.semanticscholar.org/abc.pdf"
+ )
+ is False
+ )
+
+ def test_generic_domain_pdf(self):
+ """Non-academic domain PDFs should be treated as generic PDFs."""
+ assert (
+ URLClassifier._is_pdf_url("https://company.com/reports/annual.pdf")
+ is True
+ )
+
+ def test_pdf_with_query_params(self):
+ assert (
+ URLClassifier._is_pdf_url("https://example.com/doc.pdf?v=2") is True
+ )
+
+ def test_url_with_pdf_in_query_not_matched(self):
+ """pdf in query string shouldn't trigger PDF detection."""
+ assert (
+ URLClassifier._is_pdf_url("https://example.com/viewer?file=doc.pdf")
+ is False
+ )
diff --git a/tests/research_library/routes/test_rag_routes_indexing.py b/tests/research_library/routes/test_rag_routes_indexing.py
new file mode 100644
index 0000000000..32ca69eee6
--- /dev/null
+++ b/tests/research_library/routes/test_rag_routes_indexing.py
@@ -0,0 +1,90 @@
+"""Tests for index_local_library and view_document_chunks in rag_routes.py."""
+
+from unittest.mock import patch, MagicMock
+
+RAG_PREFIX = "/library"
+
+
+class TestIndexLocalLibrary:
+ """Tests for /api/rag/index-local SSE endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.get(
+ f"{RAG_PREFIX}/api/rag/index-local?path=/tmp/docs"
+ )
+ assert response.status_code in [401, 302]
+
+ def test_missing_path_returns_400(self, authenticated_client):
+ response = authenticated_client.get(f"{RAG_PREFIX}/api/rag/index-local")
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+ assert "path" in data["error"].lower()
+
+ @patch(
+ "local_deep_research.research_library.routes.rag_routes.PathValidator"
+ )
+ def test_invalid_path_returns_400(
+ self, mock_validator, authenticated_client
+ ):
+ mock_validator.validate_local_filesystem_path.side_effect = ValueError(
+ "blocked"
+ )
+
+ response = authenticated_client.get(
+ f"{RAG_PREFIX}/api/rag/index-local?path=/etc/passwd"
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+
+ @patch(
+ "local_deep_research.research_library.routes.rag_routes.PathValidator"
+ )
+ def test_nonexistent_path_returns_400(
+ self, mock_validator, authenticated_client, tmp_path
+ ):
+ nonexistent = tmp_path / "nonexistent"
+ mock_validator.validate_local_filesystem_path.return_value = nonexistent
+ mock_validator.sanitize_for_filesystem_ops.return_value = nonexistent
+
+ response = authenticated_client.get(
+ f"{RAG_PREFIX}/api/rag/index-local?path={nonexistent}"
+ )
+ assert response.status_code == 400
+
+ @patch(
+ "local_deep_research.research_library.routes.rag_routes.PathValidator"
+ )
+ def test_file_not_directory_returns_400(
+ self, mock_validator, authenticated_client, tmp_path
+ ):
+ file_path = tmp_path / "file.txt"
+ file_path.write_text("content")
+ mock_validator.validate_local_filesystem_path.return_value = file_path
+ mock_validator.sanitize_for_filesystem_ops.return_value = file_path
+
+ response = authenticated_client.get(
+ f"{RAG_PREFIX}/api/rag/index-local?path={file_path}"
+ )
+ assert response.status_code == 400
+
+
+class TestViewDocumentChunks:
+ """Tests for /api/rag/document/<id>/chunks endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.get(f"{RAG_PREFIX}/document/123/chunks")
+ assert response.status_code in [401, 302]
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_document_not_found(self, mock_session_ctx, authenticated_client):
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_session_ctx.return_value.__exit__ = MagicMock(return_value=None)
+
+ response = authenticated_client.get(f"{RAG_PREFIX}/document/999/chunks")
+ assert response.status_code == 404
diff --git a/tests/research_library/services/test_library_rag_service_info.py b/tests/research_library/services/test_library_rag_service_info.py
new file mode 100644
index 0000000000..d2c2e63a82
--- /dev/null
+++ b/tests/research_library/services/test_library_rag_service_info.py
@@ -0,0 +1,153 @@
+"""Tests for LibraryRAGService.get_current_index_info and close methods."""
+
+from datetime import datetime
+from unittest.mock import patch, MagicMock
+
+
+def _make_service():
+ """Create a LibraryRAGService with mocked dependencies."""
+ with (
+ patch(
+ "local_deep_research.research_library.services.library_rag_service.LocalEmbeddingManager"
+ ),
+ patch(
+ "local_deep_research.research_library.services.library_rag_service.get_user_db_session"
+ ),
+ patch(
+ "local_deep_research.research_library.services.library_rag_service.FileIntegrityManager"
+ ),
+ patch(
+ "local_deep_research.research_library.services.library_rag_service.get_text_splitter"
+ ),
+ ):
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ service = LibraryRAGService(
+ username="testuser",
+ db_password="testpass",
+ )
+ return service
+
+
+class TestGetCurrentIndexInfo:
+ """Tests for get_current_index_info()."""
+
+ @patch(
+ "local_deep_research.research_library.services.library_rag_service.get_user_db_session"
+ )
+ def test_returns_none_when_no_index(self, 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)
+
+ # Collection found, but no RAG index
+ mock_collection = MagicMock()
+ mock_collection.id = "coll-123"
+
+ mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ mock_collection, # collection query
+ None, # rag_index query
+ ]
+ # For the "all indices" debug query
+ mock_session.query.return_value.all.return_value = []
+
+ service = _make_service()
+ result = service.get_current_index_info(collection_id="coll-123")
+ assert result is None
+
+ @patch(
+ "local_deep_research.research_library.services.library_rag_service.get_user_db_session"
+ )
+ def test_returns_index_info_with_collection_id(self, 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)
+
+ # Collection found
+ mock_collection = MagicMock()
+
+ # RAG index found
+ mock_rag_index = MagicMock()
+ mock_rag_index.embedding_model = "all-MiniLM-L6-v2"
+ mock_rag_index.embedding_model_type = MagicMock()
+ mock_rag_index.embedding_model_type.value = "sentence_transformers"
+ mock_rag_index.embedding_dimension = 384
+ mock_rag_index.chunk_size = 1000
+ mock_rag_index.chunk_overlap = 200
+ mock_rag_index.created_at = datetime(2024, 1, 1)
+ mock_rag_index.last_updated_at = datetime(2024, 6, 15)
+
+ # Set up query chain for collection and rag_index
+ mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ mock_collection, # collection query
+ mock_rag_index, # rag_index query
+ ]
+
+ # Chunk count and doc count
+ mock_session.query.return_value.filter_by.return_value.scalar.return_value = 500
+ mock_session.query.return_value.filter_by.return_value.count.return_value = 10
+
+ service = _make_service()
+ result = service.get_current_index_info(collection_id="coll-123")
+
+ assert result is not None
+ assert result["embedding_model"] == "all-MiniLM-L6-v2"
+ assert result["embedding_dimension"] == 384
+ assert result["chunk_size"] == 1000
+
+ @patch(
+ "local_deep_research.research_library.services.library_rag_service.get_user_db_session"
+ )
+ @patch("local_deep_research.database.library_init.get_default_library_id")
+ def test_defaults_to_library_collection(
+ self, mock_get_default, mock_session_ctx
+ ):
+ mock_get_default.return_value = "default-lib-id"
+
+ mock_session = MagicMock()
+ mock_session_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_session_ctx.return_value.__exit__ = MagicMock(return_value=None)
+
+ # No RAG index
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+ mock_session.query.return_value.all.return_value = []
+
+ service = _make_service()
+ result = service.get_current_index_info() # No collection_id
+
+ # Should have called get_default_library_id
+ mock_get_default.assert_called_once()
+ assert result is None
+
+
+class TestClose:
+ """Tests for close() method."""
+
+ def test_close_clears_resources(self):
+ service = _make_service()
+ # Simulate having resources set
+ service.faiss_index = MagicMock()
+ service.rag_index_record = MagicMock()
+ service.integrity_manager = MagicMock()
+
+ service.close()
+
+ assert service.embedding_manager is None
+ assert service.faiss_index is None
+ assert service.rag_index_record is None
+ assert service.integrity_manager is None
+ assert service._closed is True
+
+ def test_close_is_idempotent(self):
+ service = _make_service()
+ service.close()
+ service.close() # Should not raise
+ assert service._closed is True
diff --git a/tests/research_library/utils/__init__.py b/tests/research_library/utils/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/research_library/utils/test_utils.py b/tests/research_library/utils/test_utils.py
new file mode 100644
index 0000000000..02a8794f2a
--- /dev/null
+++ b/tests/research_library/utils/test_utils.py
@@ -0,0 +1,323 @@
+"""Tests for research_library/utils/__init__.py — utility functions."""
+
+import hashlib
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+
+# ---------------------------------------------------------------------------
+# get_url_hash
+# ---------------------------------------------------------------------------
+
+
+class TestGetUrlHash:
+ """Tests for get_url_hash()."""
+
+ def test_returns_sha256_hex(self):
+ from local_deep_research.research_library.utils import get_url_hash
+
+ url = "https://example.com/page"
+ expected = hashlib.sha256(url.lower().encode()).hexdigest()
+ assert get_url_hash(url) == expected
+
+ def test_case_insensitive(self):
+ from local_deep_research.research_library.utils import get_url_hash
+
+ assert get_url_hash("HTTPS://EXAMPLE.COM") == get_url_hash(
+ "https://example.com"
+ )
+
+ def test_different_urls_different_hashes(self):
+ from local_deep_research.research_library.utils import get_url_hash
+
+ assert get_url_hash("https://a.com") != get_url_hash("https://b.com")
+
+ def test_empty_url(self):
+ from local_deep_research.research_library.utils import get_url_hash
+
+ result = get_url_hash("")
+ assert isinstance(result, str)
+ assert len(result) == 64 # SHA256 hex length
+
+
+# ---------------------------------------------------------------------------
+# get_library_storage_path
+# ---------------------------------------------------------------------------
+
+
+class TestGetLibraryStoragePath:
+ """Tests for get_library_storage_path()."""
+
+ @patch("local_deep_research.utilities.db_utils.get_settings_manager")
+ @patch("local_deep_research.research_library.utils.get_library_directory")
+ def test_user_isolation_mode(self, mock_lib_dir, mock_get_sm, tmp_path):
+ mock_lib_dir.return_value = tmp_path / "library"
+ mock_sm = MagicMock()
+ mock_sm.get_setting.side_effect = lambda key, default: {
+ "research_library.storage_path": str(tmp_path / "library"),
+ "research_library.shared_library": False,
+ }.get(key, default)
+ mock_get_sm.return_value = mock_sm
+
+ from local_deep_research.research_library.utils import (
+ get_library_storage_path,
+ )
+
+ result = get_library_storage_path("alice")
+ assert result == tmp_path / "library" / "alice"
+ assert result.exists()
+
+ @patch("local_deep_research.utilities.db_utils.get_settings_manager")
+ @patch("local_deep_research.research_library.utils.get_library_directory")
+ def test_shared_library_mode(self, mock_lib_dir, mock_get_sm, tmp_path):
+ mock_lib_dir.return_value = tmp_path / "library"
+ mock_sm = MagicMock()
+ mock_sm.get_setting.side_effect = lambda key, default: {
+ "research_library.storage_path": str(tmp_path / "library"),
+ "research_library.shared_library": True,
+ }.get(key, default)
+ mock_get_sm.return_value = mock_sm
+
+ from local_deep_research.research_library.utils import (
+ get_library_storage_path,
+ )
+
+ result = get_library_storage_path("alice")
+ # Shared mode: no username subdirectory
+ assert result == tmp_path / "library"
+ assert result.exists()
+
+ @patch("local_deep_research.utilities.db_utils.get_settings_manager")
+ @patch("local_deep_research.research_library.utils.get_library_directory")
+ def test_creates_directory_if_not_exists(
+ self, mock_lib_dir, mock_get_sm, tmp_path
+ ):
+ base = tmp_path / "new_dir"
+ mock_lib_dir.return_value = base
+ mock_sm = MagicMock()
+ mock_sm.get_setting.side_effect = lambda key, default: {
+ "research_library.storage_path": str(base),
+ "research_library.shared_library": False,
+ }.get(key, default)
+ mock_get_sm.return_value = mock_sm
+
+ from local_deep_research.research_library.utils import (
+ get_library_storage_path,
+ )
+
+ result = get_library_storage_path("bob")
+ assert result.exists()
+ assert result.is_dir()
+
+
+# ---------------------------------------------------------------------------
+# open_file_location
+# ---------------------------------------------------------------------------
+
+
+class TestOpenFileLocation:
+ """Tests for open_file_location()."""
+
+ @patch("local_deep_research.research_library.utils.PathValidator")
+ @patch("local_deep_research.research_library.utils.subprocess.run")
+ @patch("local_deep_research.research_library.utils.sys")
+ def test_linux_success(self, mock_sys, mock_run, mock_validator, tmp_path):
+ mock_sys.platform = "linux"
+ mock_validator.validate_local_filesystem_path.return_value = (
+ tmp_path / "file.txt"
+ )
+ mock_run.return_value = MagicMock(returncode=0)
+
+ from local_deep_research.research_library.utils import (
+ open_file_location,
+ )
+
+ assert open_file_location(str(tmp_path / "file.txt")) is True
+ mock_run.assert_called_once_with(
+ ["xdg-open", str(tmp_path)],
+ capture_output=True,
+ text=True,
+ shell=False,
+ )
+
+ @patch("local_deep_research.research_library.utils.PathValidator")
+ @patch("local_deep_research.research_library.utils.subprocess.run")
+ @patch("local_deep_research.research_library.utils.sys")
+ def test_linux_failure(self, mock_sys, mock_run, mock_validator, tmp_path):
+ mock_sys.platform = "linux"
+ mock_validator.validate_local_filesystem_path.return_value = (
+ tmp_path / "file.txt"
+ )
+ mock_run.return_value = MagicMock(returncode=1, stderr="error")
+
+ from local_deep_research.research_library.utils import (
+ open_file_location,
+ )
+
+ assert open_file_location(str(tmp_path / "file.txt")) is False
+
+ @patch("local_deep_research.research_library.utils.PathValidator")
+ @patch("local_deep_research.research_library.utils.subprocess.run")
+ @patch("local_deep_research.research_library.utils.sys")
+ def test_macos_success(self, mock_sys, mock_run, mock_validator, tmp_path):
+ mock_sys.platform = "darwin"
+ mock_validator.validate_local_filesystem_path.return_value = (
+ tmp_path / "file.txt"
+ )
+ mock_run.return_value = MagicMock(returncode=0)
+
+ from local_deep_research.research_library.utils import (
+ open_file_location,
+ )
+
+ assert open_file_location(str(tmp_path / "file.txt")) is True
+ mock_run.assert_called_once_with(
+ ["open", str(tmp_path)],
+ capture_output=True,
+ text=True,
+ shell=False,
+ )
+
+ @patch("local_deep_research.research_library.utils.PathValidator")
+ def test_path_validation_failure(self, mock_validator):
+ mock_validator.validate_local_filesystem_path.side_effect = ValueError(
+ "blocked"
+ )
+
+ from local_deep_research.research_library.utils import (
+ open_file_location,
+ )
+
+ assert open_file_location("/etc/passwd") is False
+
+
+# ---------------------------------------------------------------------------
+# get_relative_library_path / get_absolute_library_path
+# ---------------------------------------------------------------------------
+
+
+class TestLibraryPathConversions:
+ """Tests for get_relative_library_path and get_absolute_library_path."""
+
+ @patch(
+ "local_deep_research.research_library.utils.get_library_storage_path"
+ )
+ def test_relative_path_within_library(self, mock_storage, tmp_path):
+ library_root = tmp_path / "library" / "alice"
+ library_root.mkdir(parents=True)
+ mock_storage.return_value = library_root
+
+ from local_deep_research.research_library.utils import (
+ get_relative_library_path,
+ )
+
+ abs_path = str(library_root / "subdir" / "file.pdf")
+ result = get_relative_library_path(abs_path, "alice")
+ assert result == str(Path("subdir") / "file.pdf")
+
+ @patch(
+ "local_deep_research.research_library.utils.get_library_storage_path"
+ )
+ def test_relative_path_outside_library_returns_filename(
+ self, mock_storage, tmp_path
+ ):
+ mock_storage.return_value = tmp_path / "library"
+
+ from local_deep_research.research_library.utils import (
+ get_relative_library_path,
+ )
+
+ result = get_relative_library_path("/other/dir/file.pdf", "alice")
+ assert result == "file.pdf"
+
+ @patch(
+ "local_deep_research.research_library.utils.get_library_storage_path"
+ )
+ def test_absolute_path_from_relative(self, mock_storage, tmp_path):
+ library_root = tmp_path / "library" / "alice"
+ mock_storage.return_value = library_root
+
+ from local_deep_research.research_library.utils import (
+ get_absolute_library_path,
+ )
+
+ result = get_absolute_library_path("subdir/file.pdf", "alice")
+ assert result == library_root / "subdir" / "file.pdf"
+
+
+# ---------------------------------------------------------------------------
+# get_absolute_path_from_settings
+# ---------------------------------------------------------------------------
+
+
+class TestGetAbsolutePathFromSettings:
+ """Tests for get_absolute_path_from_settings."""
+
+ @patch("local_deep_research.utilities.db_utils.get_settings_manager")
+ @patch("local_deep_research.research_library.utils.get_library_directory")
+ def test_with_relative_path(self, mock_lib_dir, mock_get_sm, tmp_path):
+ mock_lib_dir.return_value = tmp_path / "library"
+ mock_sm = MagicMock()
+ mock_sm.get_setting.return_value = str(tmp_path / "library")
+ mock_get_sm.return_value = mock_sm
+
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ )
+
+ result = get_absolute_path_from_settings("docs/file.pdf")
+ assert result == tmp_path / "library" / "docs" / "file.pdf"
+
+ @patch("local_deep_research.utilities.db_utils.get_settings_manager")
+ @patch("local_deep_research.research_library.utils.get_library_directory")
+ def test_empty_relative_path_returns_root(
+ self, mock_lib_dir, mock_get_sm, tmp_path
+ ):
+ mock_lib_dir.return_value = tmp_path / "library"
+ mock_sm = MagicMock()
+ mock_sm.get_setting.return_value = str(tmp_path / "library")
+ mock_get_sm.return_value = mock_sm
+
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ )
+
+ result = get_absolute_path_from_settings("")
+ assert result == tmp_path / "library"
+
+
+# ---------------------------------------------------------------------------
+# handle_api_error
+# ---------------------------------------------------------------------------
+
+
+class TestHandleApiError:
+ """Tests for handle_api_error."""
+
+ def test_returns_generic_error_message(self, app):
+ from local_deep_research.research_library.utils import handle_api_error
+
+ with app.app_context():
+ response, status_code = handle_api_error(
+ "test operation", ValueError("secret details"), 500
+ )
+ data = response.get_json()
+ assert status_code == 500
+ assert data["success"] is False
+ # Must NOT leak the exception message
+ assert "secret details" not in data["error"]
+ assert "internal error" in data["error"].lower()
+
+ def test_custom_status_code(self, app):
+ from local_deep_research.research_library.utils import handle_api_error
+
+ with app.app_context():
+ _, status_code = handle_api_error("op", RuntimeError("err"), 503)
+ assert status_code == 503
+
+ def test_default_status_code_is_500(self, app):
+ from local_deep_research.research_library.utils import handle_api_error
+
+ with app.app_context():
+ _, status_code = handle_api_error("op", RuntimeError("err"))
+ assert status_code == 500
diff --git a/tests/security/test_url_validator_js.py b/tests/security/test_url_validator_js.py
new file mode 100644
index 0000000000..81d062eb76
--- /dev/null
+++ b/tests/security/test_url_validator_js.py
@@ -0,0 +1,66 @@
+"""Tests for get_javascript_url_validator() in security/url_validator.py."""
+
+from local_deep_research.security.url_validator import (
+ get_javascript_url_validator,
+)
+
+
+class TestGetJavascriptUrlValidator:
+ """Tests for the JavaScript URL validator code generator."""
+
+ def test_returns_string(self):
+ result = get_javascript_url_validator()
+ assert isinstance(result, str)
+
+ def test_contains_url_validator_object(self):
+ js = get_javascript_url_validator()
+ assert "URLValidator" in js
+
+ def test_defines_unsafe_schemes(self):
+ js = get_javascript_url_validator()
+ assert "UNSAFE_SCHEMES" in js
+ for scheme in ["javascript", "data", "vbscript", "file", "blob"]:
+ assert scheme in js
+
+ def test_defines_safe_schemes(self):
+ js = get_javascript_url_validator()
+ assert "SAFE_SCHEMES" in js
+ assert "http" in js
+ assert "https" in js
+
+ def test_has_is_unsafe_scheme_function(self):
+ js = get_javascript_url_validator()
+ assert "isUnsafeScheme" in js
+
+ def test_has_is_safe_url_function(self):
+ js = get_javascript_url_validator()
+ assert "isSafeUrl" in js
+
+ def test_has_sanitize_url_function(self):
+ js = get_javascript_url_validator()
+ assert "sanitizeUrl" in js
+
+ def test_supports_trusted_domains(self):
+ js = get_javascript_url_validator()
+ assert "trustedDomains" in js
+
+ def test_supports_allow_mailto(self):
+ js = get_javascript_url_validator()
+ assert "allowMailto" in js
+
+ def test_supports_allow_fragments(self):
+ js = get_javascript_url_validator()
+ assert "allowFragments" in js
+
+ def test_sanitize_adds_default_scheme(self):
+ js = get_javascript_url_validator()
+ # Should have logic to add https:// by default
+ assert "defaultScheme" in js
+
+ def test_is_valid_javascript(self):
+ """Basic syntax check — the JS should be parseable."""
+ js = get_javascript_url_validator()
+ # Check balanced braces
+ assert js.count("{") == js.count("}")
+ # Check no obvious syntax errors
+ assert "function(" in js or "function (" in js
diff --git a/tests/web/routes/test_metrics_routes_rate_limits.py b/tests/web/routes/test_metrics_routes_rate_limits.py
new file mode 100644
index 0000000000..b60a5b2842
--- /dev/null
+++ b/tests/web/routes/test_metrics_routes_rate_limits.py
@@ -0,0 +1,162 @@
+"""Tests for api_current_rate_limits and api_cost_calculation in metrics_routes.py."""
+
+import time
+from unittest.mock import patch, MagicMock
+
+METRICS_PREFIX = "/metrics"
+
+
+class TestApiCurrentRateLimits:
+ """Tests for /api/rate-limiting/current endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.get(f"{METRICS_PREFIX}/api/rate-limiting/current")
+ assert response.status_code in [401, 302]
+
+ @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
+ def test_returns_current_limits(
+ self, mock_get_tracker, authenticated_client
+ ):
+ now = time.time()
+ mock_tracker = MagicMock()
+ mock_tracker.get_stats.return_value = [
+ ("google", 2.0, 1.0, 5.0, now, 100, 0.95),
+ ("bing", 1.5, 0.5, 3.0, now, 50, 0.6),
+ ]
+ mock_get_tracker.return_value = mock_tracker
+
+ response = authenticated_client.get(
+ f"{METRICS_PREFIX}/api/rate-limiting/current"
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["status"] == "success"
+ assert len(data["current_limits"]) == 2
+
+ google = data["current_limits"][0]
+ assert google["engine_type"] == "google"
+ assert google["base_wait_seconds"] == 2.0
+ assert google["success_rate"] == 95.0
+ assert google["status"] == "healthy"
+
+ bing = data["current_limits"][1]
+ assert bing["status"] == "degraded"
+
+ @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
+ def test_poor_status_threshold(
+ self, mock_get_tracker, authenticated_client
+ ):
+ now = time.time()
+ mock_tracker = MagicMock()
+ mock_tracker.get_stats.return_value = [
+ ("failing_engine", 10.0, 5.0, 30.0, now, 200, 0.3),
+ ]
+ mock_get_tracker.return_value = mock_tracker
+
+ response = authenticated_client.get(
+ f"{METRICS_PREFIX}/api/rate-limiting/current"
+ )
+ data = response.get_json()
+ assert data["current_limits"][0]["status"] == "poor"
+
+ @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
+ def test_empty_stats(self, mock_get_tracker, authenticated_client):
+ mock_tracker = MagicMock()
+ mock_tracker.get_stats.return_value = []
+ mock_get_tracker.return_value = mock_tracker
+
+ response = authenticated_client.get(
+ f"{METRICS_PREFIX}/api/rate-limiting/current"
+ )
+ data = response.get_json()
+ assert data["status"] == "success"
+ assert data["current_limits"] == []
+
+ @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
+ def test_error_returns_500(self, mock_get_tracker, authenticated_client):
+ mock_get_tracker.side_effect = RuntimeError("tracker error")
+
+ response = authenticated_client.get(
+ f"{METRICS_PREFIX}/api/rate-limiting/current"
+ )
+ assert response.status_code == 500
+ data = response.get_json()
+ assert data["status"] == "error"
+
+
+class TestApiCostCalculation:
+ """Tests for /api/cost-calculation endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.post(
+ f"{METRICS_PREFIX}/api/cost-calculation",
+ json={"model_name": "gpt-4", "prompt_tokens": 100},
+ )
+ assert response.status_code in [401, 302]
+
+ @patch("local_deep_research.metrics.pricing.cost_calculator.CostCalculator")
+ def test_successful_calculation(self, mock_cc_cls, authenticated_client):
+ mock_calc = MagicMock()
+ mock_calc.calculate_cost_sync.return_value = {
+ "prompt_cost": 0.003,
+ "completion_cost": 0.006,
+ "total_cost": 0.009,
+ }
+ mock_cc_cls.return_value = mock_calc
+
+ response = authenticated_client.post(
+ f"{METRICS_PREFIX}/api/cost-calculation",
+ json={
+ "model_name": "gpt-4",
+ "provider": "openai",
+ "prompt_tokens": 100,
+ "completion_tokens": 200,
+ },
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["status"] == "success"
+ assert data["model_name"] == "gpt-4"
+ assert data["total_tokens"] == 300
+ assert data["total_cost"] == 0.009
+
+ def test_missing_model_name(self, authenticated_client):
+ response = authenticated_client.post(
+ f"{METRICS_PREFIX}/api/cost-calculation",
+ json={"prompt_tokens": 100},
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert "model_name" in data["error"].lower()
+
+ def test_no_json_body(self, authenticated_client):
+ response = authenticated_client.post(
+ f"{METRICS_PREFIX}/api/cost-calculation",
+ )
+ assert response.status_code == 400
+
+ @patch("local_deep_research.metrics.pricing.cost_calculator.CostCalculator")
+ def test_defaults_to_zero_tokens(self, mock_cc_cls, authenticated_client):
+ mock_calc = MagicMock()
+ mock_calc.calculate_cost_sync.return_value = {"total_cost": 0.0}
+ mock_cc_cls.return_value = mock_calc
+
+ response = authenticated_client.post(
+ f"{METRICS_PREFIX}/api/cost-calculation",
+ json={"model_name": "gpt-4"},
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["prompt_tokens"] == 0
+ assert data["completion_tokens"] == 0
+ assert data["total_tokens"] == 0
+
+ @patch("local_deep_research.metrics.pricing.cost_calculator.CostCalculator")
+ def test_error_returns_500(self, mock_cc_cls, authenticated_client):
+ mock_cc_cls.side_effect = RuntimeError("pricing error")
+
+ response = authenticated_client.post(
+ f"{METRICS_PREFIX}/api/cost-calculation",
+ json={"model_name": "gpt-4"},
+ )
+ assert response.status_code == 500
diff --git a/tests/web/routes/test_ollama_status.py b/tests/web/routes/test_ollama_status.py
new file mode 100644
index 0000000000..77a8f5a855
--- /dev/null
+++ b/tests/web/routes/test_ollama_status.py
@@ -0,0 +1,349 @@
+"""Tests for Ollama status/model check endpoints in api_routes.py."""
+
+from unittest.mock import patch, MagicMock
+
+import requests
+
+API_PREFIX = "/research/api"
+
+
+class TestCheckOllamaStatus:
+ """Tests for /check/ollama_status endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.get(f"{API_PREFIX}/check/ollama_status")
+ assert response.status_code in [401, 302]
+
+ def test_non_ollama_provider_returns_running(self, authenticated_client):
+ """When provider is not ollama, should return running=True."""
+ with authenticated_client.application.test_request_context():
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "openai",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_status")
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["running"] is True
+ assert (
+ "openai" in data["message"].lower()
+ or "not Ollama" in data["message"]
+ )
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_ollama_running_new_api_format(
+ self, mock_safe_get, authenticated_client
+ ):
+ """Ollama returns 200 with models list (new API format)."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {
+ "models": [{"name": "llama3"}, {"name": "gemma3:12b"}]
+ }
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_status")
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["running"] is True
+ assert data["model_count"] == 2
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_ollama_running_old_api_format(
+ self, mock_safe_get, authenticated_client
+ ):
+ """Ollama returns 200 with array (old API format)."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = [{"name": "llama3"}]
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_status")
+ data = response.get_json()
+ assert data["running"] is True
+ assert data["model_count"] == 1
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_ollama_invalid_json(self, mock_safe_get, authenticated_client):
+ """Ollama returns 200 but invalid JSON."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.side_effect = ValueError("bad json")
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_status")
+ data = response.get_json()
+ assert data["running"] is True
+ assert "invalid" in data["message"].lower()
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_ollama_non_200_status(self, mock_safe_get, authenticated_client):
+ """Ollama returns non-200 status code."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 503
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_status")
+ data = response.get_json()
+ assert data["running"] is False
+ assert data["status_code"] == 503
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_ollama_connection_error(self, mock_safe_get, authenticated_client):
+ """Ollama connection refused."""
+ mock_safe_get.side_effect = requests.exceptions.ConnectionError(
+ "refused"
+ )
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_status")
+ data = response.get_json()
+ assert data["running"] is False
+ assert data["error_type"] == "connection_error"
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_ollama_timeout(self, mock_safe_get, authenticated_client):
+ """Ollama request times out."""
+ mock_safe_get.side_effect = requests.exceptions.Timeout("timed out")
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_status")
+ data = response.get_json()
+ assert data["running"] is False
+ assert data["error_type"] == "timeout"
+
+
+class TestCheckOllamaModel:
+ """Tests for /check/ollama_model endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.get(f"{API_PREFIX}/check/ollama_model")
+ assert response.status_code in [401, 302]
+
+ def test_non_ollama_provider(self, authenticated_client):
+ """When provider is not ollama, should return available=True."""
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "openai",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is True
+ assert data["provider"] == "openai"
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_model_exists_new_format(self, mock_safe_get, authenticated_client):
+ """Model exists in Ollama (new API format)."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {
+ "models": [{"name": "llama3"}, {"name": "gemma3:12b"}]
+ }
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "llama3",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is True
+ assert data["model"] == "llama3"
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_model_not_found(self, mock_safe_get, authenticated_client):
+ """Model not found in Ollama."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {"models": [{"name": "llama3"}]}
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "nonexistent-model",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is False
+ assert "nonexistent-model" in data["message"]
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_no_models_available(self, mock_safe_get, authenticated_client):
+ """Ollama has no models."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {"models": []}
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "llama3",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is False
+ assert "no models" in data["message"].lower()
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_model_name_case_insensitive(
+ self, mock_safe_get, authenticated_client
+ ):
+ """Model name comparison should be case-insensitive."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {"models": [{"name": "Llama3"}]}
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "llama3",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is True
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_model_from_query_param(self, mock_safe_get, authenticated_client):
+ """Model name from query parameter overrides config."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {"models": [{"name": "custom-model"}]}
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "default-model",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(
+ f"{API_PREFIX}/check/ollama_model?model=custom-model"
+ )
+ data = response.get_json()
+ assert data["available"] is True
+ assert data["model"] == "custom-model"
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_ollama_api_non_200(self, mock_safe_get, authenticated_client):
+ """Ollama API returns non-200."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 500
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "llama3",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is False
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_json_parse_error(self, mock_safe_get, authenticated_client):
+ """Ollama returns invalid JSON."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.side_effect = ValueError("bad json")
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "llama3",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is False
+ assert data["error_type"] == "json_parse_error"
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_connection_error(self, mock_safe_get, authenticated_client):
+ mock_safe_get.side_effect = requests.exceptions.ConnectionError(
+ "refused"
+ )
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "llama3",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is False
+ assert data["error_type"] == "connection_error"
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_timeout_error(self, mock_safe_get, authenticated_client):
+ mock_safe_get.side_effect = requests.exceptions.Timeout("timeout")
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "llama3",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is False
+ assert data["error_type"] == "timeout"
+
+ @patch("local_deep_research.web.routes.api_routes.safe_get")
+ def test_old_api_format(self, mock_safe_get, authenticated_client):
+ """Test with old Ollama API format (plain array)."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = [
+ {"name": "llama3"},
+ {"name": "codellama"},
+ ]
+ mock_safe_get.return_value = mock_resp
+
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "codellama",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ data = response.get_json()
+ assert data["available"] is True
diff --git a/tests/web/routes/test_research_routes_config.py b/tests/web/routes/test_research_routes_config.py
new file mode 100644
index 0000000000..94d11f0c24
--- /dev/null
+++ b/tests/web/routes/test_research_routes_config.py
@@ -0,0 +1,157 @@
+"""Tests for save_raw_config and get_upload_limits in research_routes.py."""
+
+from unittest.mock import patch
+
+RESEARCH_PREFIX = ""
+
+
+class TestSaveRawConfig:
+ """Tests for /api/save_raw_config endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={"raw_config": "[search]\ntool = 'google'"},
+ )
+ assert response.status_code in [401, 302]
+
+ def test_missing_raw_config(self, authenticated_client):
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={},
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+
+ def test_empty_raw_config(self, authenticated_client):
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={"raw_config": ""},
+ )
+ assert response.status_code == 400
+
+ def test_invalid_toml_syntax(self, authenticated_client):
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={"raw_config": "this is {{not valid toml"},
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+ assert "TOML" in data["error"]
+
+ def test_blocked_key_module_path(self, authenticated_client):
+ """Config with module_path key should be rejected."""
+ toml_config = '[custom]\nmodule_path = "evil.module"'
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={"raw_config": toml_config},
+ )
+ assert response.status_code == 403
+ data = response.get_json()
+ assert data["success"] is False
+ assert "blocked_keys" in data
+
+ def test_blocked_key_class_name(self, authenticated_client):
+ """Config with class_name key should be rejected."""
+ toml_config = '[providers]\nclass_name = "EvilClass"'
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={"raw_config": toml_config},
+ )
+ assert response.status_code == 403
+
+ def test_blocked_key_nested(self, authenticated_client):
+ """Blocked keys in nested dicts should also be caught."""
+ toml_config = '[a.b]\nmodule = "evil"'
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={"raw_config": toml_config},
+ )
+ assert response.status_code == 403
+
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ )
+ @patch(
+ "local_deep_research.web.routes.research_routes.get_config_directory"
+ )
+ def test_valid_config_saved(
+ self, mock_config_dir, mock_write, authenticated_client, tmp_path
+ ):
+ mock_config_dir.return_value = tmp_path
+
+ toml_config = '[search]\ntool = "google"\niterations = 5'
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={"raw_config": toml_config},
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["success"] is True
+ mock_write.assert_called_once()
+
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ )
+ @patch(
+ "local_deep_research.web.routes.research_routes.get_config_directory"
+ )
+ def test_write_error_returns_500(
+ self, mock_config_dir, mock_write, authenticated_client, tmp_path
+ ):
+ mock_config_dir.return_value = tmp_path
+ mock_write.side_effect = RuntimeError("write failed")
+
+ toml_config = '[search]\ntool = "google"'
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={"raw_config": toml_config},
+ )
+ assert response.status_code == 500
+
+ def test_no_json_body(self, authenticated_client):
+ """Missing JSON body should be rejected."""
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ content_type="application/json",
+ )
+ # require_json_body decorator handles this
+ assert response.status_code == 400
+
+ def test_does_not_expose_internal_errors(self, authenticated_client):
+ """Invalid TOML should not expose exception details."""
+ response = authenticated_client.post(
+ f"{RESEARCH_PREFIX}/api/save_raw_config",
+ json={"raw_config": "invalid = [unclosed"},
+ )
+ data = response.get_json()
+ # Should show generic message, not Python traceback
+ assert "TOML" in data["error"]
+ assert "Traceback" not in data.get("error", "")
+
+
+class TestGetUploadLimits:
+ """Tests for /api/upload/limits endpoint."""
+
+ def test_accessible_without_authentication(self, client):
+ """Upload limits are public config, no auth needed."""
+ response = client.get(f"{RESEARCH_PREFIX}/api/config/limits")
+ assert response.status_code == 200
+
+ def test_returns_upload_limits(self, client):
+ response = client.get(f"{RESEARCH_PREFIX}/api/config/limits")
+ assert response.status_code == 200
+ data = response.get_json()
+ assert "max_file_size" in data
+ assert "max_files" in data
+ assert "allowed_mime_types" in data
+ assert isinstance(data["max_file_size"], int)
+ assert isinstance(data["max_files"], int)
+ assert isinstance(data["allowed_mime_types"], list)
+
+ def test_mime_types_include_pdf(self, client):
+ response = client.get(f"{RESEARCH_PREFIX}/api/config/limits")
+ data = response.get_json()
+ assert "application/pdf" in data["allowed_mime_types"]
diff --git a/tests/web/routes/test_settings_routes_rate_limiting.py b/tests/web/routes/test_settings_routes_rate_limiting.py
new file mode 100644
index 0000000000..71b034b13e
--- /dev/null
+++ b/tests/web/routes/test_settings_routes_rate_limiting.py
@@ -0,0 +1,299 @@
+"""Tests for rate limiting and notification endpoints in settings_routes.py."""
+
+from unittest.mock import patch, MagicMock
+import time
+
+SETTINGS_PREFIX = "/settings"
+
+
+class TestApiGetRateLimitingStatus:
+ """Tests for /api/rate-limiting/status endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.get(f"{SETTINGS_PREFIX}/api/rate-limiting/status")
+ assert response.status_code in [401, 302]
+
+ @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
+ def test_returns_status_and_engines(
+ self, mock_get_tracker, authenticated_client
+ ):
+ mock_tracker = MagicMock()
+ mock_tracker.enabled = True
+ mock_tracker.exploration_rate = 0.1
+ mock_tracker.learning_rate = 0.05
+ mock_tracker.memory_window = 100
+ mock_tracker.get_stats.return_value = [
+ ("google", 2.0, 1.0, 5.0, time.time(), 50, 0.95),
+ ("bing", 1.5, 0.5, 3.0, time.time(), 30, 0.8),
+ ]
+ mock_get_tracker.return_value = mock_tracker
+
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/status"
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["status"]["enabled"] is True
+ assert len(data["engines"]) == 2
+ assert data["engines"][0]["engine_type"] == "google"
+ assert data["engines"][0]["success_rate"] == 95.0
+
+ @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
+ def test_handles_none_success_rate(
+ self, mock_get_tracker, authenticated_client
+ ):
+ mock_tracker = MagicMock()
+ mock_tracker.enabled = True
+ mock_tracker.exploration_rate = 0.1
+ mock_tracker.learning_rate = 0.05
+ mock_tracker.memory_window = 100
+ mock_tracker.get_stats.return_value = [
+ ("new_engine", 1.0, 0.5, 2.0, time.time(), 0, None),
+ ]
+ mock_get_tracker.return_value = mock_tracker
+
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/status"
+ )
+ data = response.get_json()
+ assert data["engines"][0]["success_rate"] == 0.0
+
+ @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
+ def test_error_returns_500(self, mock_get_tracker, authenticated_client):
+ mock_get_tracker.side_effect = RuntimeError("tracker init failed")
+
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/status"
+ )
+ assert response.status_code == 500
+ data = response.get_json()
+ assert "error" in data
+
+
+class TestApiResetEngineRateLimiting:
+ """Tests for /api/rate-limiting/engines/<engine_type>/reset endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.post(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/engines/google/reset"
+ )
+ assert response.status_code in [401, 302]
+
+ @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
+ def test_resets_engine(self, mock_get_tracker, authenticated_client):
+ mock_tracker = MagicMock()
+ mock_get_tracker.return_value = mock_tracker
+
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/engines/google/reset"
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert "google" in data["message"]
+ mock_tracker.reset_engine.assert_called_once_with("google")
+
+ @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
+ def test_error_returns_500(self, mock_get_tracker, authenticated_client):
+ mock_tracker = MagicMock()
+ mock_tracker.reset_engine.side_effect = RuntimeError("fail")
+ mock_get_tracker.return_value = mock_tracker
+
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/engines/google/reset"
+ )
+ assert response.status_code == 500
+
+
+class TestApiCleanupRateLimiting:
+ """Tests for /api/rate-limiting/cleanup endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.post(f"{SETTINGS_PREFIX}/api/rate-limiting/cleanup")
+ assert response.status_code in [401, 302]
+
+ @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
+ def test_cleanup_default_days(self, mock_get_tracker, authenticated_client):
+ mock_tracker = MagicMock()
+ mock_get_tracker.return_value = mock_tracker
+
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/cleanup"
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert "30 days" in data["message"]
+ mock_tracker.cleanup_old_data.assert_called_once_with(30)
+
+ @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
+ def test_cleanup_custom_days(self, mock_get_tracker, authenticated_client):
+ mock_tracker = MagicMock()
+ mock_get_tracker.return_value = mock_tracker
+
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/cleanup",
+ json={"days": 7},
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert "7 days" in data["message"]
+ mock_tracker.cleanup_old_data.assert_called_once_with(7)
+
+ @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
+ def test_error_returns_500(self, mock_get_tracker, authenticated_client):
+ mock_get_tracker.side_effect = RuntimeError("fail")
+
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/cleanup"
+ )
+ assert response.status_code == 500
+
+
+class TestCheckOllamaStatusSettings:
+ """Tests for /api/ollama-status endpoint in settings_routes."""
+
+ def test_requires_authentication(self, client):
+ response = client.get(f"{SETTINGS_PREFIX}/api/ollama-status")
+ assert response.status_code in [401, 302]
+
+ @patch("local_deep_research.web.routes.settings_routes.safe_get")
+ @patch(
+ "local_deep_research.web.routes.settings_routes._get_setting_from_session"
+ )
+ def test_ollama_running(
+ self, mock_get_setting, mock_safe_get, authenticated_client
+ ):
+ mock_get_setting.return_value = "http://localhost:11434"
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {"version": "0.3.0"}
+ mock_safe_get.return_value = mock_resp
+
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/ollama-status"
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["running"] is True
+ assert data["version"] == "0.3.0"
+
+ @patch("local_deep_research.web.routes.settings_routes.safe_get")
+ @patch(
+ "local_deep_research.web.routes.settings_routes._get_setting_from_session"
+ )
+ def test_ollama_non_200(
+ self, mock_get_setting, mock_safe_get, authenticated_client
+ ):
+ mock_get_setting.return_value = "http://localhost:11434"
+ mock_resp = MagicMock()
+ mock_resp.status_code = 500
+ mock_safe_get.return_value = mock_resp
+
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/ollama-status"
+ )
+ data = response.get_json()
+ assert data["running"] is False
+
+ @patch("local_deep_research.web.routes.settings_routes.safe_get")
+ @patch(
+ "local_deep_research.web.routes.settings_routes._get_setting_from_session"
+ )
+ def test_ollama_connection_error(
+ self, mock_get_setting, mock_safe_get, authenticated_client
+ ):
+ import requests
+
+ mock_get_setting.return_value = "http://localhost:11434"
+ mock_safe_get.side_effect = requests.exceptions.ConnectionError(
+ "refused"
+ )
+
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/ollama-status"
+ )
+ data = response.get_json()
+ assert data["running"] is False
+
+
+class TestApiTestNotificationUrl:
+ """Tests for /api/notifications/test-url endpoint."""
+
+ def test_requires_authentication(self, client):
+ response = client.post(
+ f"{SETTINGS_PREFIX}/api/notifications/test-url",
+ json={"service_url": "http://example.com"},
+ )
+ assert response.status_code in [401, 302]
+
+ @patch("local_deep_research.notifications.service.NotificationService")
+ def test_successful_test(self, mock_ns_cls, authenticated_client):
+ mock_ns = MagicMock()
+ mock_ns.test_service.return_value = {
+ "success": True,
+ "message": "Notification sent",
+ "error": "",
+ }
+ mock_ns_cls.return_value = mock_ns
+
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/notifications/test-url",
+ json={"service_url": "tgram://token/chat_id"},
+ )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["success"] is True
+
+ @patch("local_deep_research.notifications.service.NotificationService")
+ def test_failed_test(self, mock_ns_cls, authenticated_client):
+ mock_ns = MagicMock()
+ mock_ns.test_service.return_value = {
+ "success": False,
+ "message": "",
+ "error": "Invalid URL",
+ }
+ mock_ns_cls.return_value = mock_ns
+
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/notifications/test-url",
+ json={"service_url": "invalid://url"},
+ )
+ data = response.get_json()
+ assert data["success"] is False
+
+ def test_missing_service_url(self, authenticated_client):
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/notifications/test-url",
+ json={},
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+
+ def test_no_json_body(self, authenticated_client):
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/notifications/test-url",
+ )
+ # No JSON body causes get_json() to return None, hitting the error handler
+ assert response.status_code in [400, 500]
+
+ @patch("local_deep_research.notifications.service.NotificationService")
+ def test_does_not_leak_internal_details(
+ self, mock_ns_cls, authenticated_client
+ ):
+ """Response should only contain expected safe fields."""
+ mock_ns = MagicMock()
+ mock_ns.test_service.return_value = {
+ "success": True,
+ "message": "OK",
+ "error": "",
+ "internal_debug": "SECRET_TOKEN_123",
+ }
+ mock_ns_cls.return_value = mock_ns
+
+ response = authenticated_client.post(
+ f"{SETTINGS_PREFIX}/api/notifications/test-url",
+ json={"service_url": "tgram://token/chat_id"},
+ )
+ data = response.get_json()
+ assert "internal_debug" not in data
+ assert "SECRET_TOKEN_123" not in str(data)
diff --git a/tests/web/services/test_socket_service_init.py b/tests/web/services/test_socket_service_init.py
new file mode 100644
index 0000000000..c49e12da58
--- /dev/null
+++ b/tests/web/services/test_socket_service_init.py
@@ -0,0 +1,136 @@
+"""Tests for SocketIOService.__init_singleton and singleton behavior."""
+
+from unittest.mock import patch
+import pytest
+from flask import Flask
+
+from local_deep_research.web.services.socket_service import SocketIOService
+
+
[email protected](autouse=True)
+def reset_singleton():
+ """Reset singleton before each test."""
+ SocketIOService._instance = None
+ yield
+ SocketIOService._instance = None
+
+
+def minimal_app():
+ """Create a minimal Flask app (no create_app() which triggers SocketIOService)."""
+ app = Flask(__name__)
+ app.config["SECRET_KEY"] = "test"
+ app.config["TESTING"] = True
+ return app
+
+
+class TestSocketIOServiceSingleton:
+ """Tests for singleton creation and behavior."""
+
+ def test_requires_app_on_first_creation(self):
+ """Should raise ValueError if no app provided on first init."""
+ with pytest.raises(ValueError, match="Flask app must be specified"):
+ SocketIOService()
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ @patch("local_deep_research.settings.env_registry.get_env_setting")
+ def test_creates_singleton_with_app(
+ self, mock_env, mock_socketio, minimal_app
+ ):
+ mock_env.return_value = None
+
+ service = SocketIOService(app=minimal_app)
+ assert service is not None
+ assert SocketIOService._instance is service
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ @patch("local_deep_research.settings.env_registry.get_env_setting")
+ def test_second_call_returns_same_instance(
+ self, mock_env, mock_socketio, minimal_app
+ ):
+ mock_env.return_value = None
+
+ first = SocketIOService(app=minimal_app)
+ second = SocketIOService(app=minimal_app)
+ assert first is second
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ @patch("local_deep_research.settings.env_registry.get_env_setting")
+ def test_second_call_without_app_returns_existing(
+ self, mock_env, mock_socketio, minimal_app
+ ):
+ mock_env.return_value = None
+
+ first = SocketIOService(app=minimal_app)
+ second = SocketIOService() # No app needed on second call
+ assert first is second
+
+
+class TestSocketIOServiceCorsConfig:
+ """Tests for WebSocket CORS configuration in __init_singleton."""
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ @patch("local_deep_research.settings.env_registry.get_env_setting")
+ def test_default_cors_is_wildcard(
+ self, mock_env, mock_socketio, minimal_app
+ ):
+ """No env var set -> permissive default (*)."""
+ mock_env.return_value = None
+
+ SocketIOService(app=minimal_app)
+ mock_socketio.assert_called_once()
+ call_kwargs = mock_socketio.call_args[1]
+ assert call_kwargs["cors_allowed_origins"] == "*"
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ @patch("local_deep_research.settings.env_registry.get_env_setting")
+ def test_wildcard_env_setting(self, mock_env, mock_socketio, minimal_app):
+ mock_env.return_value = "*"
+
+ SocketIOService(app=minimal_app)
+ call_kwargs = mock_socketio.call_args[1]
+ assert call_kwargs["cors_allowed_origins"] == "*"
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ @patch("local_deep_research.settings.env_registry.get_env_setting")
+ def test_specific_origins(self, mock_env, mock_socketio, minimal_app):
+ mock_env.return_value = "https://a.com, https://b.com"
+
+ SocketIOService(app=minimal_app)
+ call_kwargs = mock_socketio.call_args[1]
+ assert call_kwargs["cors_allowed_origins"] == [
+ "https://a.com",
+ "https://b.com",
+ ]
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ @patch("local_deep_research.settings.env_registry.get_env_setting")
+ def test_empty_env_disables_cors(
+ self, mock_env, mock_socketio, minimal_app
+ ):
+ """Empty string env var -> same-origin only (None)."""
+ mock_env.return_value = ""
+
+ SocketIOService(app=minimal_app)
+ call_kwargs = mock_socketio.call_args[1]
+ assert call_kwargs["cors_allowed_origins"] is None
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ @patch("local_deep_research.settings.env_registry.get_env_setting")
+ def test_socketio_async_mode_threading(
+ self, mock_env, mock_socketio, minimal_app
+ ):
+ mock_env.return_value = None
+
+ SocketIOService(app=minimal_app)
+ call_kwargs = mock_socketio.call_args[1]
+ assert call_kwargs["async_mode"] == "threading"
+
+ @patch("local_deep_research.web.services.socket_service.SocketIO")
+ @patch("local_deep_research.settings.env_registry.get_env_setting")
+ def test_socketio_path(self, mock_env, mock_socketio, minimal_app):
+ mock_env.return_value = None
+
+ SocketIOService(app=minimal_app)
+ call_kwargs = mock_socketio.call_args[1]
+ assert call_kwargs["path"] == "/socket.io"