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 auth decorators, research service, queue processor, and rate limiter

LearningCircuita38a755cb607
diff --git a/tests/web/auth/test_decorators.py b/tests/web/auth/test_decorators.py
new file mode 100644
index 0000000000..281aeb613f
--- /dev/null
+++ b/tests/web/auth/test_decorators.py
@@ -0,0 +1,314 @@
+"""
+Tests for web/auth/decorators.py
+
+Tests cover:
+- login_required decorator
+- current_user function
+- get_current_db_session function
+- inject_current_user function
+"""
+
+from unittest.mock import Mock, patch
+from flask import Flask, session, g
+
+
+class TestLoginRequiredDecorator:
+ """Tests for login_required decorator."""
+
+ def test_unauthenticated_api_request_returns_401(self):
+ """Test that unauthenticated API requests return 401 JSON error."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ with patch("local_deep_research.web.auth.decorators.db_manager"):
+ from local_deep_research.web.auth.decorators import login_required
+
+ @app.route("/api/test")
+ @login_required
+ def test_route():
+ return {"success": True}
+
+ with app.test_client() as client:
+ response = client.get("/api/test")
+ assert response.status_code == 401
+ assert response.json["error"] == "Authentication required"
+
+ def test_unauthenticated_settings_api_request_returns_401(self):
+ """Test that unauthenticated settings API requests return 401."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ with patch("local_deep_research.web.auth.decorators.db_manager"):
+ from local_deep_research.web.auth.decorators import login_required
+
+ @app.route("/settings/api/test")
+ @login_required
+ def test_route():
+ return {"success": True}
+
+ with app.test_client() as client:
+ response = client.get("/settings/api/test")
+ assert response.status_code == 401
+
+ def test_unauthenticated_web_request_redirects(self):
+ """Test that unauthenticated web requests redirect to login."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ # Register auth blueprint with login route
+ from flask import Blueprint
+
+ auth = Blueprint("auth", __name__)
+
+ @auth.route("/login")
+ def login():
+ return "Login Page"
+
+ app.register_blueprint(auth, url_prefix="/auth")
+
+ with patch("local_deep_research.web.auth.decorators.db_manager"):
+ from local_deep_research.web.auth.decorators import login_required
+
+ @app.route("/dashboard")
+ @login_required
+ def dashboard():
+ return "Dashboard"
+
+ with app.test_client() as client:
+ response = client.get("/dashboard")
+ assert response.status_code == 302
+ assert "/auth/login" in response.location
+
+ def test_authenticated_without_db_connection_api_returns_401(self):
+ """Test authenticated user without DB connection on API route."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.connections.get.return_value = None
+
+ from local_deep_research.web.auth.decorators import login_required
+
+ @app.route("/api/test")
+ @login_required
+ def test_route():
+ return {"success": True}
+
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ response = client.get("/api/test")
+ assert response.status_code == 401
+ assert response.json["error"] == "Database connection required"
+
+ def test_authenticated_with_db_connection_succeeds(self):
+ """Test authenticated user with DB connection succeeds."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.connections.get.return_value = Mock()
+
+ from local_deep_research.web.auth.decorators import login_required
+
+ @app.route("/api/test")
+ @login_required
+ def test_route():
+ return {"success": True}
+
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ response = client.get("/api/test")
+ assert response.status_code == 200
+
+
+class TestCurrentUser:
+ """Tests for current_user function."""
+
+ def test_current_user_returns_username(self):
+ """Test current_user returns username from session."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ from local_deep_research.web.auth.decorators import current_user
+
+ with app.test_request_context():
+ session["username"] = "testuser"
+ assert current_user() == "testuser"
+
+ def test_current_user_returns_none_when_not_authenticated(self):
+ """Test current_user returns None when not authenticated."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ from local_deep_research.web.auth.decorators import current_user
+
+ with app.test_request_context():
+ assert current_user() is None
+
+
+class TestGetCurrentDbSession:
+ """Tests for get_current_db_session function."""
+
+ def test_get_session_returns_session_for_authenticated_user(self):
+ """Test get_current_db_session returns session for authenticated user."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ mock_session = Mock()
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.get_session.return_value = mock_session
+
+ from local_deep_research.web.auth.decorators import (
+ get_current_db_session,
+ )
+
+ with app.test_request_context():
+ session["username"] = "testuser"
+ result = get_current_db_session()
+ assert result == mock_session
+ mock_db_manager.get_session.assert_called_once_with("testuser")
+
+ def test_get_session_returns_none_when_not_authenticated(self):
+ """Test get_current_db_session returns None when not authenticated."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ from local_deep_research.web.auth.decorators import (
+ get_current_db_session,
+ )
+
+ with app.test_request_context():
+ result = get_current_db_session()
+ assert result is None
+
+
+class TestInjectCurrentUser:
+ """Tests for inject_current_user function."""
+
+ def test_inject_user_sets_g_current_user(self):
+ """Test inject_current_user sets g.current_user."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ mock_db_session = Mock()
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.get_session.return_value = mock_db_session
+ mock_db_manager.connections.get.return_value = Mock()
+
+ from local_deep_research.web.auth.decorators import (
+ inject_current_user,
+ )
+
+ with app.test_request_context():
+ session["username"] = "testuser"
+ inject_current_user()
+ assert g.current_user == "testuser"
+ assert g.db_session == mock_db_session
+
+ def test_inject_user_no_session(self):
+ """Test inject_current_user when no session."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ from local_deep_research.web.auth.decorators import inject_current_user
+
+ with app.test_request_context():
+ inject_current_user()
+ assert g.current_user is None
+ assert g.db_session is None
+
+ def test_inject_user_with_db_error(self):
+ """Test inject_current_user handles DB errors gracefully."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.get_session.side_effect = Exception("DB Error")
+
+ from local_deep_research.web.auth.decorators import (
+ inject_current_user,
+ )
+
+ with app.test_request_context():
+ session["username"] = "testuser"
+ inject_current_user()
+ assert g.current_user == "testuser"
+ assert g.db_session is None
+
+ def test_inject_user_clears_stale_session_for_regular_routes(self):
+ """Test inject_current_user clears stale session for regular routes."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.get_session.return_value = None
+ mock_db_manager.connections.get.return_value = None
+
+ from local_deep_research.web.auth.decorators import (
+ inject_current_user,
+ )
+
+ with app.test_request_context("/dashboard"):
+ session["username"] = "testuser"
+ inject_current_user()
+ # Session should be cleared
+ assert g.current_user is None
+ assert g.db_session is None
+
+ def test_inject_user_allows_api_routes_without_db(self):
+ """Test inject_current_user allows API routes without DB connection."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.get_session.return_value = None
+ mock_db_manager.connections.get.return_value = None
+
+ from local_deep_research.web.auth.decorators import (
+ inject_current_user,
+ )
+
+ with app.test_request_context("/api/test"):
+ session["username"] = "testuser"
+ inject_current_user()
+ # g.current_user should still be set for API routes
+ assert g.current_user == "testuser"
+
+ def test_inject_user_allows_auth_routes_without_db(self):
+ """Test inject_current_user allows auth routes without DB connection."""
+ app = Flask(__name__)
+ app.secret_key = "test"
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.get_session.return_value = None
+ mock_db_manager.connections.get.return_value = None
+
+ from local_deep_research.web.auth.decorators import (
+ inject_current_user,
+ )
+
+ with app.test_request_context("/auth/login"):
+ session["username"] = "testuser"
+ inject_current_user()
+ # g.current_user should still be set for auth routes
+ assert g.current_user == "testuser"
diff --git a/tests/web/queue/test_processor_v2.py b/tests/web/queue/test_processor_v2.py
new file mode 100644
index 0000000000..e3d21c5d62
--- /dev/null
+++ b/tests/web/queue/test_processor_v2.py
@@ -0,0 +1,405 @@
+"""
+Tests for web/queue/processor_v2.py
+
+Tests cover:
+- QueueProcessorV2 initialization
+- start/stop methods
+- notify_user_activity
+- notify_research_queued
+- _start_research_directly
+"""
+
+from unittest.mock import Mock, patch
+import threading
+
+
+class TestQueueProcessorV2Init:
+ """Tests for QueueProcessorV2 initialization."""
+
+ def test_init_default_interval(self):
+ """Test initialization with default check interval."""
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+
+ assert processor.check_interval == 10
+ assert processor.running is False
+ assert processor.thread is None
+ assert len(processor._users_to_check) == 0
+
+ def test_init_custom_interval(self):
+ """Test initialization with custom check interval."""
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2(check_interval=30)
+
+ assert processor.check_interval == 30
+
+
+class TestQueueProcessorV2StartStop:
+ """Tests for start/stop methods."""
+
+ def test_start_sets_running(self):
+ """Test that start sets running to True."""
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+
+ with patch.object(threading, "Thread") as mock_thread:
+ mock_thread_instance = Mock()
+ mock_thread.return_value = mock_thread_instance
+
+ processor.start()
+
+ assert processor.running is True
+ mock_thread_instance.start.assert_called_once()
+
+ def test_start_already_running(self):
+ """Test that start does nothing if already running."""
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+ processor.running = True
+
+ with patch.object(threading, "Thread") as mock_thread:
+ processor.start()
+
+ mock_thread.assert_not_called()
+
+ def test_stop_sets_running_false(self):
+ """Test that stop sets running to False."""
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+ processor.running = True
+ processor.thread = Mock()
+
+ processor.stop()
+
+ assert processor.running is False
+ processor.thread.join.assert_called_once_with(timeout=10)
+
+
+class TestNotifyUserActivity:
+ """Tests for notify_user_activity method."""
+
+ def test_adds_user_to_check_list(self):
+ """Test that notify adds user to check list."""
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+
+ processor.notify_user_activity("testuser", "session123")
+
+ assert "testuser:session123" in processor._users_to_check
+
+ def test_adds_multiple_users(self):
+ """Test that multiple users can be added."""
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+
+ processor.notify_user_activity("user1", "session1")
+ processor.notify_user_activity("user2", "session2")
+
+ assert "user1:session1" in processor._users_to_check
+ assert "user2:session2" in processor._users_to_check
+
+
+class TestNotifyResearchQueued:
+ """Tests for notify_research_queued method."""
+
+ def test_queues_research_without_kwargs(self):
+ """Test research is queued when no kwargs provided."""
+ mock_session = Mock()
+ mock_queue_service = Mock()
+
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ with patch(
+ "local_deep_research.web.queue.processor_v2.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_get_session.return_value.__exit__ = Mock(
+ return_value=False
+ )
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.UserQueueService"
+ ) as mock_queue_class:
+ mock_queue_class.return_value = mock_queue_service
+
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+ processor.notify_research_queued("testuser", "research-123")
+
+ mock_queue_service.add_task_metadata.assert_called_once_with(
+ task_id="research-123",
+ task_type="research",
+ priority=0,
+ )
+
+ def test_handles_queue_error_gracefully(self):
+ """Test that queue errors are handled gracefully."""
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ with patch(
+ "local_deep_research.web.queue.processor_v2.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ side_effect=Exception("DB Error")
+ )
+
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+ # Should not raise
+ processor.notify_research_queued("testuser", "research-123")
+
+
+class TestStartResearchDirectly:
+ """Tests for _start_research_directly method."""
+
+ def test_creates_active_record(self):
+ """Test that active research record is created."""
+ mock_session = Mock()
+ mock_queue_service = Mock()
+
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ with patch(
+ "local_deep_research.web.queue.processor_v2.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_get_session.return_value.__exit__ = Mock(
+ return_value=False
+ )
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.UserQueueService"
+ ) as mock_queue_class:
+ mock_queue_class.return_value = mock_queue_service
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.start_research_process"
+ ) as mock_start:
+ mock_thread = Mock()
+ mock_thread.ident = 12345
+ mock_start.return_value = mock_thread
+
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+ processor._start_research_directly(
+ "testuser",
+ "research-123",
+ "password123",
+ query="test query",
+ mode="detailed",
+ )
+
+ mock_session.add.assert_called()
+ mock_session.commit.assert_called()
+
+
+class TestRetryConstants:
+ """Tests for retry configuration constants."""
+
+ def test_retry_constants_exist(self):
+ """Test that retry constants are defined."""
+ from local_deep_research.web.queue.processor_v2 import (
+ MAX_RESEARCH_LOOKUP_RETRIES,
+ INITIAL_RESEARCH_LOOKUP_DELAY,
+ RETRY_BACKOFF_MULTIPLIER,
+ )
+
+ assert MAX_RESEARCH_LOOKUP_RETRIES == 3
+ assert INITIAL_RESEARCH_LOOKUP_DELAY == 0.5
+ assert RETRY_BACKOFF_MULTIPLIER == 2
+
+
+class TestPendingOperations:
+ """Tests for pending operations tracking."""
+
+ def test_pending_operations_initialization(self):
+ """Test that pending operations dict is initialized."""
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+
+ assert processor.pending_operations == {}
+ assert hasattr(processor, "_pending_operations_lock")
+
+
+class TestDirectModeExecution:
+ """Tests for direct mode execution logic."""
+
+ def test_direct_mode_with_session_id(self):
+ """Test direct mode when session_id is provided."""
+ mock_engine = Mock()
+ mock_session = Mock()
+ mock_settings_manager = Mock()
+ mock_settings_manager.get_setting.side_effect = [
+ "direct", # queue_mode
+ 3, # max_concurrent
+ ]
+
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ with patch(
+ "local_deep_research.web.queue.processor_v2.session_password_store"
+ ) as mock_password_store:
+ mock_password_store.get_session_password.return_value = (
+ "password123"
+ )
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.open_user_database.return_value = (
+ mock_engine
+ )
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_get_session.return_value.__exit__ = Mock(
+ return_value=False
+ )
+
+ # Mock query for active count
+ mock_session.query.return_value.filter_by.return_value.count.return_value = 0
+
+ with patch(
+ "local_deep_research.settings.manager.SettingsManager"
+ ) as mock_settings_class:
+ mock_settings_class.return_value = (
+ mock_settings_manager
+ )
+
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+
+ with patch.object(
+ processor, "_start_research_directly"
+ ) as mock_start_direct:
+ processor.notify_research_queued(
+ "testuser",
+ "research-123",
+ session_id="session456",
+ query="test",
+ mode="quick",
+ )
+
+ mock_start_direct.assert_called_once()
+
+
+class TestQueueModeExecution:
+ """Tests for queue mode execution logic."""
+
+ def test_falls_back_to_queue_when_max_concurrent_reached(self):
+ """Test that queue is used when max concurrent reached."""
+ mock_engine = Mock()
+ mock_session = Mock()
+ mock_settings_manager = Mock()
+ mock_settings_manager.get_setting.side_effect = [
+ "direct", # queue_mode
+ 1, # max_concurrent (set to 1)
+ ]
+ mock_queue_service = Mock()
+
+ with patch("local_deep_research.web.queue.processor_v2.logger"):
+ with patch(
+ "local_deep_research.web.queue.processor_v2.session_password_store"
+ ) as mock_password_store:
+ mock_password_store.get_session_password.return_value = (
+ "password123"
+ )
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.db_manager"
+ ) as mock_db_manager:
+ mock_db_manager.open_user_database.return_value = (
+ mock_engine
+ )
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_get_session.return_value.__exit__ = Mock(
+ return_value=False
+ )
+
+ # Mock query for active count - already at max
+ mock_session.query.return_value.filter_by.return_value.count.return_value = 1
+
+ with patch(
+ "local_deep_research.settings.manager.SettingsManager"
+ ) as mock_settings_class:
+ mock_settings_class.return_value = (
+ mock_settings_manager
+ )
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.UserQueueService"
+ ) as mock_queue_class:
+ mock_queue_class.return_value = (
+ mock_queue_service
+ )
+
+ from local_deep_research.web.queue.processor_v2 import (
+ QueueProcessorV2,
+ )
+
+ processor = QueueProcessorV2()
+
+ processor.notify_research_queued(
+ "testuser",
+ "research-123",
+ session_id="session456",
+ query="test",
+ mode="quick",
+ )
+
+ # Queue service should be called
+ mock_queue_service.add_task_metadata.assert_called()
diff --git a/tests/web/services/test_research_service.py b/tests/web/services/test_research_service.py
new file mode 100644
index 0000000000..b7b1b67d09
--- /dev/null
+++ b/tests/web/services/test_research_service.py
@@ -0,0 +1,471 @@
+"""
+Tests for web/services/research_service.py
+
+Tests cover:
+- get_citation_formatter function
+- export_report_to_memory function
+- save_research_strategy function
+- get_research_strategy function
+- start_research_process function
+- _generate_report_path function
+"""
+
+import pytest
+from unittest.mock import Mock, patch
+from pathlib import Path
+import hashlib
+
+
+class TestGetCitationFormatter:
+ """Tests for get_citation_formatter function."""
+
+ def test_get_citation_formatter_default(self):
+ """Test default citation formatter."""
+ with patch(
+ "local_deep_research.config.search_config.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.return_value = "number_hyperlinks"
+
+ from local_deep_research.web.services.research_service import (
+ get_citation_formatter,
+ )
+ from local_deep_research.text_optimization import CitationMode
+
+ formatter = get_citation_formatter()
+
+ assert formatter is not None
+ assert formatter.mode == CitationMode.NUMBER_HYPERLINKS
+
+ def test_get_citation_formatter_domain_hyperlinks(self):
+ """Test domain_hyperlinks citation format."""
+ with patch(
+ "local_deep_research.config.search_config.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.return_value = "domain_hyperlinks"
+
+ from local_deep_research.web.services.research_service import (
+ get_citation_formatter,
+ )
+ from local_deep_research.text_optimization import CitationMode
+
+ formatter = get_citation_formatter()
+
+ assert formatter.mode == CitationMode.DOMAIN_HYPERLINKS
+
+ def test_get_citation_formatter_no_hyperlinks(self):
+ """Test no_hyperlinks citation format."""
+ with patch(
+ "local_deep_research.config.search_config.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.return_value = "no_hyperlinks"
+
+ from local_deep_research.web.services.research_service import (
+ get_citation_formatter,
+ )
+ from local_deep_research.text_optimization import CitationMode
+
+ formatter = get_citation_formatter()
+
+ assert formatter.mode == CitationMode.NO_HYPERLINKS
+
+ def test_get_citation_formatter_unknown_format(self):
+ """Test unknown format defaults to NUMBER_HYPERLINKS."""
+ with patch(
+ "local_deep_research.config.search_config.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.return_value = "unknown_format"
+
+ from local_deep_research.web.services.research_service import (
+ get_citation_formatter,
+ )
+ from local_deep_research.text_optimization import CitationMode
+
+ formatter = get_citation_formatter()
+
+ assert formatter.mode == CitationMode.NUMBER_HYPERLINKS
+
+
+class TestExportReportToMemory:
+ """Tests for export_report_to_memory function."""
+
+ def test_export_pdf_format(self):
+ """Test export to PDF format."""
+ mock_pdf_service = Mock()
+ mock_pdf_service.markdown_to_pdf.return_value = b"PDF content"
+
+ with patch(
+ "local_deep_research.web.services.pdf_service.get_pdf_service"
+ ) as mock_get_pdf:
+ mock_get_pdf.return_value = mock_pdf_service
+
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ content, filename, mimetype = export_report_to_memory(
+ "# Test Report\n\nContent here",
+ format="pdf",
+ title="Test Report",
+ )
+
+ assert content == b"PDF content"
+ assert filename.endswith(".pdf")
+ assert mimetype == "application/pdf"
+
+ def test_export_pdf_adds_title_if_missing(self):
+ """Test PDF export adds title when not present."""
+ mock_pdf_service = Mock()
+ mock_pdf_service.markdown_to_pdf.return_value = b"PDF content"
+
+ with patch(
+ "local_deep_research.web.services.pdf_service.get_pdf_service"
+ ) as mock_get_pdf:
+ mock_get_pdf.return_value = mock_pdf_service
+
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ export_report_to_memory(
+ "Some content without header",
+ format="pdf",
+ title="My Report",
+ )
+
+ # Check that markdown_to_pdf was called with title prepended
+ call_args = mock_pdf_service.markdown_to_pdf.call_args
+ assert "# My Report" in call_args[0][0]
+
+ def test_export_latex_format(self):
+ """Test export to LaTeX format."""
+ mock_exporter = Mock()
+ mock_exporter.export_to_latex.return_value = "\\documentclass{article}"
+
+ with patch(
+ "local_deep_research.text_optimization.citation_formatter.LaTeXExporter"
+ ) as mock_latex_class:
+ mock_latex_class.return_value = mock_exporter
+
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ content, filename, mimetype = export_report_to_memory(
+ "# Test\n\nContent",
+ format="latex",
+ title="Test Report",
+ )
+
+ assert b"\\documentclass{article}" in content
+ assert filename.endswith(".tex")
+ assert mimetype == "text/plain"
+
+ def test_export_quarto_format(self):
+ """Test export to Quarto format creates zip."""
+ mock_exporter = Mock()
+ mock_exporter.export_to_quarto.return_value = "---\ntitle: Test\n---"
+ mock_exporter._generate_bibliography.return_value = "@article{test}"
+
+ with patch(
+ "local_deep_research.text_optimization.citation_formatter.QuartoExporter"
+ ) as mock_quarto_class:
+ mock_quarto_class.return_value = mock_exporter
+
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ content, filename, mimetype = export_report_to_memory(
+ "# Test\n\nContent",
+ format="quarto",
+ title="Test Report",
+ )
+
+ assert isinstance(content, bytes)
+ assert filename.endswith(".zip")
+ assert mimetype == "application/zip"
+
+ def test_export_ris_format(self):
+ """Test export to RIS format."""
+ mock_exporter = Mock()
+ mock_exporter.export_to_ris.return_value = "TY - JOUR\nER -"
+
+ with patch(
+ "local_deep_research.text_optimization.citation_formatter.RISExporter"
+ ) as mock_ris_class:
+ mock_ris_class.return_value = mock_exporter
+
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ content, filename, mimetype = export_report_to_memory(
+ "# Test\n\nContent",
+ format="ris",
+ title="Test Report",
+ )
+
+ assert b"TY - JOUR" in content
+ assert filename.endswith(".ris")
+ assert mimetype == "text/plain"
+
+ def test_export_unsupported_format_raises_error(self):
+ """Test unsupported format raises ValueError."""
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ with pytest.raises(ValueError) as exc_info:
+ export_report_to_memory("# Test", format="docx")
+
+ assert "Unsupported export format" in str(exc_info.value)
+
+
+class TestSaveResearchStrategy:
+ """Tests for save_research_strategy function."""
+
+ def test_save_new_strategy(self):
+ """Test saving a new strategy."""
+ mock_session = Mock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ with patch(
+ "local_deep_research.web.services.research_service.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_get_session.return_value.__exit__ = Mock(return_value=False)
+
+ from local_deep_research.web.services.research_service import (
+ save_research_strategy,
+ )
+
+ save_research_strategy("research-123", "source-based", "testuser")
+
+ mock_session.add.assert_called_once()
+ mock_session.commit.assert_called_once()
+
+ def test_update_existing_strategy(self):
+ """Test updating an existing strategy."""
+ mock_existing = Mock()
+ mock_existing.strategy_name = "old-strategy"
+
+ mock_session = Mock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_existing
+
+ with patch(
+ "local_deep_research.web.services.research_service.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_get_session.return_value.__exit__ = Mock(return_value=False)
+
+ from local_deep_research.web.services.research_service import (
+ save_research_strategy,
+ )
+
+ save_research_strategy("research-123", "new-strategy", "testuser")
+
+ assert mock_existing.strategy_name == "new-strategy"
+ mock_session.commit.assert_called_once()
+
+ def test_save_strategy_handles_error(self):
+ """Test that errors are handled gracefully."""
+ with patch(
+ "local_deep_research.web.services.research_service.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ side_effect=Exception("DB Error")
+ )
+
+ from local_deep_research.web.services.research_service import (
+ save_research_strategy,
+ )
+
+ # Should not raise, just log the error
+ save_research_strategy("research-123", "strategy", "testuser")
+
+
+class TestGetResearchStrategy:
+ """Tests for get_research_strategy function."""
+
+ def test_get_strategy_found(self):
+ """Test getting an existing strategy."""
+ mock_strategy = Mock()
+ mock_strategy.strategy_name = "source-based"
+
+ mock_session = Mock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_strategy
+
+ with patch(
+ "local_deep_research.web.services.research_service.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_get_session.return_value.__exit__ = Mock(return_value=False)
+
+ from local_deep_research.web.services.research_service import (
+ get_research_strategy,
+ )
+
+ result = get_research_strategy("research-123", "testuser")
+
+ assert result == "source-based"
+
+ def test_get_strategy_not_found(self):
+ """Test getting strategy when not found."""
+ mock_session = Mock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ with patch(
+ "local_deep_research.web.services.research_service.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_get_session.return_value.__exit__ = Mock(return_value=False)
+
+ from local_deep_research.web.services.research_service import (
+ get_research_strategy,
+ )
+
+ result = get_research_strategy("nonexistent", "testuser")
+
+ assert result is None
+
+ def test_get_strategy_handles_error(self):
+ """Test that errors return None."""
+ with patch(
+ "local_deep_research.web.services.research_service.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ side_effect=Exception("DB Error")
+ )
+
+ from local_deep_research.web.services.research_service import (
+ get_research_strategy,
+ )
+
+ result = get_research_strategy("research-123", "testuser")
+
+ assert result is None
+
+
+class TestStartResearchProcess:
+ """Tests for start_research_process function."""
+
+ def test_start_research_creates_thread(self):
+ """Test that start_research_process creates a thread."""
+ mock_callback = Mock()
+ active_research = {}
+ termination_flags = {}
+
+ with patch(
+ "local_deep_research.web.services.research_service.thread_with_app_context"
+ ) as mock_thread_ctx:
+ mock_thread_ctx.return_value = mock_callback
+
+ with patch(
+ "local_deep_research.web.services.research_service.threading.Thread"
+ ) as mock_thread_class:
+ mock_thread = Mock()
+ mock_thread_class.return_value = mock_thread
+
+ from local_deep_research.web.services.research_service import (
+ start_research_process,
+ )
+
+ start_research_process(
+ research_id="test-123",
+ query="test query",
+ mode="quick",
+ active_research=active_research,
+ termination_flags=termination_flags,
+ run_research_callback=mock_callback,
+ )
+
+ mock_thread.start.assert_called_once()
+ assert "test-123" in active_research
+ assert active_research["test-123"]["status"] == "in_progress"
+
+
+class TestGenerateReportPath:
+ """Tests for _generate_report_path function."""
+
+ def test_generates_unique_path(self):
+ """Test that unique paths are generated."""
+ with patch(
+ "local_deep_research.web.services.research_service.OUTPUT_DIR",
+ Path("/tmp/reports"),
+ ):
+ from local_deep_research.web.services.research_service import (
+ _generate_report_path,
+ )
+
+ path = _generate_report_path("test query")
+
+ assert str(path).startswith("/tmp/reports/research_report_")
+ assert str(path).endswith(".md")
+
+ def test_generates_consistent_hash(self):
+ """Test that same query generates same hash prefix."""
+ with patch(
+ "local_deep_research.web.services.research_service.OUTPUT_DIR",
+ Path("/tmp/reports"),
+ ):
+ from local_deep_research.web.services.research_service import (
+ _generate_report_path,
+ )
+
+ query = "test query"
+ expected_hash = hashlib.md5(
+ query.encode("utf-8"), usedforsecurity=False
+ ).hexdigest()[:10]
+
+ path = _generate_report_path(query)
+
+ assert expected_hash in str(path)
+
+
+class TestFilenameGeneration:
+ """Tests for filename generation in export."""
+
+ def test_filename_sanitization(self):
+ """Test that special characters are removed from filename."""
+ import re
+
+ title = "Test: Report! @#$%"
+ safe_title = (
+ re.sub(r"[^\w\s-]", "", title).strip().replace(" ", "_")[:50]
+ )
+
+ assert safe_title == "Test_Report"
+
+ def test_filename_truncation(self):
+ """Test that long titles are truncated."""
+ import re
+
+ title = "A" * 100
+ safe_title = (
+ re.sub(r"[^\w\s-]", "", title).strip().replace(" ", "_")[:50]
+ )
+
+ assert len(safe_title) == 50
+
+ def test_empty_title_uses_default(self):
+ """Test that empty title uses default."""
+ title = None
+ safe_title = (
+ (
+ title.strip().replace(" ", "_")[:50]
+ if title
+ else "research_report"
+ )
+ if title
+ else "research_report"
+ )
+
+ assert safe_title == "research_report"
diff --git a/tests/web_search_engines/engines/__init__.py b/tests/web_search_engines/engines/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/web_search_engines/rate_limiting/__init__.py b/tests/web_search_engines/rate_limiting/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/web_search_engines/rate_limiting/test_tracker.py b/tests/web_search_engines/rate_limiting/test_tracker.py
new file mode 100644
index 0000000000..1bd442dcde
--- /dev/null
+++ b/tests/web_search_engines/rate_limiting/test_tracker.py
@@ -0,0 +1,526 @@
+"""
+Tests for web_search_engines/rate_limiting/tracker.py
+
+Tests cover:
+- AdaptiveRateLimitTracker initialization
+- _apply_profile method
+- _load_estimates method
+- get_wait_time method
+- record_attempt method
+"""
+
+from unittest.mock import patch
+
+
+class TestAdaptiveRateLimitTrackerInit:
+ """Tests for AdaptiveRateLimitTracker initialization."""
+
+ def test_init_default_settings(self):
+ """Test initialization with default settings."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+
+ assert tracker.memory_window == 100
+ assert tracker.enabled is False # Programmatic mode default
+ assert tracker.programmatic_mode is True
+
+ def test_init_with_settings_snapshot(self):
+ """Test initialization with settings snapshot."""
+ settings = {
+ "rate_limiting.memory_window": 50,
+ "rate_limiting.exploration_rate": 0.15,
+ "rate_limiting.learning_rate": 0.4,
+ "rate_limiting.decay_per_day": 0.9,
+ "rate_limiting.enabled": True,
+ "rate_limiting.profile": "aggressive",
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+
+ def get_setting_side_effect(key, **kwargs):
+ return settings.get(key)
+
+ mock_get_setting.side_effect = get_setting_side_effect
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(
+ settings_snapshot=settings, programmatic_mode=True
+ )
+
+ assert tracker.settings_snapshot == settings
+
+ def test_init_in_memory_structures(self):
+ """Test that in-memory structures are initialized."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+
+ assert tracker.recent_attempts == {}
+ assert tracker.current_estimates == {}
+ assert tracker._estimates_loaded is True # In programmatic mode
+
+
+class TestApplyProfile:
+ """Tests for _apply_profile method."""
+
+ def test_conservative_profile(self):
+ """Test conservative profile reduces exploration."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+
+ tracker._apply_profile("conservative")
+
+ # Conservative should reduce exploration rate
+ assert tracker.exploration_rate <= 0.05
+
+ def test_aggressive_profile(self):
+ """Test aggressive profile increases exploration."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+
+ tracker._apply_profile("aggressive")
+
+ # Aggressive should increase exploration rate (but max 0.2)
+ assert tracker.exploration_rate <= 0.2
+
+ def test_balanced_profile(self):
+ """Test balanced profile keeps settings as-is."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+ original_rate = 0.1
+
+ tracker.exploration_rate = original_rate
+ tracker._apply_profile("balanced")
+
+ assert tracker.exploration_rate == original_rate
+
+
+class TestGetWaitTime:
+ """Tests for get_wait_time method."""
+
+ def test_disabled_returns_minimal_wait(self):
+ """Test that disabled rate limiting returns minimal wait."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+ tracker.enabled = False
+
+ wait_time = tracker.get_wait_time("test_engine")
+
+ assert wait_time == 0.1
+
+ def test_new_engine_returns_optimistic_default(self):
+ """Test that unknown engine gets optimistic default."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_search_context"
+ ) as mock_context:
+ mock_context.return_value = {"username": "test"}
+
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+ tracker.enabled = True
+ tracker._estimates_loaded = True
+
+ wait_time = tracker.get_wait_time("new_engine")
+
+ assert wait_time == 0.1 # Optimistic default
+
+ def test_local_engine_returns_zero(self):
+ """Test that LocalSearchEngine gets zero wait time."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_search_context"
+ ) as mock_context:
+ mock_context.return_value = {"username": "test"}
+
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+ tracker.enabled = True
+ tracker._estimates_loaded = True
+
+ wait_time = tracker.get_wait_time("LocalSearchEngine")
+
+ assert wait_time == 0.0
+
+ def test_known_engine_uses_estimate(self):
+ """Test that known engine uses learned estimate."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_search_context"
+ ) as mock_context:
+ mock_context.return_value = {"username": "test"}
+
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+ tracker.enabled = True
+ tracker._estimates_loaded = True
+ tracker.exploration_rate = (
+ 0 # Disable exploration for predictable test
+ )
+ tracker.current_estimates["test_engine"] = {
+ "base": 1.0,
+ "min": 0.5,
+ "max": 2.0,
+ "confidence": 1.0,
+ }
+
+ wait_time = tracker.get_wait_time("test_engine")
+
+ # Should be within jitter range of base
+ assert 0.5 <= wait_time <= 2.0
+
+
+class TestLoadEstimates:
+ """Tests for _load_estimates method."""
+
+ def test_programmatic_mode_skips_loading(self):
+ """Test that programmatic mode skips database loading."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+
+ assert tracker._estimates_loaded is True
+
+ def test_fallback_mode_skips_loading(self):
+ """Test that fallback mode skips database loading."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm"
+ ) as mock_fallback:
+ mock_fallback.return_value = True
+
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=False)
+
+ # Should mark as not loaded since fallback mode
+ assert tracker._estimates_loaded is False
+
+
+class TestGetDbImports:
+ """Tests for _get_db_imports function."""
+
+ def test_get_db_imports_success(self):
+ """Test successful database import loading."""
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ _get_db_imports,
+ )
+
+ # Reset global state
+ import local_deep_research.web_search_engines.rate_limiting.tracker as tracker_module
+
+ tracker_module._db_imports = None
+
+ imports = _get_db_imports()
+
+ assert "RateLimitAttempt" in imports
+ assert "RateLimitEstimate" in imports
+ assert "get_user_db_session" in imports
+
+ def test_get_db_imports_cached(self):
+ """Test that imports are cached."""
+ import local_deep_research.web_search_engines.rate_limiting.tracker as tracker_module
+
+ # Set cached value
+ tracker_module._db_imports = {"cached": True}
+
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ _get_db_imports,
+ )
+
+ imports = _get_db_imports()
+
+ assert imports == {"cached": True}
+
+ # Reset for other tests
+ tracker_module._db_imports = None
+
+
+class TestEnsureEstimatesLoaded:
+ """Tests for _ensure_estimates_loaded method."""
+
+ def test_already_loaded_returns_early(self):
+ """Test that already loaded returns early."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker._get_db_imports"
+ ) as mock_imports:
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+ tracker._estimates_loaded = True
+
+ tracker._ensure_estimates_loaded()
+
+ mock_imports.assert_not_called()
+
+
+class TestTrackerSettings:
+ """Tests for tracker settings and defaults."""
+
+ def test_memory_window_default(self):
+ """Test default memory window value."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+
+ assert tracker.memory_window == 100
+
+ def test_exploration_rate_default(self):
+ """Test default exploration rate."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+
+ assert tracker.exploration_rate == 0.1
+
+ def test_learning_rate_default(self):
+ """Test default learning rate."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+
+ assert tracker.learning_rate == 0.3
+
+ def test_decay_per_day_default(self):
+ """Test default decay per day."""
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = NoSettingsContextError("No settings")
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"
+ ):
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ tracker = AdaptiveRateLimitTracker(programmatic_mode=True)
+
+ assert tracker.decay_per_day == 0.95