~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 72 high-value tests across 5 modules (round 11) (#2597)
LearningCircuitbae4eee372cd
diff --git a/tests/advanced_search_system/strategies/test_source_strategy_logic.py b/tests/advanced_search_system/strategies/test_source_strategy_logic.pynew file mode 100644index 0000000000..0ec2a2cb21--- /dev/null+++ b/tests/advanced_search_system/strategies/test_source_strategy_logic.py@@ -0,0 +1,228 @@+"""+Tests for pure logic in SourceBasedSearchStrategy:+- Long query detection (lines 250-264)+- Question assembly deduplication (lines 281-286)+- Progress percentage formula (lines 227-229)+- Question context limiting (lines 317-324)++Does NOT duplicate _format_search_results_as_context tests (already in test_strategy_pure_logic.py).+"""++from unittest.mock import Mock+++def _make_strategy(**overrides):+ """Build a minimal mock object with the attributes used by the logic under test."""+ s = Mock()+ s.search_original_query = overrides.get("search_original_query", True)+ s.questions_by_iteration = {}+ s.all_links_of_system = []+ s.progress_callback = overrides.get("progress_callback", None)+ s._settings_snapshot = overrides.get("settings_snapshot", {})+ s.question_generator = Mock()+ s.get_setting = overrides.get(+ "get_setting", lambda key, default=None: default+ )+ return s+++# ---------------------------------------------------------------------------+# 2a. Long query detection+# ---------------------------------------------------------------------------+++class TestLongQueryDetection:+ """Tests for long query detection (lines 250-264)."""++ def test_query_at_max_length_stays_true(self):+ """Query exactly at 300 chars → search_original_query stays True."""+ s = _make_strategy()+ query = "a" * 300+ max_len = 300+ # Simulate the logic+ if s.search_original_query and len(query.strip()) > max_len:+ s.search_original_query = False+ assert s.search_original_query is True++ def test_query_over_max_becomes_false(self):+ """Query at 301 chars → search_original_query becomes False."""+ s = _make_strategy()+ query = "a" * 301+ max_len = 300+ if s.search_original_query and len(query.strip()) > max_len:+ s.search_original_query = False+ assert s.search_original_query is False++ def test_whitespace_stripped_before_check(self):+ """Leading/trailing whitespace stripped before length check."""+ s = _make_strategy()+ query = " " + "a" * 299 + " " # 299 actual chars + whitespace+ max_len = 300+ if s.search_original_query and len(query.strip()) > max_len:+ s.search_original_query = False+ assert s.search_original_query is True # 299 < 300++ def test_custom_max_from_settings(self):+ """Custom max_query_length (500) from settings."""+ s = _make_strategy()+ query = "a" * 450+ max_len = 500+ if s.search_original_query and len(query.strip()) > max_len:+ s.search_original_query = False+ assert s.search_original_query is True # 450 < 500++ def test_search_original_query_false_skips_check(self):+ """search_original_query=False initially → length check skipped."""+ s = _make_strategy(search_original_query=False)+ query = "a" * 1000+ max_len = 300+ if s.search_original_query and len(query.strip()) > max_len:+ s.search_original_query = False+ # Still False — the check never ran because initial value was False+ assert s.search_original_query is False++ def test_empty_query_under_limit(self):+ """Empty query has 0 chars, under any limit."""+ s = _make_strategy()+ query = ""+ max_len = 300+ if s.search_original_query and len(query.strip()) > max_len:+ s.search_original_query = False+ assert s.search_original_query is True+++# ---------------------------------------------------------------------------+# 2b. Question assembly deduplication+# ---------------------------------------------------------------------------+++class TestQuestionAssembly:+ """Tests for question assembly deduplication (lines 281-286)."""++ def test_query_prepended_when_not_in_questions(self):+ """search_original_query=True, query NOT in questions → prepended."""+ query = "my query"+ questions = ["q1", "q2"]+ search_original_query = True+ all_questions = (+ [query] + questions+ if search_original_query and query not in questions+ else questions+ )+ assert all_questions == ["my query", "q1", "q2"]++ def test_query_not_duplicated_when_already_present(self):+ """search_original_query=True, query in questions → NOT duplicated."""+ query = "my query"+ questions = ["my query", "q2"]+ search_original_query = True+ all_questions = (+ [query] + questions+ if search_original_query and query not in questions+ else questions+ )+ assert all_questions == ["my query", "q2"]++ def test_query_skipped_when_flag_false(self):+ """search_original_query=False → questions returned without query."""+ query = "my query"+ questions = ["q1", "q2"]+ search_original_query = False+ all_questions = (+ [query] + questions+ if search_original_query and query not in questions+ else questions+ )+ assert all_questions == ["q1", "q2"]++ def test_empty_questions_with_flag_true(self):+ """Empty questions + flag=True → returns [query]."""+ query = "my query"+ questions = []+ search_original_query = True+ all_questions = (+ [query] + questions+ if search_original_query and query not in questions+ else questions+ )+ assert all_questions == ["my query"]++ def test_order_preserved_query_first(self):+ """Original query always first when included."""+ query = "original"+ questions = ["q1", "q2", "q3"]+ search_original_query = True+ all_questions = (+ [query] + questions+ if search_original_query and query not in questions+ else questions+ )+ assert all_questions[0] == "original"+ assert all_questions[1:] == ["q1", "q2", "q3"]+++# ---------------------------------------------------------------------------+# 2c. Progress percentage formula+# ---------------------------------------------------------------------------+++class TestProgressFormula:+ """Tests for iteration_progress_base formula (line 227-229)."""++ def _calc(self, iteration, iterations_to_run):+ return 5 + (iteration - 1) * (70 / iterations_to_run)++ def test_iter1_of_2(self):+ assert self._calc(1, 2) == 5.0++ def test_iter2_of_2(self):+ assert self._calc(2, 2) == 40.0++ def test_iter1_of_5(self):+ assert self._calc(1, 5) == 5.0++ def test_iter5_of_5(self):+ # 5 + 4*(70/5) = 5 + 56 = 61+ assert self._calc(5, 5) == 61.0++ def test_single_iteration_no_division_by_zero(self):+ """iterations_to_run=1 → safe, returns 5."""+ assert self._calc(1, 1) == 5.0+++# ---------------------------------------------------------------------------+# 2d. Question context limiting+# ---------------------------------------------------------------------------+++class TestQuestionContextLimiting:+ """Tests for question context limiting (lines 317-324)."""++ def test_50_results_limit_30_returns_last_30(self):+ results = list(range(50))+ limit = 30+ sliced = results[-limit:]+ assert len(sliced) == 30+ assert sliced[0] == 20 # last 30 of 0..49++ def test_10_results_limit_30_returns_all(self):+ results = list(range(10))+ limit = 30+ sliced = results[-limit:]+ assert len(sliced) == 10++ def test_default_limit_is_30(self):+ """get_setting returns 30 by default."""+ s = _make_strategy()+ val = int(s.get_setting("search.question_context_limit", 30))+ assert val == 30++ def test_custom_limit_from_settings(self):+ """Custom limit from settings snapshot."""+ s = _make_strategy(+ get_setting=lambda key, default=None: 50+ if key == "search.question_context_limit"+ else default+ )+ val = int(s.get_setting("search.question_context_limit", 30))+ assert val == 50diff --git a/tests/config/test_context_window_provider.py b/tests/config/test_context_window_provider.pynew file mode 100644index 0000000000..6f73b583fe--- /dev/null+++ b/tests/config/test_context_window_provider.py@@ -0,0 +1,179 @@+"""+Tests for _get_context_window_for_provider() in llm_config.py.++Covers the 3 branches: local providers (default 4096),+cloud unrestricted (returns None), cloud restricted (default 128000).+"""++from unittest.mock import patch+++def _get_fn():+ from local_deep_research.config.llm_config import (+ _get_context_window_for_provider,+ )++ return _get_context_window_for_provider+++class TestLocalProviders:+ """Local providers (ollama, llamacpp, lmstudio) use smaller default."""++ @patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=4096,+ )+ def test_ollama_returns_default(self, mock_setting):+ result = _get_fn()("ollama")+ assert result == 4096+ mock_setting.assert_called_once_with(+ "llm.local_context_window_size", 4096, settings_snapshot=None+ )++ @patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=4096,+ )+ def test_llamacpp_returns_default(self, mock_setting):+ assert _get_fn()("llamacpp") == 4096++ @patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=4096,+ )+ def test_lmstudio_returns_default(self, mock_setting):+ assert _get_fn()("lmstudio") == 4096++ @patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=8192,+ )+ def test_snapshot_overrides_local_window(self, mock_setting):+ result = _get_fn()(+ "ollama", settings_snapshot={"llm.local_context_window_size": 8192}+ )+ assert result == 8192++ @patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value="4096",+ )+ def test_string_coerced_to_int(self, mock_setting):+ """String values are coerced to int."""+ result = _get_fn()("ollama")+ assert result == 4096+ assert isinstance(result, int)++ @patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=None,+ )+ def test_none_falls_back_to_default_4096(self, mock_setting):+ """None value → fallback to 4096."""+ result = _get_fn()("ollama")+ assert result == 4096+++class TestCloudUnrestricted:+ """Cloud providers with unrestricted=True return None."""++ @patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=True,+ )+ def test_openai_unrestricted_returns_none(self, mock_setting):+ result = _get_fn()("openai")+ assert result is None++ @patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=True,+ )+ def test_anthropic_unrestricted_returns_none(self, mock_setting):+ assert _get_fn()("anthropic") is None++ @patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ return_value=True,+ )+ def test_unknown_provider_treated_as_cloud(self, mock_setting):+ """Unknown provider goes through cloud branch."""+ assert _get_fn()("some_new_provider") is None+++class TestCloudRestricted:+ """Cloud providers with unrestricted=False use configurable limit."""++ def test_cloud_restricted_returns_default_128000(self):+ """When unrestricted=False, defaults to 128000."""+ call_count = 0++ def fake_get_setting(key, default, settings_snapshot=None):+ nonlocal call_count+ call_count += 1+ if key == "llm.context_window_unrestricted":+ return False+ if key == "llm.context_window_size":+ return 128000+ return default++ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ side_effect=fake_get_setting,+ ):+ result = _get_fn()("openai")+ assert result == 128000++ def test_cloud_restricted_snapshot_override(self):+ """Settings snapshot overrides cloud window size."""++ def fake_get_setting(key, default, settings_snapshot=None):+ if key == "llm.context_window_unrestricted":+ return False+ if key == "llm.context_window_size":+ return 32000+ return default++ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ side_effect=fake_get_setting,+ ):+ result = _get_fn()(+ "openai", settings_snapshot={"llm.context_window_size": 32000}+ )+ assert result == 32000++ def test_cloud_restricted_string_coerced(self):+ """String window size coerced to int."""++ def fake_get_setting(key, default, settings_snapshot=None):+ if key == "llm.context_window_unrestricted":+ return False+ if key == "llm.context_window_size":+ return "64000"+ return default++ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ side_effect=fake_get_setting,+ ):+ result = _get_fn()("openai")+ assert result == 64000+ assert isinstance(result, int)++ def test_cloud_restricted_none_falls_back_to_128000(self):+ """None value → fallback to 128000."""++ def fake_get_setting(key, default, settings_snapshot=None):+ if key == "llm.context_window_unrestricted":+ return False+ if key == "llm.context_window_size":+ return None+ return default++ with patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot",+ side_effect=fake_get_setting,+ ):+ result = _get_fn()("openai")+ assert result == 128000diff --git a/tests/mcp/test_mcp_call_tool_parsing.py b/tests/mcp/test_mcp_call_tool_parsing.pynew file mode 100644index 0000000000..0353299486--- /dev/null+++ b/tests/mcp/test_mcp_call_tool_parsing.py@@ -0,0 +1,213 @@+"""+Tests for MCPClient.call_tool() result parsing logic.++The parsing logic is extracted and tested directly since the mcp package+may not be installed in the test environment. This tests the exact same+branching logic from client.py:303-331.+"""++import asyncio+from unittest.mock import AsyncMock, Mock++import pytest++# Skip if mcp package not available+try:+ import mcp # noqa: F401++ MCP_AVAILABLE = True+except ImportError:+ MCP_AVAILABLE = False+++def _parse_tool_result(result):+ """+ Extract the parsing logic from MCPClient.call_tool() (lines 303-331).++ This is the exact logic from client.py, isolated for unit testing.+ """+ if result.isError:+ return {+ "status": "error",+ "error": str(result.content),+ }++ content = []+ if result.content is not None and hasattr(result.content, "__iter__"):+ for item in result.content:+ if hasattr(item, "text"):+ content.append(item.text)+ elif hasattr(item, "data"):+ content.append(str(item.data))+ else:+ content.append(str(item))+ elif result.content is not None:+ content.append(str(result.content))++ return {+ "status": "success",+ "content": "\n".join(content) if content else "",+ "raw": result.content,+ }+++def _make_result(is_error=False, content=None):+ """Create a mock tool result."""+ result = Mock()+ result.isError = is_error+ result.content = content+ return result+++class TestErrorResult:+ """Tests for error result handling."""++ def test_error_returns_status_error(self):+ """isError=True → status=error dict."""+ result = _make_result(is_error=True, content=[Mock(text="bad")])+ output = _parse_tool_result(result)+ assert output["status"] == "error"+ assert "error" in output++ def test_error_content_stringified(self):+ """Error content is converted to string."""+ result = _make_result(is_error=True, content="timeout occurred")+ output = _parse_tool_result(result)+ assert "timeout occurred" in output["error"]+++class TestTextContent:+ """Tests for success results with .text attributes."""++ def test_text_content_joined_with_newlines(self):+ """Multiple .text items → joined with newlines."""+ items = [+ Mock(text="line1", spec=["text"]),+ Mock(text="line2", spec=["text"]),+ ]+ result = _make_result(content=items)+ output = _parse_tool_result(result)+ assert output["status"] == "success"+ assert output["content"] == "line1\nline2"++ def test_single_text_item(self):+ """Single .text item → correct extraction."""+ items = [Mock(text="only", spec=["text"])]+ result = _make_result(content=items)+ output = _parse_tool_result(result)+ assert output["content"] == "only"+++class TestDataContent:+ """Tests for success results with .data attributes."""++ def test_data_content_stringified(self):+ """Items with .data → str(data) joined."""+ item1 = Mock(spec=["data"])+ item1.data = b"bytes1"+ item2 = Mock(spec=["data"])+ item2.data = b"bytes2"+ result = _make_result(content=[item1, item2])+ output = _parse_tool_result(result)+ assert "bytes1" in output["content"]+ assert "bytes2" in output["content"]+++class TestMixedContent:+ """Tests for mixed content types."""++ def test_mixed_text_and_data(self):+ """Mixed .text and .data items → all extracted."""+ text_item = Mock(spec=["text"])+ text_item.text = "hello"+ data_item = Mock(spec=["data"])+ data_item.data = "world"+ result = _make_result(content=[text_item, data_item])+ output = _parse_tool_result(result)+ assert "hello" in output["content"]+ assert "world" in output["content"]++ def test_item_without_text_or_data_uses_str(self):+ """Item without .text/.data → str() fallback."""+ result = _make_result(content=["plain string"])+ output = _parse_tool_result(result)+ assert output["content"] == "plain string"+++class TestEdgeCases:+ """Edge cases for result parsing."""++ def test_none_content_returns_empty(self):+ """None content → empty string."""+ result = _make_result(content=None)+ output = _parse_tool_result(result)+ assert output["status"] == "success"+ assert output["content"] == ""++ def test_empty_list_returns_empty(self):+ """Empty list → empty string."""+ result = _make_result(content=[])+ output = _parse_tool_result(result)+ assert output["content"] == ""++ def test_non_iterable_content_str_fallback(self):+ """Non-iterable (int) → str conversion."""+ result = _make_result(content=42)+ output = _parse_tool_result(result)+ assert output["content"] == "42"++ def test_bare_string_content_iterates_characters(self):+ """Bare string content iterates char-by-char (documents production behavior).++ A bare string has __iter__, so the code enters the iterable branch+ and iterates character by character. Each char lacks .text/.data,+ so str(char) is used → characters joined with newlines.++ This documents the current behavior. If the production code is fixed+ to check `isinstance(content, str)` first, update this test.+ """+ result = _make_result(content="hello")+ output = _parse_tool_result(result)+ # Current behavior: iterates characters, joins with \n+ assert output["content"] == "h\ne\nl\nl\no"++ def test_result_has_raw_key(self):+ """Output includes 'raw' with original content."""+ items = [Mock(text="data", spec=["text"])]+ result = _make_result(content=items)+ output = _parse_tool_result(result)+ assert output["raw"] is items++[email protected](not MCP_AVAILABLE, reason="MCP package not installed")+class TestCallToolIntegration:+ """Integration tests that require the actual MCPClient class."""++ @pytest.mark.asyncio+ async def test_not_connected_raises_error(self):+ """Not connected → MCPClientError."""+ from local_deep_research.mcp.client import MCPClient, MCPClientError++ client = MCPClient.__new__(MCPClient)+ client._connected = False+ client._session = None++ with pytest.raises(MCPClientError, match="Not connected"):+ await client.call_tool("tool", {})++ @pytest.mark.asyncio+ async def test_timeout_raises_mcp_error(self):+ """Timeout → MCPClientError."""+ from local_deep_research.mcp.client import MCPClient, MCPClientError++ client = MCPClient.__new__(MCPClient)+ client.name = "test"+ client.timeout = 0.01+ client._connected = True+ client._session = AsyncMock()+ client._session.call_tool = AsyncMock(+ side_effect=asyncio.TimeoutError()+ )++ with pytest.raises(MCPClientError, match="timed out"):+ await client.call_tool("tool", {})diff --git a/tests/research_library/deletion/utils/test_cascade_deletion_order.py b/tests/research_library/deletion/utils/test_cascade_deletion_order.pynew file mode 100644index 0000000000..3c08298c40--- /dev/null+++ b/tests/research_library/deletion/utils/test_cascade_deletion_order.py@@ -0,0 +1,138 @@+"""+Tests for CascadeHelper.delete_document_completely() deletion order.++Verifies that deletion happens in the correct order:+1. DocumentBlob+2. DocumentCollection links+3. Document itself+"""++from unittest.mock import MagicMock++from local_deep_research.research_library.deletion.utils.cascade_helper import (+ CascadeHelper,+)+++def _make_session(blob_deleted=1, collection_deleted=1, doc_deleted=1):+ """Build a mock session with configurable delete return values."""+ session = MagicMock()++ # Track call order+ call_order = []++ def make_query_chain(model_class, delete_return):+ chain = MagicMock()+ chain.filter_by.return_value = chain+ chain.delete.side_effect = lambda **kw: (+ call_order.append(model_class.__name__),+ delete_return,+ )[1]+ return chain++ from local_deep_research.database.models.library import (+ Document,+ DocumentBlob,+ DocumentCollection,+ )++ query_map = {+ DocumentBlob: make_query_chain(DocumentBlob, blob_deleted),+ DocumentCollection: make_query_chain(+ DocumentCollection, collection_deleted+ ),+ Document: make_query_chain(Document, doc_deleted),+ }++ session.query.side_effect = lambda model: query_map[model]+ session._call_order = call_order+ return session+++class TestDeletionOrder:+ """Verify deletion order: Blob → Collection → Document."""++ def test_deletion_order_blob_before_collection_before_document(self):+ """DocumentBlob deleted BEFORE DocumentCollection BEFORE Document."""+ session = _make_session()+ CascadeHelper.delete_document_completely(session, "doc-123")+ assert session._call_order == [+ "DocumentBlob",+ "DocumentCollection",+ "Document",+ ]++ def test_document_exists_returns_true(self):+ """Document deleted (1 row) → returns True."""+ session = _make_session(doc_deleted=1)+ result = CascadeHelper.delete_document_completely(session, "doc-123")+ assert result is True++ def test_document_not_exists_returns_false(self):+ """Document not found (0 rows deleted) → returns False."""+ session = _make_session(doc_deleted=0)+ result = CascadeHelper.delete_document_completely(session, "doc-123")+ assert result is False++ def test_no_blob_still_returns_true(self):+ """No blob exists but document exists → still True."""+ session = _make_session(blob_deleted=0, doc_deleted=1)+ result = CascadeHelper.delete_document_completely(session, "doc-123")+ assert result is True++ def test_synchronize_session_false_used(self):+ """synchronize_session=False used for all delete calls."""+ session = _make_session()+ CascadeHelper.delete_document_completely(session, "doc-123")++ from local_deep_research.database.models.library import (+ Document,+ DocumentBlob,+ DocumentCollection,+ )++ for model in [DocumentBlob, DocumentCollection, Document]:+ chain = session.query(model)+ chain.filter_by.return_value.delete.assert_called_with(+ synchronize_session=False+ )++ def test_multiple_collection_links_all_deleted(self):+ """Multiple collection links → all deleted in one call."""+ session = _make_session(collection_deleted=5)+ result = CascadeHelper.delete_document_completely(session, "doc-123")+ assert result is True+ # Verify collection delete was called+ assert "DocumentCollection" in session._call_order++ def test_session_query_called_with_correct_models(self):+ """Session.query called with DocumentBlob, DocumentCollection, Document."""+ session = _make_session()+ CascadeHelper.delete_document_completely(session, "doc-123")++ from local_deep_research.database.models.library import (+ Document,+ DocumentBlob,+ DocumentCollection,+ )++ called_models = [c.args[0] for c in session.query.call_args_list]+ assert called_models == [DocumentBlob, DocumentCollection, Document]++ def test_filter_by_uses_document_id(self):+ """All filter_by calls use the provided document_id."""+ session = _make_session()+ CascadeHelper.delete_document_completely(session, "abc-456")++ from local_deep_research.database.models.library import (+ Document,+ DocumentBlob,+ DocumentCollection,+ )++ for model in [DocumentBlob, DocumentCollection]:+ chain = session.query(model)+ chain.filter_by.assert_called_with(document_id="abc-456")++ doc_chain = session.query(Document)+ doc_chain.filter_by.assert_called_with(id="abc-456")diff --git a/tests/web/services/test_research_service_execution.py b/tests/web/services/test_research_service_execution.pynew file mode 100644index 0000000000..dbe3bc7bba--- /dev/null+++ b/tests/web/services/test_research_service_execution.py@@ -0,0 +1,215 @@+"""+Tests for run_research_process() core execution logic.++Covers:+- Quick vs detailed mode branching+- Settings context creation+- Progress callback invocation+- Termination handling+- Error handling+- Research status updates+"""++import pytest+++class TestSettingsContext:+ """Tests for SettingsContext created inside run_research_process."""++ def test_settings_context_extracts_values_from_setting_objects(self):+ """SettingsContext extracts 'value' from setting dicts."""+ # Replicate the SettingsContext class logic from research_service.py+ snapshot = {+ "llm.provider": {"value": "openai", "type": "string"},+ "search.tool": "google", # plain value+ }++ # Simulate the extraction logic+ values = {}+ for key, setting in snapshot.items():+ if isinstance(setting, dict) and "value" in setting:+ values[key] = setting["value"]+ else:+ values[key] = setting++ assert values["llm.provider"] == "openai"+ assert values["search.tool"] == "google"++ def test_settings_context_get_setting_from_snapshot(self):+ """get_setting returns value from snapshot, default for missing."""+ values = {"llm.provider": "openai"}++ def get_setting(key, default=None):+ return values.get(key, default)++ assert get_setting("llm.provider") == "openai"+ assert get_setting("missing.key", "fallback") == "fallback"++ def test_settings_context_empty_snapshot(self):+ """Empty snapshot → all get_setting calls return default."""+ values = {}++ def get_setting(key, default=None):+ return values.get(key, default)++ assert get_setting("any.key", 42) == 42+++class TestProgressCallback:+ """Tests for progress callback logic."""++ def test_progress_adjusted_for_detailed_output_generation(self):+ """Detailed mode output_generation → capped at 80."""+ mode = "detailed"+ metadata = {"phase": "output_generation"}+ progress_percent = 90++ adjusted_progress = progress_percent+ if mode == "detailed" and metadata.get("phase") == "output_generation":+ adjusted_progress = min(80, progress_percent)++ assert adjusted_progress == 80++ def test_progress_adjusted_for_detailed_report_generation(self):+ """Detailed mode report_generation → scaled 80-95%."""+ mode = "detailed"+ metadata = {"phase": "report_generation"}+ progress_percent = 50++ adjusted_progress = progress_percent+ if mode == "detailed" and metadata.get("phase") == "report_generation":+ if progress_percent is not None:+ normalized = progress_percent / 100+ adjusted_progress = 80 + (normalized * 15)++ assert adjusted_progress == 87.5++ def test_progress_adjusted_for_quick_output_generation(self):+ """Quick mode output_generation → at least 85%, scaled 85-95%."""+ mode = "quick"+ metadata = {"phase": "output_generation"}+ progress_percent = 50++ adjusted_progress = progress_percent+ if mode == "quick" and metadata.get("phase") == "output_generation":+ adjusted_progress = max(85, progress_percent)+ if progress_percent is not None and progress_percent > 0:+ normalized = progress_percent / 100+ adjusted_progress = 85 + (normalized * 10)++ assert adjusted_progress == 90.0++ def test_search_plan_extracted_from_message(self):+ """SEARCH_PLAN: in message → engines extracted."""+ message = "Planning SEARCH_PLAN: google, bing, wikipedia"+ metadata = {}++ if "SEARCH_PLAN:" in message:+ engines = message.split("SEARCH_PLAN:")[1].strip()+ metadata["planned_engines"] = engines+ metadata["phase"] = "search_planning"++ assert metadata["planned_engines"] == "google, bing, wikipedia"+ assert metadata["phase"] == "search_planning"++ def test_engine_selected_extracted_from_message(self):+ """ENGINE_SELECTED: in message → engine extracted."""+ message = "Selected ENGINE_SELECTED: google"+ metadata = {}++ if "ENGINE_SELECTED:" in message:+ engine = message.split("ENGINE_SELECTED:")[1].strip()+ metadata["selected_engine"] = engine+ metadata["phase"] = "search"++ assert metadata["selected_engine"] == "google"+++class TestTerminationHandling:+ """Tests for termination checks in research process."""++ def test_termination_during_progress_raises(self):+ """Termination requested during progress → raises exception."""+ from local_deep_research.web.services.research_service import (+ ResearchTerminatedException,+ )++ with pytest.raises(ResearchTerminatedException):+ raise ResearchTerminatedException("Research was terminated by user")+++def _classify_error(error_message):+ """Replicate error classification logic from run_research_process (lines 714-733)."""+ if "status code: 503" in error_message:+ return "ollama_unavailable"+ elif "status code: 404" in error_message:+ return "model_not_found"+ elif "status code:" in error_message:+ return "api_error"+ elif "connection" in error_message.lower():+ return "connection_error"+ return "unknown"+++class TestErrorClassification:+ """Tests for search error classification in run_research_process."""++ @pytest.mark.parametrize(+ "error_message, expected_type",+ [+ ("Request failed with status code: 503", "ollama_unavailable"),+ ("status code: 404 not found", "model_not_found"),+ ("status code: 429 rate limited", "api_error"),+ ("status code: 500 internal error", "api_error"),+ ("Connection refused to localhost:11434", "connection_error"),+ ("TCP connection reset by peer", "connection_error"),+ ("Something unexpected happened", "unknown"),+ ("", "unknown"),+ ],+ )+ def test_error_classification(self, error_message, expected_type):+ assert _classify_error(error_message) == expected_type++ def test_503_takes_priority_over_generic_status_code(self):+ """503 is matched specifically before generic 'status code:' pattern."""+ assert _classify_error("status code: 503") == "ollama_unavailable"++ def test_404_takes_priority_over_generic_status_code(self):+ """404 is matched specifically before generic 'status code:' pattern."""+ assert _classify_error("status code: 404") == "model_not_found"+++class TestResearchModes:+ """Tests for mode-specific behavior."""++ def test_quick_mode_checks_findings(self):+ """Quick mode checks for findings or formatted_findings."""+ results = {"findings": ["f1"], "formatted_findings": "Summary text"}+ mode = "quick"++ if mode == "quick":+ has_findings = bool(+ results.get("findings") or results.get("formatted_findings")+ )+ else:+ has_findings = False++ assert has_findings is True++ def test_quick_mode_detects_error_in_findings(self):+ """Quick mode detects 'Error:' prefix in formatted_findings."""+ results = {"formatted_findings": "Error: token limit exceeded"}++ raw = results["formatted_findings"]+ is_error = isinstance(raw, str) and raw.startswith("Error:")++ assert is_error is True++ def test_quick_mode_no_error_prefix(self):+ """Normal formatted_findings → not detected as error."""+ results = {"formatted_findings": "This is a normal summary."}++ raw = results["formatted_findings"]+ is_error = isinstance(raw, str) and raw.startswith("Error:")++ assert is_error is False