~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: add 246 high-value tests across 13 modules targeting untested code paths (#2225)
LearningCircuit4a33c077dcbf
diff --git a/src/local_deep_research/notifications/queue_helpers.py b/src/local_deep_research/notifications/queue_helpers.pyindex 57e7e12bdb..b83e66af2f 100644--- a/src/local_deep_research/notifications/queue_helpers.py+++ b/src/local_deep_research/notifications/queue_helpers.py@@ -133,7 +133,7 @@ def send_queue_failed_notification_from_session(db_session: Database session to fetch settings from"""try:- from ...settings import SettingsManager+ from ..settings import SettingsManager# Get settings snapshot from database sessionsettings_manager = SettingsManager(db_session)@@ -189,8 +189,8 @@ def send_research_completed_notification_from_session()# Import here to avoid circular dependencies- from ...database.models import ResearchHistory- from ...settings import SettingsManager+ from ..database.models import ResearchHistory+ from ..settings import SettingsManagerfrom .manager import NotificationManagerfrom .url_builder import build_notification_url@@ -229,7 +229,7 @@ def send_research_completed_notification_from_session(}# Get report content for notification- from ...storage import get_report_storage+ from ..storage import get_report_storagestorage = get_report_storage(session=db_session)report_content = storage.get_report(research_id)@@ -324,8 +324,8 @@ def send_research_failed_notification_from_session()# Import here to avoid circular dependencies- from ...database.models import ResearchHistory- from ...settings import SettingsManager+ from ..database.models import ResearchHistory+ from ..settings import SettingsManagerfrom .manager import NotificationManager# Get research details for notificationdiff --git a/tests/api/test_settings_utils_typed_value.py b/tests/api/test_settings_utils_typed_value.pynew file mode 100644index 0000000000..6514a81684--- /dev/null+++ b/tests/api/test_settings_utils_typed_value.py@@ -0,0 +1,161 @@+"""Tests for InMemorySettingsManager._get_typed_value.++This method dispatches value type conversion based on ui_element type.+Critical for ensuring settings are stored with correct types. Edge+cases around type conversion failures are untested.+"""++import pytest++from local_deep_research.api.settings_utils import InMemorySettingsManager+++def manager():+ """Create an InMemorySettingsManager instance."""+ return InMemorySettingsManager()+++class TestGetTypedValueText:+ """Text type conversion — string passthrough."""++ def test_string_passthrough(self, manager):+ result = manager._get_typed_value({"ui_element": "text"}, "hello")+ assert result == "hello"++ def test_int_converted_to_string(self, manager):+ result = manager._get_typed_value({"ui_element": "text"}, 42)+ assert result == "42"+++class TestGetTypedValueCheckbox:+ """Checkbox type conversion — uses parse_boolean."""++ def test_true_string(self, manager):+ result = manager._get_typed_value({"ui_element": "checkbox"}, "true")+ assert result is True++ def test_false_string(self, manager):+ result = manager._get_typed_value({"ui_element": "checkbox"}, "false")+ assert result is False++ def test_bool_passthrough(self, manager):+ result = manager._get_typed_value({"ui_element": "checkbox"}, True)+ assert result is True++ def test_zero_is_false(self, manager):+ result = manager._get_typed_value({"ui_element": "checkbox"}, 0)+ assert result is False+++class TestGetTypedValueNumber:+ """Number type conversion — uses _parse_number."""++ def test_integer_string(self, manager):+ result = manager._get_typed_value({"ui_element": "number"}, "42")+ assert result == 42+ assert isinstance(result, int)++ def test_float_string(self, manager):+ result = manager._get_typed_value({"ui_element": "number"}, "3.14")+ assert result == 3.14+ assert isinstance(result, float)++ def test_int_passthrough(self, manager):+ result = manager._get_typed_value({"ui_element": "number"}, 42)+ assert result == 42++ def test_float_whole_number_becomes_int(self, manager):+ result = manager._get_typed_value({"ui_element": "number"}, "5.0")+ assert result == 5+ assert isinstance(result, int)+++class TestGetTypedValueRange:+ """Range type (slider) — same behavior as number."""++ def test_range_like_number(self, manager):+ result = manager._get_typed_value({"ui_element": "range"}, "0.7")+ assert result == 0.7+++class TestGetTypedValueSelect:+ """Select type — string passthrough."""++ def test_string_passthrough(self, manager):+ result = manager._get_typed_value({"ui_element": "select"}, "option_a")+ assert result == "option_a"+++class TestGetTypedValueMultiselect:+ """Multiselect type — uses _parse_multiselect."""++ def test_list_passthrough(self, manager):+ result = manager._get_typed_value(+ {"ui_element": "multiselect"}, ["a", "b"]+ )+ assert result == ["a", "b"]++ def test_json_string_parsed(self, manager):+ result = manager._get_typed_value(+ {"ui_element": "multiselect"}, '["x","y"]'+ )+ assert result == ["x", "y"]++ def test_comma_separated_parsed(self, manager):+ result = manager._get_typed_value(+ {"ui_element": "multiselect"}, "a,b,c"+ )+ assert result == ["a", "b", "c"]+++class TestGetTypedValueJSON:+ """JSON type — value passed through as-is."""++ def test_dict_passthrough(self, manager):+ val = {"key": "value"}+ result = manager._get_typed_value({"ui_element": "json"}, val)+ assert result == val++ def test_list_passthrough(self, manager):+ val = [1, 2, 3]+ result = manager._get_typed_value({"ui_element": "json"}, val)+ assert result == val+++class TestGetTypedValuePassword:+ """Password type — string passthrough."""++ def test_password_string(self, manager):+ result = manager._get_typed_value(+ {"ui_element": "password"}, "secret123"+ )+ assert result == "secret123"+++class TestGetTypedValueUnknownType:+ """Unknown ui_element types — value returned as-is."""++ def test_unknown_type_returns_value(self, manager):+ result = manager._get_typed_value(+ {"ui_element": "custom_widget"}, "val"+ )+ assert result == "val"++ def test_missing_ui_element_defaults_to_text(self, manager):+ result = manager._get_typed_value({}, "val")+ assert result == "val"+++class TestGetTypedValueConversionFailure:+ """Type conversion failures — value returned as-is."""++ def test_non_numeric_for_number(self, manager):+ result = manager._get_typed_value(+ {"ui_element": "number"}, "not_a_number"+ )+ assert result == "not_a_number"++ def test_none_for_number(self, manager):+ result = manager._get_typed_value({"ui_element": "number"}, None)+ assert result is Nonediff --git a/tests/benchmarks/test_graders_edge_cases.py b/tests/benchmarks/test_graders_edge_cases.pynew file mode 100644index 0000000000..b9a91f6103--- /dev/null+++ b/tests/benchmarks/test_graders_edge_cases.py@@ -0,0 +1,112 @@+"""Additional edge case tests for benchmarks/graders.py.++Focuses on extract_answer_from_response edge cases and citation+stripping that are not covered by the existing test suite.+"""++from local_deep_research.benchmarks.graders import extract_answer_from_response+++class TestCitationStripping:+ """Tests for citation removal from responses."""++ def test_adjacent_citations_all_removed(self):+ result = extract_answer_from_response(+ "Answer[1][2][3] here.", "simpleqa"+ )+ assert "[1]" not in result["extracted_answer"]+ assert "[2]" not in result["extracted_answer"]+ assert "[3]" not in result["extracted_answer"]++ def test_high_numbered_citation_removed(self):+ result = extract_answer_from_response(+ "Fact [99] and [100].", "simpleqa"+ )+ assert "[99]" not in result["extracted_answer"]+ assert "[100]" not in result["extracted_answer"]++ def test_non_numeric_brackets_preserved(self):+ result = extract_answer_from_response(+ "Use [option A] for best results.", "simpleqa"+ )+ assert "[option A]" in result["extracted_answer"]++ def test_citations_removed_before_browsecomp_extraction(self):+ response = "Exact Answer: The result [1] is Paris [2]\nConfidence: 90%"+ result = extract_answer_from_response(response, "browsecomp")+ assert "[1]" not in result["extracted_answer"]+ assert "[2]" not in result["extracted_answer"]+ assert "Paris" in result["extracted_answer"]+++class TestBrowseCompEdgeCases:+ """Edge cases for BrowseComp extraction."""++ def test_exact_answer_with_colon_in_value(self):+ response = "Exact Answer: Time: 12:30 PM\nConfidence: 85%"+ result = extract_answer_from_response(response, "browsecomp")+ assert "12:30" in result["extracted_answer"]++ def test_exact_answer_with_numbers(self):+ response = "Exact Answer: 3.14159\nConfidence: 100%"+ result = extract_answer_from_response(response, "browsecomp")+ assert result["extracted_answer"] == "3.14159"++ def test_confidence_with_leading_zeros(self):+ response = "Exact Answer: test\nConfidence: 05%"+ result = extract_answer_from_response(response, "browsecomp")+ assert result["confidence"] == "05"++ def test_exact_answer_whitespace_stripped(self):+ response = "Exact Answer: Paris \nConfidence: 80%"+ result = extract_answer_from_response(response, "browsecomp")+ assert result["extracted_answer"] == "Paris"++ def test_multiple_exact_answer_lines_first_wins(self):+ response = "Exact Answer: First\nExact Answer: Second\nConfidence: 70%"+ result = extract_answer_from_response(response, "browsecomp")+ assert result["extracted_answer"] == "First"++ def test_answer_with_parentheses(self):+ response = "Exact Answer: Albert Einstein (1879-1955)\nConfidence: 95%"+ result = extract_answer_from_response(response, "browsecomp")+ assert "Albert Einstein" in result["extracted_answer"]+ assert "(1879-1955)" in result["extracted_answer"]++ def test_answer_with_comma(self):+ response = "Exact Answer: New York, United States\nConfidence: 90%"+ result = extract_answer_from_response(response, "browsecomp")+ assert "New York, United States" == result["extracted_answer"]++ def test_empty_exact_answer_captures_next_line(self):+ # When answer is empty, greedy \s* in regex consumes the newline,+ # so (.*?) ends up matching the next line content.+ response = "Exact Answer: \nConfidence: 50%"+ result = extract_answer_from_response(response, "browsecomp")+ # This is the actual regex behavior — not ideal but matches implementation+ assert result["extracted_answer"] == "Confidence: 50%"++ def test_only_newline_after_answer(self):+ response = "Exact Answer: Tokyo"+ result = extract_answer_from_response(response, "browsecomp")+ assert result["extracted_answer"] == "Tokyo"+++class TestSimpleQAEdgeCases:+ """Edge cases for SimpleQA extraction."""++ def test_multiline_response_preserved(self):+ response = "Line 1\nLine 2\nLine 3"+ result = extract_answer_from_response(response, "simpleqa")+ assert "Line 1" in result["extracted_answer"]+ assert "Line 3" in result["extracted_answer"]++ def test_unicode_response_preserved(self):+ response = "La réponse est: café"+ result = extract_answer_from_response(response, "simpleqa")+ assert "café" in result["extracted_answer"]++ def test_response_with_only_citations(self):+ result = extract_answer_from_response("[1][2][3]", "simpleqa")+ # All citations removed, should be empty-ish+ assert "[" not in result["extracted_answer"]diff --git a/tests/exporters/test_odt_sanitize_metadata.py b/tests/exporters/test_odt_sanitize_metadata.pynew file mode 100644index 0000000000..65b00b4947--- /dev/null+++ b/tests/exporters/test_odt_sanitize_metadata.py@@ -0,0 +1,79 @@+"""Tests for ODTExporter._sanitize_metadata.++This is a security-critical function that prevents Pandoc argument injection+via user-supplied metadata values. Zero prior direct test coverage.+"""++import pytest++from local_deep_research.exporters.odt_exporter import ODTExporter+++def exporter():+ """Create an ODTExporter instance."""+ return ODTExporter()+++class TestSanitizeMetadataInjectionPrevention:+ """Tests for _sanitize_metadata argument injection prevention."""++ def test_normal_text_unchanged(self, exporter):+ assert (+ exporter._sanitize_metadata("My Research Report")+ == "My Research Report"+ )++ def test_double_dash_removed(self, exporter):+ assert (+ exporter._sanitize_metadata("--output=evil.sh") == "output=evil.sh"+ )++ def test_newlines_replaced_with_spaces(self, exporter):+ assert exporter._sanitize_metadata("line1\nline2") == "line1 line2"++ def test_multiple_double_dashes(self, exporter):+ result = exporter._sanitize_metadata("--flag1 --flag2 --flag3")+ assert "--" not in result++ def test_empty_string(self, exporter):+ assert exporter._sanitize_metadata("") == ""++ def test_only_dashes(self, exporter):+ assert exporter._sanitize_metadata("----") == ""++ def test_single_dash_preserved(self, exporter):+ assert exporter._sanitize_metadata("well-known") == "well-known"++ def test_unicode_preserved(self, exporter):+ assert exporter._sanitize_metadata("Ünïcödé Títlé") == "Ünïcödé Títlé"++ def test_triple_dash_removes_double_part(self, exporter):+ result = exporter._sanitize_metadata("---metadata")+ assert "--" not in result++ def test_mixed_injection_patterns(self, exporter):+ result = exporter._sanitize_metadata(+ "Title\n--variable=x\n--output=/tmp/evil"+ )+ assert "\n" not in result+ assert "--" not in result++ def test_embedded_single_dashes_preserved(self, exporter):+ assert (+ exporter._sanitize_metadata("state-of-the-art")+ == "state-of-the-art"+ )++ def test_tab_characters_preserved(self, exporter):+ result = exporter._sanitize_metadata("col1\tcol2")+ assert "\t" in result++ def test_extract_media_injection(self, exporter):+ result = exporter._sanitize_metadata("--extract-media=/tmp")+ assert "--" not in result++ def test_multiple_newlines(self, exporter):+ result = exporter._sanitize_metadata("a\nb\nc\nd")+ assert "\n" not in result+ assert "a b c d" == resultdiff --git a/tests/notifications/test_queue_helpers_extended.py b/tests/notifications/test_queue_helpers_extended.pynew file mode 100644index 0000000000..a9cfb4b014--- /dev/null+++ b/tests/notifications/test_queue_helpers_extended.py@@ -0,0 +1,537 @@+"""+Extended tests for notifications/queue_helpers.py — _from_session functions.++The existing test_queue_helpers.py only verifies "function exists" and+"handles None db_session" for the _from_session functions. These tests+exercise the actual DB-lookup + notification-sending logic (~300 lines).++NOTE: This commit also fixes a bug where the _from_session functions used+3-dot relative imports (from ...settings) instead of 2-dot (from ..settings),+causing all _from_session notifications to silently fail.++Tests cover:+- send_queue_failed_notification_from_session: settings retrieval, success/failure logging+- send_research_completed_notification_from_session: research lookup, report truncation, URL building+- send_research_failed_notification_from_session: error sanitization, research lookup+"""++from unittest.mock import Mock, MagicMock, patch+++HELPERS = "local_deep_research.notifications.queue_helpers"++# Patch targets for lazy imports inside _from_session functions.+# These must be patched at their SOURCE module since the functions use+# 'from ..X import Y' which resolves to the source, not the caller module.+SETTINGS_MGR = "local_deep_research.settings.SettingsManager"+NOTIF_MGR = "local_deep_research.notifications.manager.NotificationManager"+URL_BUILDER = (+ "local_deep_research.notifications.url_builder.build_notification_url"+)+REPORT_STORAGE = "local_deep_research.storage.get_report_storage"+++# ---------------------------------------------------------------------------+# send_queue_failed_notification_from_session+# ---------------------------------------------------------------------------+++class TestSendQueueFailedNotificationFromSession:+ """Tests for send_queue_failed_notification_from_session."""++ @patch(f"{HELPERS}.send_queue_failed_notification")+ def test_success_path_sends_notification(self, mock_send):+ """Success path: creates settings snapshot, calls send."""+ from local_deep_research.notifications.queue_helpers import (+ send_queue_failed_notification_from_session,+ )++ mock_send.return_value = True++ mock_db = MagicMock()+ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {"snap": True}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_queue_failed_notification_from_session(+ username="alice",+ research_id="r-001",+ query="test query",+ error_message="Timeout",+ db_session=mock_db,+ )++ mock_send.assert_called_once_with(+ username="alice",+ research_id="r-001",+ query="test query",+ error_message="Timeout",+ settings_snapshot={"snap": True},+ )++ @patch(f"{HELPERS}.send_queue_failed_notification")+ def test_send_returns_false_logs_warning(self, mock_send):+ """When send returns False, logs warning (doesn't raise)."""+ from local_deep_research.notifications.queue_helpers import (+ send_queue_failed_notification_from_session,+ )++ mock_send.return_value = False++ mock_db = MagicMock()+ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ # Should not raise+ send_queue_failed_notification_from_session(+ username="alice",+ research_id="r-002",+ query="q",+ error_message="err",+ db_session=mock_db,+ )++ def test_settings_manager_raises_caught_silently(self):+ """SettingsManager exception is caught silently."""+ from local_deep_research.notifications.queue_helpers import (+ send_queue_failed_notification_from_session,+ )++ mock_db = MagicMock()++ with patch(SETTINGS_MGR, side_effect=RuntimeError("bad session")):+ # Should not raise+ send_queue_failed_notification_from_session(+ username="alice",+ research_id="r-003",+ query="q",+ error_message="err",+ db_session=mock_db,+ )++ @patch(f"{HELPERS}.send_queue_failed_notification")+ def test_send_returns_true_logs_info(self, mock_send):+ """When send returns True, logs info (success path)."""+ from local_deep_research.notifications.queue_helpers import (+ send_queue_failed_notification_from_session,+ )++ mock_send.return_value = True+ mock_db = MagicMock()+ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_queue_failed_notification_from_session(+ username="alice",+ research_id="r-004",+ query="q",+ error_message="err",+ db_session=mock_db,+ )++ mock_send.assert_called_once()+++# ---------------------------------------------------------------------------+# send_research_completed_notification_from_session+# ---------------------------------------------------------------------------+++class TestSendResearchCompletedNotificationFromSession:+ """Tests for send_research_completed_notification_from_session."""++ @patch(REPORT_STORAGE)+ @patch(URL_BUILDER)+ @patch(NOTIF_MGR)+ def test_research_found_builds_context_with_query_and_url(+ self, mock_nm_class, mock_build_url, mock_get_storage+ ):+ """When research is found, context includes query, URL, summary."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_completed_notification_from_session,+ )+ from local_deep_research.notifications.templates import EventType++ mock_db = MagicMock()+ mock_research = Mock()+ mock_research.query = "How does AI work?"+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ mock_build_url.return_value = "https://app.test/research/r-100"++ mock_storage = Mock()+ mock_storage.get_report.return_value = "Short report"+ mock_get_storage.return_value = mock_storage++ mock_nm = Mock()+ mock_nm.send_notification.return_value = True+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_research_completed_notification_from_session(+ username="alice",+ research_id="r-100",+ db_session=mock_db,+ )++ call_kwargs = mock_nm.send_notification.call_args.kwargs+ assert call_kwargs["event_type"] == EventType.RESEARCH_COMPLETED+ ctx = call_kwargs["context"]+ assert ctx["query"] == "How does AI work?"+ assert ctx["url"] == "https://app.test/research/r-100"+ assert ctx["summary"] == "Short report"++ @patch(REPORT_STORAGE)+ @patch(URL_BUILDER)+ @patch(NOTIF_MGR)+ def test_report_over_200_chars_truncated(+ self, mock_nm_class, mock_build_url, mock_get_storage+ ):+ """Report content >200 chars is truncated with '...'."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_completed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_research = Mock()+ mock_research.query = "query"+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )+ mock_build_url.return_value = "https://app.test/r"++ long_report = "A" * 300+ mock_storage = Mock()+ mock_storage.get_report.return_value = long_report+ mock_get_storage.return_value = mock_storage++ mock_nm = Mock()+ mock_nm.send_notification.return_value = True+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_research_completed_notification_from_session(+ username="alice", research_id="r-101", db_session=mock_db+ )++ ctx = mock_nm.send_notification.call_args.kwargs["context"]+ assert ctx["summary"] == "A" * 200 + "..."+ assert len(ctx["summary"]) == 203++ @patch(REPORT_STORAGE)+ @patch(URL_BUILDER)+ @patch(NOTIF_MGR)+ def test_report_exactly_200_chars_not_truncated(+ self, mock_nm_class, mock_build_url, mock_get_storage+ ):+ """Report content <=200 chars is used as-is."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_completed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_research = Mock()+ mock_research.query = "query"+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )+ mock_build_url.return_value = "https://app.test/r"++ report_200 = "B" * 200+ mock_storage = Mock()+ mock_storage.get_report.return_value = report_200+ mock_get_storage.return_value = mock_storage++ mock_nm = Mock()+ mock_nm.send_notification.return_value = True+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_research_completed_notification_from_session(+ username="alice", research_id="r-102", db_session=mock_db+ )++ ctx = mock_nm.send_notification.call_args.kwargs["context"]+ assert ctx["summary"] == "B" * 200++ @patch(REPORT_STORAGE)+ @patch(URL_BUILDER)+ @patch(NOTIF_MGR)+ def test_report_none_uses_default_summary(+ self, mock_nm_class, mock_build_url, mock_get_storage+ ):+ """Report is None -> summary is 'No summary available'."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_completed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_research = Mock()+ mock_research.query = "query"+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )+ mock_build_url.return_value = "https://app.test/r"++ mock_storage = Mock()+ mock_storage.get_report.return_value = None+ mock_get_storage.return_value = mock_storage++ mock_nm = Mock()+ mock_nm.send_notification.return_value = True+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_research_completed_notification_from_session(+ username="alice", research_id="r-103", db_session=mock_db+ )++ ctx = mock_nm.send_notification.call_args.kwargs["context"]+ assert ctx["summary"] == "No summary available"++ @patch(NOTIF_MGR)+ def test_research_not_found_sends_minimal_context(self, mock_nm_class):+ """Research not found -> sends notification with minimal context."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_completed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ mock_nm = Mock()+ mock_nm.send_notification.return_value = True+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_research_completed_notification_from_session(+ username="alice", research_id="r-999", db_session=mock_db+ )++ ctx = mock_nm.send_notification.call_args.kwargs["context"]+ assert ctx["query"] == "Research r-999"+ assert ctx["summary"] == "Research completed but details unavailable"++ def test_exception_caught_silently(self):+ """Top-level exception is caught silently."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_completed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_db.query.side_effect = RuntimeError("DB gone")++ # Should not raise+ send_research_completed_notification_from_session(+ username="alice", research_id="r-998", db_session=mock_db+ )++ @patch(REPORT_STORAGE)+ @patch(URL_BUILDER)+ @patch(NOTIF_MGR)+ def test_send_returns_false_does_not_raise(+ self, mock_nm_class, mock_build_url, mock_get_storage+ ):+ """send_notification returning False doesn't raise."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_completed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_research = Mock()+ mock_research.query = "query"+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )+ mock_build_url.return_value = "https://app.test/r"+ mock_storage = Mock()+ mock_storage.get_report.return_value = "report"+ mock_get_storage.return_value = mock_storage++ mock_nm = Mock()+ mock_nm.send_notification.return_value = False+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ # Should not raise+ send_research_completed_notification_from_session(+ username="alice", research_id="r-104", db_session=mock_db+ )+++# ---------------------------------------------------------------------------+# send_research_failed_notification_from_session+# ---------------------------------------------------------------------------+++class TestSendResearchFailedNotificationFromSession:+ """Tests for send_research_failed_notification_from_session."""++ @patch(NOTIF_MGR)+ def test_sanitizes_error_message(self, mock_nm_class):+ """Error message is sanitized to generic 'Check logs' message."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_failed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_research = Mock()+ mock_research.query = "test"+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ mock_nm = Mock()+ mock_nm.send_notification.return_value = True+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_research_failed_notification_from_session(+ username="alice",+ research_id="r-200",+ error_message="SECRET: API key abc123 leaked",+ db_session=mock_db,+ )++ ctx = mock_nm.send_notification.call_args.kwargs["context"]+ assert ctx["error"] == "Research failed. Check logs for details."++ @patch(NOTIF_MGR)+ def test_original_error_not_in_notification(self, mock_nm_class):+ """Original error_message is NOT passed to notification context."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_failed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_research = Mock()+ mock_research.query = "test"+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ mock_nm = Mock()+ mock_nm.send_notification.return_value = True+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_research_failed_notification_from_session(+ username="alice",+ research_id="r-201",+ error_message="password=hunter2 connection refused",+ db_session=mock_db,+ )++ ctx = mock_nm.send_notification.call_args.kwargs["context"]+ assert "hunter2" not in str(ctx)+ assert "password" not in str(ctx)++ @patch(NOTIF_MGR)+ def test_research_not_found_sends_minimal(self, mock_nm_class):+ """Research not found -> sends minimal context."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_failed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ mock_nm = Mock()+ mock_nm.send_notification.return_value = True+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_research_failed_notification_from_session(+ username="alice",+ research_id="r-999",+ error_message="not found",+ db_session=mock_db,+ )++ ctx = mock_nm.send_notification.call_args.kwargs["context"]+ assert ctx["query"] == "Research r-999"+ assert ctx["error"] == "Research failed. Check logs for details."++ def test_exception_caught_silently(self):+ """Top-level exception is caught silently."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_failed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_db.query.side_effect = RuntimeError("DB gone")++ # Should not raise+ send_research_failed_notification_from_session(+ username="alice",+ research_id="r-998",+ error_message="error",+ db_session=mock_db,+ )++ @patch(NOTIF_MGR)+ def test_research_found_uses_query_from_db(self, mock_nm_class):+ """When research is found, uses research.query from DB."""+ from local_deep_research.notifications.queue_helpers import (+ send_research_failed_notification_from_session,+ )++ mock_db = MagicMock()+ mock_research = Mock()+ mock_research.query = "What is quantum computing?"+ mock_db.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ mock_nm = Mock()+ mock_nm.send_notification.return_value = True+ mock_nm_class.return_value = mock_nm++ mock_settings = Mock()+ mock_settings.get_settings_snapshot.return_value = {}++ with patch(SETTINGS_MGR, return_value=mock_settings):+ send_research_failed_notification_from_session(+ username="alice",+ research_id="r-202",+ error_message="timeout",+ db_session=mock_db,+ )++ ctx = mock_nm.send_notification.call_args.kwargs["context"]+ assert ctx["query"] == "What is quantum computing?"diff --git a/tests/rate_limiting/test_llm_detection_extended.py b/tests/rate_limiting/test_llm_detection_extended.pynew file mode 100644index 0000000000..acf1963812--- /dev/null+++ b/tests/rate_limiting/test_llm_detection_extended.py@@ -0,0 +1,175 @@+"""+Extended tests for rate_limiting/llm/detection.py — provider-specific detection.++The existing test_llm_rate_limiting.py covers basic patterns but misses:+- OpenAI-specific module check (line 52)+- Anthropic-specific module check (line 58)+- extract_retry_after edge cases (date headers, decimals, multiple patterns)++Tests cover:+- OpenAI provider-specific detection (module == "openai")+- Anthropic provider-specific detection ("anthropic" in module)+- extract_retry_after edge cases+"""++from unittest.mock import Mock+++def _make_exception(class_name, module, message):+ """Create an exception instance with a custom __class__.__module__ and __name__.++ Python builtins don't support __class__ reassignment, so we create a new+ exception type with the desired module and instantiate directly.+ """+ cls = type(class_name, (Exception,), {"__module__": module})+ return cls(message)+++# ---------------------------------------------------------------------------+# OpenAI-specific detection+# ---------------------------------------------------------------------------+++class TestOpenAISpecificDetection:+ """Tests for OpenAI provider-specific rate limit detection."""++ def test_openai_module_ratelimiterror_429_detected(self):+ """OpenAI module + ratelimiterror type + '429' -> True."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ is_llm_rate_limit_error,+ )++ error = _make_exception("RateLimitError", "openai", "Error code: 429")+ assert is_llm_rate_limit_error(error) is True++ def test_openai_module_non_429_not_detected(self):+ """OpenAI module but non-rate-limit error -> not detected."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ is_llm_rate_limit_error,+ )++ error = _make_exception(+ "AuthenticationError", "openai", "Invalid API key"+ )+ assert is_llm_rate_limit_error(error) is False++ def test_openai_apierror_with_429_detected(self):+ """OpenAI ApiError with '429' in message -> True."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ is_llm_rate_limit_error,+ )++ error = _make_exception(+ "ApiError", "openai", "Request failed with status 429"+ )+ assert is_llm_rate_limit_error(error) is True+++# ---------------------------------------------------------------------------+# Anthropic-specific detection+# ---------------------------------------------------------------------------+++class TestAnthropicSpecificDetection:+ """Tests for Anthropic provider-specific rate limit detection."""++ def test_anthropic_module_rate_limit_detected(self):+ """'anthropic' in module + 'rate_limit' in message -> True."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ is_llm_rate_limit_error,+ )++ error = _make_exception(+ "RateLimitError",+ "anthropic._exceptions",+ "rate_limit_error: too many requests",+ )+ assert is_llm_rate_limit_error(error) is True++ def test_anthropic_module_429_detected(self):+ """'anthropic' in module + '429' in message -> True."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ is_llm_rate_limit_error,+ )++ error = _make_exception(+ "ApiStatusError",+ "anthropic._exceptions",+ "HTTP 429 from Anthropic API",+ )+ assert is_llm_rate_limit_error(error) is True++ def test_anthropic_module_unrelated_error_not_detected(self):+ """'anthropic' in module + unrelated message -> False."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ is_llm_rate_limit_error,+ )++ error = _make_exception(+ "AuthenticationError",+ "anthropic._exceptions",+ "Invalid API key provided",+ )+ assert is_llm_rate_limit_error(error) is False+++# ---------------------------------------------------------------------------+# extract_retry_after edge cases+# ---------------------------------------------------------------------------+++class TestExtractRetryAfterEdgeCases:+ """Edge cases for extract_retry_after."""++ def test_non_numeric_retry_after_header(self):+ """Non-numeric Retry-After header (date string) is handled gracefully."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ extract_retry_after,+ )++ error = Mock()+ error.response = Mock()+ error.response.headers = {+ "Retry-After": "Wed, 21 Oct 2015 07:28:00 GMT"+ }+ error.__str__ = lambda self: "Rate limited"++ # Date string can't be parsed as float, falls through to message parsing+ result = extract_retry_after(error)+ assert isinstance(result, (int, float))++ def test_decimal_seconds_in_message(self):+ """'retry after 30.5 seconds' with decimal -> 30.5."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ extract_retry_after,+ )++ error = Exception("Please retry after 30.5 seconds")++ result = extract_retry_after(error)+ assert result == 30.5++ def test_multiple_patterns_returns_first_match(self):+ """Multiple patterns in same message -> first match returned."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ extract_retry_after,+ )++ # "try again in X seconds" pattern comes before "wait X seconds"+ error = Exception(+ "Rate limited. Try again in 15 seconds. Or wait 30 seconds."+ )++ result = extract_retry_after(error)+ assert result == 15.0++ def test_no_patterns_returns_zero(self):+ """No matching patterns -> returns 0."""+ from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ extract_retry_after,+ )++ error = Exception("Something went wrong with no timing info")++ result = extract_retry_after(error)+ assert result == 0diff --git a/tests/rate_limiting/test_llm_wrapper_extended.py b/tests/rate_limiting/test_llm_wrapper_extended.pynew file mode 100644index 0000000000..8364ea4ce9--- /dev/null+++ b/tests/rate_limiting/test_llm_wrapper_extended.py@@ -0,0 +1,356 @@+"""+Extended tests for rate_limiting/llm/wrapper.py — active rate limiting paths.++The existing test_llm_rate_limiting.py only covers disabled rate limiting.+Two tests are skipped with "Rate limiting is disabled by default".+These tests exercise the actual rate-limiting code paths.++Tests cover:+- AdaptiveLLMWait.__call__: tracker wait, retry-after merging, error recording+- RateLimitedLLMWrapper._check_if_local_model: provider + URL detection+- RateLimitedLLMWrapper._do_invoke: error wrapping+- RateLimitedLLMWrapper.invoke with rate limiting active+- __str__ and __repr__+"""++from unittest.mock import Mock++import pytest+++WRAPPER_MODULE = (+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper"+)+++# ---------------------------------------------------------------------------+# AdaptiveLLMWait.__call__+# ---------------------------------------------------------------------------+++class TestAdaptiveLLMWait:+ """Tests for AdaptiveLLMWait wait strategy."""++ def test_returns_tracker_wait_time_no_error(self):+ """Returns tracker wait time when no error."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ AdaptiveLLMWait,+ )++ mock_tracker = Mock()+ mock_tracker.get_wait_time.return_value = 5.0++ wait = AdaptiveLLMWait(mock_tracker, "openai-api")++ # Simulate retry_state with no failure+ retry_state = Mock()+ retry_state.outcome = None++ result = wait(retry_state)++ assert result == 5.0+ mock_tracker.get_wait_time.assert_called_once_with("openai-api")++ def test_returns_max_of_tracker_and_retry_after(self):+ """Returns max(tracker_wait, retry_after) when error has retry-after."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ AdaptiveLLMWait,+ )++ mock_tracker = Mock()+ mock_tracker.get_wait_time.return_value = 2.0++ wait = AdaptiveLLMWait(mock_tracker, "openai-api")++ # First call: record an error with retry-after+ error = Mock()+ error.response = Mock()+ error.response.headers = {"Retry-After": "10"}+ error.__str__ = lambda self: "rate limit"++ retry_state = Mock()+ retry_state.outcome = Mock()+ retry_state.outcome.failed = True+ retry_state.outcome.exception.return_value = error++ result = wait(retry_state)++ # Should be max(2.0, 10.0) = 10.0+ assert result == 10.0++ def test_records_last_error_from_failed_outcome(self):+ """Records last_error from failed outcome."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ AdaptiveLLMWait,+ )++ mock_tracker = Mock()+ mock_tracker.get_wait_time.return_value = 1.0++ wait = AdaptiveLLMWait(mock_tracker, "test")++ error = Exception("rate limit hit")++ retry_state = Mock()+ retry_state.outcome = Mock()+ retry_state.outcome.failed = True+ retry_state.outcome.exception.return_value = error++ wait(retry_state)++ assert wait.last_error is error++ def test_uses_last_error_across_calls(self):+ """last_error persists and is used in subsequent calls."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ AdaptiveLLMWait,+ )++ mock_tracker = Mock()+ mock_tracker.get_wait_time.return_value = 1.0++ wait = AdaptiveLLMWait(mock_tracker, "test")++ # First call: record error with retry-after in message+ error = Exception("retry after 30 seconds")+ retry_state = Mock()+ retry_state.outcome = Mock()+ retry_state.outcome.failed = True+ retry_state.outcome.exception.return_value = error+ result1 = wait(retry_state)+ assert result1 == 30.0++ # Second call: no new error, but last_error still has retry-after+ retry_state2 = Mock()+ retry_state2.outcome = None+ result2 = wait(retry_state2)+ assert result2 == 30.0+++# ---------------------------------------------------------------------------+# RateLimitedLLMWrapper._check_if_local_model+# ---------------------------------------------------------------------------+++class TestCheckIfLocalModel:+ """Tests for _check_if_local_model."""++ def test_true_for_local_providers(self):+ """Returns True for known local provider names."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ for provider in [+ "ollama",+ "lmstudio",+ "llamacpp",+ "vllm",+ "local",+ "none",+ ]:+ base_llm = Mock()+ wrapper = create_rate_limited_llm_wrapper(+ base_llm, provider=provider+ )+ assert wrapper._check_if_local_model() is True, (+ f"Failed for {provider}"+ )++ def test_true_for_localhost_base_url(self):+ """Returns True when base_url contains localhost."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ base_llm.base_url = "http://localhost:11434/v1"+ wrapper = create_rate_limited_llm_wrapper(base_llm, provider="custom")+ assert wrapper._check_if_local_model() is True++ def test_true_for_127_0_0_1_base_url(self):+ """Returns True when base_url contains 127.0.0.1."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ base_llm.base_url = "http://127.0.0.1:8080/api"+ wrapper = create_rate_limited_llm_wrapper(base_llm, provider="custom")+ assert wrapper._check_if_local_model() is True++ def test_false_for_remote_urls(self):+ """Returns False for remote URLs and providers."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ base_llm.base_url = "https://api.openai.com/v1"+ wrapper = create_rate_limited_llm_wrapper(base_llm, provider="openai")+ assert wrapper._check_if_local_model() is False+++# ---------------------------------------------------------------------------+# RateLimitedLLMWrapper._do_invoke+# ---------------------------------------------------------------------------+++class TestDoInvoke:+ """Tests for _do_invoke."""++ def test_rate_limit_error_wrapped_into_rate_limit_error(self):+ """Rate limit errors are wrapped into RateLimitError."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )+ from local_deep_research.web_search_engines.rate_limiting.exceptions import (+ RateLimitError,+ )++ base_llm = Mock()+ base_llm.invoke.side_effect = Exception(+ "429 Too Many Requests rate limit"+ )+ wrapper = create_rate_limited_llm_wrapper(base_llm)++ with pytest.raises(RateLimitError, match="LLM rate limit"):+ wrapper._do_invoke("test prompt")++ def test_non_rate_limit_error_passed_through(self):+ """Non-rate-limit errors pass through unchanged."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ base_llm.invoke.side_effect = ValueError("Invalid input format")+ wrapper = create_rate_limited_llm_wrapper(base_llm)++ with pytest.raises(ValueError, match="Invalid input format"):+ wrapper._do_invoke("test prompt")++ def test_successful_invoke_returns_result(self):+ """Successful invoke returns result."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ base_llm.invoke.return_value = "LLM response"+ wrapper = create_rate_limited_llm_wrapper(base_llm)++ result = wrapper._do_invoke("test prompt")+ assert result == "LLM response"+++# ---------------------------------------------------------------------------+# RateLimitedLLMWrapper.invoke with rate limiting active+# ---------------------------------------------------------------------------+++class TestInvokeWithRateLimiting:+ """Tests for invoke() with rate limiting enabled."""++ def test_successful_first_attempt_records_success(self):+ """Successful first attempt records success in tracker."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ base_llm.invoke.return_value = "response"++ mock_tracker = Mock()+ mock_tracker.get_wait_time.return_value = 0++ wrapper = create_rate_limited_llm_wrapper(base_llm, provider="openai")++ # Force-enable rate limiting+ wrapper.rate_limiter = mock_tracker++ result = wrapper.invoke("prompt")++ assert result == "response"+ mock_tracker.record_outcome.assert_called_once_with(+ engine_type=wrapper._get_rate_limit_key(),+ wait_time=0,+ success=True,+ retry_count=0,+ )++ def test_invoke_without_rate_limiter_delegates_directly(self):+ """Without rate limiter, invoke delegates to _do_invoke."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ base_llm.invoke.return_value = "direct response"++ wrapper = create_rate_limited_llm_wrapper(base_llm)+ assert wrapper.rate_limiter is None++ result = wrapper.invoke("prompt")+ assert result == "direct response"+ base_llm.invoke.assert_called_once_with("prompt")++ def test_rate_limit_error_records_failure(self):+ """Rate limit error is recorded as failure in tracker."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ base_llm.invoke.side_effect = Exception("429 rate limit exceeded")++ mock_tracker = Mock()+ mock_tracker.get_wait_time.return_value = 0++ wrapper = create_rate_limited_llm_wrapper(base_llm, provider="openai")+ wrapper.rate_limiter = mock_tracker++ # tenacity wraps the final error in RetryError after exhausting retries+ with pytest.raises(Exception):+ wrapper.invoke("prompt")++ # Should have recorded a failure+ failure_calls = [+ c+ for c in mock_tracker.record_outcome.call_args_list+ if c.kwargs.get("success") is False+ ]+ assert len(failure_calls) >= 1+++# ---------------------------------------------------------------------------+# __str__ and __repr__+# ---------------------------------------------------------------------------+++class TestStringRepresentations:+ """Tests for __str__ and __repr__."""++ def test_str_format(self):+ """__str__ returns expected format."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ base_llm.__str__ = lambda self: "MockLLM"+ wrapper = create_rate_limited_llm_wrapper(base_llm)++ assert str(wrapper) == "RateLimited(MockLLM)"++ def test_repr_format(self):+ """__repr__ returns expected format."""+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ base_llm = Mock()+ wrapper = create_rate_limited_llm_wrapper(base_llm)++ result = repr(wrapper)+ assert result.startswith("RateLimitedLLMWrapper(")diff --git a/tests/report/test_report_generator_helpers.py b/tests/report/test_report_generator_helpers.pynew file mode 100644index 0000000000..fae1ccdca3--- /dev/null+++ b/tests/report/test_report_generator_helpers.py@@ -0,0 +1,175 @@+"""Tests for ReportGenerator helper methods.++Covers _truncate_at_sentence_boundary and _build_previous_context — two+pure-logic helpers with zero prior test coverage that are critical for+report quality and repetition avoidance.+"""++from unittest.mock import MagicMock++import pytest++from local_deep_research.report_generator import IntegratedReportGenerator+++def generator():+ """Create an IntegratedReportGenerator with mocked dependencies."""+ mock_llm = MagicMock()+ mock_search = MagicMock()+ gen = IntegratedReportGenerator.__new__(IntegratedReportGenerator)+ gen.llm = mock_llm+ gen.search_system = mock_search+ gen.max_context_sections = 3+ gen.max_context_chars = 4000+ return gen+++# ── _truncate_at_sentence_boundary ──+++class TestTruncateAtSentenceBoundary:+ """Tests for _truncate_at_sentence_boundary."""++ def test_text_shorter_than_limit_returned_unchanged(self, generator):+ text = "Short text."+ assert generator._truncate_at_sentence_boundary(text, 100) == text++ def test_text_exactly_at_limit_returned_unchanged(self, generator):+ text = "Exact." + "x" * 94 # 100 chars+ assert generator._truncate_at_sentence_boundary(text, 100) == text++ def test_truncates_at_period_followed_by_space(self, generator):+ text = "First sentence. Second sentence. Third sentence that goes on."+ result = generator._truncate_at_sentence_boundary(text, 35)+ assert result.startswith("First sentence. Second sentence.")+ assert result.endswith("\n[...truncated]")++ def test_truncates_at_exclamation_mark(self, generator):+ text = "Wow! This is amazing! More content follows here."+ result = generator._truncate_at_sentence_boundary(text, 25)+ assert "Wow! This is amazing!" in result+ assert "[...truncated]" in result++ def test_truncates_at_question_mark(self, generator):+ text = "Is this working? Yes it is working perfectly fine here."+ result = generator._truncate_at_sentence_boundary(text, 20)+ assert "Is this working?" in result+ assert "[...truncated]" in result++ def test_boundary_at_end_of_truncated_text(self, generator):+ # Period at exactly the last position of truncated text+ text = "Hello." + "x" * 100+ result = generator._truncate_at_sentence_boundary(text, 6)+ # "Hello." is 6 chars, truncated[:6] = "Hello."+ # last_sentence_end = 6, min_acceptable = int(6*0.8)=4, 6 > 4 → use boundary+ assert "Hello." in result+ assert "[...truncated]" in result++ def test_no_sentence_boundary_falls_back_to_hard_truncation(+ self, generator+ ):+ text = "a" * 200+ result = generator._truncate_at_sentence_boundary(text, 100)+ assert result == "a" * 100 + "\n[...truncated]"++ def test_sentence_boundary_too_early_falls_back(self, generator):+ # Period at position 5 out of 100 → below 80% threshold+ text = "Hi. " + "x" * 200+ result = generator._truncate_at_sentence_boundary(text, 100)+ # min_acceptable = 80, last_sentence_end = 4, 4 < 80 → hard truncation+ assert result == text[:100] + "\n[...truncated]"++ def test_sentence_boundary_at_80_percent_threshold(self, generator):+ # Exactly at 80% boundary+ # max_chars=100, min_acceptable=80+ text = "x" * 80 + ". " + "y" * 50+ result = generator._truncate_at_sentence_boundary(text, 100)+ # last_sentence_end=81, min_acceptable=80, 81 > 80 → use boundary+ assert result.endswith("\n[...truncated]")+ assert result.startswith("x" * 80 + ".")++ def test_period_followed_by_newline(self, generator):+ text = "First sentence.\nSecond sentence continues for a while here."+ result = generator._truncate_at_sentence_boundary(text, 20)+ assert "First sentence." in result+ assert "[...truncated]" in result++ def test_period_not_followed_by_space_or_newline_ignored(self, generator):+ # "3.14" has a period but it's followed by a digit, not space+ text = "The value is 3.14 and more text follows after that point."+ result = generator._truncate_at_sentence_boundary(text, 20)+ # Only sentence boundaries followed by space/newline are valid+ # In "The value is 3.14 a", the period at index 14 is followed by '1', not space+ # So falls back to hard truncation+ assert result == text[:20] + "\n[...truncated]"++ def test_empty_text(self, generator):+ assert generator._truncate_at_sentence_boundary("", 100) == ""++ def test_single_character(self, generator):+ assert generator._truncate_at_sentence_boundary("a", 100) == "a"++ def test_multiple_sentence_endings_uses_last_valid(self, generator):+ text = "One. Two. Three. Four. Five. Six. Seven. Eight."+ result = generator._truncate_at_sentence_boundary(text, 30)+ # Should find the last boundary within the first 30 chars+ # "One. Two. Three. Four. Five. " is 29 chars+ assert "[...truncated]" in result+++# ── _build_previous_context ──+++class TestBuildPreviousContext:+ """Tests for _build_previous_context."""++ def test_empty_list_returns_empty_string(self, generator):+ assert generator._build_previous_context([]) == ""++ def test_single_finding_included(self, generator):+ result = generator._build_previous_context(["Finding 1"])+ assert "Finding 1" in result+ assert "DO NOT REPEAT" in result+ assert "CONTENT ALREADY WRITTEN" in result++ def test_respects_max_context_sections_limit(self, generator):+ generator.max_context_sections = 2+ findings = ["Finding 1", "Finding 2", "Finding 3", "Finding 4"]+ result = generator._build_previous_context(findings)+ # Should only include last 2 findings+ assert "Finding 3" in result+ assert "Finding 4" in result+ assert "Finding 1" not in result+ assert "Finding 2" not in result++ def test_joins_with_separator(self, generator):+ result = generator._build_previous_context(["A", "B"])+ assert "\n\n---\n\n" in result++ def test_truncates_long_context(self, generator):+ generator.max_context_chars = 50+ long_finding = "x" * 100+ result = generator._build_previous_context([long_finding])+ # The content should be truncated+ assert "[...truncated]" in result++ def test_formatting_markers_present(self, generator):+ result = generator._build_previous_context(["Test content"])+ assert "=== CONTENT ALREADY WRITTEN (DO NOT REPEAT) ===" in result+ assert "=== END OF PREVIOUS CONTENT ===" in result+ assert "CRITICAL:" in result++ def test_context_within_char_limit_not_truncated(self, generator):+ generator.max_context_chars = 10000+ result = generator._build_previous_context(["Short finding."])+ assert "[...truncated]" not in result++ def test_uses_last_n_sections(self, generator):+ generator.max_context_sections = 3+ findings = [f"Finding {i}" for i in range(10)]+ result = generator._build_previous_context(findings)+ assert "Finding 7" in result+ assert "Finding 8" in result+ assert "Finding 9" in result+ assert "Finding 0" not in resultdiff --git a/tests/routes/test_is_blocked_setting.py b/tests/routes/test_is_blocked_setting.pynew file mode 100644index 0000000000..2ce2675ccf--- /dev/null+++ b/tests/routes/test_is_blocked_setting.py@@ -0,0 +1,102 @@+"""Tests for is_blocked_setting — security check for dangerous settings.++This function prevents users from modifying settings that could enable+dynamic code imports/execution. Zero prior test coverage.+"""++from local_deep_research.web.routes.settings_routes import is_blocked_setting+++class TestIsBlockedSettingModulePaths:+ """Settings with 'module' in the key should be blocked."""++ def test_module_path_blocked(self):+ assert is_blocked_setting("search.custom_engine.module_path") is True++ def test_custom_module_blocked(self):+ assert is_blocked_setting("search.custom_module") is True++ def test_module_loader_blocked(self):+ assert is_blocked_setting("search.module_loader") is True++ def test_module_standalone_blocked(self):+ assert is_blocked_setting("module") is True+++class TestIsBlockedSettingClassPaths:+ """Settings with 'class' in the key should be blocked."""++ def test_class_name_blocked(self):+ assert is_blocked_setting("search.engine.class_name") is True++ def test_handler_class_blocked(self):+ assert is_blocked_setting("handler_class") is True++ def test_class_loader_blocked(self):+ assert is_blocked_setting("class_loader") is True++ def test_class_standalone_blocked(self):+ assert is_blocked_setting("class") is True+++class TestIsBlockedSettingCaseInsensitive:+ """Blocking should be case-insensitive."""++ def test_uppercase_module(self):+ assert is_blocked_setting("SEARCH.MODULE_PATH") is True++ def test_mixed_case_class(self):+ assert is_blocked_setting("Handler_Class") is True++ def test_uppercase_class(self):+ assert is_blocked_setting("CLASS_NAME") is True++ def test_mixed_case_module(self):+ assert is_blocked_setting("Custom_Module") is True+++class TestIsBlockedSettingAllowedKeys:+ """Normal settings should NOT be blocked."""++ def test_temperature_allowed(self):+ assert is_blocked_setting("llm.temperature") is False++ def test_model_name_allowed(self):+ assert is_blocked_setting("llm.model_name") is False++ def test_search_engine_allowed(self):+ assert is_blocked_setting("search.engine") is False++ def test_report_format_allowed(self):+ assert is_blocked_setting("report.format") is False++ def test_app_theme_allowed(self):+ assert is_blocked_setting("app.theme") is False++ def test_max_results_allowed(self):+ assert is_blocked_setting("search.max_results") is False++ def test_output_language_allowed(self):+ assert is_blocked_setting("general.output_language") is False++ def test_empty_key_allowed(self):+ assert is_blocked_setting("") is False+++class TestIsBlockedSettingEdgeCases:+ """Edge cases for the blocking logic."""++ def test_module_as_substring_blocked(self):+ # "module" appears as substring — should still block+ assert is_blocked_setting("my_module_path") is True++ def test_class_as_substring_blocked(self):+ assert is_blocked_setting("subclass_handler") is True++ def test_nested_key_with_module(self):+ assert is_blocked_setting("a.b.c.module.d") is True++ def test_path_pattern_blocked(self):+ # Check all patterns in BLOCKED_SETTING_PATTERNS+ assert is_blocked_setting("search.module_path") is True+ assert is_blocked_setting("search.class_name") is Truediff --git a/tests/settings/test_settings_parsing.py b/tests/settings/test_settings_parsing.pynew file mode 100644index 0000000000..7b4f1c1eac--- /dev/null+++ b/tests/settings/test_settings_parsing.py@@ -0,0 +1,223 @@+"""Tests for SettingsManager._create_setting metadata inference.++_create_setting infers category, ui_element, and other metadata from key+patterns and value types during bulk import operations.+"""++from unittest.mock import MagicMock++import pytest+++class TestCreateSettingCategoryInference:+ """Tests for _create_setting category determination from key prefix."""++ @pytest.fixture+ def mock_manager(self):+ """Create a mock SettingsManager with _create_setting accessible."""+ from enum import Enum++ class MockSettingType(Enum):+ DATABASE = "database"++ from local_deep_research.settings.manager import SettingsManager++ manager = MagicMock()+ manager._create_setting = SettingsManager._create_setting.__get__(+ manager, type(manager)+ )+ return manager, MockSettingType.DATABASE++ def test_app_prefix_category(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.theme", "dark", st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["category"]+ == "app_interface"+ )++ def test_llm_temperature_gets_parameters_category(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("llm.temperature", 0.7, st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["category"]+ == "llm_parameters"+ )++ def test_llm_max_tokens_gets_parameters_category(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("llm.max_tokens", 4096, st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["category"]+ == "llm_parameters"+ )++ def test_llm_general_setting(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("llm.provider", "openai", st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["category"]+ == "llm_general"+ )++ def test_search_iterations_gets_parameters(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("search.iterations", 3, st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["category"]+ == "search_parameters"+ )++ def test_search_questions_gets_parameters(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("search.questions", 5, st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["category"]+ == "search_parameters"+ )++ def test_search_general_setting(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("search.engine", "ddg", st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["category"]+ == "search_general"+ )++ def test_report_prefix_category(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("report.format", "pdf", st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["category"]+ == "report_parameters"+ )++ def test_unknown_prefix_gets_none(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("custom.setting", "val", st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["category"] is None+ )+++class TestCreateSettingUIElementInference:+ """Tests for _create_setting UI element inference from value types."""++ @pytest.fixture+ def mock_manager(self):+ from enum import Enum++ class MockSettingType(Enum):+ DATABASE = "database"++ from local_deep_research.settings.manager import SettingsManager++ manager = MagicMock()+ manager._create_setting = SettingsManager._create_setting.__get__(+ manager, type(manager)+ )+ return manager, MockSettingType.DATABASE++ def test_bool_value_checkbox(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.enabled", True, st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["ui_element"]+ == "checkbox"+ )++ def test_int_value_number(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.count", 42, st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["ui_element"]+ == "number"+ )++ def test_float_value_number(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.ratio", 0.5, st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["ui_element"]+ == "number"+ )++ def test_dict_value_textarea(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.config", {"k": "v"}, st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["ui_element"]+ == "textarea"+ )++ def test_list_value_textarea(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.items", [1, 2], st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["ui_element"]+ == "textarea"+ )++ def test_string_value_text(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.name", "hello", st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["ui_element"]+ == "text"+ )+++class TestCreateSettingNameDerivation:+ """Tests for setting name and description generation."""++ @pytest.fixture+ def mock_manager(self):+ from enum import Enum++ class MockSettingType(Enum):+ DATABASE = "database"++ from local_deep_research.settings.manager import SettingsManager++ manager = MagicMock()+ manager._create_setting = SettingsManager._create_setting.__get__(+ manager, type(manager)+ )+ return manager, MockSettingType.DATABASE++ def test_name_from_last_segment(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("llm.model_name", "gpt-4", st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["name"]+ == "Model Name"+ )++ def test_description_includes_key(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.theme", "dark", st)+ assert (+ "app.theme"+ in manager.create_or_update_setting.call_args[0][0]["description"]+ )++ def test_key_stored_correctly(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("search.engine", "ddg", st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["key"]+ == "search.engine"+ )++ def test_value_stored_correctly(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.flag", True, st)+ assert manager.create_or_update_setting.call_args[0][0]["value"] is True++ def test_type_stored_as_lowercase(self, mock_manager):+ manager, st = mock_manager+ manager._create_setting("app.x", "v", st)+ assert (+ manager.create_or_update_setting.call_args[0][0]["type"]+ == "database"+ )diff --git a/tests/text_processing/test_text_cleaner_extended.py b/tests/text_processing/test_text_cleaner_extended.pynew file mode 100644index 0000000000..0be1b3bbbc--- /dev/null+++ b/tests/text_processing/test_text_cleaner_extended.py@@ -0,0 +1,124 @@+"""Extended tests for text_cleaner.remove_surrogates.++Adds edge cases for surrogate pair handling, emoji preservation, and+encoding scenarios not covered by the existing test_text_cleaner.py.+"""++from local_deep_research.text_processing.text_cleaner import remove_surrogates+++class TestRemoveSurrogatesEmojiAndSymbols:+ """Emoji and special symbol preservation."""++ def test_common_emoji_preserved(self):+ text = "Hello 🌍 World 🚀"+ assert remove_surrogates(text) == text++ def test_math_symbols_preserved(self):+ text = "∑ ∫ ∏ √ ∞ ≈"+ assert remove_surrogates(text) == text++ def test_currency_symbols_preserved(self):+ text = "Price: €100 ¥200 £50"+ assert remove_surrogates(text) == text++ def test_box_drawing_preserved(self):+ text = "┌──┐\n│ │\n└──┘"+ assert remove_surrogates(text) == text+++class TestRemoveSurrogatesMixedScripts:+ """Mixed script handling."""++ def test_cjk_characters_preserved(self):+ text = "日本語テスト Chinese中文 Korean한국어"+ assert remove_surrogates(text) == text++ def test_arabic_preserved(self):+ text = "مرحبا بالعالم"+ assert remove_surrogates(text) == text++ def test_cyrillic_preserved(self):+ text = "Привет мир"+ assert remove_surrogates(text) == text++ def test_devanagari_preserved(self):+ text = "नमस्ते दुनिया"+ assert remove_surrogates(text) == text+++class TestRemoveSurrogatesSurrogatePairs:+ """Surrogate pair specific tests."""++ def test_lone_high_surrogate_handled(self):+ text = "before\ud800after"+ result = remove_surrogates(text)+ assert "before" in result+ assert "after" in result+ result.encode("utf-8") # Must not raise++ def test_lone_low_surrogate_handled(self):+ text = "text\udfffend"+ result = remove_surrogates(text)+ assert "text" in result+ assert "end" in result+ result.encode("utf-8")++ def test_consecutive_high_surrogates(self):+ text = "\ud800\ud801\ud802"+ result = remove_surrogates(text)+ result.encode("utf-8")++ def test_surrogate_at_start(self):+ text = "\ud800hello"+ result = remove_surrogates(text)+ assert "hello" in result+ result.encode("utf-8")++ def test_surrogate_at_end(self):+ text = "hello\ud800"+ result = remove_surrogates(text)+ assert "hello" in result+ result.encode("utf-8")++ def test_only_surrogates(self):+ text = "\ud800\udc00\ud801"+ result = remove_surrogates(text)+ result.encode("utf-8") # Must not raise+++class TestRemoveSurrogatesLargeInput:+ """Performance and large input tests."""++ def test_large_clean_text(self):+ text = "x" * 100000+ result = remove_surrogates(text)+ assert len(result) == 100000++ def test_large_text_with_scattered_surrogates(self):+ parts = []+ for i in range(100):+ parts.append("normal text " * 10)+ parts.append("\ud800")+ text = "".join(parts)+ result = remove_surrogates(text)+ result.encode("utf-8")+ assert "normal text" in result+++class TestRemoveSurrogatesSpecialCases:+ """Special and boundary cases."""++ def test_null_byte_handled(self):+ text = "before\x00after"+ result = remove_surrogates(text)+ assert "before" in result+ assert "after" in result++ def test_replacement_char_preserved(self):+ text = "test\ufffdtext"+ assert remove_surrogates(text) == text++ def test_bom_preserved(self):+ text = "\ufeffHello"+ assert remove_surrogates(text) == textdiff --git a/tests/utilities/test_search_cache_eviction.py b/tests/utilities/test_search_cache_eviction.pynew file mode 100644index 0000000000..53a86bfd7a--- /dev/null+++ b/tests/utilities/test_search_cache_eviction.py@@ -0,0 +1,172 @@+"""Tests for SearchCache._normalize_query and _evict_lru_memory.++_normalize_query handles query normalization for consistent caching.+_evict_lru_memory manages memory cache size via LRU eviction.+Both have zero prior test coverage.+"""++import pytest++from local_deep_research.utilities.search_cache import SearchCache+++def cache(tmp_path):+ """Create a SearchCache with a temp database."""+ return SearchCache(+ cache_dir=str(tmp_path / "search_cache"),+ default_ttl=3600,+ max_memory_items=5,+ )+++# ── _normalize_query ──+++class TestNormalizeQuery:+ """Tests for _normalize_query method."""++ def test_converts_to_lowercase(self, cache):+ assert cache._normalize_query("Hello World") == "hello world"++ def test_strips_whitespace(self, cache):+ assert cache._normalize_query(" hello ") == "hello"++ def test_collapses_internal_whitespace(self, cache):+ assert (+ cache._normalize_query("hello world test") == "hello world test"+ )++ def test_removes_double_quotes(self, cache):+ assert cache._normalize_query('"hello world"') == "hello world"++ def test_removes_single_quotes(self, cache):+ assert cache._normalize_query("it's a test") == "its a test"++ def test_preserves_other_punctuation(self, cache):+ assert cache._normalize_query("hello, world!") == "hello, world!"++ def test_empty_string(self, cache):+ assert cache._normalize_query("") == ""++ def test_tabs_and_newlines_collapsed(self, cache):+ assert (+ cache._normalize_query("hello\tworld\ntest") == "hello world test"+ )++ def test_unicode_preserved(self, cache):+ result = cache._normalize_query("Héllo Wörld")+ assert result == "héllo wörld"++ def test_mixed_quotes_all_removed(self, cache):+ result = cache._normalize_query("\"it's\" a 'test'")+ assert '"' not in result+ assert "'" not in result+++# ── _evict_lru_memory ──+++class TestEvictLruMemory:+ """Tests for _evict_lru_memory method."""++ def test_no_eviction_when_under_limit(self, cache):+ cache._memory_cache = {"a": 1, "b": 2}+ cache._access_times = {"a": 100, "b": 200}+ cache.max_memory_items = 5++ cache._evict_lru_memory()++ assert len(cache._memory_cache) == 2++ def test_eviction_when_over_limit(self, cache):+ cache.max_memory_items = 3+ # Add 5 items+ for i in range(5):+ key = f"key_{i}"+ cache._memory_cache[key] = {"data": i}+ cache._access_times[key] = i * 100 # Older items have lower times++ cache._evict_lru_memory()++ # Should have evicted to get below limit+ assert len(cache._memory_cache) <= cache.max_memory_items++ def test_evicts_oldest_items_first(self, cache):+ # _evict_lru_memory removes (count - max + 100) items for efficiency.+ # With max=200 and count=250: removes 250-200+100=150 oldest items.+ cache.max_memory_items = 200+ for i in range(250):+ cache._memory_cache[f"key_{i}"] = {"data": i}+ cache._access_times[f"key_{i}"] = i++ cache._evict_lru_memory()++ remaining = set(cache._memory_cache.keys())+ # 100 items should survive (250 - 150 removed)+ assert len(remaining) == 100+ # Remaining items should be the newest (highest access times)+ for key in remaining:+ idx = int(key.split("_")[1])+ assert idx >= 150 # Only items 150-249 should survive++ def test_eviction_removes_from_both_caches(self, cache):+ cache.max_memory_items = 1+ cache._memory_cache = {"a": 1, "b": 2, "c": 3}+ cache._access_times = {"a": 100, "b": 200, "c": 300}++ cache._evict_lru_memory()++ # Evicted items should be removed from both dicts+ for key in list(cache._memory_cache.keys()):+ assert key in cache._access_times++ def test_no_eviction_at_exact_limit(self, cache):+ cache.max_memory_items = 3+ cache._memory_cache = {"a": 1, "b": 2, "c": 3}+ cache._access_times = {"a": 100, "b": 200, "c": 300}++ cache._evict_lru_memory()++ assert len(cache._memory_cache) == 3++ def test_empty_cache_no_error(self, cache):+ cache._memory_cache = {}+ cache._access_times = {}+ cache.max_memory_items = 5++ cache._evict_lru_memory() # Should not raise++ assert len(cache._memory_cache) == 0+++# ── _get_query_hash ──+++class TestGetQueryHash:+ """Tests for _get_query_hash determinism and partitioning."""++ def test_same_query_same_hash(self, cache):+ h1 = cache._get_query_hash("hello world")+ h2 = cache._get_query_hash("hello world")+ assert h1 == h2++ def test_case_insensitive_hashing(self, cache):+ h1 = cache._get_query_hash("Hello World")+ h2 = cache._get_query_hash("hello world")+ assert h1 == h2++ def test_different_engines_different_hashes(self, cache):+ h1 = cache._get_query_hash("test", "google")+ h2 = cache._get_query_hash("test", "bing")+ assert h1 != h2++ def test_whitespace_normalized_before_hashing(self, cache):+ h1 = cache._get_query_hash("hello world")+ h2 = cache._get_query_hash("hello world")+ assert h1 == h2++ def test_quotes_stripped_before_hashing(self, cache):+ h1 = cache._get_query_hash('"hello world"')+ h2 = cache._get_query_hash("hello world")+ assert h1 == h2diff --git a/tests/utilities/test_search_utilities_formatting.py b/tests/utilities/test_search_utilities_formatting.pynew file mode 100644index 0000000000..b6119213ad--- /dev/null+++ b/tests/utilities/test_search_utilities_formatting.py@@ -0,0 +1,289 @@+"""+Tests for search_utilities.py — format_links_to_markdown and format_findings+edge cases not covered by the existing test_search_utilities.py and+test_search_utilities_extended.py files.++Tests cover:+- format_links_to_markdown: None/empty URL handling, special characters, index+ aggregation for 'link' key fallback+- format_findings: iteration numbering, question_by_iteration edge cases,+ findings with search results that have errors, malformed finding structures+"""+++# ---------------------------------------------------------------------------+# format_links_to_markdown — additional edge cases+# ---------------------------------------------------------------------------+++class TestFormatLinksToMarkdownNoneUrls:+ """Tests for format_links_to_markdown with None/empty URLs."""++ def test_none_url_skipped(self):+ """Links with None url are skipped."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {"title": "Valid", "url": "https://valid.com", "index": "1"},+ {"title": "None URL", "url": None, "index": "2"},+ ]++ result = format_links_to_markdown(links)++ assert "https://valid.com" in result+ assert "None URL" not in result++ def test_empty_string_url_skipped(self):+ """Links with empty string url are skipped."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {"title": "Empty URL", "url": "", "index": "1"},+ {"title": "Good", "url": "https://good.com", "index": "2"},+ ]++ result = format_links_to_markdown(links)++ assert "https://good.com" in result+ assert "Empty URL" not in result++ def test_no_url_or_link_key_skipped(self):+ """Links with neither 'url' nor 'link' key are skipped."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {"title": "No URL key", "index": "1"},+ ]++ result = format_links_to_markdown(links)++ assert "No URL key" not in result+++class TestFormatLinksToMarkdownSpecialChars:+ """Tests for format_links_to_markdown with special characters."""++ def test_url_with_query_params(self):+ """URLs with query parameters are preserved."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {+ "title": "Search",+ "url": "https://example.com/search?q=hello+world&lang=en",+ "index": "1",+ }+ ]++ result = format_links_to_markdown(links)+ assert "https://example.com/search?q=hello+world&lang=en" in result++ def test_url_with_fragment(self):+ """URLs with fragments are preserved."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {+ "title": "Section",+ "url": "https://example.com/page#section-2",+ "index": "1",+ }+ ]++ result = format_links_to_markdown(links)+ assert "https://example.com/page#section-2" in result++ def test_title_with_special_markdown_chars(self):+ """Titles with markdown-special chars are included."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {+ "title": "Results [2024] — *Important*",+ "url": "https://example.com",+ "index": "1",+ }+ ]++ result = format_links_to_markdown(links)+ assert "Results [2024]" in result+++class TestFormatLinksToMarkdownIndexAggregation:+ """Tests for index aggregation in format_links_to_markdown."""++ def test_link_key_fallback_aggregates_indices(self):+ """'link' key fallback still aggregates indices for same URL."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {"title": "Same", "link": "https://same.com", "index": "1"},+ {"title": "Same", "link": "https://same.com", "index": "4"},+ ]++ result = format_links_to_markdown(links)+ assert result.count("https://same.com") == 1+ assert "1" in result+ assert "4" in result++ def test_mixed_url_and_link_keys(self):+ """Handles mix of 'url' and 'link' keys for same actual URL."""+ from local_deep_research.utilities.search_utilities import (+ format_links_to_markdown,+ )++ links = [+ {"title": "First", "url": "https://a.com", "index": "1"},+ {"title": "Second", "link": "https://b.com", "index": "2"},+ ]++ result = format_links_to_markdown(links)+ assert "https://a.com" in result+ assert "https://b.com" in result+++# ---------------------------------------------------------------------------+# format_findings — additional edge cases+# ---------------------------------------------------------------------------+++class TestFormatFindingsIterationNumbering:+ """Tests for iteration numbering in format_findings."""++ def test_single_iteration_with_questions(self):+ """Single iteration with questions formatted correctly."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ questions = {1: ["Q1", "Q2", "Q3"]}++ result = format_findings([], "Summary content", questions)++ assert "Iteration 1" in result+ assert "1. Q1" in result+ assert "2. Q2" in result+ assert "3. Q3" in result++ def test_non_sequential_iteration_numbers(self):+ """Non-sequential iteration numbers (e.g., 1, 3, 5) handled correctly."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ questions = {+ 1: ["First iter Q"],+ 3: ["Third iter Q"],+ 5: ["Fifth iter Q"],+ }++ result = format_findings([], "Summary", questions)++ assert "Iteration 1" in result+ assert "Iteration 3" in result+ assert "Iteration 5" in result+ assert "Iteration 2" not in result++ def test_zero_iteration_key(self):+ """Iteration 0 (used by IterDRAG) is formatted."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ questions = {0: ["Sub-query A", "Sub-query B"]}++ result = format_findings([], "Summary", questions)++ assert "Iteration 0" in result+ assert "Sub-query A" in result+++class TestFormatFindingsMalformedStructures:+ """Tests for malformed finding structures."""++ def test_finding_missing_content_key(self):+ """Finding without 'content' key uses default."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [{"phase": "Phase 1", "search_results": []}]++ result = format_findings(findings, "Summary", {})++ assert "No content available" in result++ def test_finding_missing_phase_key(self):+ """Finding without 'phase' key uses default."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [{"content": "Some content", "search_results": []}]++ result = format_findings(findings, "Summary", {})++ assert "Unknown Phase" in result+ assert "Some content" in result++ def test_finding_with_only_question_field(self):+ """Finding with only 'question' field displays it."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [+ {+ "phase": "Custom",+ "content": "Answer text",+ "question": "How does X work?",+ "search_results": [],+ }+ ]++ result = format_findings(findings, "Summary", {})++ assert "How does X work?" in result+ assert "SEARCH QUESTION" in result++ def test_empty_questions_dict_shows_warning_section(self):+ """Empty questions dict (no iterations) omits section."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings([], "Summary", {})++ assert "SEARCH QUESTIONS BY ITERATION" not in result++ def test_findings_with_search_results_error(self):+ """Findings with non-list search_results handled gracefully."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [+ {+ "phase": "Search",+ "content": "Content",+ "search_results": None, # None instead of list+ }+ ]++ # Should not crash+ result = format_findings(findings, "Summary", {})+ assert "Content" in resultdiff --git a/tests/web/queue/test_processor_v2_real.py b/tests/web/queue/test_processor_v2_real.pynew file mode 100644index 0000000000..6e4552246e--- /dev/null+++ b/tests/web/queue/test_processor_v2_real.py@@ -0,0 +1,805 @@+"""+Tests for QueueProcessorV2 — real integration tests for core queue orchestration.++These tests exercise the actual class methods with proper mocking of external+dependencies (database, password store, research service), unlike the fake tests+in test_processor_v2_core/operations/research.py that only test Python primitives.++Tests cover:+- notify_research_queued: direct vs queue mode branching+- notify_research_completed: status updates + notifications+- notify_research_failed: error message defaulting, sanitization+- _process_queue_loop: user:session parsing, removal logic+- _process_user_queue: slot calculation, empty queue, no password+- _start_research: new vs legacy settings format+- process_pending_operations_for_user: progress/error updates, rollback+"""++import time+import threading+from unittest.mock import Mock, MagicMock, patch++import pytest+++MODULE = "local_deep_research.web.queue.processor_v2"+SETTINGS_MGR = "local_deep_research.settings.manager.SettingsManager"+++def _make_processor():+ """Create a QueueProcessorV2 instance without triggering module-level side effects."""+ from local_deep_research.web.queue.processor_v2 import QueueProcessorV2++ return QueueProcessorV2(check_interval=1)+++# ---------------------------------------------------------------------------+# notify_research_queued — direct vs queue mode branching+# ---------------------------------------------------------------------------+++class TestNotifyResearchQueuedDirectMode:+ """Tests for notify_research_queued when queue_mode='direct'."""++ @patch(f"{MODULE}.get_user_db_session")+ @patch(f"{MODULE}.db_manager")+ @patch(f"{MODULE}.session_password_store")+ def test_direct_mode_slots_available_starts_directly(+ self, mock_pw_store, mock_db_mgr, mock_get_session+ ):+ """direct mode + slots available -> calls _start_research_directly."""+ processor = _make_processor()++ mock_pw_store.get_session_password.return_value = "pw"+ mock_db_mgr.open_user_database.return_value = Mock()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ # SettingsManager says direct mode, max 3 concurrent+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda key, default: {+ "app.queue_mode": "direct",+ "app.max_concurrent_researches": 3,+ }.get(key, default)++ # 0 active researches -> has slots+ mock_session.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(SETTINGS_MGR, return_value=mock_settings):+ with patch.object(+ processor, "_start_research_directly"+ ) as mock_start:+ processor.notify_research_queued(+ "alice",+ "r-001",+ session_id="sess1",+ query="test query",+ )+ mock_start.assert_called_once()++ @patch(f"{MODULE}.get_user_db_session")+ @patch(f"{MODULE}.db_manager")+ @patch(f"{MODULE}.session_password_store")+ def test_direct_mode_slots_full_falls_back_to_queue(+ self, mock_pw_store, mock_db_mgr, mock_get_session+ ):+ """direct mode + slots full -> queues instead."""+ processor = _make_processor()++ mock_pw_store.get_session_password.return_value = "pw"+ mock_db_mgr.open_user_database.return_value = Mock()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda key, default: {+ "app.queue_mode": "direct",+ "app.max_concurrent_researches": 2,+ }.get(key, default)++ # 2 active = full at max 2+ mock_session.query.return_value.filter_by.return_value.count.return_value = 2++ with patch(SETTINGS_MGR, return_value=mock_settings):+ with patch(f"{MODULE}.UserQueueService") as mock_qs_class:+ mock_qs = Mock()+ mock_qs_class.return_value = mock_qs++ processor.notify_research_queued(+ "alice",+ "r-002",+ session_id="sess1",+ query="test",+ )+ mock_qs.add_task_metadata.assert_called_once()++ @patch(f"{MODULE}.get_user_db_session")+ @patch(f"{MODULE}.db_manager")+ @patch(f"{MODULE}.session_password_store")+ def test_queue_mode_always_queues(+ self, mock_pw_store, mock_db_mgr, mock_get_session+ ):+ """queue_mode='queue' -> always queues regardless of slots."""+ processor = _make_processor()++ mock_pw_store.get_session_password.return_value = "pw"+ mock_db_mgr.open_user_database.return_value = Mock()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda key, default: {+ "app.queue_mode": "queue",+ "app.max_concurrent_researches": 3,+ }.get(key, default)++ with patch(SETTINGS_MGR, return_value=mock_settings):+ with patch(f"{MODULE}.UserQueueService") as mock_qs_class:+ mock_qs = Mock()+ mock_qs_class.return_value = mock_qs++ with patch.object(+ processor, "_start_research_directly"+ ) as mock_start:+ processor.notify_research_queued(+ "alice",+ "r-003",+ session_id="sess1",+ query="test",+ )+ mock_start.assert_not_called()+ mock_qs.add_task_metadata.assert_called_once()++ @patch(f"{MODULE}.get_user_db_session")+ def test_missing_session_id_falls_back_to_queue(self, mock_get_session):+ """No session_id kwarg -> falls back to queue mode."""+ processor = _make_processor()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ with patch(f"{MODULE}.UserQueueService") as mock_qs_class:+ mock_qs = Mock()+ mock_qs_class.return_value = mock_qs++ # No session_id in kwargs+ processor.notify_research_queued("alice", "r-004", query="test")+ mock_qs.add_task_metadata.assert_called_once()++ @patch(f"{MODULE}.get_user_db_session")+ @patch(f"{MODULE}.session_password_store")+ def test_missing_password_falls_back_to_queue(+ self, mock_pw_store, mock_get_session+ ):+ """No password for session -> falls back to queue mode."""+ processor = _make_processor()++ mock_pw_store.get_session_password.return_value = None++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ with patch(f"{MODULE}.UserQueueService") as mock_qs_class:+ mock_qs = Mock()+ mock_qs_class.return_value = mock_qs++ processor.notify_research_queued(+ "alice", "r-005", session_id="sess1", query="test"+ )+ mock_qs.add_task_metadata.assert_called_once()++ @patch(f"{MODULE}.get_user_db_session")+ @patch(f"{MODULE}.db_manager")+ @patch(f"{MODULE}.session_password_store")+ def test_exception_in_direct_falls_back_to_queue(+ self, mock_pw_store, mock_db_mgr, mock_get_session+ ):+ """Exception during direct execution -> falls back to queue."""+ processor = _make_processor()++ mock_pw_store.get_session_password.return_value = "pw"+ mock_db_mgr.open_user_database.side_effect = RuntimeError("DB error")++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ with patch(f"{MODULE}.UserQueueService") as mock_qs_class:+ mock_qs = Mock()+ mock_qs_class.return_value = mock_qs++ processor.notify_research_queued(+ "alice", "r-006", session_id="sess1", query="test"+ )+ mock_qs.add_task_metadata.assert_called_once()++ @patch(f"{MODULE}.get_user_db_session")+ def test_no_kwargs_queues_directly(self, mock_get_session):+ """No kwargs at all -> goes straight to queue fallback."""+ processor = _make_processor()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ with patch(f"{MODULE}.UserQueueService") as mock_qs_class:+ mock_qs = Mock()+ mock_qs_class.return_value = mock_qs++ processor.notify_research_queued("alice", "r-007")+ mock_qs.add_task_metadata.assert_called_once()+++# ---------------------------------------------------------------------------+# notify_research_completed — updates status + sends notification+# ---------------------------------------------------------------------------+++class TestNotifyResearchCompleted:+ """Tests for notify_research_completed."""++ @patch(f"{MODULE}.send_research_completed_notification_from_session")+ @patch(f"{MODULE}.get_user_db_session")+ def test_updates_status_and_sends_notification(+ self, mock_get_session, mock_send_notif+ ):+ """Updates queue status to COMPLETED and sends notification."""+ processor = _make_processor()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ with patch(f"{MODULE}.UserQueueService") as mock_qs_class:+ mock_qs = Mock()+ mock_qs_class.return_value = mock_qs++ processor.notify_research_completed(+ "alice", "r-010", user_password="pw"+ )++ mock_qs.update_task_status.assert_called_once()+ mock_send_notif.assert_called_once_with(+ username="alice",+ research_id="r-010",+ db_session=mock_session,+ )++ @patch(f"{MODULE}.get_user_db_session")+ def test_exception_does_not_propagate(self, mock_get_session):+ """Exception in status update is caught silently."""+ processor = _make_processor()++ mock_get_session.side_effect = RuntimeError("DB unavailable")++ # Should not raise+ processor.notify_research_completed("alice", "r-011")++ @patch(f"{MODULE}.send_research_completed_notification_from_session")+ @patch(f"{MODULE}.get_user_db_session")+ def test_passes_password_to_session(+ self, mock_get_session, mock_send_notif+ ):+ """User password is passed to get_user_db_session."""+ processor = _make_processor()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ with patch(f"{MODULE}.UserQueueService"):+ processor.notify_research_completed(+ "bob", "r-012", user_password="secret"+ )++ mock_get_session.assert_called_once_with("bob", "secret")+++# ---------------------------------------------------------------------------+# notify_research_failed — error message defaulting, sanitization+# ---------------------------------------------------------------------------+++class TestNotifyResearchFailed:+ """Tests for notify_research_failed."""++ @patch(f"{MODULE}.send_research_failed_notification_from_session")+ @patch(f"{MODULE}.get_user_db_session")+ def test_sends_error_message_to_queue_service(+ self, mock_get_session, mock_send_notif+ ):+ """Passes error_message to queue service update."""+ processor = _make_processor()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ with patch(f"{MODULE}.UserQueueService") as mock_qs_class:+ mock_qs = Mock()+ mock_qs_class.return_value = mock_qs++ processor.notify_research_failed(+ "alice", "r-020", error_message="OOM", user_password="pw"+ )++ mock_qs.update_task_status.assert_called_once()+ args, kwargs = mock_qs.update_task_status.call_args+ assert (+ kwargs.get("error_message") == "OOM" or args[2]+ if len(args) > 2+ else True+ )++ @patch(f"{MODULE}.send_research_failed_notification_from_session")+ @patch(f"{MODULE}.get_user_db_session")+ def test_defaults_error_message_to_unknown(+ self, mock_get_session, mock_send_notif+ ):+ """None error_message defaults to 'Unknown error' for notification."""+ processor = _make_processor()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ with patch(f"{MODULE}.UserQueueService"):+ processor.notify_research_failed(+ "alice", "r-021", user_password="pw"+ )++ mock_send_notif.assert_called_once_with(+ username="alice",+ research_id="r-021",+ error_message="Unknown error",+ db_session=mock_session,+ )++ @patch(f"{MODULE}.get_user_db_session")+ def test_exception_does_not_propagate(self, mock_get_session):+ """Exception in failure handling is caught."""+ processor = _make_processor()++ mock_get_session.side_effect = RuntimeError("DB error")++ # Should not raise+ processor.notify_research_failed("alice", "r-022", error_message="bad")+++# ---------------------------------------------------------------------------+# _process_queue_loop — user:session parsing, removal logic+# ---------------------------------------------------------------------------+++class TestProcessQueueLoop:+ """Tests for _process_queue_loop."""++ def test_parses_user_session_format(self):+ """Correctly parses 'username:session_id' entries."""+ processor = _make_processor()+ processor._users_to_check.add("alice:sess-abc")++ with patch.object(+ processor, "_process_user_queue", return_value=True+ ) as mock_pq:+ # Run one iteration then stop+ processor.running = True++ def stop_after_one():+ time.sleep(0.05)+ processor.running = False++ threading.Thread(target=stop_after_one).start()+ processor._process_queue_loop()++ mock_pq.assert_called_with("alice", "sess-abc")++ def test_removes_users_with_empty_queues(self):+ """Users whose queues are empty get removed from check set."""+ processor = _make_processor()+ processor._users_to_check.add("alice:sess1")+ processor._users_to_check.add("bob:sess2")++ def side_effect(username, session_id):+ return username == "alice" # alice's queue is empty++ with patch.object(+ processor, "_process_user_queue", side_effect=side_effect+ ):+ processor.running = True++ def stop_after_one():+ time.sleep(0.05)+ processor.running = False++ threading.Thread(target=stop_after_one).start()+ processor._process_queue_loop()++ assert "alice:sess1" not in processor._users_to_check+ assert "bob:sess2" in processor._users_to_check++ def test_keeps_users_on_error(self):+ """Users are kept if _process_user_queue raises."""+ processor = _make_processor()+ processor._users_to_check.add("alice:sess1")++ with patch.object(+ processor,+ "_process_user_queue",+ side_effect=RuntimeError("transient"),+ ):+ processor.running = True++ def stop_after_one():+ time.sleep(0.05)+ processor.running = False++ threading.Thread(target=stop_after_one).start()+ processor._process_queue_loop()++ assert "alice:sess1" in processor._users_to_check+++# ---------------------------------------------------------------------------+# _process_user_queue — slot calculation, empty queue, no password+# ---------------------------------------------------------------------------+++class TestProcessUserQueue:+ """Tests for _process_user_queue."""++ @patch(f"{MODULE}.session_password_store")+ def test_no_password_returns_true(self, mock_pw_store):+ """No password -> returns True (remove from checking)."""+ processor = _make_processor()+ mock_pw_store.get_session_password.return_value = None++ result = processor._process_user_queue("alice", "sess1")+ assert result is True++ @patch(f"{MODULE}.get_user_db_session")+ @patch(f"{MODULE}.db_manager")+ @patch(f"{MODULE}.session_password_store")+ def test_empty_queue_returns_true(+ self, mock_pw_store, mock_db_mgr, mock_get_session+ ):+ """Empty queue -> returns True."""+ processor = _make_processor()++ mock_pw_store.get_session_password.return_value = "pw"+ mock_db_mgr.open_user_database.return_value = Mock()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ mock_settings = Mock()+ mock_settings.get_setting.return_value = 3++ mock_qs = Mock()+ mock_qs.get_queue_status.return_value = {+ "active_tasks": 0,+ "queued_tasks": 0,+ }++ with patch(SETTINGS_MGR, return_value=mock_settings):+ with patch(f"{MODULE}.UserQueueService", return_value=mock_qs):+ result = processor._process_user_queue("alice", "sess1")++ assert result is True++ @patch(f"{MODULE}.get_user_db_session")+ @patch(f"{MODULE}.db_manager")+ @patch(f"{MODULE}.session_password_store")+ def test_no_slots_available_returns_false(+ self, mock_pw_store, mock_db_mgr, mock_get_session+ ):+ """No available slots -> returns False (keep checking)."""+ processor = _make_processor()++ mock_pw_store.get_session_password.return_value = "pw"+ mock_db_mgr.open_user_database.return_value = Mock()++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ mock_get_session.return_value = mock_session++ mock_settings = Mock()+ mock_settings.get_setting.return_value = 2++ mock_qs = Mock()+ mock_qs.get_queue_status.return_value = {+ "active_tasks": 2,+ "queued_tasks": 1,+ }++ with patch(SETTINGS_MGR, return_value=mock_settings):+ with patch(f"{MODULE}.UserQueueService", return_value=mock_qs):+ result = processor._process_user_queue("alice", "sess1")++ assert result is False++ @patch(f"{MODULE}.db_manager")+ @patch(f"{MODULE}.session_password_store")+ def test_failed_db_open_returns_false(self, mock_pw_store, mock_db_mgr):+ """Failed database open -> returns False (keep checking)."""+ processor = _make_processor()++ mock_pw_store.get_session_password.return_value = "pw"+ mock_db_mgr.open_user_database.return_value = None++ result = processor._process_user_queue("alice", "sess1")+ assert result is False+++# ---------------------------------------------------------------------------+# _start_research — new vs legacy settings format+# ---------------------------------------------------------------------------+++class TestStartResearch:+ """Tests for _start_research."""++ @patch(f"{MODULE}.start_research_process")+ def test_new_format_extracts_submission_and_settings(+ self, mock_start_research+ ):+ """New format: {submission: {...}, settings_snapshot: {...}}."""+ processor = _make_processor()++ mock_thread = Mock()+ mock_thread.ident = 12345+ mock_start_research.return_value = mock_thread++ mock_session = MagicMock()+ mock_research = Mock()+ mock_research.status = "queued"+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ queued = Mock()+ queued.research_id = "r-100"+ queued.query = "test query"+ queued.mode = "standard"+ queued.settings_snapshot = {+ "submission": {+ "model_provider": "openai",+ "model": "gpt-4",+ "strategy": "graph-based",+ },+ "settings_snapshot": {"setting_a": "value_a"},+ }++ with patch(f"{MODULE}.UserActiveResearch"):+ processor._start_research(mock_session, "alice", "pw", queued)++ # Verify start_research_process was called with new-format extracted params+ call_kwargs = mock_start_research.call_args.kwargs+ assert call_kwargs["model_provider"] == "openai"+ assert call_kwargs["model"] == "gpt-4"+ assert call_kwargs["strategy"] == "graph-based"+ assert call_kwargs["settings_snapshot"] == {"setting_a": "value_a"}++ @patch(f"{MODULE}.start_research_process")+ def test_legacy_format_uses_flat_dict(self, mock_start_research):+ """Legacy format: flat dict used as submission_params."""+ processor = _make_processor()++ mock_thread = Mock()+ mock_thread.ident = 12345+ mock_start_research.return_value = mock_thread++ mock_session = MagicMock()+ mock_research = Mock()+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ queued = Mock()+ queued.research_id = "r-101"+ queued.query = "legacy query"+ queued.mode = "standard"+ queued.settings_snapshot = {+ "model_provider": "anthropic",+ "model": "claude-3",+ }++ with patch(f"{MODULE}.UserActiveResearch"):+ processor._start_research(mock_session, "alice", "pw", queued)++ call_kwargs = mock_start_research.call_args.kwargs+ assert call_kwargs["model_provider"] == "anthropic"+ assert call_kwargs["model"] == "claude-3"+ assert call_kwargs["settings_snapshot"] == {}++ @patch(f"{MODULE}.start_research_process")+ def test_none_settings_snapshot_handled(self, mock_start_research):+ """None settings_snapshot treated as empty dict."""+ processor = _make_processor()++ mock_thread = Mock()+ mock_thread.ident = 12345+ mock_start_research.return_value = mock_thread++ mock_session = MagicMock()+ mock_research = Mock()+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ queued = Mock()+ queued.research_id = "r-102"+ queued.query = "test"+ queued.mode = "standard"+ queued.settings_snapshot = None++ with patch(f"{MODULE}.UserActiveResearch"):+ processor._start_research(mock_session, "alice", "pw", queued)++ call_kwargs = mock_start_research.call_args.kwargs+ assert call_kwargs["settings_snapshot"] == {}++ def test_research_not_found_raises(self):+ """Raises ValueError when research record not found."""+ processor = _make_processor()++ mock_session = MagicMock()+ mock_session.query.return_value.filter_by.return_value.first.return_value = None++ queued = Mock()+ queued.research_id = "r-999"+ queued.settings_snapshot = {}++ with pytest.raises(ValueError, match="not found"):+ processor._start_research(mock_session, "alice", "pw", queued)+++# ---------------------------------------------------------------------------+# process_pending_operations_for_user — progress/error updates, rollback+# ---------------------------------------------------------------------------+++class TestProcessPendingOperationsForUser:+ """Tests for process_pending_operations_for_user."""++ def test_progress_update_sets_progress(self):+ """Progress update operation sets research.progress."""+ processor = _make_processor()++ # Queue a progress update+ processor.queue_progress_update("alice", "r-200", 42.5)++ mock_session = MagicMock()+ mock_research = Mock()+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ count = processor.process_pending_operations_for_user(+ "alice", mock_session+ )++ assert count == 1+ assert mock_research.progress == 42.5+ mock_session.commit.assert_called()++ def test_error_update_sets_all_fields(self):+ """Error update sets status, error_message, metadata, completed_at."""+ processor = _make_processor()++ processor.queue_error_update(+ username="alice",+ research_id="r-201",+ status="failed",+ error_message="OOM killed",+ metadata={"retries": 3},+ completed_at="2026-01-01T00:00:00",+ report_path="/tmp/error.html",+ )++ mock_session = MagicMock()+ mock_research = Mock()+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ count = processor.process_pending_operations_for_user(+ "alice", mock_session+ )++ assert count == 1+ assert mock_research.status == "failed"+ assert mock_research.error_message == "OOM killed"+ assert mock_research.research_meta == {"retries": 3}+ assert mock_research.completed_at == "2026-01-01T00:00:00"+ assert mock_research.report_path == "/tmp/error.html"++ def test_no_operations_returns_zero(self):+ """No pending operations for user -> returns 0."""+ processor = _make_processor()++ mock_session = MagicMock()+ count = processor.process_pending_operations_for_user(+ "alice", mock_session+ )++ assert count == 0++ def test_operations_for_other_users_not_processed(self):+ """Only processes operations for the specified user."""+ processor = _make_processor()++ processor.queue_progress_update("bob", "r-300", 50.0)+ processor.queue_progress_update("alice", "r-301", 75.0)++ mock_session = MagicMock()+ mock_research = Mock()+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ count = processor.process_pending_operations_for_user(+ "alice", mock_session+ )++ assert count == 1+ assert mock_research.progress == 75.0+ # Bob's operation should still be pending+ assert len(processor.pending_operations) == 1++ def test_exception_triggers_rollback(self):+ """Exception during processing triggers session rollback."""+ processor = _make_processor()++ processor.queue_progress_update("alice", "r-400", 50.0)++ mock_session = MagicMock()+ mock_session.query.side_effect = RuntimeError("DB error")++ count = processor.process_pending_operations_for_user(+ "alice", mock_session+ )++ assert count == 0+ mock_session.rollback.assert_called_once()++ def test_error_update_without_report_path(self):+ """Error update without report_path doesn't set report_path."""+ processor = _make_processor()++ processor.queue_error_update(+ username="alice",+ research_id="r-401",+ status="suspended",+ error_message="Timeout",+ metadata={},+ completed_at="2026-01-01",+ )++ mock_session = MagicMock()+ mock_research = Mock(+ spec=[+ "status",+ "error_message",+ "research_meta",+ "completed_at",+ "report_path",+ ]+ )+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ count = processor.process_pending_operations_for_user(+ "alice", mock_session+ )+ assert count == 1+ assert mock_research.status == "suspended"