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 33 edge-case tests for sanitizer, queue middleware, settings parser, and exporters (round 18) (#2667)

LearningCircuit8fe804a866ed
diff --git a/tests/exporters/test_exporter_edge_cases.py b/tests/exporters/test_exporter_edge_cases.py
new file mode 100644
index 0000000000..475cdca51b
--- /dev/null
+++ b/tests/exporters/test_exporter_edge_cases.py
@@ -0,0 +1,83 @@
+"""Edge-case tests for BaseExporter._generate_safe_filename() and _prepend_title_if_needed().
+
+Extends test_base_exporter.py with boundary conditions not covered:
+all-special-char titles, exact 50-char boundary, all-whitespace titles,
+and #NoSpace heading detection.
+"""
+
+
+class TestGenerateSafeFilenameEdgeCases:
+ """Edge cases for _generate_safe_filename()."""
+
+ def _get_exporter(self):
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ return LaTeXExporter()
+
+ def test_all_special_chars_produces_extension_only(self):
+ """Title with only special chars: regex removes all → empty safe_title."""
+ exporter = self._get_exporter()
+ result = exporter._generate_safe_filename("@#$%^&*()")
+ # safe_title is "" (truthy title enters if-branch but regex strips all)
+ assert result == ".tex"
+
+ def test_exactly_50_chars_preserved(self):
+ """Title that is exactly 50 chars after cleaning should not be truncated."""
+ exporter = self._get_exporter()
+ title = "A" * 50
+ result = exporter._generate_safe_filename(title)
+ assert result == "A" * 50 + ".tex"
+
+ def test_51_chars_truncated_to_50(self):
+ """Title 51 chars after cleaning should truncate to 50."""
+ exporter = self._get_exporter()
+ title = "A" * 51
+ result = exporter._generate_safe_filename(title)
+ name_part = result.replace(".tex", "")
+ assert len(name_part) == 50
+
+ def test_all_whitespace_title_produces_extension_only(self):
+ """Whitespace-only title is truthy but strip() makes it empty."""
+ exporter = self._get_exporter()
+ result = exporter._generate_safe_filename(" ")
+ # " " is truthy → enters if-branch → regex keeps spaces → strip() → ""
+ assert result == ".tex"
+
+
+class TestPrependTitleEdgeCases:
+ """Edge cases for _prepend_title_if_needed()."""
+
+ def _get_exporter(self):
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ return LaTeXExporter()
+
+ def test_hash_without_space_still_detected_as_heading(self):
+ """Content starting with '#' (no space) is still treated as a heading."""
+ exporter = self._get_exporter()
+ result = exporter._prepend_title_if_needed("#NoSpace content", "Title")
+ # lstrip().startswith("#") → True → no prepend
+ assert result == "#NoSpace content"
+
+ def test_title_partial_match_does_prepend(self):
+ """Content with '# Title Extra' should NOT match title='Title'."""
+ exporter = self._get_exporter()
+ # content.startswith("# Title") is True for "# Title Extra"
+ result = exporter._prepend_title_if_needed(
+ "# Title Extra\ncontent", "Title"
+ )
+ # "# Title Extra".startswith("# Title") → True → no prepend
+ assert result == "# Title Extra\ncontent"
+
+ def test_title_substring_mismatch(self):
+ """Content heading that differs from title at start."""
+ exporter = self._get_exporter()
+ result = exporter._prepend_title_if_needed("# Other\ncontent", "Title")
+ # Doesn't start with "# Title", but starts with "#" → no prepend
+ assert result == "# Other\ncontent"
+
+ def test_content_with_only_newlines_gets_title(self):
+ """Content of just newlines has no heading → title prepended."""
+ exporter = self._get_exporter()
+ result = exporter._prepend_title_if_needed("\n\n\n", "Title")
+ assert result == "# Title\n\n\n\n\n"
diff --git a/tests/security/test_log_sanitizer_edge_cases.py b/tests/security/test_log_sanitizer_edge_cases.py
new file mode 100644
index 0000000000..a074536a9c
--- /dev/null
+++ b/tests/security/test_log_sanitizer_edge_cases.py
@@ -0,0 +1,35 @@
+"""Edge-case tests for sanitize_for_log() max_length boundary behavior.
+
+The main test_log_sanitizer.py tests normal truncation (max_length > 3) but
+misses the branch at line 42 where max_length <= 3 skips the ellipsis.
+"""
+
+from local_deep_research.security.log_sanitizer import sanitize_for_log
+
+
+class TestSanitizeForLogMaxLengthBoundary:
+ """Tests for max_length <= 3 branch in sanitize_for_log()."""
+
+ def test_max_length_3_returns_ellipsis(self):
+ """max_length=3 with long input: max_length > 3 is False, so no ellipsis."""
+ result = sanitize_for_log("abcdef", max_length=3)
+ # max_length > 3 is False → falls to else → cleaned[:3]
+ assert result == "abc"
+
+ def test_max_length_2_truncates_without_ellipsis(self):
+ result = sanitize_for_log("abcdef", max_length=2)
+ assert result == "ab"
+
+ def test_max_length_1_single_char(self):
+ result = sanitize_for_log("abcdef", max_length=1)
+ assert result == "a"
+
+ def test_max_length_0_returns_empty(self):
+ result = sanitize_for_log("abcdef", max_length=0)
+ assert result == ""
+
+ def test_max_length_4_gets_one_char_plus_ellipsis(self):
+ """max_length=4 is > 3, so ellipsis branch applies."""
+ result = sanitize_for_log("abcdef", max_length=4)
+ assert result == "a..."
+ assert len(result) == 4
diff --git a/tests/settings/test_filter_setting_columns.py b/tests/settings/test_filter_setting_columns.py
new file mode 100644
index 0000000000..4b7cc7a55f
--- /dev/null
+++ b/tests/settings/test_filter_setting_columns.py
@@ -0,0 +1,40 @@
+"""Tests for _filter_setting_columns() in settings/manager.py.
+
+This function has zero test coverage. It filters a dict to only keys
+that match columns on the Setting model, preventing crashes when
+default_settings.json contains unknown keys.
+"""
+
+from local_deep_research.settings.manager import _filter_setting_columns
+
+
+class TestFilterSettingColumns:
+ """Tests for _filter_setting_columns()."""
+
+ def test_valid_key_passes_through(self):
+ """Known Setting column names should be preserved."""
+ result = _filter_setting_columns({"key": "test_key"})
+ assert "key" in result
+ assert result["key"] == "test_key"
+
+ def test_invalid_key_filtered_out(self):
+ """Keys not matching any Setting column should be removed."""
+ result = _filter_setting_columns(
+ {"key": "test_key", "nonexistent_xyz_column": "val"}
+ )
+ assert "key" in result
+ assert "nonexistent_xyz_column" not in result
+
+ def test_empty_dict(self):
+ result = _filter_setting_columns({})
+ assert result == {}
+
+ def test_all_invalid_keys(self):
+ result = _filter_setting_columns({"bogus_a": 1, "bogus_b": 2})
+ assert result == {}
+
+ def test_none_value_preserved(self):
+ """Filtering is by key name, not value — None values should pass."""
+ result = _filter_setting_columns({"key": None})
+ assert "key" in result
+ assert result["key"] is None
diff --git a/tests/settings/test_parse_edge_cases.py b/tests/settings/test_parse_edge_cases.py
new file mode 100644
index 0000000000..6f2f77ca35
--- /dev/null
+++ b/tests/settings/test_parse_edge_cases.py
@@ -0,0 +1,62 @@
+"""Edge-case tests for _parse_number() and _parse_multiselect().
+
+These cover branches missed by existing test_parse_multiselect.py and
+test_manager_behavior.py: scientific notation, ValueError paths,
+JSON-to-non-list parsing, and degenerate input strings.
+"""
+
+import pytest
+
+from local_deep_research.settings.manager import (
+ _parse_multiselect,
+ _parse_number,
+)
+
+
+class TestParseNumberEdgeCases:
+ """Edge cases for _parse_number()."""
+
+ def test_scientific_notation_whole_returns_int(self):
+ """1e2 = 100.0 which is_integer() → returns int(100)."""
+ assert _parse_number("1e2") == 100
+ assert isinstance(_parse_number("1e2"), int)
+
+ def test_scientific_notation_fractional_returns_float(self):
+ """1.5e2 = 150.0 which is_integer() → returns int(150)."""
+ result = _parse_number("1.5e2")
+ # 150.0.is_integer() is True so this returns int
+ assert result == 150
+
+ def test_negative_whole_returns_int(self):
+ assert _parse_number("-5.0") == -5
+ assert isinstance(_parse_number("-5.0"), int)
+
+ def test_non_numeric_raises_valueerror(self):
+ with pytest.raises(ValueError):
+ _parse_number("abc")
+
+
+class TestParseMultiselectEdgeCases:
+ """Edge cases not covered by test_parse_multiselect.py."""
+
+ def test_json_parses_to_dict_falls_to_comma_split(self):
+ """JSON that parses to a dict (not list) falls through to comma split."""
+ result = _parse_multiselect('{"a": 1}')
+ # JSON parses OK but isinstance(parsed, list) is False
+ # Falls through to comma-separated split
+ assert isinstance(result, list)
+ assert result == ['{"a": 1}']
+
+ def test_only_commas_returns_empty_list(self):
+ """String of only commas → all items strip to empty → filtered out."""
+ result = _parse_multiselect(",,,")
+ assert result == []
+
+ def test_non_string_non_list_passthrough_none(self):
+ """None should pass through unchanged."""
+ assert _parse_multiselect(None) is None
+
+ def test_whitespace_only_string(self):
+ """Whitespace-only string: stripped → doesn't start with '[' → comma split → empty."""
+ result = _parse_multiselect(" ")
+ assert result == []
diff --git a/tests/web/auth/test_queue_middleware_v2_behavior.py b/tests/web/auth/test_queue_middleware_v2_behavior.py
new file mode 100644
index 0000000000..b1edb4426b
--- /dev/null
+++ b/tests/web/auth/test_queue_middleware_v2_behavior.py
@@ -0,0 +1,203 @@
+"""Behavioral tests for notify_queue_processor().
+
+The existing test_queue_middleware_extended.py only checks importability
+(``assert callable(...)``). These tests exercise actual request-time logic:
+skip conditions, session lookups, queue processor calls, and error handling.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import flask
+import pytest
+
+
+def app():
+ """Minimal Flask app for request context."""
+ app = flask.Flask(__name__)
+ app.secret_key = "test"
+ return app
+
+
+class TestNotifyQueueProcessor:
+ """Tests for notify_queue_processor() before_request handler."""
+
+ def test_skips_when_should_skip_returns_true(self, app):
+ """Early return when should_skip_queue_checks() is True."""
+ with app.test_request_context():
+ with patch(
+ "local_deep_research.web.auth.queue_middleware_v2.should_skip_queue_checks",
+ return_value=True,
+ ):
+ from local_deep_research.web.auth.queue_middleware_v2 import (
+ notify_queue_processor,
+ )
+
+ # Should not touch session at all
+ with patch(
+ "local_deep_research.web.auth.queue_middleware_v2.session"
+ ) as mock_session:
+ notify_queue_processor()
+ mock_session.get.assert_not_called()
+
+ def test_noop_when_username_missing(self, app):
+ """No queue processing when session lacks username."""
+ with app.test_request_context():
+ with (
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.should_skip_queue_checks",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.session",
+ {"session_id": "sid123"},
+ ),
+ ):
+ from local_deep_research.web.auth.queue_middleware_v2 import (
+ notify_queue_processor,
+ )
+
+ notify_queue_processor()
+ # No assertion on queue_processor — it shouldn't be imported
+
+ def test_noop_when_session_id_missing(self, app):
+ """No queue processing when session lacks session_id."""
+ with app.test_request_context():
+ with (
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.should_skip_queue_checks",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.session",
+ {"username": "alice"},
+ ),
+ ):
+ from local_deep_research.web.auth.queue_middleware_v2 import (
+ notify_queue_processor,
+ )
+
+ notify_queue_processor()
+
+ def test_noop_when_db_session_missing(self, app):
+ """No queue calls when g.db_session is absent."""
+ with app.test_request_context():
+ with (
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.should_skip_queue_checks",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.session",
+ {"username": "alice", "session_id": "sid123"},
+ ),
+ ):
+ from local_deep_research.web.auth.queue_middleware_v2 import (
+ notify_queue_processor,
+ )
+
+ # g has no db_session attribute
+ notify_queue_processor()
+
+ def test_calls_queue_processor_on_success(self, app):
+ """Full success path: notifies activity and processes request."""
+ mock_processor = MagicMock()
+ mock_processor.process_user_request.return_value = 2
+
+ with app.test_request_context():
+ flask.g.db_session = MagicMock()
+ with (
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.should_skip_queue_checks",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.session",
+ {"username": "alice", "session_id": "sid123"},
+ ),
+ patch.dict(
+ "sys.modules",
+ {
+ "local_deep_research.web.queue.processor_v2": MagicMock(
+ queue_processor=mock_processor
+ )
+ },
+ ),
+ ):
+ from local_deep_research.web.auth.queue_middleware_v2 import (
+ notify_queue_processor,
+ )
+
+ notify_queue_processor()
+
+ mock_processor.notify_user_activity.assert_called_once_with(
+ "alice", "sid123"
+ )
+ mock_processor.process_user_request.assert_called_once_with(
+ "alice", "sid123"
+ )
+
+ def test_zero_queued_items_no_debug_log(self, app):
+ """When process_user_request returns 0, no debug log emitted."""
+ mock_processor = MagicMock()
+ mock_processor.process_user_request.return_value = 0
+
+ with app.test_request_context():
+ flask.g.db_session = MagicMock()
+ with (
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.should_skip_queue_checks",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.session",
+ {"username": "alice", "session_id": "sid123"},
+ ),
+ patch.dict(
+ "sys.modules",
+ {
+ "local_deep_research.web.queue.processor_v2": MagicMock(
+ queue_processor=mock_processor
+ )
+ },
+ ),
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.logger"
+ ) as mock_logger,
+ ):
+ from local_deep_research.web.auth.queue_middleware_v2 import (
+ notify_queue_processor,
+ )
+
+ notify_queue_processor()
+
+ mock_logger.debug.assert_not_called()
+
+ def test_exception_caught_silently(self, app):
+ """Exceptions in queue processing must not propagate."""
+ with app.test_request_context():
+ flask.g.db_session = MagicMock()
+ with (
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.should_skip_queue_checks",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.web.auth.queue_middleware_v2.session",
+ {"username": "alice", "session_id": "sid123"},
+ ),
+ patch.dict(
+ "sys.modules",
+ {
+ "local_deep_research.web.queue.processor_v2": MagicMock(
+ side_effect=ImportError("no module")
+ )
+ },
+ ),
+ ):
+ from local_deep_research.web.auth.queue_middleware_v2 import (
+ notify_queue_processor,
+ )
+
+ # Must not raise
+ notify_queue_processor()