Skip to content

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

test: add 90 high-value tests across 8 modules targeting untested code paths (round 4) (#2240)

LearningCircuit899ec3867d80
diff --git a/tests/advanced_search_system/findings/test_format_links.py b/tests/advanced_search_system/findings/test_format_links.py
new file mode 100644
index 0000000000..b1ed61a008
--- /dev/null
+++ b/tests/advanced_search_system/findings/test_format_links.py
@@ -0,0 +1,86 @@
+"""
+Tests for format_links() in advanced_search_system/findings/repository.py
+
+Tests cover:
+- Single link formatting
+- Multiple links with correct numbering
+- Numbering starts at 1
+- Title and URL in output
+- Empty list
+- Special characters in title and URL
+"""
+
+from local_deep_research.advanced_search_system.findings.repository import (
+ format_links,
+)
+
+
+class TestFormatLinks:
+ """Tests for format_links()."""
+
+ def test_single_link(self):
+ """Single link is formatted with number 1."""
+ links = [{"title": "Example", "url": "https://example.com"}]
+ result = format_links(links)
+ assert "1." in result
+ assert "Example" in result
+ assert "https://example.com" in result
+
+ def test_multiple_links(self):
+ """Multiple links are formatted with incrementing numbers."""
+ links = [
+ {"title": "First", "url": "https://first.com"},
+ {"title": "Second", "url": "https://second.com"},
+ {"title": "Third", "url": "https://third.com"},
+ ]
+ result = format_links(links)
+ assert "1." in result
+ assert "2." in result
+ assert "3." in result
+
+ def test_numbering_starts_at_1(self):
+ """First link is numbered 1, not 0."""
+ links = [{"title": "Test", "url": "https://test.com"}]
+ result = format_links(links)
+ assert result.startswith("1.")
+ assert "0." not in result
+
+ def test_title_and_url_on_separate_lines(self):
+ """Title and URL appear with URL on indented line."""
+ links = [{"title": "My Title", "url": "https://example.com/page"}]
+ result = format_links(links)
+ lines = result.split("\n")
+ assert len(lines) == 2
+ assert "My Title" in lines[0]
+ assert "URL:" in lines[1]
+ assert "https://example.com/page" in lines[1]
+
+ def test_empty_list(self):
+ """Empty list returns empty string."""
+ result = format_links([])
+ assert result == ""
+
+ def test_special_characters_in_title(self):
+ """Special characters in title are preserved."""
+ links = [{"title": "Q&A <Guide> 'Test'", "url": "https://example.com"}]
+ result = format_links(links)
+ assert "Q&A <Guide> 'Test'" in result
+
+ def test_special_characters_in_url(self):
+ """Special characters in URL are preserved."""
+ links = [
+ {"title": "Test", "url": "https://example.com/path?q=hello&lang=en"}
+ ]
+ result = format_links(links)
+ assert "https://example.com/path?q=hello&lang=en" in result
+
+ def test_multiline_output_for_multiple_links(self):
+ """Each link produces two lines (title + URL)."""
+ links = [
+ {"title": "A", "url": "https://a.com"},
+ {"title": "B", "url": "https://b.com"},
+ ]
+ result = format_links(links)
+ # 2 links × 2 lines each, joined with newline between link blocks
+ lines = result.split("\n")
+ assert len(lines) == 4
diff --git a/tests/api/test_settings_snapshot.py b/tests/api/test_settings_snapshot.py
new file mode 100644
index 0000000000..97c5b1fa1c
--- /dev/null
+++ b/tests/api/test_settings_snapshot.py
@@ -0,0 +1,151 @@
+"""
+Tests for InMemorySettingsManager.get_settings_snapshot() and import_settings()
+in api/settings_utils.py.
+
+Tests cover:
+- get_settings_snapshot: full format extraction, simplified format passthrough, mixed
+- import_settings: overwrite=True, overwrite=False, delete_extra, type handling, empty
+"""
+
+from unittest.mock import patch, MagicMock
+
+
+def _make_manager_with_settings(settings_dict):
+ """Create an InMemorySettingsManager with pre-loaded settings (no disk I/O)."""
+ with patch(
+ "local_deep_research.api.settings_utils.InMemorySettingsManager.__init__",
+ lambda self: None,
+ ):
+ from local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ mgr = InMemorySettingsManager()
+ mgr._settings = settings_dict.copy()
+ mgr._base_manager = MagicMock()
+ return mgr
+
+
+class TestGetSettingsSnapshot:
+ """Tests for get_settings_snapshot()."""
+
+ def test_full_format_extracts_value(self):
+ """Dict-with-value entries → snapshot has just the value."""
+ mgr = _make_manager_with_settings(
+ {"key1": {"value": 42, "ui_element": "number"}}
+ )
+ snapshot = mgr.get_settings_snapshot()
+ assert snapshot["key1"] == 42
+
+ def test_simplified_format_passthrough(self):
+ """Non-dict or dict-without-value entries pass through as-is."""
+ mgr = _make_manager_with_settings({"key1": "simple_value"})
+ snapshot = mgr.get_settings_snapshot()
+ assert snapshot["key1"] == "simple_value"
+
+ def test_mixed_formats(self):
+ """Mix of full and simplified formats in one snapshot."""
+ mgr = _make_manager_with_settings(
+ {
+ "full_key": {"value": True, "ui_element": "checkbox"},
+ "simple_key": 100,
+ "dict_no_value": {"other": "data"},
+ }
+ )
+ snapshot = mgr.get_settings_snapshot()
+ assert snapshot["full_key"] is True
+ assert snapshot["simple_key"] == 100
+ assert snapshot["dict_no_value"] == {"other": "data"}
+
+ def test_empty_settings(self):
+ """Empty settings → empty snapshot."""
+ mgr = _make_manager_with_settings({})
+ assert mgr.get_settings_snapshot() == {}
+
+ def test_none_value_in_full_format(self):
+ """Full format with value=None → snapshot has None."""
+ mgr = _make_manager_with_settings(
+ {"key": {"value": None, "ui_element": "text"}}
+ )
+ snapshot = mgr.get_settings_snapshot()
+ assert snapshot["key"] is None
+
+ def test_snapshot_is_independent_copy(self):
+ """Modifying snapshot doesn't affect internal settings."""
+ mgr = _make_manager_with_settings(
+ {"key": {"value": "original", "ui_element": "text"}}
+ )
+ snapshot = mgr.get_settings_snapshot()
+ snapshot["key"] = "modified"
+ # Internal still has original value
+ assert mgr._settings["key"]["value"] == "original"
+
+ def test_list_value(self):
+ """Full format with list value → snapshot has the list."""
+ mgr = _make_manager_with_settings(
+ {"key": {"value": [1, 2, 3], "ui_element": "text"}}
+ )
+ snapshot = mgr.get_settings_snapshot()
+ assert snapshot["key"] == [1, 2, 3]
+
+
+class TestImportSettings:
+ """Tests for import_settings()."""
+
+ def test_import_overwrites_existing(self):
+ """overwrite=True replaces existing settings."""
+ mgr = _make_manager_with_settings({"key1": "old_value"})
+ mgr.import_settings({"key1": "new_value"}, overwrite=True)
+ assert mgr._settings["key1"] == "new_value"
+
+ def test_import_no_overwrite_skips_existing(self):
+ """overwrite=False skips keys that already exist."""
+ mgr = _make_manager_with_settings({"key1": "original"})
+ mgr.import_settings({"key1": "ignored", "key2": "new"}, overwrite=False)
+ assert mgr._settings["key1"] == "original"
+ assert mgr._settings["key2"] == "new"
+
+ def test_import_adds_new_keys(self):
+ """New keys are always added regardless of overwrite flag."""
+ mgr = _make_manager_with_settings({})
+ mgr.import_settings({"new_key": "value"}, overwrite=False)
+ assert mgr._settings["new_key"] == "value"
+
+ def test_delete_extra_clears_first(self):
+ """delete_extra=True clears existing settings before importing."""
+ mgr = _make_manager_with_settings({"old_key": "old_value"})
+ mgr.import_settings({"new_key": "new_value"}, delete_extra=True)
+ assert "old_key" not in mgr._settings
+ assert mgr._settings["new_key"] == "new_value"
+
+ def test_delete_extra_false_preserves(self):
+ """delete_extra=False preserves existing settings."""
+ mgr = _make_manager_with_settings({"old_key": "old_value"})
+ mgr.import_settings({"new_key": "new_value"}, delete_extra=False)
+ assert "old_key" in mgr._settings
+ assert "new_key" in mgr._settings
+
+ def test_import_full_format_with_type_conversion(self):
+ """Full format dicts get _get_typed_value applied."""
+ mgr = _make_manager_with_settings({})
+ mgr._get_typed_value = MagicMock(return_value=42)
+ mgr.import_settings(
+ {"key": {"value": "42", "ui_element": "number"}}, overwrite=True
+ )
+ mgr._get_typed_value.assert_called()
+ # Value should be the typed result
+ assert mgr._settings["key"]["value"] == 42
+
+ def test_import_simple_value_no_type_conversion(self):
+ """Simple (non-dict) values are stored as-is without type conversion."""
+ mgr = _make_manager_with_settings({})
+ mgr._get_typed_value = MagicMock()
+ mgr.import_settings({"key": "plain_string"}, overwrite=True)
+ mgr._get_typed_value.assert_not_called()
+ assert mgr._settings["key"] == "plain_string"
+
+ def test_import_empty_dict(self):
+ """Importing empty dict changes nothing."""
+ mgr = _make_manager_with_settings({"existing": "value"})
+ mgr.import_settings({})
+ assert mgr._settings["existing"] == "value"
diff --git a/tests/config/test_thread_settings_child_keys.py b/tests/config/test_thread_settings_child_keys.py
new file mode 100644
index 0000000000..8d8aa486b6
--- /dev/null
+++ b/tests/config/test_thread_settings_child_keys.py
@@ -0,0 +1,233 @@
+"""
+Tests for get_setting_from_snapshot() child key search logic
+in config/thread_settings.py.
+
+Tests cover:
+- Exact key match (full and simplified format)
+- Child key aggregation (prefix.suffix → {suffix: value})
+- Multiple child keys
+- NoSettingsContextError when no default and no match
+- Default returned when key missing
+- Interaction with check_fallback_llm
+"""
+
+import pytest
+
+
+class TestGetSettingFromSnapshotExactMatch:
+ """Tests for exact key matching in get_setting_from_snapshot()."""
+
+ def test_exact_key_full_format(self):
+ """Exact key match with full format dict extracts typed value."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ snapshot = {"search.engine": {"value": "google", "ui_element": "text"}}
+ result = get_setting_from_snapshot(
+ "search.engine", settings_snapshot=snapshot
+ )
+ assert result == "google"
+
+ def test_exact_key_simplified_format(self):
+ """Exact key match with simplified value returns value directly."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ snapshot = {"search.engine": "google"}
+ result = get_setting_from_snapshot(
+ "search.engine", settings_snapshot=snapshot
+ )
+ assert result == "google"
+
+ def test_exact_key_integer_value(self):
+ """Exact key with integer value works."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ snapshot = {"max_results": 50}
+ result = get_setting_from_snapshot(
+ "max_results", settings_snapshot=snapshot
+ )
+ assert result == 50
+
+ def test_exact_key_boolean_value(self):
+ """Exact key with boolean value works."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ snapshot = {"enabled": True}
+ result = get_setting_from_snapshot(
+ "enabled", settings_snapshot=snapshot
+ )
+ assert result is True
+
+
+class TestGetSettingFromSnapshotChildKeys:
+ """Tests for child key aggregation logic."""
+
+ def test_single_child_key(self):
+ """Single child key builds a dict with just that suffix."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ snapshot = {"search.engine": "google"}
+ result = get_setting_from_snapshot("search", settings_snapshot=snapshot)
+ assert isinstance(result, dict)
+ assert result["engine"] == "google"
+
+ def test_multiple_child_keys(self):
+ """Multiple child keys are aggregated into one dict."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ snapshot = {
+ "search.engine": "google",
+ "search.timeout": 30,
+ "search.retries": 3,
+ }
+ result = get_setting_from_snapshot("search", settings_snapshot=snapshot)
+ assert result == {"engine": "google", "timeout": 30, "retries": 3}
+
+ def test_child_keys_full_format(self):
+ """Child keys with full format dicts extract values."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ snapshot = {
+ "search.engine": {"value": "bing", "ui_element": "text"},
+ }
+ result = get_setting_from_snapshot("search", settings_snapshot=snapshot)
+ assert isinstance(result, dict)
+ assert result["engine"] == "bing"
+
+ def test_no_child_keys_match(self):
+ """No child keys match → falls through to default/error."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ snapshot = {"other.key": "value"}
+ result = get_setting_from_snapshot(
+ "search", default="fallback", settings_snapshot=snapshot
+ )
+ assert result == "fallback"
+
+ def test_child_keys_not_confused_with_partial_prefix(self):
+ """Key 'search_extra.foo' should NOT match prefix 'search.'."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ snapshot = {
+ "search_extra.engine": "nope",
+ "search.engine": "yes",
+ }
+ result = get_setting_from_snapshot("search", settings_snapshot=snapshot)
+ assert result == {"engine": "yes"}
+
+
+class TestGetSettingFromSnapshotDefaults:
+ """Tests for default values and error raising."""
+
+ def test_default_returned_when_key_missing(self):
+ """When key not in snapshot and default given, return default."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ result = get_setting_from_snapshot(
+ "nonexistent", default=42, settings_snapshot={"other": "val"}
+ )
+ assert result == 42
+
+ def test_no_settings_context_error_no_default(self):
+ """No snapshot match, no context, no default → NoSettingsContextError."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ NoSettingsContextError,
+ )
+
+ with pytest.raises(NoSettingsContextError):
+ get_setting_from_snapshot(
+ "missing_key", settings_snapshot={"other": "val"}
+ )
+
+ def test_none_default_still_raises(self):
+ """default=None (the default) still raises NoSettingsContextError."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ NoSettingsContextError,
+ )
+
+ with pytest.raises(NoSettingsContextError):
+ get_setting_from_snapshot(
+ "missing_key", default=None, settings_snapshot={"other": "val"}
+ )
+
+ def test_empty_snapshot_with_default(self):
+ """Empty snapshot with default returns the default."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ result = get_setting_from_snapshot(
+ "key", default="default_val", settings_snapshot={}
+ )
+ assert result == "default_val"
+
+ def test_none_snapshot_with_default(self):
+ """None snapshot with default returns the default."""
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ result = get_setting_from_snapshot(
+ "key", default="fallback", settings_snapshot=None
+ )
+ assert result == "fallback"
+
+
+class TestGetSettingFromSnapshotFallbackLlm:
+ """Tests for check_fallback_llm behavior."""
+
+ def test_fallback_llm_env_returns_default(self, monkeypatch):
+ """With LDR_USE_FALLBACK_LLM set, returns default."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")
+ monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)
+
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ result = get_setting_from_snapshot(
+ "missing",
+ default="fallback_val",
+ settings_snapshot={"other": "x"},
+ check_fallback_llm=True,
+ )
+ assert result == "fallback_val"
+
+ def test_testing_with_mocks_skips_fallback(self, monkeypatch):
+ """With both LDR_USE_FALLBACK_LLM and LDR_TESTING_WITH_MOCKS, doesn't use fallback path."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")
+ monkeypatch.setenv("LDR_TESTING_WITH_MOCKS", "1")
+
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ # Should not short-circuit to fallback — should return default via normal path
+ result = get_setting_from_snapshot(
+ "missing",
+ default="normal_default",
+ settings_snapshot={"other": "x"},
+ check_fallback_llm=True,
+ )
+ assert result == "normal_default"
diff --git a/tests/database/test_kdf_iterations.py b/tests/database/test_kdf_iterations.py
new file mode 100644
index 0000000000..d9f529d016
--- /dev/null
+++ b/tests/database/test_kdf_iterations.py
@@ -0,0 +1,100 @@
+"""
+Tests for _get_min_kdf_iterations() in database/sqlcipher_utils.py
+
+Tests cover:
+- Production mode (no test env vars) returns 100K iterations
+- PYTEST_CURRENT_TEST env var triggers test mode (1 iteration)
+- LDR_TEST_MODE env var triggers test mode (1 iteration)
+- Both env vars set → still returns 1
+- Constants have correct values
+"""
+
+
+class TestGetMinKdfIterations:
+ """Tests for _get_min_kdf_iterations()."""
+
+ def test_production_mode_returns_100k(self, monkeypatch):
+ """No test env vars → production iterations (100_000)."""
+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)
+ monkeypatch.delenv("LDR_TEST_MODE", raising=False)
+
+ from local_deep_research.database.sqlcipher_utils import (
+ _get_min_kdf_iterations,
+ )
+
+ assert _get_min_kdf_iterations() == 100_000
+
+ def test_pytest_current_test_triggers_test_mode(self, monkeypatch):
+ """PYTEST_CURRENT_TEST set → test iterations (1)."""
+ monkeypatch.setenv("PYTEST_CURRENT_TEST", "tests/test_foo.py::test_bar")
+ monkeypatch.delenv("LDR_TEST_MODE", raising=False)
+
+ from local_deep_research.database.sqlcipher_utils import (
+ _get_min_kdf_iterations,
+ )
+
+ assert _get_min_kdf_iterations() == 1
+
+ def test_ldr_test_mode_triggers_test_mode(self, monkeypatch):
+ """LDR_TEST_MODE set → test iterations (1)."""
+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)
+ monkeypatch.setenv("LDR_TEST_MODE", "1")
+
+ from local_deep_research.database.sqlcipher_utils import (
+ _get_min_kdf_iterations,
+ )
+
+ assert _get_min_kdf_iterations() == 1
+
+ def test_both_env_vars_set(self, monkeypatch):
+ """Both env vars set → still returns test iterations."""
+ monkeypatch.setenv("PYTEST_CURRENT_TEST", "tests/test_foo.py::test_bar")
+ monkeypatch.setenv("LDR_TEST_MODE", "1")
+
+ from local_deep_research.database.sqlcipher_utils import (
+ _get_min_kdf_iterations,
+ )
+
+ assert _get_min_kdf_iterations() == 1
+
+ def test_empty_pytest_current_test_is_production(self, monkeypatch):
+ """Empty string for PYTEST_CURRENT_TEST is falsy → production mode."""
+ monkeypatch.setenv("PYTEST_CURRENT_TEST", "")
+ monkeypatch.delenv("LDR_TEST_MODE", raising=False)
+
+ from local_deep_research.database.sqlcipher_utils import (
+ _get_min_kdf_iterations,
+ )
+
+ assert _get_min_kdf_iterations() == 100_000
+
+ def test_empty_ldr_test_mode_is_production(self, monkeypatch):
+ """Empty string for LDR_TEST_MODE is falsy → production mode."""
+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)
+ monkeypatch.setenv("LDR_TEST_MODE", "")
+
+ from local_deep_research.database.sqlcipher_utils import (
+ _get_min_kdf_iterations,
+ )
+
+ assert _get_min_kdf_iterations() == 100_000
+
+
+class TestKdfConstants:
+ """Tests for KDF iteration constants."""
+
+ def test_production_constant_is_100k(self):
+ """MIN_KDF_ITERATIONS_PRODUCTION should be 100_000."""
+ from local_deep_research.database.sqlcipher_utils import (
+ MIN_KDF_ITERATIONS_PRODUCTION,
+ )
+
+ assert MIN_KDF_ITERATIONS_PRODUCTION == 100_000
+
+ def test_testing_constant_is_1(self):
+ """MIN_KDF_ITERATIONS_TESTING should be 1."""
+ from local_deep_research.database.sqlcipher_utils import (
+ MIN_KDF_ITERATIONS_TESTING,
+ )
+
+ assert MIN_KDF_ITERATIONS_TESTING == 1
diff --git a/tests/exporters/test_odt_footer.py b/tests/exporters/test_odt_footer.py
new file mode 100644
index 0000000000..08e6521e51
--- /dev/null
+++ b/tests/exporters/test_odt_footer.py
@@ -0,0 +1,59 @@
+"""
+Tests for OdtExporter._add_footer() in exporters/odt_exporter.py
+
+Tests cover:
+- Footer appended to content
+- Footer contains GitHub link
+- Footer starts with separator
+- Empty content input
+- Content with trailing newlines
+- Footer attribution text present
+"""
+
+import pytest
+
+from local_deep_research.exporters.odt_exporter import ODTExporter
+
+
+def exporter():
+ """Create a real ODTExporter — no __init__ args needed."""
+ return ODTExporter()
+
+
+class TestAddFooter:
+ """Tests for _add_footer()."""
+
+ def test_basic_append(self, exporter):
+ """Footer is appended to markdown content."""
+ result = exporter._add_footer("Hello world")
+ assert result.startswith("Hello world")
+ assert len(result) > len("Hello world")
+
+ def test_footer_contains_github_link(self, exporter):
+ """Footer includes the GitHub repository URL."""
+ result = exporter._add_footer("Content")
+ assert "github.com/LearningCircuit/local-deep-research" in result
+
+ def test_footer_has_separator(self, exporter):
+ """Footer includes a horizontal rule separator (---)."""
+ result = exporter._add_footer("Content")
+ footer_part = result[len("Content") :]
+ assert "---" in footer_part
+
+ def test_empty_content(self, exporter):
+ """Empty content still gets a footer."""
+ result = exporter._add_footer("")
+ assert "---" in result
+ assert "local-deep-research" in result
+
+ def test_content_with_trailing_newlines(self, exporter):
+ """Content with trailing newlines gets footer appended after them."""
+ result = exporter._add_footer("Content\n\n")
+ assert result.startswith("Content\n\n")
+ assert "---" in result
+
+ def test_footer_mentions_ldr(self, exporter):
+ """Footer contains LDR or Local Deep Research attribution."""
+ result = exporter._add_footer("Test")
+ assert "Local Deep Research" in result
diff --git a/tests/library/download_management/test_resource_filter_info.py b/tests/library/download_management/test_resource_filter_info.py
new file mode 100644
index 0000000000..c6b5988d8e
--- /dev/null
+++ b/tests/library/download_management/test_resource_filter_info.py
@@ -0,0 +1,247 @@
+"""
+Tests for ResourceFilter: should_skip_resource(), get_skipped_resources_info(),
+and get_retry_statistics() in filters/resource_filter.py.
+
+All tests mock the retry_manager to isolate the filtering logic.
+"""
+
+from datetime import timedelta
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.library.download_management.retry_manager import (
+ RetryDecision,
+ ResourceFilterResult,
+)
+
+
+def _make_filter_with_mock_retry():
+ """Create a ResourceFilter with a mocked retry_manager."""
+ with patch(
+ "local_deep_research.library.download_management.filters.resource_filter.RetryManager"
+ ):
+ from local_deep_research.library.download_management.filters.resource_filter import (
+ ResourceFilter,
+ )
+
+ rf = ResourceFilter.__new__(ResourceFilter)
+ rf.username = "test_user"
+ rf.retry_manager = MagicMock()
+ return rf
+
+
+class TestShouldSkipResource:
+ """Tests for should_skip_resource()."""
+
+ def test_can_retry_returns_no_skip(self):
+ """When retry_manager says can_retry=True, should_skip is False."""
+ rf = _make_filter_with_mock_retry()
+ rf.retry_manager.should_retry_resource.return_value = RetryDecision(
+ can_retry=True, reason="OK"
+ )
+ skip, reason = rf.should_skip_resource(42)
+ assert skip is False
+
+ def test_cannot_retry_returns_skip(self):
+ """When can_retry=False, should_skip is True with reason."""
+ rf = _make_filter_with_mock_retry()
+ rf.retry_manager.should_retry_resource.return_value = RetryDecision(
+ can_retry=False, reason="Permanently failed"
+ )
+ skip, reason = rf.should_skip_resource(42)
+ assert skip is True
+ assert reason == "Permanently failed"
+
+ def test_none_reason_gives_default(self):
+ """When reason is None, a default reason string is provided."""
+ rf = _make_filter_with_mock_retry()
+ rf.retry_manager.should_retry_resource.return_value = RetryDecision(
+ can_retry=False, reason=None
+ )
+ skip, reason = rf.should_skip_resource(99)
+ assert skip is True
+ assert "not available" in reason.lower()
+
+ def test_delegates_to_retry_manager(self):
+ """Verify the resource_id is passed to retry_manager."""
+ rf = _make_filter_with_mock_retry()
+ rf.retry_manager.should_retry_resource.return_value = RetryDecision(
+ can_retry=True
+ )
+ rf.should_skip_resource(123)
+ rf.retry_manager.should_retry_resource.assert_called_once_with(123)
+
+
+class TestGetSkippedResourcesInfo:
+ """Tests for get_skipped_resources_info()."""
+
+ def _setup_filter(self, filter_results):
+ """Set up filter with mocked filter_downloadable_resources."""
+ rf = _make_filter_with_mock_retry()
+ rf.retry_manager.filter_resources.return_value = filter_results
+ rf.retry_manager.status_tracker = MagicMock()
+ rf.retry_manager.status_tracker.get_resource_status.return_value = {
+ "attempts": 3
+ }
+ return rf
+
+ def test_empty_resources(self):
+ """No resources → all counts zero."""
+ rf = self._setup_filter([])
+ result = rf.get_skipped_resources_info([])
+ assert result["total_skipped"] == 0
+ assert result["permanently_failed"] == []
+ assert result["temporarily_failed"] == []
+ assert result["other_skipped"] == []
+ assert result["skipped_resources"] == []
+
+ def test_all_can_retry(self):
+ """All resources can retry → nothing skipped."""
+ results = [
+ ResourceFilterResult(1, can_retry=True, status="available"),
+ ResourceFilterResult(2, can_retry=True, status="available"),
+ ]
+ rf = self._setup_filter(results)
+ info = rf.get_skipped_resources_info(["r1", "r2"])
+ assert info["total_skipped"] == 0
+
+ def test_permanently_failed_categorization(self):
+ """Permanently failed resources go to permanently_failed list."""
+ results = [
+ ResourceFilterResult(
+ 1,
+ can_retry=False,
+ status="permanently_failed",
+ reason="Too many failures",
+ ),
+ ]
+ rf = self._setup_filter(results)
+ info = rf.get_skipped_resources_info(["r1"])
+ assert info["total_skipped"] == 1
+ assert len(info["permanently_failed"]) == 1
+ assert info["permanently_failed"][0]["resource_id"] == 1
+
+ def test_temporarily_failed_categorization(self):
+ """Temporarily failed resources go to temporarily_failed list."""
+ results = [
+ ResourceFilterResult(
+ 2,
+ can_retry=False,
+ status="temporarily_failed",
+ reason="Cooling down",
+ estimated_wait=timedelta(minutes=5),
+ ),
+ ]
+ rf = self._setup_filter(results)
+ info = rf.get_skipped_resources_info(["r2"])
+ assert len(info["temporarily_failed"]) == 1
+ assert info["temporarily_failed"][0]["estimated_wait_minutes"] == 5.0
+
+ def test_other_skipped_categorization(self):
+ """Non-standard statuses go to other_skipped."""
+ results = [
+ ResourceFilterResult(
+ 3, can_retry=False, status="unknown_status", reason="Unknown"
+ ),
+ ]
+ rf = self._setup_filter(results)
+ info = rf.get_skipped_resources_info(["r3"])
+ assert len(info["other_skipped"]) == 1
+ assert info["other_skipped"][0]["status"] == "unknown_status"
+
+ def test_mixed_statuses(self):
+ """Mix of permanently_failed, temporarily_failed, other, and retryable."""
+ results = [
+ ResourceFilterResult(1, can_retry=True, status="available"),
+ ResourceFilterResult(
+ 2, can_retry=False, status="permanently_failed", reason="Dead"
+ ),
+ ResourceFilterResult(
+ 3, can_retry=False, status="temporarily_failed", reason="Wait"
+ ),
+ ResourceFilterResult(
+ 4, can_retry=False, status="rate_limited", reason="Slow down"
+ ),
+ ]
+ rf = self._setup_filter(results)
+ info = rf.get_skipped_resources_info(["r1", "r2", "r3", "r4"])
+ assert info["total_skipped"] == 3
+ assert len(info["permanently_failed"]) == 1
+ assert len(info["temporarily_failed"]) == 1
+ assert len(info["other_skipped"]) == 1
+
+ def test_estimated_wait_none(self):
+ """When estimated_wait is None, estimated_wait_minutes is None."""
+ results = [
+ ResourceFilterResult(
+ 5,
+ can_retry=False,
+ status="permanently_failed",
+ reason="Failed",
+ estimated_wait=None,
+ ),
+ ]
+ rf = self._setup_filter(results)
+ info = rf.get_skipped_resources_info(["r5"])
+ assert info["permanently_failed"][0]["estimated_wait_minutes"] is None
+
+ def test_estimated_wait_timedelta(self):
+ """Timedelta estimated_wait → minutes conversion."""
+ results = [
+ ResourceFilterResult(
+ 6,
+ can_retry=False,
+ status="temporarily_failed",
+ reason="Cooldown",
+ estimated_wait=timedelta(minutes=10),
+ ),
+ ]
+ rf = self._setup_filter(results)
+ info = rf.get_skipped_resources_info(["r6"])
+ assert info["temporarily_failed"][0]["estimated_wait_minutes"] == 10.0
+
+ def test_status_info_included(self):
+ """Status info from status_tracker is included."""
+ results = [
+ ResourceFilterResult(
+ 7, can_retry=False, status="permanently_failed", reason="Done"
+ ),
+ ]
+ rf = self._setup_filter(results)
+ rf.retry_manager.status_tracker.get_resource_status.return_value = {
+ "attempts": 5,
+ "last_failure": "timeout",
+ }
+ info = rf.get_skipped_resources_info(["r7"])
+ assert info["permanently_failed"][0]["status_info"]["attempts"] == 5
+
+ def test_skipped_resources_list_matches_total(self):
+ """The skipped_resources flat list has all skipped entries."""
+ results = [
+ ResourceFilterResult(
+ 1, can_retry=False, status="permanently_failed", reason="A"
+ ),
+ ResourceFilterResult(
+ 2, can_retry=False, status="temporarily_failed", reason="B"
+ ),
+ ]
+ rf = self._setup_filter(results)
+ info = rf.get_skipped_resources_info(["r1", "r2"])
+ assert len(info["skipped_resources"]) == info["total_skipped"] == 2
+
+
+class TestGetRetryStatistics:
+ """Tests for get_retry_statistics()."""
+
+ def test_delegates_to_retry_manager(self):
+ """Delegates directly to retry_manager.get_retry_statistics()."""
+ rf = _make_filter_with_mock_retry()
+ rf.retry_manager.get_retry_statistics.return_value = {"total": 10}
+ result = rf.get_retry_statistics()
+ assert result == {"total": 10}
+ rf.retry_manager.get_retry_statistics.assert_called_once()
+
+ def test_returns_dict(self):
+ """Return type is dict."""
+ rf = _make_filter_with_mock_retry()
+ rf.retry_manager.get_retry_statistics.return_value = {}
+ assert isinstance(rf.get_retry_statistics(), dict)
diff --git a/tests/routes/__init__.py b/tests/routes/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/routes/test_blocked_settings_error.py b/tests/routes/test_blocked_settings_error.py
new file mode 100644
index 0000000000..1d4e2b61bb
--- /dev/null
+++ b/tests/routes/test_blocked_settings_error.py
@@ -0,0 +1,82 @@
+"""
+Tests for get_blocked_settings_error() in web/routes/settings_routes.py
+
+Tests cover:
+- Response structure (status, message, errors list)
+- Single and multiple blocked keys
+- Empty list input
+- Error message consistency
+- Special characters and dotted key names
+"""
+
+from local_deep_research.web.routes.settings_routes import (
+ get_blocked_settings_error,
+)
+
+
+class TestGetBlockedSettingsError:
+ """Tests for the security error response formatter."""
+
+ def test_response_has_required_keys(self):
+ """Response must have status, message, and errors."""
+ result = get_blocked_settings_error(["some_key"])
+ assert "status" in result
+ assert "message" in result
+ assert "errors" in result
+
+ def test_status_is_error(self):
+ """Status field must be 'error'."""
+ result = get_blocked_settings_error(["key"])
+ assert result["status"] == "error"
+
+ def test_message_mentions_security(self):
+ """Message should reference security violation."""
+ result = get_blocked_settings_error(["key"])
+ assert "security" in result["message"].lower()
+
+ def test_single_key(self):
+ """Single blocked key produces one error entry."""
+ result = get_blocked_settings_error(["api_key"])
+ assert len(result["errors"]) == 1
+ assert result["errors"][0]["key"] == "api_key"
+ assert result["errors"][0]["name"] == "api_key"
+
+ def test_multiple_keys(self):
+ """Multiple blocked keys produce matching error entries."""
+ keys = ["api_key", "secret_token", "password"]
+ result = get_blocked_settings_error(keys)
+ assert len(result["errors"]) == 3
+ error_keys = [e["key"] for e in result["errors"]]
+ assert error_keys == keys
+
+ def test_empty_list(self):
+ """Empty list produces empty errors array."""
+ result = get_blocked_settings_error([])
+ assert result["errors"] == []
+ assert result["status"] == "error"
+
+ def test_error_entry_has_key_name_error(self):
+ """Each error entry has key, name, and error fields."""
+ result = get_blocked_settings_error(["test_key"])
+ entry = result["errors"][0]
+ assert "key" in entry
+ assert "name" in entry
+ assert "error" in entry
+
+ def test_error_message_mentions_security_reason(self):
+ """Error message in each entry mentions security."""
+ result = get_blocked_settings_error(["key"])
+ assert "security" in result["errors"][0]["error"].lower()
+
+ def test_special_characters_in_key(self):
+ """Keys with special characters are preserved as-is."""
+ key = "config.api-key_v2"
+ result = get_blocked_settings_error([key])
+ assert result["errors"][0]["key"] == key
+
+ def test_dotted_key_names(self):
+ """Dotted keys (e.g., search.engine.timeout) are preserved."""
+ key = "search.engine.timeout"
+ result = get_blocked_settings_error([key])
+ assert result["errors"][0]["key"] == key
+ assert result["errors"][0]["name"] == key
diff --git a/tests/web/models/test_calculate_duration_edge_cases.py b/tests/web/models/test_calculate_duration_edge_cases.py
new file mode 100644
index 0000000000..071b55c6ec
--- /dev/null
+++ b/tests/web/models/test_calculate_duration_edge_cases.py
@@ -0,0 +1,143 @@
+"""
+Edge case tests for calculate_duration() in web/models/database.py.
+
+These tests target the dateutil.parser fallback paths and timezone
+handling that are NOT covered by the existing test_database.py.
+"""
+
+from unittest.mock import patch
+from datetime import datetime, timezone, timedelta
+
+
+class TestDateutilFallbackPaths:
+ """Tests for the dateutil.parser.parse fallback code paths."""
+
+ def test_completed_at_dateutil_fallback(self):
+ """Weird completed_at format that fails fromisoformat but dateutil can parse."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ created_at = "2025-01-01T10:00:00+00:00"
+ # Month name format — fromisoformat fails, dateutil parses it
+ completed_at = "Jan 1, 2025 10:05:00 UTC"
+
+ result = calculate_duration(created_at, completed_at)
+ assert result is not None
+ assert result == 300 # 5 minutes
+
+ def test_created_at_dateutil_fallback(self):
+ """Weird created_at format that fails standard parsing but dateutil can handle."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ created_at = "Jan 1, 2025 10:00:00 UTC"
+ completed_at = "2025-01-01T10:02:00+00:00"
+
+ result = calculate_duration(created_at, completed_at)
+ assert result is not None
+ assert result == 120 # 2 minutes
+
+ def test_created_at_completely_unparseable_returns_none(self):
+ """Completely unparseable created_at → returns None."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ result = calculate_duration(
+ "not-a-date-at-all", "2025-01-01T10:00:00+00:00"
+ )
+ assert result is None
+
+ def test_completed_at_unparseable_falls_back_to_now(self):
+ """Completely unparseable completed_at → falls back to current time."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ now = datetime.now(timezone.utc)
+ created_at = (now - timedelta(seconds=60)).isoformat()
+
+ # Patch dateutil.parser.parse to fail when called for the completed_at
+ with patch(
+ "dateutil.parser.parse", side_effect=Exception("Cannot parse")
+ ):
+ result = calculate_duration(created_at, "completely-invalid-!!!")
+ # Falls back to datetime.now(UTC), so duration ≈ 60s
+ assert result is not None
+ assert 55 <= result <= 70
+
+
+class TestTimezoneHandling:
+ """Tests for timezone-aware vs timezone-naive mixing."""
+
+ def test_timezone_offset_format(self):
+ """Timestamps with +HH:MM offset are handled."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ created_at = "2025-01-01T10:00:00+05:30"
+ completed_at = "2025-01-01T10:30:00+05:30"
+
+ result = calculate_duration(created_at, completed_at)
+ assert result == 1800 # 30 minutes
+
+ def test_different_timezone_offsets(self):
+ """Timestamps with different timezone offsets are normalized."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ # Same absolute moment, different offsets
+ created_at = "2025-01-01T10:00:00+00:00"
+ completed_at = "2025-01-01T12:00:00+02:00" # Same as 10:00 UTC
+
+ result = calculate_duration(created_at, completed_at)
+ assert result == 0 # Same instant
+
+ def test_negative_timezone_offset(self):
+ """Negative timezone offset works correctly."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ created_at = "2025-01-01T10:00:00-05:00" # UTC 15:00
+ completed_at = "2025-01-01T16:00:00+00:00" # UTC 16:00
+
+ result = calculate_duration(created_at, completed_at)
+ assert result == 3600 # 1 hour difference
+
+
+class TestSpaceSeparatedFormats:
+ """Tests for space-separated timestamp formats."""
+
+ def test_space_separated_with_microseconds_and_tz(self):
+ """Space-separated format with microseconds and timezone."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ # Include timezone to avoid naive datetime issues with astimezone
+ created_at = "2025-01-01 10:00:00.123456+00:00"
+ completed_at = "2025-01-01 10:01:00.654321+00:00"
+
+ result = calculate_duration(created_at, completed_at)
+ assert result is not None
+ assert result == 60 or result == 61
+
+ def test_space_separated_without_microseconds_and_tz(self):
+ """Space-separated format without microseconds, with timezone."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ created_at = "2025-01-01 10:00:00+00:00"
+ completed_at = "2025-01-01 10:05:00+00:00"
+
+ result = calculate_duration(created_at, completed_at)
+ assert result == 300 # 5 minutes
+
+ def test_space_to_t_replacement_fallback(self):
+ """Space-separated with timezone falls back to replace(' ', 'T')."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ # This has timezone info but no T separator — triggers the replace fallback
+ created_at = "2025-01-01 10:00:00+00:00"
+ completed_at = "2025-01-01 10:03:00+00:00"
+
+ result = calculate_duration(created_at, completed_at)
+ assert result == 180 # 3 minutes
+
+ def test_iso_with_explicit_utc_offset(self):
+ """ISO format with explicit UTC offset."""
+ from local_deep_research.web.models.database import calculate_duration
+
+ created_at = "2025-01-01T10:00:00+00:00"
+ completed_at = "2025-01-01T10:10:00+00:00"
+
+ result = calculate_duration(created_at, completed_at)
+ assert result == 600 # 10 minutes