Skip to content

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

test: increase coverage for MCP validators, route_registry, password_utils, settings_utils (#3049)

LearningCircuit6c84b6f5b6e0
diff --git a/tests/api/test_settings_utils_gaps.py b/tests/api/test_settings_utils_gaps.py
new file mode 100644
index 0000000000..4fdd3fc800
--- /dev/null
+++ b/tests/api/test_settings_utils_gaps.py
@@ -0,0 +1,360 @@
+"""
+Gap tests for settings_utils: _get_typed_value edge cases,
+get_bool_setting, get_settings_snapshot, extract_setting_value
+corner cases, and extract_bool_setting with non-bool inputs.
+
+These complement the existing test_settings_utils_typed_value.py and
+test_settings_utils_behavior.py by covering paths that those files miss.
+"""
+
+import pytest
+
+from local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ extract_bool_setting,
+ extract_setting_value,
+)
+
+
+# ---------------------------------------------------------------------------
+# Fixture
+# ---------------------------------------------------------------------------
+
+
+def manager():
+ """Create an InMemorySettingsManager with defaults loaded."""
+ return InMemorySettingsManager()
+
+
+# ---------------------------------------------------------------------------
+# _get_typed_value — additional edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestGetTypedValueTextarea:
+ """textarea ui_element — should behave like text (str conversion)."""
+
+ def test_string_passthrough(self, manager):
+ result = manager._get_typed_value(
+ {"ui_element": "textarea"}, "hello\nworld"
+ )
+ assert result == "hello\nworld"
+
+ def test_int_converted_to_string(self, manager):
+ result = manager._get_typed_value({"ui_element": "textarea"}, 99)
+ assert result == "99"
+ assert isinstance(result, str)
+
+
+class TestGetTypedValueConversionEdgeCases:
+ """Conversion failure and boundary cases not covered elsewhere."""
+
+ def test_none_returns_none_regardless_of_ui_element(self, manager):
+ """None short-circuits before any type dispatch."""
+ for ui in ("text", "checkbox", "number", "select", "json", "textarea"):
+ assert manager._get_typed_value({"ui_element": ui}, None) is None
+
+ def test_number_with_empty_string(self, manager):
+ """Empty string cannot be parsed as number; returns original value."""
+ result = manager._get_typed_value({"ui_element": "number"}, "")
+ assert result == ""
+
+ def test_range_with_negative_float(self, manager):
+ result = manager._get_typed_value({"ui_element": "range"}, "-2.5")
+ assert result == -2.5
+
+ def test_checkbox_with_none_value(self, manager):
+ """None should be returned directly (short-circuit), not converted."""
+ result = manager._get_typed_value({"ui_element": "checkbox"}, None)
+ assert result is None
+
+ def test_json_with_string_json_object(self, manager):
+ """A JSON string should be parsed into a dict."""
+ result = manager._get_typed_value({"ui_element": "json"}, '{"a": 1}')
+ assert result == {"a": 1}
+
+ def test_json_with_empty_string(self, manager):
+ """Empty string for json ui_element — should pass through as-is."""
+ result = manager._get_typed_value({"ui_element": "json"}, "")
+ # _parse_json_value returns empty strings as-is
+ assert result == ""
+
+ def test_multiselect_with_empty_list(self, manager):
+ result = manager._get_typed_value({"ui_element": "multiselect"}, [])
+ assert result == []
+
+ def test_multiselect_with_single_item_string(self, manager):
+ """A plain string without commas should still be parsed."""
+ result = manager._get_typed_value({"ui_element": "multiselect"}, "solo")
+ # _parse_multiselect with a non-bracketed, non-comma string
+ # returns a single-element list
+ assert isinstance(result, list)
+ assert "solo" in result
+
+
+class TestGetTypedValueMissingUiElement:
+ """When setting_data has no ui_element key at all."""
+
+ def test_defaults_to_text_converts_to_str(self, manager):
+ """Missing ui_element defaults to 'text', so str() is applied."""
+ result = manager._get_typed_value({}, 42)
+ assert result == "42"
+ assert isinstance(result, str)
+
+
+# ---------------------------------------------------------------------------
+# get_bool_setting — InMemorySettingsManager method
+# ---------------------------------------------------------------------------
+
+
+class TestGetBoolSetting:
+ """InMemorySettingsManager.get_bool_setting wraps get_setting + to_bool."""
+
+ def test_true_bool_value(self, manager):
+ manager.create_or_update_setting(
+ {"key": "test.gbool", "value": True, "ui_element": "checkbox"}
+ )
+ assert manager.get_bool_setting("test.gbool") is True
+
+ def test_false_bool_value(self, manager):
+ manager.create_or_update_setting(
+ {"key": "test.gbool", "value": False, "ui_element": "checkbox"}
+ )
+ assert manager.get_bool_setting("test.gbool") is False
+
+ def test_string_true(self, manager):
+ manager.create_or_update_setting(
+ {"key": "test.gbool", "value": "true", "ui_element": "checkbox"}
+ )
+ assert manager.get_bool_setting("test.gbool") is True
+
+ def test_string_on(self, manager):
+ manager.create_or_update_setting(
+ {"key": "test.gbool", "value": "on", "ui_element": "checkbox"}
+ )
+ assert manager.get_bool_setting("test.gbool") is True
+
+ def test_missing_key_returns_default_true(self, manager):
+ assert manager.get_bool_setting("nonexistent.key", default=True) is True
+
+ def test_missing_key_returns_default_false(self, manager):
+ assert (
+ manager.get_bool_setting("nonexistent.key", default=False) is False
+ )
+
+ def test_integer_1_is_true(self, manager):
+ manager.create_or_update_setting(
+ {"key": "test.gbool", "value": 1, "ui_element": "checkbox"}
+ )
+ # parse_boolean treats any truthy value (including 1) as True
+ assert manager.get_bool_setting("test.gbool") is True
+
+ def test_integer_0_is_false(self, manager):
+ manager.create_or_update_setting(
+ {"key": "test.gbool", "value": 0, "ui_element": "checkbox"}
+ )
+ assert manager.get_bool_setting("test.gbool") is False
+
+
+# ---------------------------------------------------------------------------
+# get_settings_snapshot — simplified key→value dict
+# ---------------------------------------------------------------------------
+
+
+class TestGetSettingsSnapshot:
+ """InMemorySettingsManager.get_settings_snapshot returns flat key→value."""
+
+ def test_returns_dict(self, manager):
+ snapshot = manager.get_settings_snapshot()
+ assert isinstance(snapshot, dict)
+
+ def test_values_are_extracted_from_setting_dicts(self, manager):
+ """Each setting's 'value' field should be the snapshot value."""
+ manager.create_or_update_setting(
+ {"key": "snap.test", "value": "hello", "ui_element": "text"}
+ )
+ snapshot = manager.get_settings_snapshot()
+ assert snapshot["snap.test"] == "hello"
+
+ def test_non_dict_settings_passed_through(self, manager):
+ """If a setting is not a dict (unlikely but possible), pass through."""
+ # Force a raw value into _settings
+ manager._settings["raw.val"] = "plain_string"
+ snapshot = manager.get_settings_snapshot()
+ assert snapshot["raw.val"] == "plain_string"
+
+ def test_snapshot_is_independent_copy(self, manager):
+ """Modifying snapshot should not affect manager state."""
+ snapshot = manager.get_settings_snapshot()
+ snapshot["injected"] = "bad"
+ snapshot2 = manager.get_settings_snapshot()
+ assert "injected" not in snapshot2
+
+
+# ---------------------------------------------------------------------------
+# create_or_update_setting — edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestCreateOrUpdateSettingEdgeCases:
+ def test_non_dict_returns_none(self, manager):
+ """Passing a non-dict returns None."""
+ assert manager.create_or_update_setting("not_a_dict") is None
+
+ def test_dict_without_key_returns_none(self, manager):
+ assert manager.create_or_update_setting({"value": 42}) is None
+
+ def test_does_not_mutate_input_dict(self, manager):
+ """The original dict should not be modified when value is typed."""
+ original = {
+ "key": "test.nomut",
+ "value": "42",
+ "ui_element": "number",
+ }
+ original_value = original["value"]
+ manager.create_or_update_setting(original)
+ # Original dict's value should remain unchanged
+ assert original["value"] == original_value
+
+ def test_setting_without_value_key(self, manager):
+ """A dict with 'key' but no 'value' should still be stored."""
+ result = manager.create_or_update_setting(
+ {"key": "test.noval", "ui_element": "text"}
+ )
+ assert result is not None
+ assert "test.noval" in manager.get_all_settings()
+
+
+# ---------------------------------------------------------------------------
+# import_settings — type conversion path
+# ---------------------------------------------------------------------------
+
+
+class TestImportSettingsTypedValues:
+ """import_settings applies _get_typed_value when value dicts are imported."""
+
+ def test_number_value_converted_on_import(self, manager):
+ manager.import_settings(
+ {"imp.num": {"value": "7", "ui_element": "number"}},
+ delete_extra=True,
+ )
+ # The stored value should be int 7 (whole-number float → int)
+ all_settings = manager.get_all_settings()
+ assert all_settings["imp.num"]["value"] == 7
+
+ def test_checkbox_value_converted_on_import(self, manager):
+ manager.import_settings(
+ {"imp.bool": {"value": "true", "ui_element": "checkbox"}},
+ delete_extra=True,
+ )
+ all_settings = manager.get_all_settings()
+ assert all_settings["imp.bool"]["value"] is True
+
+ def test_plain_value_stored_as_is(self, manager):
+ """Non-dict values are stored without type conversion."""
+ manager.import_settings(
+ {"imp.raw": "just_a_string"},
+ delete_extra=True,
+ )
+ all_settings = manager.get_all_settings()
+ assert all_settings["imp.raw"] == "just_a_string"
+
+
+# ---------------------------------------------------------------------------
+# extract_setting_value — additional corner cases
+# ---------------------------------------------------------------------------
+
+
+class TestExtractSettingValueEdgeCases:
+ def test_dict_without_value_key_returns_whole_dict(self):
+ """A dict that lacks 'value' is returned as-is (it's not a setting dict)."""
+ settings = {"key": {"other_field": "data"}}
+ result = extract_setting_value(settings, "key")
+ assert result == {"other_field": "data"}
+
+ def test_value_is_none_explicitly(self):
+ """When value is explicitly None, it should be returned (not default)."""
+ settings = {"key": {"value": None}}
+ result = extract_setting_value(settings, "key", default="fallback")
+ assert result is None
+
+ def test_value_is_zero(self):
+ """Falsy value 0 should be returned, not the default."""
+ settings = {"key": {"value": 0}}
+ result = extract_setting_value(settings, "key", default=99)
+ assert result == 0
+
+ def test_value_is_empty_string(self):
+ """Falsy value '' should be returned, not the default."""
+ settings = {"key": {"value": ""}}
+ result = extract_setting_value(settings, "key", default="fallback")
+ assert result == ""
+
+ def test_value_is_false(self):
+ """Falsy value False should be returned, not the default."""
+ settings = {"key": {"value": False}}
+ result = extract_setting_value(settings, "key", default=True)
+ assert result is False
+
+ def test_empty_snapshot(self):
+ result = extract_setting_value({}, "any", default="d")
+ assert result == "d"
+
+
+# ---------------------------------------------------------------------------
+# extract_bool_setting — additional edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestExtractBoolSettingEdgeCases:
+ def test_integer_1_is_true(self):
+ settings = {"flag": {"value": 1}}
+ assert extract_bool_setting(settings, "flag") is True
+
+ def test_integer_0_is_false(self):
+ settings = {"flag": {"value": 0}}
+ assert extract_bool_setting(settings, "flag") is False
+
+ def test_none_value_uses_default_true(self):
+ settings = {"flag": {"value": None}}
+ assert extract_bool_setting(settings, "flag", default=True) is True
+
+ def test_none_value_uses_default_false(self):
+ settings = {"flag": {"value": None}}
+ assert extract_bool_setting(settings, "flag", default=False) is False
+
+ def test_empty_string_is_false(self):
+ """Empty string is not in the truthy set, so it's False."""
+ settings = {"flag": {"value": ""}}
+ assert extract_bool_setting(settings, "flag") is False
+
+ def test_whitespace_string_true(self):
+ """to_bool strips whitespace before comparison."""
+ settings = {"flag": {"value": " true "}}
+ assert extract_bool_setting(settings, "flag") is True
+
+ def test_case_insensitive_TRUE(self):
+ settings = {"flag": {"value": "TRUE"}}
+ assert extract_bool_setting(settings, "flag") is True
+
+ def test_plain_value_not_dict(self):
+ """When value is stored directly (not in a dict with 'value' key)."""
+ settings = {"flag": "yes"}
+ assert extract_bool_setting(settings, "flag") is True
+
+ def test_none_snapshot_returns_default(self):
+ assert extract_bool_setting(None, "flag", default=True) is True
+
+ def test_string_enabled_is_true(self):
+ settings = {"flag": {"value": "enabled"}}
+ assert extract_bool_setting(settings, "flag") is True
+
+ def test_string_on_is_true(self):
+ settings = {"flag": {"value": "on"}}
+ assert extract_bool_setting(settings, "flag") is True
+
+ def test_arbitrary_string_is_false(self):
+ """An unrecognized string should be False."""
+ settings = {"flag": {"value": "maybe"}}
+ assert extract_bool_setting(settings, "flag") is False
diff --git a/tests/mcp/test_server_validators.py b/tests/mcp/test_server_validators.py
new file mode 100644
index 0000000000..148d5c6612
--- /dev/null
+++ b/tests/mcp/test_server_validators.py
@@ -0,0 +1,368 @@
+"""Tests for pure validation functions in local_deep_research.mcp.server."""
+
+from unittest.mock import patch
+
+import pytest
+
+# Skip all tests if MCP package is not installed
+try:
+ import mcp # noqa: F401
+
+ MCP_AVAILABLE = True
+except ImportError:
+ MCP_AVAILABLE = False
+
+pytestmark = pytest.mark.skipif(
+ not MCP_AVAILABLE, reason="MCP package not installed"
+)
+
+
+def _import_server():
+ """Lazy import to avoid collection-time failures when mcp is missing."""
+ from local_deep_research.mcp.server import (
+ ValidationError,
+ _build_settings_overrides,
+ _classify_error,
+ _validate_iterations,
+ _validate_max_results,
+ _validate_query,
+ _validate_questions_per_iteration,
+ _validate_temperature,
+ )
+
+ return {
+ "ValidationError": ValidationError,
+ "_build_settings_overrides": _build_settings_overrides,
+ "_classify_error": _classify_error,
+ "_validate_iterations": _validate_iterations,
+ "_validate_max_results": _validate_max_results,
+ "_validate_query": _validate_query,
+ "_validate_questions_per_iteration": _validate_questions_per_iteration,
+ "_validate_temperature": _validate_temperature,
+ }
+
+
+# ---------------------------------------------------------------------------
+# _classify_error
+# ---------------------------------------------------------------------------
+
+
+class TestClassifyError:
+ """Tests for _classify_error."""
+
+ @pytest.mark.parametrize(
+ "msg, expected",
+ [
+ ("503 Service Unavailable", "service_unavailable"),
+ ("server unavailable", "service_unavailable"),
+ ("404 Not Found", "model_not_found"),
+ ("resource not found", "model_not_found"),
+ ("API key invalid", "auth_error"),
+ ("authentication failed", "auth_error"),
+ ("unauthorized access", "auth_error"),
+ ("401 Unauthorized", "auth_error"),
+ ("connection timeout", "timeout"),
+ ("request timed out", "timeout"),
+ ("rate limit exceeded", "rate_limit"),
+ ("429 Too Many", "rate_limit"),
+ ("connection refused", "connection_error"),
+ ("validation failed", "validation_error"),
+ ("invalid parameter", "validation_error"),
+ ("some other error", "unknown"),
+ ("", "unknown"),
+ ],
+ )
+ def test_classification(self, msg, expected):
+ srv = _import_server()
+ assert srv["_classify_error"](msg) == expected
+
+
+# ---------------------------------------------------------------------------
+# _validate_query
+# ---------------------------------------------------------------------------
+
+
+class TestValidateQuery:
+ """Tests for _validate_query."""
+
+ def test_empty_string_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"], match="empty"):
+ srv["_validate_query"]("")
+
+ def test_whitespace_only_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"], match="empty"):
+ srv["_validate_query"](" ")
+
+ def test_none_raises(self):
+ srv = _import_server()
+ with pytest.raises((AttributeError, srv["ValidationError"])):
+ srv["_validate_query"](None)
+
+ def test_valid_query_returned(self):
+ srv = _import_server()
+ assert srv["_validate_query"]("valid query") == "valid query"
+
+ def test_strips_whitespace(self):
+ srv = _import_server()
+ assert srv["_validate_query"](" padded ") == "padded"
+
+ def test_exceeds_max_length(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"], match="exceeds maximum"):
+ srv["_validate_query"]("x" * 10001)
+
+ def test_exactly_at_max_length(self):
+ srv = _import_server()
+ query = "x" * 10000
+ assert srv["_validate_query"](query) == query
+
+
+# ---------------------------------------------------------------------------
+# _validate_iterations
+# ---------------------------------------------------------------------------
+
+
+class TestValidateIterations:
+ """Tests for _validate_iterations."""
+
+ def test_none_returns_none(self):
+ srv = _import_server()
+ assert srv["_validate_iterations"](None) is None
+
+ def test_valid_value(self):
+ srv = _import_server()
+ assert srv["_validate_iterations"](5) == 5
+
+ def test_zero_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"], match="positive integer"):
+ srv["_validate_iterations"](0)
+
+ def test_negative_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"], match="positive integer"):
+ srv["_validate_iterations"](-1)
+
+ def test_exceeds_default_max(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"], match="cannot exceed 20"):
+ srv["_validate_iterations"](21)
+
+ def test_at_default_max(self):
+ srv = _import_server()
+ assert srv["_validate_iterations"](20) == 20
+
+ def test_minimum_value(self):
+ srv = _import_server()
+ assert srv["_validate_iterations"](1) == 1
+
+ def test_string_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"]):
+ srv["_validate_iterations"]("5")
+
+ def test_float_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"]):
+ srv["_validate_iterations"](1.5)
+
+ def test_custom_max_val(self):
+ srv = _import_server()
+ assert srv["_validate_iterations"](10, max_val=10) == 10
+ with pytest.raises(srv["ValidationError"], match="cannot exceed 10"):
+ srv["_validate_iterations"](11, max_val=10)
+
+
+# ---------------------------------------------------------------------------
+# _validate_questions_per_iteration
+# ---------------------------------------------------------------------------
+
+
+class TestValidateQuestionsPerIteration:
+ """Tests for _validate_questions_per_iteration."""
+
+ def test_none_returns_none(self):
+ srv = _import_server()
+ assert srv["_validate_questions_per_iteration"](None) is None
+
+ def test_valid_value(self):
+ srv = _import_server()
+ assert srv["_validate_questions_per_iteration"](5) == 5
+
+ def test_zero_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"]):
+ srv["_validate_questions_per_iteration"](0)
+
+ def test_exceeds_max(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"], match="cannot exceed 10"):
+ srv["_validate_questions_per_iteration"](11)
+
+ def test_at_max(self):
+ srv = _import_server()
+ assert srv["_validate_questions_per_iteration"](10) == 10
+
+
+# ---------------------------------------------------------------------------
+# _validate_max_results
+# ---------------------------------------------------------------------------
+
+
+class TestValidateMaxResults:
+ """Tests for _validate_max_results."""
+
+ def test_valid_value(self):
+ srv = _import_server()
+ assert srv["_validate_max_results"](10) == 10
+
+ def test_zero_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"]):
+ srv["_validate_max_results"](0)
+
+ def test_negative_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"]):
+ srv["_validate_max_results"](-1)
+
+ def test_exceeds_max(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"], match="cannot exceed 100"):
+ srv["_validate_max_results"](101)
+
+ def test_at_max(self):
+ srv = _import_server()
+ assert srv["_validate_max_results"](100) == 100
+
+ def test_string_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"]):
+ srv["_validate_max_results"]("10")
+
+
+# ---------------------------------------------------------------------------
+# _validate_temperature
+# ---------------------------------------------------------------------------
+
+
+class TestValidateTemperature:
+ """Tests for _validate_temperature."""
+
+ def test_none_returns_none(self):
+ srv = _import_server()
+ assert srv["_validate_temperature"](None) is None
+
+ def test_valid_float(self):
+ srv = _import_server()
+ assert srv["_validate_temperature"](0.5) == 0.5
+
+ def test_zero(self):
+ srv = _import_server()
+ assert srv["_validate_temperature"](0.0) == 0.0
+
+ def test_max_boundary(self):
+ srv = _import_server()
+ assert srv["_validate_temperature"](2.0) == 2.0
+
+ def test_below_min_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"]):
+ srv["_validate_temperature"](-0.1)
+
+ def test_above_max_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"]):
+ srv["_validate_temperature"](2.1)
+
+ def test_string_raises(self):
+ srv = _import_server()
+ with pytest.raises(srv["ValidationError"], match="must be a number"):
+ srv["_validate_temperature"]("0.5")
+
+ def test_int_accepted_returns_float(self):
+ srv = _import_server()
+ result = srv["_validate_temperature"](1)
+ assert result == 1.0
+ assert isinstance(result, float)
+
+
+# ---------------------------------------------------------------------------
+# _build_settings_overrides
+# ---------------------------------------------------------------------------
+
+
+class TestBuildSettingsOverrides:
+ """Tests for _build_settings_overrides."""
+
+ @patch(
+ "local_deep_research.mcp.server._validate_strategy",
+ return_value="standard",
+ )
+ @patch(
+ "local_deep_research.mcp.server._validate_search_engine",
+ return_value="google",
+ )
+ def test_all_overrides(self, mock_engine, mock_strategy):
+ srv = _import_server()
+ result = srv["_build_settings_overrides"](
+ search_engine="google",
+ strategy="standard",
+ iterations=5,
+ questions_per_iteration=3,
+ temperature=0.7,
+ )
+ assert result["search.tool"] == "google"
+ assert result["search.search_strategy"] == "standard"
+ assert result["search.iterations"] == 5
+ assert result["search.questions_per_iteration"] == 3
+ assert result["llm.temperature"] == 0.7
+
+ @patch(
+ "local_deep_research.mcp.server._validate_strategy",
+ return_value=None,
+ )
+ @patch(
+ "local_deep_research.mcp.server._validate_search_engine",
+ return_value=None,
+ )
+ def test_all_none_returns_empty(self, mock_engine, mock_strategy):
+ srv = _import_server()
+ result = srv["_build_settings_overrides"]()
+ assert result == {}
+
+ @patch(
+ "local_deep_research.mcp.server._validate_strategy",
+ return_value=None,
+ )
+ @patch(
+ "local_deep_research.mcp.server._validate_search_engine",
+ return_value=None,
+ )
+ def test_only_some_params(self, mock_engine, mock_strategy):
+ srv = _import_server()
+ result = srv["_build_settings_overrides"](iterations=3, temperature=0.5)
+ assert result == {
+ "search.iterations": 3,
+ "llm.temperature": 0.5,
+ }
+ assert "search.tool" not in result
+ assert "search.search_strategy" not in result
+ assert "search.questions_per_iteration" not in result
+
+ @patch(
+ "local_deep_research.mcp.server._validate_strategy",
+ return_value=None,
+ )
+ @patch(
+ "local_deep_research.mcp.server._validate_search_engine",
+ return_value=None,
+ )
+ def test_engine_validates_to_none_not_added(
+ self, mock_engine, mock_strategy
+ ):
+ srv = _import_server()
+ result = srv["_build_settings_overrides"](search_engine="")
+ assert "search.tool" not in result
diff --git a/tests/test_search_system_gaps.py b/tests/test_search_system_gaps.py
new file mode 100644
index 0000000000..cd283c916f
--- /dev/null
+++ b/tests/test_search_system_gaps.py
@@ -0,0 +1,319 @@
+"""
+Gap tests for search_system.AdvancedSearchSystem.
+
+Focuses on testable pure logic:
+- Settings extraction for max_iterations / questions_per_iteration
+ (dict-with-value vs plain value vs missing -> default)
+- _perform_search settings extraction for llm_provider, llm_model, search_tool
+- close() resource cleanup
+- set_progress_callback propagation
+- analyze_topic generates search_id when not provided
+- all_links_of_system dedup (same-object identity check)
+"""
+
+from unittest.mock import Mock, patch
+
+
+# ---------------------------------------------------------------------------
+# Helper to create an AdvancedSearchSystem without hitting real imports
+# ---------------------------------------------------------------------------
+
+
+def _make_system(
+ settings_snapshot=None, strategy_name="source-based", **kwargs
+):
+ """Build an AdvancedSearchSystem with a mocked strategy factory."""
+ mock_llm = Mock()
+ mock_search = Mock()
+
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = {}
+ mock_strategy.all_links_of_system = []
+ mock_strategy.set_progress_callback = Mock()
+ mock_strategy.analyze_topic = Mock(
+ return_value={
+ "findings": [],
+ "current_knowledge": "",
+ }
+ )
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy",
+ return_value=mock_strategy,
+ ):
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=mock_llm,
+ search=mock_search,
+ strategy_name=strategy_name,
+ settings_snapshot=settings_snapshot,
+ **kwargs,
+ )
+ return system, mock_strategy
+
+
+# ---------------------------------------------------------------------------
+# __init__ -- max_iterations extraction
+# ---------------------------------------------------------------------------
+
+
+class TestMaxIterationsExtraction:
+ """AdvancedSearchSystem.__init__ reads max_iterations from settings."""
+
+ def test_explicit_value_takes_precedence(self):
+ system, _ = _make_system(
+ settings_snapshot={"search.iterations": {"value": 10}},
+ max_iterations=5,
+ )
+ assert system.max_iterations == 5
+
+ def test_dict_with_value_key(self):
+ system, _ = _make_system(
+ settings_snapshot={"search.iterations": {"value": 7}},
+ )
+ assert system.max_iterations == 7
+
+ def test_plain_value(self):
+ system, _ = _make_system(
+ settings_snapshot={"search.iterations": 4},
+ )
+ assert system.max_iterations == 4
+
+ def test_missing_defaults_to_1(self):
+ system, _ = _make_system(settings_snapshot={})
+ assert system.max_iterations == 1
+
+ def test_none_snapshot_defaults_to_1(self):
+ system, _ = _make_system(settings_snapshot=None)
+ assert system.max_iterations == 1
+
+
+# ---------------------------------------------------------------------------
+# __init__ -- questions_per_iteration extraction
+# ---------------------------------------------------------------------------
+
+
+class TestQuestionsPerIterationExtraction:
+ """AdvancedSearchSystem.__init__ reads questions_per_iteration from settings."""
+
+ def test_explicit_value_takes_precedence(self):
+ system, _ = _make_system(
+ settings_snapshot={"search.questions_per_iteration": {"value": 10}},
+ questions_per_iteration=2,
+ )
+ assert system.questions_per_iteration == 2
+
+ def test_dict_with_value_key(self):
+ system, _ = _make_system(
+ settings_snapshot={"search.questions_per_iteration": {"value": 5}},
+ )
+ assert system.questions_per_iteration == 5
+
+ def test_plain_value(self):
+ system, _ = _make_system(
+ settings_snapshot={"search.questions_per_iteration": 8},
+ )
+ assert system.questions_per_iteration == 8
+
+ def test_missing_defaults_to_3(self):
+ system, _ = _make_system(settings_snapshot={})
+ assert system.questions_per_iteration == 3
+
+
+# ---------------------------------------------------------------------------
+# _perform_search -- settings extraction for progress messages
+# ---------------------------------------------------------------------------
+
+
+class TestPerformSearchSettingsExtraction:
+ """_perform_search extracts provider/model/tool from settings snapshot."""
+
+ def _run_perform_search(self, system):
+ """Run _perform_search capturing progress callback calls."""
+ calls = []
+ system.progress_callback = lambda msg, pct, meta: calls.append(
+ (msg, pct, meta)
+ )
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback",
+ ):
+ try:
+ system._perform_search("q", "id1", True, False, "user1")
+ except Exception:
+ pass
+ return calls
+
+ def test_extracts_from_dict_with_value(self):
+ system, _ = _make_system(
+ settings_snapshot={
+ "llm.provider": {"value": "openai"},
+ "llm.model": {"value": "gpt-4"},
+ "search.tool": {"value": "google"},
+ },
+ )
+ calls = self._run_perform_search(system)
+ assert any("openai" in c[0] or "gpt-4" in c[0] for c in calls)
+
+ def test_extracts_plain_values(self):
+ system, _ = _make_system(
+ settings_snapshot={
+ "llm.provider": "anthropic",
+ "llm.model": "claude",
+ "search.tool": "searxng",
+ },
+ )
+ calls = self._run_perform_search(system)
+ assert any("anthropic" in c[0] or "claude" in c[0] for c in calls)
+
+ def test_missing_settings_use_unknown(self):
+ system, _ = _make_system(settings_snapshot={})
+ calls = self._run_perform_search(system)
+ assert any("unknown" in c[0] for c in calls)
+
+ def test_search_tool_default_from_dict(self):
+ """search.tool dict without 'value' key defaults to 'searxng'."""
+ system, _ = _make_system(
+ settings_snapshot={"search.tool": {"other": "x"}},
+ )
+ calls = self._run_perform_search(system)
+ # Should use the .get("value", "searxng") default
+ assert any("searxng" in c[0] for c in calls)
+
+
+# ---------------------------------------------------------------------------
+# all_links_of_system -- identity-based dedup
+# ---------------------------------------------------------------------------
+
+
+class TestAllLinksDedup:
+ """_perform_search avoids extending all_links when objects are same."""
+
+ def test_same_object_no_duplication(self):
+ """When strategy.all_links_of_system IS system.all_links_of_system,
+ no extension should happen (prevents issue #301)."""
+ system, mock_strategy = _make_system(settings_snapshot={})
+
+ # Make them the same object
+ mock_strategy.all_links_of_system = system.all_links_of_system
+ system.all_links_of_system.append({"link": "https://a.com"})
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback",
+ ):
+ try:
+ system._perform_search("q", "id1", True, False, "user1")
+ except Exception:
+ pass
+
+ # Should NOT be doubled
+ assert len(system.all_links_of_system) == 1
+
+ def test_different_objects_extends(self):
+ """When they are different objects, links should be extended."""
+ system, mock_strategy = _make_system(settings_snapshot={})
+
+ mock_strategy.all_links_of_system = [{"link": "https://b.com"}]
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback",
+ ):
+ try:
+ system._perform_search("q", "id1", True, False, "user1")
+ except Exception:
+ pass
+
+ assert {"link": "https://b.com"} in system.all_links_of_system
+
+
+# ---------------------------------------------------------------------------
+# close() -- resource cleanup
+# ---------------------------------------------------------------------------
+
+
+class TestClose:
+ """AdvancedSearchSystem.close cascades to strategy."""
+
+ def test_close_calls_safe_close_on_strategy(self):
+ system, mock_strategy = _make_system(settings_snapshot={})
+
+ with patch(
+ "local_deep_research.utilities.resource_utils.safe_close"
+ ) as mock_safe_close:
+ system.close()
+ mock_safe_close.assert_called_once_with(
+ mock_strategy, "search strategy"
+ )
+
+ def test_close_without_strategy_attribute(self):
+ """close() should not raise if strategy attribute is missing."""
+ system, _ = _make_system(settings_snapshot={})
+ del system.strategy
+
+ with patch(
+ "local_deep_research.utilities.resource_utils.safe_close"
+ ) as mock_safe_close:
+ system.close() # should not raise
+ mock_safe_close.assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# set_progress_callback
+# ---------------------------------------------------------------------------
+
+
+class TestSetProgressCallback:
+ def test_callback_set_on_system_and_strategy(self):
+ system, mock_strategy = _make_system(settings_snapshot={})
+
+ cb = Mock()
+ system.set_progress_callback(cb)
+
+ assert system.progress_callback is cb
+ mock_strategy.set_progress_callback.assert_called_with(cb)
+
+
+# ---------------------------------------------------------------------------
+# analyze_topic -- search_id auto-generation
+# ---------------------------------------------------------------------------
+
+
+class TestAnalyzeTopicSearchId:
+ def test_generates_uuid_when_search_id_is_none(self):
+ system, _ = _make_system(settings_snapshot={})
+
+ with patch.object(
+ system, "_perform_search", return_value={}
+ ) as mock_ps:
+ system.analyze_topic("test query")
+ args = mock_ps.call_args
+ search_id = args[0][1] # second positional arg
+ # Should be a valid UUID string (36 chars with hyphens)
+ assert len(search_id) == 36
+ assert search_id.count("-") == 4
+
+ def test_uses_provided_search_id(self):
+ system, _ = _make_system(settings_snapshot={})
+
+ with patch.object(
+ system, "_perform_search", return_value={}
+ ) as mock_ps:
+ system.analyze_topic("test query", search_id="custom-id")
+ args = mock_ps.call_args
+ search_id = args[0][1]
+ assert search_id == "custom-id"
+
+
+# ---------------------------------------------------------------------------
+# programmatic_mode flag
+# ---------------------------------------------------------------------------
+
+
+class TestProgrammaticMode:
+ def test_programmatic_mode_stored(self):
+ system, _ = _make_system(settings_snapshot={}, programmatic_mode=True)
+ assert system.programmatic_mode is True
+
+ def test_non_programmatic_mode_default(self):
+ system, _ = _make_system(settings_snapshot={})
+ assert system.programmatic_mode is False
diff --git a/tests/web/auth/test_password_utils_gaps.py b/tests/web/auth/test_password_utils_gaps.py
new file mode 100644
index 0000000000..75ae611b05
--- /dev/null
+++ b/tests/web/auth/test_password_utils_gaps.py
@@ -0,0 +1,207 @@
+"""Tests for get_user_password fallback chain in password_utils."""
+
+from unittest.mock import MagicMock, patch
+
+import flask
+
+from local_deep_research.web.auth.password_utils import get_user_password
+
+MODULE = "local_deep_research.web.auth.password_utils"
+
+
+class TestGetUserPassword:
+ """Tests for the 3-source fallback chain in get_user_password."""
+
+ def test_returns_password_from_session_store(self):
+ """Path 1: session_password_store has a password for the user."""
+ app = flask.Flask(__name__)
+ with app.test_request_context():
+ mock_store = MagicMock()
+ mock_store.get_session_password.return_value = "stored_pass"
+ with (
+ patch(f"{MODULE}.session", {"session_id": "sid123"}),
+ patch(
+ f"{MODULE}.session_password_store",
+ mock_store,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ mock_store,
+ ),
+ ):
+ result = get_user_password("alice")
+ assert result == "stored_pass"
+ mock_store.get_session_password.assert_called_once_with(
+ "alice", "sid123"
+ )
+
+ def test_returns_password_from_flask_g(self):
+ """Path 2: no session password, but g.user_password is set."""
+ app = flask.Flask(__name__)
+ with app.test_request_context():
+ mock_store = MagicMock()
+ mock_store.get_session_password.return_value = None
+ with (
+ patch(f"{MODULE}.session", {"session_id": "sid1"}),
+ patch(
+ f"{MODULE}.session_password_store",
+ mock_store,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ mock_store,
+ ),
+ patch(f"{MODULE}.g") as mock_g,
+ ):
+ mock_g.user_password = "g_password"
+ # Make getattr work on the mock
+ type(mock_g).user_password = "g_password"
+ result = get_user_password("bob")
+ assert result == "g_password"
+
+ def test_returns_password_from_temp_auth_token(self):
+ """Path 3: temp_auth_token matches username in temp_auth_store."""
+ app = flask.Flask(__name__)
+ with app.test_request_context():
+ mock_session_store = MagicMock()
+ mock_session_store.get_session_password.return_value = None
+ mock_temp_store = MagicMock()
+ mock_temp_store.peek_auth.return_value = ("carol", "temp_pass")
+
+ mock_session = MagicMock()
+ mock_session.get.side_effect = lambda k, *a: {
+ "session_id": "sid2",
+ "temp_auth_token": "tok42",
+ }.get(k, *a)
+
+ with (
+ patch(f"{MODULE}.session", mock_session),
+ patch(
+ f"{MODULE}.session_password_store",
+ mock_session_store,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ mock_session_store,
+ ),
+ patch(f"{MODULE}.g") as mock_g,
+ patch(
+ "local_deep_research.database.temp_auth.temp_auth_store",
+ mock_temp_store,
+ ),
+ ):
+ mock_g.user_password = None
+ type(mock_g).user_password = None
+ result = get_user_password("carol")
+ assert result == "temp_pass"
+ mock_temp_store.peek_auth.assert_called_once_with("tok42")
+
+ def test_returns_none_when_nothing_found(self):
+ """Path 4: none of the sources have a password."""
+ app = flask.Flask(__name__)
+ with app.test_request_context():
+ mock_session_store = MagicMock()
+ mock_session_store.get_session_password.return_value = None
+ mock_temp_store = MagicMock()
+ mock_temp_store.peek_auth.return_value = None
+
+ mock_session = MagicMock()
+ mock_session.get.side_effect = lambda k, *a: {
+ "session_id": "sid3",
+ "temp_auth_token": "tok99",
+ }.get(k, *a)
+
+ with (
+ patch(f"{MODULE}.session", mock_session),
+ patch(
+ f"{MODULE}.session_password_store",
+ mock_session_store,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ mock_session_store,
+ ),
+ patch(f"{MODULE}.g") as mock_g,
+ patch(
+ "local_deep_research.database.temp_auth.temp_auth_store",
+ mock_temp_store,
+ ),
+ ):
+ mock_g.user_password = None
+ type(mock_g).user_password = None
+ result = get_user_password("dave")
+ assert result is None
+
+ def test_returns_none_when_temp_auth_username_mismatch(self):
+ """Path 5: temp_auth_token exists but username doesn't match."""
+ app = flask.Flask(__name__)
+ with app.test_request_context():
+ mock_session_store = MagicMock()
+ mock_session_store.get_session_password.return_value = None
+ mock_temp_store = MagicMock()
+ # Token belongs to "other_user", not "eve"
+ mock_temp_store.peek_auth.return_value = (
+ "other_user",
+ "some_pass",
+ )
+
+ mock_session = MagicMock()
+ mock_session.get.side_effect = lambda k, *a: {
+ "session_id": "sid4",
+ "temp_auth_token": "tok77",
+ }.get(k, *a)
+
+ with (
+ patch(f"{MODULE}.session", mock_session),
+ patch(
+ f"{MODULE}.session_password_store",
+ mock_session_store,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ mock_session_store,
+ ),
+ patch(f"{MODULE}.g") as mock_g,
+ patch(
+ "local_deep_research.database.temp_auth.temp_auth_store",
+ mock_temp_store,
+ ),
+ ):
+ mock_g.user_password = None
+ type(mock_g).user_password = None
+ result = get_user_password("eve")
+ assert result is None
+
+ def test_no_session_id_skips_session_store(self):
+ """Path 6: no session_id so session password store is skipped."""
+ app = flask.Flask(__name__)
+ with app.test_request_context():
+ mock_session_store = MagicMock()
+ # Should never be called
+ mock_session_store.get_session_password.return_value = (
+ "SHOULD_NOT_USE"
+ )
+
+ with (
+ patch(f"{MODULE}.session", {"session_id": None}),
+ patch(
+ f"{MODULE}.session_password_store",
+ mock_session_store,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ mock_session_store,
+ ),
+ patch(f"{MODULE}.g") as mock_g,
+ ):
+ mock_g.user_password = "from_g"
+ type(mock_g).user_password = "from_g"
+ result = get_user_password("frank")
+ assert result == "from_g"
+ mock_session_store.get_session_password.assert_not_called()
diff --git a/tests/web/routes/test_route_registry_gaps.py b/tests/web/routes/test_route_registry_gaps.py
new file mode 100644
index 0000000000..df4fb56e91
--- /dev/null
+++ b/tests/web/routes/test_route_registry_gaps.py
@@ -0,0 +1,135 @@
+"""Tests for route_registry functions and data structure."""
+
+from local_deep_research.web.routes.route_registry import (
+ ROUTE_REGISTRY,
+ find_route,
+ get_all_routes,
+ get_routes_by_blueprint,
+)
+
+
+class TestGetAllRoutes:
+ """Tests for get_all_routes()."""
+
+ def test_returns_list(self):
+ result = get_all_routes()
+ assert isinstance(result, list)
+
+ def test_each_item_has_required_keys(self):
+ required_keys = {
+ "method",
+ "path",
+ "endpoint",
+ "description",
+ "blueprint",
+ }
+ for route in get_all_routes():
+ assert required_keys <= route.keys(), (
+ f"Route missing keys: {required_keys - route.keys()}"
+ )
+
+ def test_prefixed_routes_have_prefix_prepended(self):
+ """Routes from blueprints with a url_prefix get that prefix in the path."""
+ routes = get_all_routes()
+ settings_routes = [r for r in routes if r["blueprint"] == "settings"]
+ assert settings_routes, "Expected settings routes"
+ for route in settings_routes:
+ assert route["path"].startswith("/settings"), route["path"]
+
+ def test_no_prefix_routes_have_no_prefix(self):
+ """Routes with url_prefix=None keep their original path."""
+ routes = get_all_routes()
+ research_routes = [r for r in routes if r["blueprint"] == "research"]
+ assert research_routes, "Expected research routes"
+ # The research blueprint has url_prefix=None, so paths should not
+ # be double-prefixed — they start with "/" directly.
+ for route in research_routes:
+ assert not route["path"].startswith("None"), route["path"]
+
+ def test_contains_routes_from_all_blueprints(self):
+ routes = get_all_routes()
+ blueprints_in_routes = {r["blueprint"] for r in routes}
+ assert blueprints_in_routes == set(ROUTE_REGISTRY.keys())
+
+
+class TestGetRoutesByBlueprint:
+ """Tests for get_routes_by_blueprint()."""
+
+ def test_known_blueprint_returns_routes(self):
+ result = get_routes_by_blueprint("settings")
+ assert len(result) > 0
+
+ def test_unknown_blueprint_returns_empty_list(self):
+ result = get_routes_by_blueprint("nonexistent_blueprint_xyz")
+ assert result == []
+
+ def test_routes_have_required_keys(self):
+ required_keys = {"method", "path", "endpoint", "description"}
+ for route in get_routes_by_blueprint("settings"):
+ assert required_keys <= route.keys()
+
+ def test_settings_routes_have_settings_prefix(self):
+ routes = get_routes_by_blueprint("settings")
+ for route in routes:
+ assert route["path"].startswith("/settings"), route["path"]
+
+ def test_research_routes_have_no_prefix(self):
+ """research blueprint has url_prefix=None so paths are root-level."""
+ routes = get_routes_by_blueprint("research")
+ assert routes, "Expected research routes"
+ # First route is "/" — just confirm no double prefix
+ assert routes[0]["path"] == "/"
+
+
+class TestFindRoute:
+ """Tests for find_route()."""
+
+ def test_case_insensitive_match(self):
+ lower = find_route("api")
+ upper = find_route("API")
+ assert len(lower) == len(upper)
+ assert len(lower) > 0
+
+ def test_api_finds_multiple_routes(self):
+ results = find_route("api")
+ assert len(results) > 1
+
+ def test_nonexistent_pattern_returns_empty(self):
+ results = find_route("nonexistent_xyz")
+ assert results == []
+
+ def test_settings_pattern_finds_settings_routes(self):
+ results = find_route("settings")
+ assert len(results) > 0
+ for route in results:
+ assert "settings" in route["path"].lower()
+
+ def test_empty_string_matches_all(self):
+ all_routes = get_all_routes()
+ results = find_route("")
+ assert len(results) == len(all_routes)
+
+
+class TestRouteRegistryDataStructure:
+ """Tests for the ROUTE_REGISTRY dict itself."""
+
+ def test_is_dict(self):
+ assert isinstance(ROUTE_REGISTRY, dict)
+
+ def test_contains_expected_blueprints(self):
+ for key in ("research", "settings", "history", "metrics"):
+ assert key in ROUTE_REGISTRY, f"Missing blueprint: {key}"
+
+ def test_each_value_has_required_keys(self):
+ required = {"blueprint", "url_prefix", "routes"}
+ for name, info in ROUTE_REGISTRY.items():
+ assert required <= info.keys(), (
+ f"Blueprint '{name}' missing: {required - info.keys()}"
+ )
+
+ def test_each_route_tuple_has_four_elements(self):
+ for name, info in ROUTE_REGISTRY.items():
+ for route in info["routes"]:
+ assert len(route) == 4, (
+ f"Blueprint '{name}' route {route} has {len(route)} elements"
+ )