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 ~2000 coverage tests across 27 modules (#2741)

LearningCircuite5154b37e8c2
diff --git a/tests/advanced_search_system/test_constraints_coverage.py b/tests/advanced_search_system/test_constraints_coverage.py
new file mode 100644
index 0000000000..8ee55fee1d
--- /dev/null
+++ b/tests/advanced_search_system/test_constraints_coverage.py
@@ -0,0 +1,576 @@
+"""
+Comprehensive coverage tests for the constraints package.
+
+Targets gaps not covered by existing test suites:
+- Constraint dataclass edge cases (equality, hashing, mutable defaults, exotic value types)
+- to_search_terms with non-string values for specialized branches
+- is_critical boundary across every non-NAME_PATTERN type
+- ConstraintAnalyzer parsing edge cases (colons in values, extra noise lines,
+ think-tag wrapping around constraint blocks, weight edge values)
+- Package re-exports from __init__
+"""
+
+import pytest
+from unittest.mock import MagicMock
+
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.constraints.constraint_analyzer import (
+ ConstraintAnalyzer,
+)
+from local_deep_research.advanced_search_system.constraints import (
+ Constraint as ReexportedConstraint,
+ ConstraintType as ReexportedConstraintType,
+ ConstraintAnalyzer as ReexportedConstraintAnalyzer,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helper
+# ---------------------------------------------------------------------------
+
+
+def _analyzer():
+ """Create a ConstraintAnalyzer with a mock model."""
+ a = ConstraintAnalyzer.__new__(ConstraintAnalyzer)
+ a.model = MagicMock()
+ return a
+
+
+def _mock_response(analyzer, content: str):
+ analyzer.model.invoke.return_value = MagicMock(content=content)
+
+
+def _make(type_=ConstraintType.PROPERTY, value="v", weight=1.0, **kw):
+ return Constraint(
+ id=kw.pop("id", "c1"),
+ type=type_,
+ description=kw.pop("description", "desc"),
+ value=value,
+ weight=weight,
+ **kw,
+ )
+
+
+# ===================================================================
+# Package __init__ re-exports
+# ===================================================================
+
+
+class TestPackageReexports:
+ def test_constraint_reexported(self):
+ assert ReexportedConstraint is Constraint
+
+ def test_constraint_type_reexported(self):
+ assert ReexportedConstraintType is ConstraintType
+
+ def test_constraint_analyzer_reexported(self):
+ assert ReexportedConstraintAnalyzer is ConstraintAnalyzer
+
+
+# ===================================================================
+# ConstraintType enum — identity and iteration
+# ===================================================================
+
+
+class TestConstraintTypeIteration:
+ def test_all_values_are_strings(self):
+ for ct in ConstraintType:
+ assert isinstance(ct.value, str)
+
+ def test_values_are_lowercase(self):
+ for ct in ConstraintType:
+ assert ct.value == ct.value.lower()
+
+ def test_enum_members_are_unique(self):
+ values = [ct.value for ct in ConstraintType]
+ assert len(values) == len(set(values))
+
+
+# ===================================================================
+# Constraint dataclass — edge cases
+# ===================================================================
+
+
+class TestConstraintDataclassEdgeCases:
+ def test_equality_same_fields(self):
+ a = _make()
+ b = _make()
+ assert a == b
+
+ def test_inequality_different_id(self):
+ a = _make(id="c1")
+ b = _make(id="c2")
+ assert a != b
+
+ def test_metadata_default_not_shared_between_instances(self):
+ """Each instance should get its own empty dict, not a shared one."""
+ a = _make()
+ b = _make()
+ a.metadata["x"] = 1
+ assert "x" not in b.metadata
+
+ def test_value_can_be_list(self):
+ c = _make(value=["a", "b"])
+ assert c.value == ["a", "b"]
+
+ def test_value_can_be_dict(self):
+ c = _make(value={"key": 42})
+ assert c.value == {"key": 42}
+
+ def test_value_can_be_none(self):
+ c = _make(value=None)
+ assert c.value is None
+
+ def test_value_can_be_bool(self):
+ c = _make(value=True)
+ assert c.value is True
+
+ def test_weight_zero(self):
+ c = _make(weight=0.0)
+ assert c.weight == 0.0
+
+ def test_weight_negative(self):
+ c = _make(weight=-0.5)
+ assert c.weight == -0.5
+
+ def test_description_with_unicode(self):
+ c = _make(description="Formed during Würm glaciation")
+ assert "Würm" in c.description
+
+
+# ===================================================================
+# to_search_terms — non-string values in specialized branches
+# ===================================================================
+
+
+class TestToSearchTermsEdgeCases:
+ def test_property_with_numeric_value(self):
+ c = _make(type_=ConstraintType.PROPERTY, value=42)
+ # PROPERTY branch returns self.value directly (an int)
+ assert c.to_search_terms() == 42
+
+ def test_name_pattern_with_numeric_value(self):
+ c = _make(type_=ConstraintType.NAME_PATTERN, value=123)
+ result = c.to_search_terms()
+ assert "123" in result
+ assert "name trail mountain" in result
+
+ def test_event_with_numeric_value(self):
+ c = _make(type_=ConstraintType.EVENT, value=2020)
+ result = c.to_search_terms()
+ assert "2020" in result
+ assert "accident incident" in result
+
+ def test_statistic_with_numeric_value(self):
+ c = _make(type_=ConstraintType.STATISTIC, value=3.14)
+ result = c.to_search_terms()
+ assert "3.14" in result
+ assert "statistics data" in result
+
+ def test_fallback_branch_for_comparison(self):
+ c = _make(type_=ConstraintType.COMPARISON, value=99)
+ assert c.to_search_terms() == "99"
+
+ def test_fallback_branch_for_existence(self):
+ c = _make(type_=ConstraintType.EXISTENCE, value="has feature")
+ assert c.to_search_terms() == "has feature"
+
+ def test_empty_string_value_property(self):
+ c = _make(type_=ConstraintType.PROPERTY, value="")
+ assert c.to_search_terms() == ""
+
+ def test_empty_string_value_name_pattern(self):
+ c = _make(type_=ConstraintType.NAME_PATTERN, value="")
+ assert c.to_search_terms() == " name trail mountain"
+
+
+# ===================================================================
+# is_critical — boundary for every non-NAME_PATTERN type
+# ===================================================================
+
+
+class TestIsCriticalAllTypes:
+ """Verify is_critical at the 0.8 boundary for every non-NAME_PATTERN type."""
+
+ @pytest.mark.parametrize(
+ "ctype",
+ [
+ ConstraintType.PROPERTY,
+ ConstraintType.EVENT,
+ ConstraintType.STATISTIC,
+ ConstraintType.TEMPORAL,
+ ConstraintType.LOCATION,
+ ConstraintType.COMPARISON,
+ ConstraintType.EXISTENCE,
+ ],
+ )
+ def test_weight_0_8_not_critical(self, ctype):
+ c = _make(type_=ctype, weight=0.8)
+ assert c.is_critical() is False
+
+ @pytest.mark.parametrize(
+ "ctype",
+ [
+ ConstraintType.PROPERTY,
+ ConstraintType.EVENT,
+ ConstraintType.STATISTIC,
+ ConstraintType.TEMPORAL,
+ ConstraintType.LOCATION,
+ ConstraintType.COMPARISON,
+ ConstraintType.EXISTENCE,
+ ],
+ )
+ def test_weight_0_81_critical(self, ctype):
+ c = _make(type_=ctype, weight=0.81)
+ assert c.is_critical() is True
+
+ def test_name_pattern_with_weight_zero_still_critical(self):
+ c = _make(type_=ConstraintType.NAME_PATTERN, weight=0.0)
+ assert c.is_critical() is True
+
+ def test_default_weight_1_0_is_critical(self):
+ c = _make(type_=ConstraintType.PROPERTY)
+ assert c.is_critical() is True
+
+
+# ===================================================================
+# ConstraintAnalyzer._parse_constraint_type — extra edge cases
+# ===================================================================
+
+
+class TestParseConstraintTypeEdges:
+ def test_whitespace_in_type_string(self):
+ a = _analyzer()
+ # The code does .lower() but NOT .strip() — spaces would cause fallback
+ result = a._parse_constraint_type(" property ")
+ assert (
+ result == ConstraintType.PROPERTY
+ ) # Falls to default since " property " != "property"
+
+ def test_all_caps_name_pattern(self):
+ a = _analyzer()
+ assert (
+ a._parse_constraint_type("NAME_PATTERN")
+ == ConstraintType.NAME_PATTERN
+ )
+
+ def test_numeric_string_defaults_to_property(self):
+ a = _analyzer()
+ assert a._parse_constraint_type("42") == ConstraintType.PROPERTY
+
+
+# ===================================================================
+# ConstraintAnalyzer._parse_weight — extra edge cases
+# ===================================================================
+
+
+class TestParseWeightEdges:
+ def test_zero_int(self):
+ a = _analyzer()
+ assert a._parse_weight(0) == 0.0
+
+ def test_zero_float(self):
+ a = _analyzer()
+ assert a._parse_weight(0.0) == 0.0
+
+ def test_negative_float(self):
+ a = _analyzer()
+ assert a._parse_weight(-0.5) == -0.5
+
+ def test_large_float(self):
+ a = _analyzer()
+ assert a._parse_weight(100.0) == 100.0
+
+ def test_string_integer_no_decimal(self):
+ a = _analyzer()
+ assert a._parse_weight("1") == 1.0
+
+ def test_string_with_leading_text(self):
+ a = _analyzer()
+ assert a._parse_weight("Weight is 0.6 approximately") == 0.6
+
+ def test_string_with_multiple_numbers_takes_first(self):
+ a = _analyzer()
+ assert a._parse_weight("0.3 or maybe 0.9") == 0.3
+
+ def test_bool_true_treated_as_numeric(self):
+ """bool is subclass of int, so True -> 1.0."""
+ a = _analyzer()
+ assert a._parse_weight(True) == 1.0
+
+ def test_bool_false_treated_as_numeric(self):
+ a = _analyzer()
+ assert a._parse_weight(False) == 0.0
+
+ def test_list_returns_default(self):
+ a = _analyzer()
+ assert a._parse_weight([0.5]) == 1.0
+
+ def test_dict_returns_default(self):
+ a = _analyzer()
+ assert a._parse_weight({"w": 0.5}) == 1.0
+
+
+# ===================================================================
+# ConstraintAnalyzer.extract_constraints — parsing edge cases
+# ===================================================================
+
+
+class TestExtractConstraintsEdgeCases:
+ def test_value_containing_colon(self):
+ """Values with colons should be preserved after the first split."""
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "CONSTRAINT_1:\n"
+ "Type: temporal\n"
+ "Description: Time range\n"
+ "Value: between 10:00 and 14:00\n"
+ "Weight: 0.9\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 1
+ assert cs[0].value == "between 10:00 and 14:00"
+
+ def test_noise_lines_are_ignored(self):
+ """Lines that don't match key: value or CONSTRAINT_ should be skipped."""
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "Here is my analysis:\n"
+ "\n"
+ "CONSTRAINT_1:\n"
+ "Type: property\n"
+ "Description: Must be red\n"
+ "Value: red\n"
+ "Weight: 0.7\n"
+ "\n"
+ "Let me also note something extra.\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 1
+ assert cs[0].value == "red"
+
+ def test_think_tags_wrapping_entire_block(self):
+ """Think tags around the whole response should be stripped."""
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "<think>I need to think about this carefully.\n"
+ "Let me consider the constraints.</think>\n"
+ "CONSTRAINT_1:\n"
+ "Type: location\n"
+ "Description: Must be in Europe\n"
+ "Value: Europe\n"
+ "Weight: 0.8\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 1
+ assert cs[0].type == ConstraintType.LOCATION
+
+ def test_orphaned_think_close_tag(self):
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "</think>\n"
+ "CONSTRAINT_1:\n"
+ "Type: event\n"
+ "Description: Happened recently\n"
+ "Value: recent event\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 1
+
+ def test_only_last_constraint_present(self):
+ """A single constraint without a following CONSTRAINT_ marker."""
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "CONSTRAINT_1:\n"
+ "Type: existence\n"
+ "Description: Must exist\n"
+ "Value: exists\n"
+ "Weight: 1.0\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 1
+ assert cs[0].id == "c1"
+
+ def test_missing_type_still_has_required_fields(self):
+ """If type is missing, constraint is skipped because 'type' is not in required keys check.
+ Wait — the code only checks for type/description/value. Let's verify type IS required."""
+ a = _analyzer()
+ _mock_response(a, ("CONSTRAINT_1:\nDescription: No type\nValue: val\n"))
+ cs = a.extract_constraints("query")
+ # type is not in the required-keys check (only type, description, value)
+ # Actually the check is: k in ["type", "description", "value"]
+ # Without a Type: line, current_constraint won't have "type" key
+ # So the constraint should be skipped
+ assert len(cs) == 0
+
+ def test_irrelevant_key_value_lines_ignored(self):
+ """Lines like 'Notes: something' should not corrupt the constraint."""
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "CONSTRAINT_1:\n"
+ "Type: property\n"
+ "Description: Must be blue\n"
+ "Value: blue\n"
+ "Weight: 0.5\n"
+ "Notes: This is just a note\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 1
+ assert cs[0].value == "blue"
+ # "Notes" should not appear anywhere in the constraint
+ assert cs[0].description == "Must be blue"
+
+ def test_constraint_numbering_is_independent_of_model_numbering(self):
+ """Even if model uses CONSTRAINT_5 and CONSTRAINT_10, IDs are c1, c2."""
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "CONSTRAINT_5:\n"
+ "Type: property\n"
+ "Description: A\n"
+ "Value: a\n"
+ "\n"
+ "CONSTRAINT_10:\n"
+ "Type: event\n"
+ "Description: B\n"
+ "Value: b\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 2
+ assert cs[0].id == "c1"
+ assert cs[1].id == "c2"
+
+ def test_whitespace_only_response(self):
+ a = _analyzer()
+ _mock_response(a, " \n \n ")
+ cs = a.extract_constraints("query")
+ assert cs == []
+
+ def test_weight_with_annotation_parsed_in_full_flow(self):
+ """End-to-end: model returns weight like '0.7 (moderate)'."""
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "CONSTRAINT_1:\n"
+ "Type: comparison\n"
+ "Description: Greater than 100\n"
+ "Value: >100\n"
+ "Weight: 0.7 (moderate importance)\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 1
+ assert cs[0].weight == 0.7
+
+ def test_three_constraints_with_one_invalid_middle(self):
+ """First valid, second missing value, third valid — should yield 2 constraints."""
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "CONSTRAINT_1:\n"
+ "Type: property\n"
+ "Description: First\n"
+ "Value: v1\n"
+ "\n"
+ "CONSTRAINT_2:\n"
+ "Type: temporal\n"
+ "Description: Missing value field\n"
+ "\n"
+ "CONSTRAINT_3:\n"
+ "Type: location\n"
+ "Description: Third\n"
+ "Value: v3\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 2
+ assert cs[0].type == ConstraintType.PROPERTY
+ assert cs[1].type == ConstraintType.LOCATION
+ assert cs[0].id == "c1"
+ assert cs[1].id == "c2"
+
+ def test_unknown_type_defaults_to_property_in_full_flow(self):
+ a = _analyzer()
+ _mock_response(
+ a,
+ (
+ "CONSTRAINT_1:\n"
+ "Type: magical\n"
+ "Description: Unknown type\n"
+ "Value: val\n"
+ ),
+ )
+ cs = a.extract_constraints("query")
+ assert len(cs) == 1
+ assert cs[0].type == ConstraintType.PROPERTY
+
+ def test_model_invoke_receives_query_in_prompt(self):
+ """Verify the query text is passed to the model."""
+ a = _analyzer()
+ _mock_response(a, "")
+ a.extract_constraints("What is the capital of France?")
+ call_args = a.model.invoke.call_args[0][0]
+ assert "What is the capital of France?" in call_args
+
+
+# ===================================================================
+# Constraint list operations (filtering, sorting by criticality)
+# ===================================================================
+
+
+class TestConstraintListOperations:
+ def test_filter_critical_constraints(self):
+ constraints = [
+ _make(id="c1", type_=ConstraintType.PROPERTY, weight=0.5),
+ _make(id="c2", type_=ConstraintType.NAME_PATTERN, weight=0.3),
+ _make(id="c3", type_=ConstraintType.TEMPORAL, weight=0.9),
+ _make(id="c4", type_=ConstraintType.LOCATION, weight=0.7),
+ ]
+ critical = [c for c in constraints if c.is_critical()]
+ assert len(critical) == 2
+ assert {c.id for c in critical} == {"c2", "c3"}
+
+ def test_sort_constraints_by_weight(self):
+ constraints = [
+ _make(id="c1", weight=0.3),
+ _make(id="c2", weight=0.9),
+ _make(id="c3", weight=0.6),
+ ]
+ sorted_cs = sorted(constraints, key=lambda c: c.weight, reverse=True)
+ assert [c.id for c in sorted_cs] == ["c2", "c3", "c1"]
+
+ def test_to_search_terms_for_mixed_types(self):
+ constraints = [
+ _make(type_=ConstraintType.PROPERTY, value="glacier"),
+ _make(type_=ConstraintType.EVENT, value="landslide"),
+ _make(type_=ConstraintType.TEMPORAL, value="2023"),
+ ]
+ terms = [c.to_search_terms() for c in constraints]
+ assert terms[0] == "glacier"
+ assert "accident incident" in terms[1]
+ assert terms[2] == "2023"
diff --git a/tests/benchmarks/test_calculation_coverage.py b/tests/benchmarks/test_calculation_coverage.py
index 2921c8f703..ef727a5aee 100644
--- a/tests/benchmarks/test_calculation_coverage.py
+++ b/tests/benchmarks/test_calculation_coverage.py
@@ -19,6 +19,11 @@ from unittest.mock import MagicMock, patch
import pytest
+# ---------------------------------------------------------------------------
+# Helper to write JSONL files
+# ---------------------------------------------------------------------------
+
+
def _write_jsonl(path, records):
"""Write a list of dicts (or raw strings) to a JSONL file."""
with open(path, "w") as f:
@@ -29,6 +34,11 @@ def _write_jsonl(path, records):
f.write(json.dumps(r) + "\n")
+# ===========================================================================
+# calculate_metrics – coverage-gap tests
+# ===========================================================================
+
+
class TestCalculateMetricsCoverageGaps:
"""Tests targeting lines not yet exercised by existing suites."""
@@ -48,6 +58,7 @@ class TestCalculateMetricsCoverageGaps:
],
)
result = calculate_metrics(str(results_file))
+ # The function catches *any* exception while iterating and returns error
assert "error" in result
def test_confidence_as_integer_value(self, tmp_path):
@@ -104,7 +115,7 @@ class TestCalculateMetricsCoverageGaps:
assert metrics["average_confidence"] == 50
def test_confidence_as_float_string(self, tmp_path):
- """confidence='85.5' -- int('85.5') raises ValueError, skipped."""
+ """confidence='85.5' – int('85.5') raises ValueError, skipped."""
from local_deep_research.benchmarks.metrics.calculation import (
calculate_metrics,
)
@@ -118,10 +129,11 @@ class TestCalculateMetricsCoverageGaps:
],
)
metrics = calculate_metrics(str(results_file))
+ # "85.5" is skipped (ValueError on int()), only "100" counted
assert metrics["average_confidence"] == 100
def test_no_categories_key_absent_from_metrics(self, tmp_path):
- """When no result has 'category', metrics should not have 'categories'."""
+ """When no result has 'category', metrics should not contain 'categories'."""
from local_deep_research.benchmarks.metrics.calculation import (
calculate_metrics,
)
@@ -214,6 +226,11 @@ class TestCalculateMetricsCoverageGaps:
assert metrics["correct"] == 1
+# ===========================================================================
+# evaluate_benchmark_quality – mocked runner
+# ===========================================================================
+
+
class TestEvaluateBenchmarkQuality:
"""Tests for evaluate_benchmark_quality with mocked run_simpleqa_benchmark."""
@@ -227,6 +244,7 @@ class TestEvaluateBenchmarkQuality:
"local_deep_research.benchmarks.runners.run_simpleqa_benchmark",
return_value=mock_results,
) as mock_run:
+ # Provide an output_dir so no tempdir is created
result = evaluate_benchmark_quality(
system_config={"iterations": 1},
num_examples=5,
@@ -279,6 +297,7 @@ class TestEvaluateBenchmarkQuality:
evaluate_benchmark_quality,
)
+ # run_simpleqa_benchmark returns dict without "metrics"
with patch(
"local_deep_research.benchmarks.runners.run_simpleqa_benchmark",
return_value={},
@@ -356,17 +375,25 @@ class TestEvaluateBenchmarkQuality:
)
assert len(created_dirs) == 1
+ # The temp dir should have been cleaned up
assert not Path(created_dirs[0]).exists()
+# ===========================================================================
+# measure_execution_time – mocked SearchSystem
+# ===========================================================================
+
+
class TestMeasureExecutionTime:
"""Tests for measure_execution_time with mocked SearchSystem."""
- def _patch_search_system(self):
+ def _patch_search_system(self, search_time=0.1):
"""Return a context manager that patches SearchSystem."""
mock_system = MagicMock()
mock_system.search.return_value = "result"
+
mock_cls = MagicMock(return_value=mock_system)
+
return (
patch(
"local_deep_research.search_system.SearchSystem",
@@ -429,6 +456,7 @@ class TestMeasureExecutionTime:
num_runs=1,
)
+ # search_tool should have been set on the config
assert config["search_tool"] == "duckduckgo"
def test_exception_returns_zero_scores(self):
@@ -461,6 +489,8 @@ class TestMeasureExecutionTime:
)
mock_system = MagicMock()
+
+ # Make search take ~0 time (mock returns instantly)
mock_system.search.return_value = "r"
mock_cls = MagicMock(return_value=mock_system)
@@ -479,6 +509,11 @@ class TestMeasureExecutionTime:
assert result["speed_score"] == pytest.approx(expected_score, abs=0.01)
+# ===========================================================================
+# calculate_quality_metrics – delegates to evaluate_benchmark_quality
+# ===========================================================================
+
+
class TestCalculateQualityMetrics:
"""Tests for calculate_quality_metrics."""
@@ -518,6 +553,11 @@ class TestCalculateQualityMetrics:
assert result["accuracy"] == 0.0
+# ===========================================================================
+# calculate_speed_metrics – delegates to measure_execution_time
+# ===========================================================================
+
+
class TestCalculateSpeedMetrics:
"""Tests for calculate_speed_metrics."""
@@ -577,6 +617,11 @@ class TestCalculateSpeedMetrics:
)
+# ===========================================================================
+# calculate_resource_metrics – additional coverage
+# ===========================================================================
+
+
class TestCalculateResourceMetricsAdditional:
"""Additional resource metric tests for coverage gaps."""
@@ -618,6 +663,11 @@ class TestCalculateResourceMetricsAdditional:
)
+# ===========================================================================
+# calculate_combined_score – additional coverage
+# ===========================================================================
+
+
class TestCalculateCombinedScoreAdditional:
"""Additional combined score tests for coverage gaps."""
@@ -630,6 +680,7 @@ class TestCalculateCombinedScoreAdditional:
metrics = {"quality": {"quality_score": 1.0}}
weights = {"quality": 0.5, "speed": 0.3, "resource": 0.2}
score = calculate_combined_score(metrics, weights)
+ # Only quality matches: 1.0 * (0.5/1.0) = 0.5
assert score == pytest.approx(0.5)
def test_all_weights_equal(self):
@@ -659,6 +710,7 @@ class TestCalculateCombinedScoreAdditional:
}
weights = {"quality": 1000, "speed": 500, "resource": 500}
score = calculate_combined_score(metrics, weights)
+ # norm: quality=0.5, speed=0.25, resource=0.25
expected = 0.8 * 0.5 + 0.4 * 0.25 + 0.2 * 0.25
assert score == pytest.approx(expected)
diff --git a/tests/config/test_llm_config_coverage.py b/tests/config/test_llm_config_coverage.py
new file mode 100644
index 0000000000..17afe30232
--- /dev/null
+++ b/tests/config/test_llm_config_coverage.py
@@ -0,0 +1,1157 @@
+"""
+Comprehensive tests for provider availability functions and related helpers
+in local_deep_research/config/llm_config.py.
+
+Focuses on gaps not covered by existing test files:
+- is_*_available() import-error and exception branches
+- is_vllm_available() with mocked imports
+- get_available_providers() multi-provider and cache behaviour
+- wrap_llm_without_think_tags() context_limit injection, token counter, string responses
+- get_fallback_model() temperature parameter
+- _get_context_window_for_provider() edge cases
+- get_selected_llm_provider() with snapshot parameter
+"""
+
+import sys
+from unittest.mock import MagicMock, patch
+
+import pytest
+from langchain_core.language_models import FakeListChatModel
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+MODULE = "local_deep_research.config.llm_config"
+
+
+def _patch_all_availability(**overrides):
+ """Return a context manager that patches every is_*_available to False
+ unless overridden. Usage: _patch_all_availability(ollama=True, openai=True)
+ """
+ defaults = {
+ "ollama": False,
+ "openai": False,
+ "anthropic": False,
+ "google": False,
+ "openrouter": False,
+ "openai_endpoint": False,
+ "lmstudio": False,
+ "llamacpp": False,
+ "vllm": False,
+ }
+ defaults.update(overrides)
+
+ from contextlib import ExitStack
+
+ stack = ExitStack()
+ for name, val in defaults.items():
+ fn_name = f"is_{name}_available"
+ stack.enter_context(patch(f"{MODULE}.{fn_name}", return_value=val))
+ return stack
+
+
+# ===================================================================
+# is_openai_available
+# ===================================================================
+
+
+class TestIsOpenAIAvailable:
+ """Edge-case coverage for is_openai_available()."""
+
+ def test_import_error_returns_false(self):
+ """When OpenAIProvider cannot be imported, returns False."""
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.implementations.openai": None},
+ ):
+ # Force re-import by calling the function which does a local import
+ from local_deep_research.config.llm_config import (
+ is_openai_available,
+ )
+
+ result = is_openai_available()
+ assert result is False
+
+ def test_passes_settings_snapshot_through(self):
+ """settings_snapshot is forwarded to OpenAIProvider.is_available."""
+ snap = {"llm.openai.api_key": "sk-test"}
+ with patch(
+ "local_deep_research.llm.providers.implementations.openai.OpenAIProvider.is_available",
+ return_value=True,
+ ) as mock_avail:
+ from local_deep_research.config.llm_config import (
+ is_openai_available,
+ )
+
+ is_openai_available(settings_snapshot=snap)
+ mock_avail.assert_called_once_with(snap)
+
+
+# ===================================================================
+# is_anthropic_available
+# ===================================================================
+
+
+class TestIsAnthropicAvailable:
+ """Edge-case coverage for is_anthropic_available()."""
+
+ def test_import_error_returns_false(self):
+ with patch.dict(
+ sys.modules,
+ {
+ "local_deep_research.llm.providers.implementations.anthropic": None
+ },
+ ):
+ from local_deep_research.config.llm_config import (
+ is_anthropic_available,
+ )
+
+ result = is_anthropic_available()
+ assert result is False
+
+ def test_passes_settings_snapshot_through(self):
+ snap = {"llm.anthropic.api_key": "sk-ant-x"}
+ with patch(
+ "local_deep_research.llm.providers.implementations.anthropic.AnthropicProvider.is_available",
+ return_value=True,
+ ) as mock_avail:
+ from local_deep_research.config.llm_config import (
+ is_anthropic_available,
+ )
+
+ is_anthropic_available(settings_snapshot=snap)
+ mock_avail.assert_called_once_with(snap)
+
+
+# ===================================================================
+# is_ollama_available
+# ===================================================================
+
+
+class TestIsOllamaAvailable:
+ """Edge-case coverage for is_ollama_available()."""
+
+ def test_import_error_returns_false(self):
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.implementations.ollama": None},
+ ):
+ from local_deep_research.config.llm_config import (
+ is_ollama_available,
+ )
+
+ result = is_ollama_available()
+ assert result is False
+
+ def test_passes_settings_snapshot_through(self):
+ snap = {"llm.ollama.url": "http://localhost:11434"}
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.OllamaProvider.is_available",
+ return_value=True,
+ ) as mock_avail:
+ from local_deep_research.config.llm_config import (
+ is_ollama_available,
+ )
+
+ is_ollama_available(settings_snapshot=snap)
+ mock_avail.assert_called_once_with(snap)
+
+
+# ===================================================================
+# is_openai_endpoint_available
+# ===================================================================
+
+
+class TestIsOpenAIEndpointAvailable:
+ """Edge-case coverage for is_openai_endpoint_available()."""
+
+ def test_import_error_returns_false(self):
+ with patch.dict(
+ sys.modules,
+ {
+ "local_deep_research.llm.providers.implementations.custom_openai_endpoint": None
+ },
+ ):
+ from local_deep_research.config.llm_config import (
+ is_openai_endpoint_available,
+ )
+
+ result = is_openai_endpoint_available()
+ assert result is False
+
+ def test_exception_returns_false(self):
+ with patch(
+ "local_deep_research.llm.providers.implementations.custom_openai_endpoint.CustomOpenAIEndpointProvider.is_available",
+ side_effect=RuntimeError("boom"),
+ ):
+ from local_deep_research.config.llm_config import (
+ is_openai_endpoint_available,
+ )
+
+ assert is_openai_endpoint_available() is False
+
+
+# ===================================================================
+# is_lmstudio_available
+# ===================================================================
+
+
+class TestIsLMStudioAvailable:
+ """Edge-case coverage for is_lmstudio_available()."""
+
+ def test_import_error_returns_false(self):
+ with patch.dict(
+ sys.modules,
+ {
+ "local_deep_research.llm.providers.implementations.lmstudio": None
+ },
+ ):
+ from local_deep_research.config.llm_config import (
+ is_lmstudio_available,
+ )
+
+ result = is_lmstudio_available()
+ assert result is False
+
+ def test_exception_returns_false(self):
+ with patch(
+ "local_deep_research.llm.providers.implementations.lmstudio.LMStudioProvider.is_available",
+ side_effect=RuntimeError("boom"),
+ ):
+ from local_deep_research.config.llm_config import (
+ is_lmstudio_available,
+ )
+
+ assert is_lmstudio_available() is False
+
+
+# ===================================================================
+# is_llamacpp_available
+# ===================================================================
+
+
+class TestIsLlamaCppAvailable:
+ """Edge-case coverage for is_llamacpp_available()."""
+
+ def test_import_error_returns_false(self):
+ """LlamaCpp library not installed returns False."""
+ with patch.dict(sys.modules, {"langchain_community.llms": None}):
+ from local_deep_research.config.llm_config import (
+ is_llamacpp_available,
+ )
+
+ result = is_llamacpp_available()
+ assert result is False
+
+ def test_empty_string_path_returns_false(self):
+ """Empty-string model path is treated as not configured."""
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value="",
+ ):
+ from local_deep_research.config.llm_config import (
+ is_llamacpp_available,
+ )
+
+ assert is_llamacpp_available() is False
+
+ def test_non_empty_path_returns_true(self):
+ """Non-empty model path returns True (path validation is deferred)."""
+ with (
+ patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value="/some/model.gguf",
+ ),
+ patch.dict(sys.modules, {"langchain_community.llms": MagicMock()}),
+ ):
+ from local_deep_research.config.llm_config import (
+ is_llamacpp_available,
+ )
+
+ assert is_llamacpp_available() is True
+
+ def test_generic_exception_returns_false(self):
+ """Unexpected exception in is_llamacpp_available returns False."""
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ side_effect=RuntimeError("unexpected"),
+ ):
+ from local_deep_research.config.llm_config import (
+ is_llamacpp_available,
+ )
+
+ assert is_llamacpp_available() is False
+
+
+# ===================================================================
+# is_google_available
+# ===================================================================
+
+
+class TestIsGoogleAvailable:
+ """Edge-case coverage for is_google_available()."""
+
+ def test_import_error_returns_false(self):
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.google": None},
+ ):
+ from local_deep_research.config.llm_config import (
+ is_google_available,
+ )
+
+ assert is_google_available() is False
+
+ def test_exception_returns_false(self):
+ """When GoogleProvider.is_available raises, returns False."""
+ mock_module = MagicMock()
+ mock_module.GoogleProvider.is_available.side_effect = RuntimeError(
+ "boom"
+ )
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.google": mock_module},
+ ):
+ from local_deep_research.config.llm_config import (
+ is_google_available,
+ )
+
+ assert is_google_available() is False
+
+ def test_returns_true_when_provider_reports_available(self):
+ mock_module = MagicMock()
+ mock_module.GoogleProvider.is_available.return_value = True
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.google": mock_module},
+ ):
+ from local_deep_research.config.llm_config import (
+ is_google_available,
+ )
+
+ assert is_google_available() is True
+
+ def test_returns_false_when_provider_reports_unavailable(self):
+ mock_module = MagicMock()
+ mock_module.GoogleProvider.is_available.return_value = False
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.google": mock_module},
+ ):
+ from local_deep_research.config.llm_config import (
+ is_google_available,
+ )
+
+ assert is_google_available() is False
+
+
+# ===================================================================
+# is_openrouter_available
+# ===================================================================
+
+
+class TestIsOpenRouterAvailable:
+ """Edge-case coverage for is_openrouter_available()."""
+
+ def test_import_error_returns_false(self):
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.openrouter": None},
+ ):
+ from local_deep_research.config.llm_config import (
+ is_openrouter_available,
+ )
+
+ assert is_openrouter_available() is False
+
+ def test_exception_returns_false(self):
+ mock_module = MagicMock()
+ mock_module.OpenRouterProvider.is_available.side_effect = RuntimeError(
+ "boom"
+ )
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.openrouter": mock_module},
+ ):
+ from local_deep_research.config.llm_config import (
+ is_openrouter_available,
+ )
+
+ assert is_openrouter_available() is False
+
+ def test_returns_true_when_provider_reports_available(self):
+ mock_module = MagicMock()
+ mock_module.OpenRouterProvider.is_available.return_value = True
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.openrouter": mock_module},
+ ):
+ from local_deep_research.config.llm_config import (
+ is_openrouter_available,
+ )
+
+ assert is_openrouter_available() is True
+
+ def test_returns_false_when_provider_reports_unavailable(self):
+ mock_module = MagicMock()
+ mock_module.OpenRouterProvider.is_available.return_value = False
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.llm.providers.openrouter": mock_module},
+ ):
+ from local_deep_research.config.llm_config import (
+ is_openrouter_available,
+ )
+
+ assert is_openrouter_available() is False
+
+
+# ===================================================================
+# is_vllm_available (import-gated, no provider class)
+# ===================================================================
+
+
+class TestIsVLLMAvailable:
+ """Tests for is_vllm_available() which checks torch, transformers, vllm imports."""
+
+ def test_returns_false_when_torch_missing(self):
+ """Missing torch -> False."""
+ from local_deep_research.config.llm_config import is_vllm_available
+
+ with patch.dict(sys.modules, {"torch": None}):
+ # Force the function to re-execute the import check
+ # We need to call the actual function, but it caches via try/except
+ # so patching sys.modules is sufficient if we trigger an ImportError
+ original_import = (
+ __builtins__.__import__
+ if hasattr(__builtins__, "__import__")
+ else __import__
+ )
+
+ def mock_import(name, *args, **kwargs):
+ if name == "torch":
+ raise ImportError("no torch")
+ return original_import(name, *args, **kwargs)
+
+ with patch("builtins.__import__", side_effect=mock_import):
+ assert is_vllm_available() is False
+
+ def test_returns_false_when_vllm_missing(self):
+ """Missing vllm -> False."""
+ from local_deep_research.config.llm_config import is_vllm_available
+
+ original_import = __import__
+
+ def mock_import(name, *args, **kwargs):
+ if name == "vllm":
+ raise ImportError("no vllm")
+ return original_import(name, *args, **kwargs)
+
+ with patch("builtins.__import__", side_effect=mock_import):
+ assert is_vllm_available() is False
+
+ def test_returns_false_when_langchain_vllm_missing(self):
+ """Missing langchain_community.llms.VLLM -> False."""
+ from local_deep_research.config.llm_config import is_vllm_available
+
+ original_import = __import__
+
+ def mock_import(name, *args, **kwargs):
+ if name == "langchain_community.llms" or (
+ name == "langchain_community" and "VLLM" in str(args)
+ ):
+ raise ImportError("no VLLM class")
+ return original_import(name, *args, **kwargs)
+
+ with patch("builtins.__import__", side_effect=mock_import):
+ assert is_vllm_available() is False
+
+
+# ===================================================================
+# get_available_providers (cached function)
+# ===================================================================
+
+
+class TestGetAvailableProviders:
+ """Tests for get_available_providers() with multiple providers and cache."""
+
+ def setup_method(self):
+ """Clear the LRU cache before each test."""
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ get_available_providers.cache_clear()
+
+ def test_no_providers_returns_none_key(self):
+ """When nothing is available, dict contains only 'none'."""
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability():
+ result = get_available_providers()
+ assert result == {"none": "No model providers available"}
+
+ def test_only_ollama_available(self):
+ """Only ollama available."""
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(ollama=True):
+ result = get_available_providers()
+ assert "ollama" in result
+ assert result["ollama"] == "Ollama (local models)"
+ assert "none" not in result
+
+ def test_only_openai_available(self):
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(openai=True):
+ result = get_available_providers()
+ assert "openai" in result
+ assert result["openai"] == "OpenAI API"
+ assert "none" not in result
+
+ def test_only_anthropic_available(self):
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(anthropic=True):
+ result = get_available_providers()
+ assert "anthropic" in result
+ assert result["anthropic"] == "Anthropic API"
+
+ def test_only_google_available(self):
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(google=True):
+ result = get_available_providers()
+ assert "google" in result
+ assert result["google"] == "Google Gemini API"
+
+ def test_only_openrouter_available(self):
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(openrouter=True):
+ result = get_available_providers()
+ assert "openrouter" in result
+ assert result["openrouter"] == "OpenRouter API"
+
+ def test_only_openai_endpoint_available(self):
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(openai_endpoint=True):
+ result = get_available_providers()
+ assert "openai_endpoint" in result
+ assert result["openai_endpoint"] == "OpenAI-compatible Endpoint"
+
+ def test_only_lmstudio_available(self):
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(lmstudio=True):
+ result = get_available_providers()
+ assert "lmstudio" in result
+ assert result["lmstudio"] == "LM Studio (local models)"
+
+ def test_only_llamacpp_available(self):
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(llamacpp=True):
+ result = get_available_providers()
+ assert "llamacpp" in result
+ assert result["llamacpp"] == "LlamaCpp (local models)"
+
+ def test_only_vllm_available(self):
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(vllm=True):
+ result = get_available_providers()
+ assert "vllm" in result
+ assert result["vllm"] == "VLLM (local models)"
+
+ def test_multiple_providers_available(self):
+ """Multiple providers yields dict with all of them, no 'none'."""
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(ollama=True, openai=True, anthropic=True):
+ result = get_available_providers()
+ assert "ollama" in result
+ assert "openai" in result
+ assert "anthropic" in result
+ assert "none" not in result
+
+ def test_all_providers_available(self):
+ """All providers enabled results in all keys present."""
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(
+ ollama=True,
+ openai=True,
+ anthropic=True,
+ google=True,
+ openrouter=True,
+ openai_endpoint=True,
+ lmstudio=True,
+ llamacpp=True,
+ vllm=True,
+ ):
+ result = get_available_providers()
+ assert len(result) == 9
+ assert "none" not in result
+
+ def test_cache_returns_same_object(self):
+ """Calling twice without cache_clear returns the cached dict."""
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(openai=True):
+ first = get_available_providers()
+ second = get_available_providers()
+ assert first is second
+
+ def test_cache_clear_resets(self):
+ """After cache_clear, function re-evaluates availability."""
+ from local_deep_research.config.llm_config import (
+ get_available_providers,
+ )
+
+ with _patch_all_availability(openai=True):
+ first = get_available_providers()
+ assert "openai" in first
+
+ get_available_providers.cache_clear()
+
+ with _patch_all_availability(anthropic=True):
+ second = get_available_providers()
+ assert "anthropic" in second
+ assert "openai" not in second
+
+
+# ===================================================================
+# get_selected_llm_provider
+# ===================================================================
+
+
+class TestGetSelectedLlmProvider:
+ """Additional coverage for get_selected_llm_provider()."""
+
+ def test_with_explicit_snapshot(self):
+ from local_deep_research.config.llm_config import (
+ get_selected_llm_provider,
+ )
+
+ result = get_selected_llm_provider(
+ settings_snapshot={"llm.provider": "Google"}
+ )
+ assert result == "google"
+
+ def test_mixed_case_normalised(self):
+ from local_deep_research.config.llm_config import (
+ get_selected_llm_provider,
+ )
+
+ result = get_selected_llm_provider(
+ settings_snapshot={"llm.provider": "OpenAI_Endpoint"}
+ )
+ assert result == "openai_endpoint"
+
+ def test_default_when_key_missing(self):
+ from local_deep_research.config.llm_config import (
+ get_selected_llm_provider,
+ )
+
+ result = get_selected_llm_provider(settings_snapshot={})
+ assert result == "ollama"
+
+
+# ===================================================================
+# _get_context_window_for_provider (additional edge cases)
+# ===================================================================
+
+
+class TestGetContextWindowForProvider:
+ """Additional edge-case coverage for _get_context_window_for_provider."""
+
+ def test_vllm_treated_as_cloud(self):
+ """vllm is not in the local list, so it goes through the cloud branch."""
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=True,
+ ):
+ from local_deep_research.config.llm_config import (
+ _get_context_window_for_provider,
+ )
+
+ result = _get_context_window_for_provider("vllm")
+ assert result is None # unrestricted cloud
+
+ def test_openrouter_treated_as_cloud(self):
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=True,
+ ):
+ from local_deep_research.config.llm_config import (
+ _get_context_window_for_provider,
+ )
+
+ assert _get_context_window_for_provider("openrouter") is None
+
+ def test_local_provider_with_float_value(self):
+ """Float value from settings is coerced to int."""
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=8192.7,
+ ):
+ from local_deep_research.config.llm_config import (
+ _get_context_window_for_provider,
+ )
+
+ result = _get_context_window_for_provider("lmstudio")
+ assert result == 8192
+ assert isinstance(result, int)
+
+ def test_cloud_restricted_with_float_value(self):
+ """Float cloud window is coerced to int."""
+ call_num = [0]
+
+ def fake_setting(key, default, settings_snapshot=None):
+ call_num[0] += 1
+ if key == "llm.context_window_unrestricted":
+ return False
+ if key == "llm.context_window_size":
+ return 65536.9
+ return default
+
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=fake_setting
+ ):
+ from local_deep_research.config.llm_config import (
+ _get_context_window_for_provider,
+ )
+
+ result = _get_context_window_for_provider("openai")
+ assert result == 65536
+ assert isinstance(result, int)
+
+
+# ===================================================================
+# get_fallback_model
+# ===================================================================
+
+
+class TestGetFallbackModel:
+ """Additional coverage for get_fallback_model()."""
+
+ def test_returns_fake_list_chat_model(self):
+ from local_deep_research.config.llm_config import get_fallback_model
+
+ model = get_fallback_model()
+ assert isinstance(model, FakeListChatModel)
+
+ def test_temperature_param_accepted(self):
+ """temperature parameter is accepted (even though FakeListChatModel ignores it)."""
+ from local_deep_research.config.llm_config import get_fallback_model
+
+ model = get_fallback_model(temperature=0.0)
+ assert isinstance(model, FakeListChatModel)
+
+ def test_none_temperature_accepted(self):
+ from local_deep_research.config.llm_config import get_fallback_model
+
+ model = get_fallback_model(temperature=None)
+ assert isinstance(model, FakeListChatModel)
+
+ def test_response_text_mentions_ollama_or_api_keys(self):
+ from local_deep_research.config.llm_config import get_fallback_model
+
+ model = get_fallback_model()
+ msg = model.responses[0]
+ assert "Ollama" in msg or "API keys" in msg
+
+ def test_invocation_returns_ai_message(self):
+ from local_deep_research.config.llm_config import get_fallback_model
+
+ model = get_fallback_model()
+ response = model.invoke("hello")
+ assert hasattr(response, "content")
+ assert "No language models" in response.content
+
+
+# ===================================================================
+# wrap_llm_without_think_tags
+# ===================================================================
+
+
+class TestWrapLlmWithoutThinkTags:
+ """Comprehensive tests for the ProcessingLLMWrapper created by wrap_llm_without_think_tags."""
+
+ def _make_wrapper(self, mock_llm, **kwargs):
+ """Create wrapper with rate-limiting disabled."""
+ defaults = {
+ "research_id": None,
+ "provider": None,
+ "research_context": None,
+ "settings_snapshot": None,
+ }
+ defaults.update(kwargs)
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ return wrap_llm_without_think_tags(mock_llm, **defaults)
+
+ # --- basic wrapper behaviour ---
+
+ def test_wrapper_has_base_llm(self):
+ llm = MagicMock()
+ w = self._make_wrapper(llm)
+ assert w.base_llm is llm
+
+ def test_invoke_calls_base_llm(self):
+ llm = MagicMock()
+ resp = MagicMock()
+ resp.content = "hello"
+ llm.invoke.return_value = resp
+ w = self._make_wrapper(llm)
+ w.invoke("prompt")
+ llm.invoke.assert_called_once_with("prompt")
+
+ def test_think_tags_removed_from_content(self):
+ llm = MagicMock()
+ resp = MagicMock()
+ resp.content = "<think>internal reasoning</think>final answer"
+ llm.invoke.return_value = resp
+ w = self._make_wrapper(llm)
+ result = w.invoke("prompt")
+ assert "<think>" not in result.content
+ assert "final answer" in result.content
+
+ def test_think_tags_removed_from_string_response(self):
+ llm = MagicMock()
+ llm.invoke.return_value = "<think>thought</think>answer"
+ w = self._make_wrapper(llm)
+ result = w.invoke("prompt")
+ assert isinstance(result, str)
+ assert "<think>" not in result
+ assert "answer" in result
+
+ def test_response_without_content_attr_returned_as_is(self):
+ """Response that is neither string nor has .content is passed through."""
+ llm = MagicMock()
+ resp = 42 # int has no .content
+ llm.invoke.return_value = resp
+ w = self._make_wrapper(llm)
+ result = w.invoke("prompt")
+ assert result == 42
+
+ def test_invoke_exception_propagated(self):
+ llm = MagicMock()
+ llm.invoke.side_effect = ConnectionError("timeout")
+ w = self._make_wrapper(llm)
+ with pytest.raises(ConnectionError, match="timeout"):
+ w.invoke("prompt")
+
+ # --- __getattr__ delegation ---
+
+ def test_getattr_delegates_to_base_llm(self):
+ llm = MagicMock()
+ llm.model_name = "gpt-4"
+ llm.some_custom_attr = "custom_value"
+ w = self._make_wrapper(llm)
+ assert w.model_name == "gpt-4"
+ assert w.some_custom_attr == "custom_value"
+
+ # --- context_limit injection ---
+
+ def test_context_limit_set_in_research_context(self):
+ """wrap_llm sets context_limit in research_context when provider is local."""
+ llm = MagicMock()
+ research_ctx = {}
+
+ def fake_setting(key, default=None, settings_snapshot=None):
+ if key == "rate_limiting.llm_enabled":
+ return False
+ if key == "llm.local_context_window_size":
+ return 4096
+ return default
+
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=fake_setting
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrap_llm_without_think_tags(
+ llm, provider="ollama", research_context=research_ctx
+ )
+ assert research_ctx.get("context_limit") == 4096
+
+ def test_context_limit_not_overwritten_if_already_set(self):
+ """If research_context already has context_limit, it should NOT be overwritten."""
+ llm = MagicMock()
+ research_ctx = {"context_limit": 9999}
+
+ def fake_setting(key, default=None, settings_snapshot=None):
+ if key == "rate_limiting.llm_enabled":
+ return False
+ if key == "llm.local_context_window_size":
+ return 4096
+ return default
+
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=fake_setting
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrap_llm_without_think_tags(
+ llm, provider="ollama", research_context=research_ctx
+ )
+ assert research_ctx["context_limit"] == 9999
+
+ def test_context_limit_not_set_for_unrestricted_cloud(self):
+ """Cloud unrestricted provider returns None window, so context_limit not set."""
+ llm = MagicMock()
+ research_ctx = {}
+
+ def fake_setting(key, default=None, settings_snapshot=None):
+ if key == "rate_limiting.llm_enabled":
+ return False
+ if key == "llm.context_window_unrestricted":
+ return True
+ return default
+
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot", side_effect=fake_setting
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrap_llm_without_think_tags(
+ llm, provider="openai", research_context=research_ctx
+ )
+ assert "context_limit" not in research_ctx
+
+ def test_no_crash_when_research_context_is_none(self):
+ """No crash when research_context=None."""
+ llm = MagicMock()
+ w = self._make_wrapper(llm, provider="openai", research_context=None)
+ assert w is not None
+
+ # --- rate limiting integration ---
+
+ def test_rate_limiting_applied_when_enabled(self):
+ llm = MagicMock()
+ rate_limited_llm = MagicMock()
+
+ with (
+ patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.rate_limiting.llm.create_rate_limited_llm_wrapper",
+ return_value=rate_limited_llm,
+ ) as mock_rl,
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrapper = wrap_llm_without_think_tags(llm, provider="openai")
+ mock_rl.assert_called_once_with(llm, "openai")
+ # The wrapper wraps the rate-limited LLM
+ assert wrapper.base_llm is rate_limited_llm
+
+ def test_rate_limiting_not_applied_when_disabled(self):
+ llm = MagicMock()
+
+ with (
+ patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.rate_limiting.llm.create_rate_limited_llm_wrapper",
+ ) as mock_rl,
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrapper = wrap_llm_without_think_tags(llm, provider="openai")
+ mock_rl.assert_not_called()
+ assert wrapper.base_llm is llm
+
+ # --- token counter callback ---
+
+ def test_token_counter_attached_when_research_id_given(self):
+ """When research_id is set, a token counting callback is added."""
+ llm = MagicMock()
+ llm.callbacks = None
+ llm.model_name = "test-model"
+
+ mock_counter = MagicMock()
+ mock_callback = MagicMock()
+ mock_counter.create_callback.return_value = mock_callback
+
+ with (
+ patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.metrics.TokenCounter",
+ return_value=mock_counter,
+ ),
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrap_llm_without_think_tags(llm, research_id=42, provider="openai")
+ mock_counter.create_callback.assert_called_once_with(42, None)
+ assert mock_callback.preset_provider == "openai"
+ assert mock_callback.preset_model == "test-model"
+
+ def test_token_counter_uses_model_attr_fallback(self):
+ """If llm has .model but not .model_name, uses .model."""
+ llm = MagicMock(spec=["invoke", "callbacks", "model"])
+ llm.callbacks = None
+ llm.model = "claude-3-opus"
+
+ mock_counter = MagicMock()
+ mock_callback = MagicMock()
+ mock_counter.create_callback.return_value = mock_callback
+
+ with (
+ patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.metrics.TokenCounter",
+ return_value=mock_counter,
+ ),
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrap_llm_without_think_tags(
+ llm, research_id=1, provider="anthropic"
+ )
+ assert mock_callback.preset_model == "claude-3-opus"
+
+ def test_callbacks_extended_when_existing(self):
+ """If llm.callbacks already has entries, new callback is appended."""
+ existing_cb = MagicMock()
+ llm = MagicMock()
+ llm.callbacks = [existing_cb]
+ llm.model_name = "m"
+
+ mock_counter = MagicMock()
+ mock_callback = MagicMock()
+ mock_counter.create_callback.return_value = mock_callback
+
+ with (
+ patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.metrics.TokenCounter",
+ return_value=mock_counter,
+ ),
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrap_llm_without_think_tags(llm, research_id=10)
+ assert mock_callback in llm.callbacks
+ assert existing_cb in llm.callbacks
+
+ def test_no_callbacks_when_no_research_id(self):
+ """When research_id is None, no callbacks are attached."""
+ llm = MagicMock()
+ llm.callbacks = None
+
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrap_llm_without_think_tags(llm, research_id=None)
+ # callbacks should remain None (nothing to attach)
+ assert llm.callbacks is None
+
+
+# ===================================================================
+# VALID_PROVIDERS constant
+# ===================================================================
+
+
+class TestValidProviders:
+ """Sanity checks for the VALID_PROVIDERS list."""
+
+ def test_contains_all_expected(self):
+ from local_deep_research.config.llm_config import VALID_PROVIDERS
+
+ expected = {
+ "ollama",
+ "openai",
+ "anthropic",
+ "google",
+ "openrouter",
+ "vllm",
+ "openai_endpoint",
+ "lmstudio",
+ "llamacpp",
+ "none",
+ }
+ assert set(VALID_PROVIDERS) == expected
+
+ def test_is_list(self):
+ from local_deep_research.config.llm_config import VALID_PROVIDERS
+
+ assert isinstance(VALID_PROVIDERS, list)
+
+ def test_no_duplicates(self):
+ from local_deep_research.config.llm_config import VALID_PROVIDERS
+
+ assert len(VALID_PROVIDERS) == len(set(VALID_PROVIDERS))
diff --git a/tests/document_loaders/test_loader_registry_coverage.py b/tests/document_loaders/test_loader_registry_coverage.py
new file mode 100644
index 0000000000..334ea33179
--- /dev/null
+++ b/tests/document_loaders/test_loader_registry_coverage.py
@@ -0,0 +1,450 @@
+"""
+Comprehensive tests for loader_registry module.
+
+Covers registry lookup logic, loader selection by file type,
+optional-loader availability flags, loader kwargs, error handling,
+and edge cases not covered in existing test files.
+"""
+
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+from langchain_core.document_loaders import BaseLoader
+
+from local_deep_research.document_loaders.loader_registry import (
+ LOADER_REGISTRY,
+ get_loader_class_for_extension,
+ get_loader_for_path,
+ get_supported_extensions,
+ is_extension_supported,
+)
+
+
+# ---------------------------------------------------------------------------
+# Registry structure and content
+# ---------------------------------------------------------------------------
+
+
+class TestRegistryStructure:
+ """Verify the structure and invariants of LOADER_REGISTRY."""
+
+ def test_every_loader_class_is_a_type(self):
+ """Every loader_class value must be a class (type), not an instance."""
+ for ext, entry in LOADER_REGISTRY.items():
+ assert isinstance(entry["loader_class"], type), (
+ f"{ext}: loader_class should be a type, got {type(entry['loader_class'])}"
+ )
+
+ def test_loader_kwargs_defaults_to_empty_dict(self):
+ """loader_kwargs should always be a dict (may be empty)."""
+ for ext, entry in LOADER_REGISTRY.items():
+ kwargs = entry.get("loader_kwargs", {})
+ assert isinstance(kwargs, dict), (
+ f"{ext}: loader_kwargs is not a dict"
+ )
+
+ def test_minimum_number_of_registered_extensions(self):
+ """Registry should have a reasonable minimum number of extensions."""
+ # Core set: pdf, txt, md, markdown, docx, doc, csv, xlsx, xls,
+ # html, htm, ppt, pptx, xml, eml, tsv, json, yaml, yml,
+ # ipynb, enex, toml, mhtml, mht = 24
+ assert len(LOADER_REGISTRY) >= 24
+
+
+class TestRegistrySpecificLoaderClasses:
+ """Verify that specific extensions map to the expected loader class."""
+
+ @pytest.mark.parametrize(
+ "ext, expected_class_name",
+ [
+ (".pdf", "PyPDFLoader"),
+ (".txt", "TextLoader"),
+ (".md", "UnstructuredMarkdownLoader"),
+ (".markdown", "UnstructuredMarkdownLoader"),
+ (".docx", "UnstructuredWordDocumentLoader"),
+ (".doc", "UnstructuredWordDocumentLoader"),
+ (".csv", "CSVLoader"),
+ (".xlsx", "UnstructuredExcelLoader"),
+ (".xls", "UnstructuredExcelLoader"),
+ (".html", "UnstructuredHTMLLoader"),
+ (".htm", "UnstructuredHTMLLoader"),
+ (".ppt", "UnstructuredPowerPointLoader"),
+ (".pptx", "UnstructuredPowerPointLoader"),
+ (".xml", "UnstructuredXMLLoader"),
+ (".eml", "UnstructuredEmailLoader"),
+ (".tsv", "CSVLoader"),
+ (".json", "SimpleJSONLoader"),
+ (".yaml", "YAMLLoader"),
+ (".yml", "YAMLLoader"),
+ (".ipynb", "NotebookLoader"),
+ (".enex", "EverNoteLoader"),
+ (".toml", "TomlLoader"),
+ (".mhtml", "MHTMLLoader"),
+ (".mht", "MHTMLLoader"),
+ ],
+ )
+ def test_extension_maps_to_expected_class(self, ext, expected_class_name):
+ entry = LOADER_REGISTRY[ext]
+ assert entry["loader_class"].__name__ == expected_class_name
+
+
+class TestRegistrySpecificKwargs:
+ """Test that specific extensions carry the expected kwargs."""
+
+ def test_txt_encoding_kwargs(self):
+ entry = LOADER_REGISTRY[".txt"]
+ assert entry["loader_kwargs"]["encoding"] == "utf-8"
+ assert entry["loader_kwargs"]["autodetect_encoding"] is True
+
+ def test_tsv_delimiter_kwargs(self):
+ entry = LOADER_REGISTRY[".tsv"]
+ assert "csv_args" in entry["loader_kwargs"]
+ assert entry["loader_kwargs"]["csv_args"]["delimiter"] == "\t"
+
+ def test_ipynb_include_outputs(self):
+ entry = LOADER_REGISTRY[".ipynb"]
+ assert entry["loader_kwargs"]["include_outputs"] is True
+ assert entry["loader_kwargs"]["remove_newline"] is True
+
+ def test_enex_load_single_document_false(self):
+ entry = LOADER_REGISTRY[".enex"]
+ assert entry["loader_kwargs"]["load_single_document"] is False
+
+ def test_pdf_kwargs_empty(self):
+ entry = LOADER_REGISTRY[".pdf"]
+ assert entry["loader_kwargs"] == {}
+
+
+# ---------------------------------------------------------------------------
+# Optional loader availability flags
+# ---------------------------------------------------------------------------
+
+
+class TestOptionalLoaderFlags:
+ """Test that optional loaders are conditionally registered."""
+
+ def test_odt_conditional_registration(self):
+ from local_deep_research.document_loaders import loader_registry as mod
+
+ if mod.HAS_ODT_LOADER:
+ assert ".odt" in LOADER_REGISTRY
+ else:
+ assert ".odt" not in LOADER_REGISTRY
+
+ def test_epub_conditional_registration(self):
+ from local_deep_research.document_loaders import loader_registry as mod
+
+ if mod.HAS_EPUB_LOADER:
+ assert ".epub" in LOADER_REGISTRY
+ else:
+ assert ".epub" not in LOADER_REGISTRY
+
+ def test_rtf_conditional_registration(self):
+ from local_deep_research.document_loaders import loader_registry as mod
+
+ if mod.HAS_RTF_LOADER:
+ assert ".rtf" in LOADER_REGISTRY
+ else:
+ assert ".rtf" not in LOADER_REGISTRY
+
+ def test_rst_conditional_registration(self):
+ from local_deep_research.document_loaders import loader_registry as mod
+
+ if mod.HAS_RST_LOADER:
+ assert ".rst" in LOADER_REGISTRY
+ else:
+ assert ".rst" not in LOADER_REGISTRY
+
+ def test_org_conditional_registration(self):
+ from local_deep_research.document_loaders import loader_registry as mod
+
+ if mod.HAS_ORG_LOADER:
+ assert ".org" in LOADER_REGISTRY
+ else:
+ assert ".org" not in LOADER_REGISTRY
+
+ def test_image_conditional_registration(self):
+ from local_deep_research.document_loaders import loader_registry as mod
+
+ image_exts = [".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".heic"]
+ if mod.HAS_IMAGE_LOADER:
+ for ext in image_exts:
+ assert ext in LOADER_REGISTRY, (
+ f"{ext} missing despite HAS_IMAGE_LOADER"
+ )
+ else:
+ for ext in image_exts:
+ assert ext not in LOADER_REGISTRY, (
+ f"{ext} present despite no HAS_IMAGE_LOADER"
+ )
+
+
+# ---------------------------------------------------------------------------
+# get_supported_extensions
+# ---------------------------------------------------------------------------
+
+
+class TestGetSupportedExtensionsCoverage:
+ def test_matches_registry_keys(self):
+ """Return value must match LOADER_REGISTRY keys exactly."""
+ assert set(get_supported_extensions()) == set(LOADER_REGISTRY.keys())
+
+ def test_returns_fresh_list_each_call(self):
+ """Each call returns a new list object (no shared mutable state)."""
+ a = get_supported_extensions()
+ b = get_supported_extensions()
+ assert a is not b
+
+
+# ---------------------------------------------------------------------------
+# is_extension_supported - additional edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestIsExtensionSupportedEdgeCases:
+ def test_empty_string(self):
+ assert is_extension_supported("") is False
+
+ def test_dot_only(self):
+ assert is_extension_supported(".") is False
+
+ def test_multiple_dots(self):
+ """Extension like '.tar.gz' -- only last suffix matters in Path, but
+ the function receives raw string; '.tar.gz' starts with dot so treated
+ as-is and should not match."""
+ assert is_extension_supported(".tar.gz") is False
+
+ def test_whitespace_extension(self):
+ assert is_extension_supported(" ") is False
+ assert is_extension_supported(" .pdf") is False
+
+ def test_numeric_extension(self):
+ assert is_extension_supported(".123") is False
+
+ def test_all_registered_extensions_report_supported(self):
+ """Cross-check: every key in LOADER_REGISTRY should be supported."""
+ for ext in LOADER_REGISTRY:
+ assert is_extension_supported(ext) is True, (
+ f"{ext} not reported as supported"
+ )
+
+ def test_without_dot_case_insensitive(self):
+ """Without-dot + uppercase should still resolve."""
+ assert is_extension_supported("JSON") is True
+ assert is_extension_supported("Csv") is True
+
+
+# ---------------------------------------------------------------------------
+# get_loader_class_for_extension - additional coverage
+# ---------------------------------------------------------------------------
+
+
+class TestGetLoaderClassForExtensionCoverage:
+ def test_returns_none_for_empty_string(self):
+ assert get_loader_class_for_extension("") is None
+
+ def test_returns_none_for_dot_only(self):
+ assert get_loader_class_for_extension(".") is None
+
+ def test_yml_same_class_as_yaml(self):
+ r1 = get_loader_class_for_extension(".yml")
+ r2 = get_loader_class_for_extension(".yaml")
+ assert r1 is not None and r2 is not None
+ assert r1[0] is r2[0]
+
+ def test_htm_same_class_as_html(self):
+ r1 = get_loader_class_for_extension(".htm")
+ r2 = get_loader_class_for_extension(".html")
+ assert r1 is not None and r2 is not None
+ assert r1[0] is r2[0]
+
+ def test_markdown_same_class_as_md(self):
+ r1 = get_loader_class_for_extension(".markdown")
+ r2 = get_loader_class_for_extension(".md")
+ assert r1 is not None and r2 is not None
+ assert r1[0] is r2[0]
+
+ def test_mht_same_class_as_mhtml(self):
+ r1 = get_loader_class_for_extension(".mht")
+ r2 = get_loader_class_for_extension(".mhtml")
+ assert r1 is not None and r2 is not None
+ assert r1[0] is r2[0]
+
+ def test_xls_same_class_as_xlsx(self):
+ r1 = get_loader_class_for_extension(".xls")
+ r2 = get_loader_class_for_extension(".xlsx")
+ assert r1 is not None and r2 is not None
+ assert r1[0] is r2[0]
+
+ def test_doc_same_class_as_docx(self):
+ r1 = get_loader_class_for_extension(".doc")
+ r2 = get_loader_class_for_extension(".docx")
+ assert r1 is not None and r2 is not None
+ assert r1[0] is r2[0]
+
+ def test_ppt_same_class_as_pptx(self):
+ r1 = get_loader_class_for_extension(".ppt")
+ r2 = get_loader_class_for_extension(".pptx")
+ assert r1 is not None and r2 is not None
+ assert r1[0] is r2[0]
+
+ @pytest.mark.parametrize("ext", list(LOADER_REGISTRY.keys()))
+ def test_all_registry_extensions_resolve(self, ext):
+ """Every registered extension must resolve to a non-None result."""
+ result = get_loader_class_for_extension(ext)
+ assert result is not None, f"{ext} returned None"
+ assert len(result) == 2
+
+ def test_tsv_kwargs_include_tab_delimiter(self):
+ result = get_loader_class_for_extension(".tsv")
+ assert result is not None
+ kwargs = result[1]
+ assert kwargs["csv_args"]["delimiter"] == "\t"
+
+
+# ---------------------------------------------------------------------------
+# get_loader_for_path - comprehensive coverage
+# ---------------------------------------------------------------------------
+
+
+class TestGetLoaderForPathCoverage:
+ def test_returns_base_loader_subclass_for_txt(self, tmp_path: Path):
+ f = tmp_path / "sample.txt"
+ f.write_text("hello")
+ loader = get_loader_for_path(f)
+ assert loader is not None
+ assert isinstance(loader, BaseLoader)
+
+ def test_returns_base_loader_subclass_for_csv(self, tmp_path: Path):
+ f = tmp_path / "data.csv"
+ f.write_text("a,b\n1,2\n")
+ loader = get_loader_for_path(f)
+ assert loader is not None
+ assert isinstance(loader, BaseLoader)
+
+ def test_returns_none_for_unsupported_extension(self, tmp_path: Path):
+ f = tmp_path / "file.zzz"
+ f.write_text("data")
+ assert get_loader_for_path(f) is None
+
+ def test_accepts_pathlib_path(self, tmp_path: Path):
+ f = tmp_path / "test.txt"
+ f.write_text("x")
+ loader = get_loader_for_path(f)
+ assert loader is not None
+
+ def test_accepts_string_path(self, tmp_path: Path):
+ f = tmp_path / "test.txt"
+ f.write_text("x")
+ loader = get_loader_for_path(str(f))
+ assert loader is not None
+
+ def test_case_insensitive_extension(self, tmp_path: Path):
+ f = tmp_path / "TEST.TXT"
+ f.write_text("x")
+ loader = get_loader_for_path(f)
+ assert loader is not None
+
+ def test_mixed_case_extension(self, tmp_path: Path):
+ f = tmp_path / "readme.Md"
+ f.write_text("# Title")
+ loader = get_loader_for_path(f)
+ assert loader is not None
+
+ def test_returns_none_on_loader_constructor_exception(self, tmp_path: Path):
+ """When the loader constructor raises, get_loader_for_path returns None."""
+ f = tmp_path / "broken.txt"
+ f.write_text("content")
+
+ with patch.dict(
+ LOADER_REGISTRY,
+ {".txt": {"loader_class": _RaisingLoader, "loader_kwargs": {}}},
+ ):
+ result = get_loader_for_path(f)
+ assert result is None
+
+ def test_no_suffix_returns_none(self, tmp_path: Path):
+ """File without extension should return None."""
+ f = tmp_path / "Makefile"
+ f.write_text("all:")
+ assert get_loader_for_path(f) is None
+
+ def test_hidden_file_with_extension(self, tmp_path: Path):
+ """Hidden file like .gitignore has suffix '' on some systems; ensure
+ no crash even if suffix is empty."""
+ f = tmp_path / ".hidden"
+ f.write_text("secret")
+ # .hidden has suffix '' -- should return None gracefully
+ result = get_loader_for_path(f)
+ # Just ensure no exception; result depends on whether '.hidden' is registered
+ assert result is None or isinstance(result, BaseLoader)
+
+ def test_double_extension_uses_last_suffix(self, tmp_path: Path):
+ """Path('a.backup.txt').suffix == '.txt', so it should resolve to TextLoader."""
+ f = tmp_path / "notes.backup.txt"
+ f.write_text("content")
+ loader = get_loader_for_path(f)
+ assert loader is not None
+
+ def test_json_loader_for_json_file(self, tmp_path: Path):
+ from local_deep_research.document_loaders.json_loader import (
+ SimpleJSONLoader,
+ )
+
+ f = tmp_path / "data.json"
+ f.write_text('{"key": "value"}')
+ loader = get_loader_for_path(f)
+ assert loader is not None
+ assert isinstance(loader, SimpleJSONLoader)
+
+ def test_yaml_loader_for_yaml_file(self, tmp_path: Path):
+ from local_deep_research.document_loaders.yaml_loader import YAMLLoader
+
+ f = tmp_path / "config.yaml"
+ f.write_text("key: value")
+ loader = get_loader_for_path(f)
+ assert loader is not None
+ assert isinstance(loader, YAMLLoader)
+
+ def test_yaml_loader_for_yml_file(self, tmp_path: Path):
+ from local_deep_research.document_loaders.yaml_loader import YAMLLoader
+
+ f = tmp_path / "config.yml"
+ f.write_text("key: value")
+ loader = get_loader_for_path(f)
+ assert loader is not None
+ assert isinstance(loader, YAMLLoader)
+
+
+# ---------------------------------------------------------------------------
+# Consistency checks
+# ---------------------------------------------------------------------------
+
+
+class TestConsistencyBetweenFunctions:
+ """Ensure is_extension_supported, get_loader_class_for_extension, and
+ get_supported_extensions agree."""
+
+ @pytest.mark.parametrize("ext", list(LOADER_REGISTRY.keys()))
+ def test_supported_extension_resolves_to_loader_class(self, ext):
+ assert is_extension_supported(ext) is True
+ assert get_loader_class_for_extension(ext) is not None
+
+ def test_unsupported_extension_consistent_across_functions(self):
+ ext = ".this_does_not_exist_42"
+ assert is_extension_supported(ext) is False
+ assert get_loader_class_for_extension(ext) is None
+ assert ext not in get_supported_extensions()
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+class _RaisingLoader:
+ """Fake loader whose __init__ always raises, used to test error handling."""
+
+ def __init__(self, *args, **kwargs):
+ raise RuntimeError("Intentional test error")
diff --git a/tests/news/test_news_analyzer_coverage.py b/tests/news/test_news_analyzer_coverage.py
new file mode 100644
index 0000000000..2f7f618d9d
--- /dev/null
+++ b/tests/news/test_news_analyzer_coverage.py
@@ -0,0 +1,569 @@
+"""
+Comprehensive pytest tests for NewsAnalyzer pure logic helpers.
+
+Focuses on edge cases and scenarios not covered by existing test files:
+- _validate_news_item: truthy/falsy edge cases, numeric values, type variations
+- _count_categories: case sensitivity, special characters, None category value
+- _summarize_impact: float scores, extreme values, mixed missing/present scores
+- _prepare_snippets: snippet vs content precedence, multiple results ordering,
+ edge-length strings (exactly 200 chars), results with no recognized fields
+- _empty_analysis: structural guarantees, timestamp format
+- close(): ownership semantics
+- analyze_news: exception path returns empty analysis
+"""
+
+import json
+from datetime import datetime
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.news.core.news_analyzer import NewsAnalyzer
+
+
+# ---------------------------------------------------------------------------
+# Fixture: create analyzer without hitting real get_llm
+# ---------------------------------------------------------------------------
+
+
+def analyzer():
+ """NewsAnalyzer with a no-op mock LLM (does not own it)."""
+ mock_llm = Mock()
+ return NewsAnalyzer(llm_client=mock_llm)
+
+
+def analyzer_no_llm():
+ """NewsAnalyzer where llm_client is explicitly None."""
+ na = NewsAnalyzer(llm_client=Mock())
+ na.llm_client = None
+ return na
+
+
+# ===========================================================================
+# _validate_news_item – edge cases beyond empty/missing
+# ===========================================================================
+
+
+class TestValidateNewsItemEdgeCases:
+ """Edge-case validation for _validate_news_item."""
+
+ def test_integer_headline_truthy(self, analyzer):
+ """Non-zero int is truthy -> should pass the `and item[field]` check."""
+ assert analyzer._validate_news_item({"headline": 42, "summary": "ok"})
+
+ def test_integer_zero_headline_falsy(self, analyzer):
+ """0 is falsy -> should fail validation."""
+ assert not analyzer._validate_news_item(
+ {"headline": 0, "summary": "ok"}
+ )
+
+ def test_whitespace_only_headline_passes(self, analyzer):
+ """Whitespace-only string is truthy (non-empty)."""
+ assert analyzer._validate_news_item(
+ {"headline": " ", "summary": "text"}
+ )
+
+ def test_whitespace_only_summary_passes(self, analyzer):
+ assert analyzer._validate_news_item({"headline": "h", "summary": " "})
+
+ def test_list_headline_truthy(self, analyzer):
+ """A non-empty list is truthy."""
+ assert analyzer._validate_news_item(
+ {"headline": ["x"], "summary": "ok"}
+ )
+
+ def test_empty_list_headline_falsy(self, analyzer):
+ """Empty list is falsy."""
+ assert not analyzer._validate_news_item(
+ {"headline": [], "summary": "ok"}
+ )
+
+ def test_false_boolean_headline(self, analyzer):
+ assert not analyzer._validate_news_item(
+ {"headline": False, "summary": "ok"}
+ )
+
+ def test_true_boolean_headline(self, analyzer):
+ assert analyzer._validate_news_item({"headline": True, "summary": "ok"})
+
+ def test_both_none(self, analyzer):
+ assert not analyzer._validate_news_item(
+ {"headline": None, "summary": None}
+ )
+
+ def test_only_extra_fields_no_required(self, analyzer):
+ assert not analyzer._validate_news_item(
+ {"category": "Tech", "impact_score": 9, "url": "http://x.com"}
+ )
+
+
+# ===========================================================================
+# _count_categories – edge cases
+# ===========================================================================
+
+
+class TestCountCategoriesEdgeCases:
+ """Edge cases for _count_categories."""
+
+ def test_none_category_value_treated_as_none_key(self, analyzer):
+ """If category key exists but value is None, .get returns None (not 'Other')."""
+ items = [{"category": None}]
+ result = analyzer._count_categories(items)
+ # .get("category", "Other") returns None because key exists
+ assert None in result
+ assert result[None] == 1
+
+ def test_empty_string_category_is_kept(self, analyzer):
+ """Empty-string category is not replaced by 'Other'."""
+ items = [{"category": ""}]
+ result = analyzer._count_categories(items)
+ assert "" in result
+ assert result[""] == 1
+
+ def test_case_sensitive_categories(self, analyzer):
+ """'Tech' and 'tech' are counted separately."""
+ items = [{"category": "Tech"}, {"category": "tech"}]
+ result = analyzer._count_categories(items)
+ assert result == {"Tech": 1, "tech": 1}
+
+ def test_single_item_many_categories_single_count(self, analyzer):
+ items = [{"category": f"cat_{i}"} for i in range(50)]
+ result = analyzer._count_categories(items)
+ assert len(result) == 50
+ assert all(v == 1 for v in result.values())
+
+ def test_special_characters_in_category(self, analyzer):
+ items = [
+ {"category": "AI & ML"},
+ {"category": "AI & ML"},
+ {"category": "U.S. Politics"},
+ ]
+ result = analyzer._count_categories(items)
+ assert result["AI & ML"] == 2
+ assert result["U.S. Politics"] == 1
+
+ def test_unicode_categories(self, analyzer):
+ items = [{"category": "Politique"}, {"category": "Politique"}]
+ result = analyzer._count_categories(items)
+ assert result["Politique"] == 2
+
+
+# ===========================================================================
+# _summarize_impact – edge cases
+# ===========================================================================
+
+
+class TestSummarizeImpactEdgeCases:
+ """Edge cases for _summarize_impact."""
+
+ def test_empty_returns_only_average_and_high_count(self, analyzer):
+ """Empty list returns exactly {average: 0, high_impact_count: 0} with no max/min."""
+ result = analyzer._summarize_impact([])
+ assert result == {"average": 0, "high_impact_count": 0}
+ assert "max" not in result
+ assert "min" not in result
+
+ def test_all_default_scores(self, analyzer):
+ """Items without impact_score all default to 5."""
+ items = [{}, {}, {}]
+ result = analyzer._summarize_impact(items)
+ assert result["average"] == 5.0
+ assert result["max"] == 5
+ assert result["min"] == 5
+ assert result["high_impact_count"] == 0
+
+ def test_float_impact_scores(self, analyzer):
+ """Float scores are handled (sum/len works on floats)."""
+ items = [{"impact_score": 7.5}, {"impact_score": 8.5}]
+ result = analyzer._summarize_impact(items)
+ assert result["average"] == 8.0
+ assert result["max"] == 8.5
+ assert result["min"] == 7.5
+ # 8.5 >= 8 -> 1 high impact
+ assert result["high_impact_count"] == 1
+
+ def test_boundary_score_exactly_8(self, analyzer):
+ """Score of exactly 8 counts as high impact."""
+ items = [{"impact_score": 8}]
+ result = analyzer._summarize_impact(items)
+ assert result["high_impact_count"] == 1
+
+ def test_boundary_score_just_below_8(self, analyzer):
+ """Score of 7.99 does not count as high impact."""
+ items = [{"impact_score": 7.99}]
+ result = analyzer._summarize_impact(items)
+ assert result["high_impact_count"] == 0
+
+ def test_very_large_score(self, analyzer):
+ items = [{"impact_score": 1000}]
+ result = analyzer._summarize_impact(items)
+ assert result["max"] == 1000
+ assert result["high_impact_count"] == 1
+
+ def test_negative_score(self, analyzer):
+ items = [{"impact_score": -3}]
+ result = analyzer._summarize_impact(items)
+ assert result["average"] == -3
+ assert result["min"] == -3
+ assert result["high_impact_count"] == 0
+
+ def test_zero_score(self, analyzer):
+ items = [{"impact_score": 0}]
+ result = analyzer._summarize_impact(items)
+ assert result["average"] == 0
+ assert result["high_impact_count"] == 0
+
+ def test_mixed_present_and_missing_scores(self, analyzer):
+ """Mix of items with and without impact_score."""
+ items = [
+ {"impact_score": 10},
+ {}, # defaults to 5
+ {"impact_score": 3},
+ ]
+ result = analyzer._summarize_impact(items)
+ assert result["average"] == 6.0 # (10+5+3)/3
+ assert result["max"] == 10
+ assert result["min"] == 3
+ assert result["high_impact_count"] == 1 # only 10
+
+ def test_single_high_impact(self, analyzer):
+ items = [{"impact_score": 9}]
+ result = analyzer._summarize_impact(items)
+ assert result["average"] == 9
+ assert result["high_impact_count"] == 1
+ assert result["max"] == 9
+ assert result["min"] == 9
+
+
+# ===========================================================================
+# _prepare_snippets – edge cases
+# ===========================================================================
+
+
+class TestPrepareSnippetsEdgeCases:
+ """Edge cases for _prepare_snippets."""
+
+ def test_empty_list_returns_empty_string(self, analyzer):
+ assert analyzer._prepare_snippets([]) == ""
+
+ def test_snippet_exactly_200_chars(self, analyzer):
+ """Snippet of exactly 200 chars is included in full (plus '...')."""
+ text = "A" * 200
+ result = analyzer._prepare_snippets([{"snippet": text}])
+ assert "A" * 200 + "..." in result
+
+ def test_snippet_201_chars_truncated(self, analyzer):
+ text = "B" * 201
+ result = analyzer._prepare_snippets([{"snippet": text}])
+ assert "B" * 200 in result
+ assert "B" * 201 not in result
+
+ def test_content_exactly_200_chars(self, analyzer):
+ text = "C" * 200
+ result = analyzer._prepare_snippets([{"content": text}])
+ assert "C" * 200 + "..." in result
+
+ def test_snippet_takes_precedence_over_content(self, analyzer):
+ """When both snippet and content exist, snippet is used."""
+ result = analyzer._prepare_snippets(
+ [{"snippet": "SNIPPET_TEXT", "content": "CONTENT_TEXT"}]
+ )
+ assert "SNIPPET_TEXT" in result
+ assert "CONTENT_TEXT" not in result
+
+ def test_content_used_when_snippet_missing(self, analyzer):
+ result = analyzer._prepare_snippets([{"content": "CONTENT_ONLY"}])
+ assert "Content: CONTENT_ONLY" in result
+
+ def test_content_used_when_snippet_empty_string(self, analyzer):
+ """Empty-string snippet is falsy, so content should be used."""
+ result = analyzer._prepare_snippets(
+ [{"snippet": "", "content": "FALLBACK"}]
+ )
+ assert "Content: FALLBACK" in result
+ assert "Snippet:" not in result
+
+ def test_no_recognized_fields(self, analyzer):
+ """Result with no title/url/snippet/content produces just the number prefix."""
+ result = analyzer._prepare_snippets([{"random_key": "value"}])
+ assert result.strip() == "[1]"
+
+ def test_multiple_results_numbered_sequentially(self, analyzer):
+ results = [{"title": f"T{i}"} for i in range(5)]
+ output = analyzer._prepare_snippets(results)
+ for i in range(1, 6):
+ assert f"[{i}]" in output
+
+ def test_title_url_snippet_all_present(self, analyzer):
+ result = analyzer._prepare_snippets(
+ [{"title": "Headline", "url": "http://x.com", "snippet": "Blurb"}]
+ )
+ assert "Title: Headline" in result
+ assert "URL: http://x.com" in result
+ assert "Snippet: Blurb" in result
+
+ def test_newlines_separate_results(self, analyzer):
+ results = [{"title": "A"}, {"title": "B"}]
+ output = analyzer._prepare_snippets(results)
+ # There should be at least a blank line between entries due to
+ # internal newlines in each snippet block joined by \n
+ assert len(output.split("\n\n")) >= 2
+ assert "[1]" in output
+ assert "[2]" in output
+
+ def test_empty_title_skipped(self, analyzer):
+ """Empty-string title is falsy, so Title: line should not appear."""
+ result = analyzer._prepare_snippets([{"title": ""}])
+ assert "Title:" not in result
+
+ def test_empty_url_skipped(self, analyzer):
+ result = analyzer._prepare_snippets([{"url": ""}])
+ assert "URL:" not in result
+
+
+# ===========================================================================
+# _empty_analysis – structural guarantees
+# ===========================================================================
+
+
+class TestEmptyAnalysisStructure:
+ """Structural tests for _empty_analysis."""
+
+ def test_returns_dict(self, analyzer):
+ result = analyzer._empty_analysis()
+ assert isinstance(result, dict)
+
+ def test_all_expected_keys(self, analyzer):
+ result = analyzer._empty_analysis()
+ expected = {
+ "items",
+ "item_count",
+ "big_picture",
+ "watch_for",
+ "patterns",
+ "topics",
+ "categories",
+ "impact_summary",
+ "timestamp",
+ }
+ assert set(result.keys()) == expected
+
+ def test_items_is_list(self, analyzer):
+ assert isinstance(analyzer._empty_analysis()["items"], list)
+
+ def test_watch_for_is_list(self, analyzer):
+ assert isinstance(analyzer._empty_analysis()["watch_for"], list)
+
+ def test_topics_is_list(self, analyzer):
+ assert isinstance(analyzer._empty_analysis()["topics"], list)
+
+ def test_categories_is_dict(self, analyzer):
+ assert isinstance(analyzer._empty_analysis()["categories"], dict)
+
+ def test_impact_summary_is_dict(self, analyzer):
+ assert isinstance(analyzer._empty_analysis()["impact_summary"], dict)
+
+ def test_timestamp_is_valid_iso(self, analyzer):
+ ts = analyzer._empty_analysis()["timestamp"]
+ parsed = datetime.fromisoformat(ts)
+ assert parsed.tzinfo is not None # should be timezone-aware
+
+ def test_impact_summary_keys(self, analyzer):
+ summary = analyzer._empty_analysis()["impact_summary"]
+ assert "average" in summary
+ assert "high_impact_count" in summary
+
+ def test_two_calls_produce_different_timestamps(self, analyzer):
+ """Timestamps should reflect the call time (not cached)."""
+ t1 = analyzer._empty_analysis()["timestamp"]
+ t2 = analyzer._empty_analysis()["timestamp"]
+ # They may be equal if called within the same microsecond;
+ # just verify both parse correctly
+ datetime.fromisoformat(t1)
+ datetime.fromisoformat(t2)
+
+
+# ===========================================================================
+# close() – ownership semantics
+# ===========================================================================
+
+
+class TestClose:
+ """Tests for close() ownership logic."""
+
+ def test_close_does_not_close_external_llm(self):
+ """When llm_client is provided externally, close() should NOT close it."""
+ mock_llm = Mock()
+ na = NewsAnalyzer(llm_client=mock_llm)
+ assert na._owns_llm is False
+ with patch(
+ "local_deep_research.news.core.news_analyzer.close_llm"
+ ) as mock_close:
+ na.close()
+ mock_close.assert_not_called()
+
+ def test_close_closes_owned_llm(self):
+ """When no llm_client is provided, NewsAnalyzer creates one and owns it."""
+ with patch(
+ "local_deep_research.news.core.news_analyzer.get_llm"
+ ) as mock_get:
+ mock_llm = Mock()
+ mock_get.return_value = mock_llm
+ na = NewsAnalyzer()
+ assert na._owns_llm is True
+ with patch(
+ "local_deep_research.news.core.news_analyzer.close_llm"
+ ) as mock_close:
+ na.close()
+ mock_close.assert_called_once_with(mock_llm)
+
+
+# ===========================================================================
+# analyze_news – exception handling path
+# ===========================================================================
+
+
+class TestAnalyzeNewsExceptionPath:
+ """Tests that analyze_news returns _empty_analysis on internal errors."""
+
+ def test_exception_in_extract_returns_empty(self):
+ """If extract_news_items raises, analyze_news catches and returns empty."""
+ mock_llm = Mock()
+ na = NewsAnalyzer(llm_client=mock_llm)
+ with patch.object(
+ na, "extract_news_items", side_effect=RuntimeError("boom")
+ ):
+ result = na.analyze_news([{"content": "data"}])
+ assert result["items"] == []
+ assert result["item_count"] == 0
+
+ def test_empty_search_results_skips_llm(self):
+ """Empty input should return empty analysis without invoking LLM."""
+ mock_llm = Mock()
+ na = NewsAnalyzer(llm_client=mock_llm)
+ result = na.analyze_news([])
+ mock_llm.invoke.assert_not_called()
+ assert result["item_count"] == 0
+
+
+# ===========================================================================
+# extract_news_items – ID generation and filtering
+# ===========================================================================
+
+
+class TestExtractNewsItemsIDsAndFiltering:
+ """Tests for extract_news_items ID assignment and item filtering."""
+
+ def test_each_item_gets_unique_id(self):
+ mock_llm = Mock()
+ items = [
+ {"headline": f"News {i}", "summary": f"Summary {i}"}
+ for i in range(3)
+ ]
+ mock_llm.invoke.return_value = Mock(content=json.dumps(items))
+ na = NewsAnalyzer(llm_client=mock_llm)
+ result = na.extract_news_items([{"title": "source"}])
+ ids = [item["id"] for item in result]
+ assert len(ids) == len(set(ids)), "All IDs should be unique"
+
+ def test_invalid_items_filtered_out(self):
+ mock_llm = Mock()
+ items = [
+ {"headline": "Valid", "summary": "Yes"},
+ {"headline": "", "summary": "No headline"},
+ {"summary": "Missing headline entirely"},
+ {"headline": "Also valid", "summary": "Content"},
+ ]
+ mock_llm.invoke.return_value = Mock(content=json.dumps(items))
+ na = NewsAnalyzer(llm_client=mock_llm)
+ result = na.extract_news_items([{"title": "source"}])
+ assert len(result) == 2
+ headlines = {r["headline"] for r in result}
+ assert "Valid" in headlines
+ assert "Also valid" in headlines
+
+ def test_max_items_caps_output(self):
+ mock_llm = Mock()
+ items = [{"headline": f"H{i}", "summary": f"S{i}"} for i in range(20)]
+ mock_llm.invoke.return_value = Mock(content=json.dumps(items))
+ na = NewsAnalyzer(llm_client=mock_llm)
+ result = na.extract_news_items([{"title": "source"}], max_items=3)
+ assert len(result) <= 3
+
+
+# ===========================================================================
+# _validate_news_item + _count_categories + _summarize_impact combined
+# ===========================================================================
+
+
+class TestHelperInteraction:
+ """Test helpers work together on realistic data."""
+
+ def test_realistic_news_items(self, analyzer):
+ items = [
+ {
+ "headline": "AI Model Surpasses Human Benchmark",
+ "summary": "A new AI model has exceeded human performance on key tasks.",
+ "category": "Technology",
+ "impact_score": 9,
+ },
+ {
+ "headline": "Markets Rally on Rate Cut Hopes",
+ "summary": "Global stock markets surged amid expectations of rate cuts.",
+ "category": "Finance",
+ "impact_score": 7,
+ },
+ {
+ "headline": "Climate Summit Reaches Agreement",
+ "summary": "World leaders agreed on new carbon reduction targets.",
+ "category": "Environment",
+ "impact_score": 8,
+ },
+ {
+ "headline": "Tech Giant Faces Antitrust Probe",
+ "summary": "Regulators launched a new investigation into market dominance.",
+ "category": "Technology",
+ "impact_score": 6,
+ },
+ ]
+
+ # All items should be valid
+ for item in items:
+ assert analyzer._validate_news_item(item)
+
+ # Category counts
+ cats = analyzer._count_categories(items)
+ assert cats == {"Technology": 2, "Finance": 1, "Environment": 1}
+
+ # Impact summary
+ impact = analyzer._summarize_impact(items)
+ assert impact["average"] == 7.5
+ assert impact["high_impact_count"] == 2 # scores 9 and 8
+ assert impact["max"] == 9
+ assert impact["min"] == 6
+
+ def test_all_invalid_items(self, analyzer):
+ items = [
+ {"headline": "", "summary": ""},
+ {"category": "Tech"},
+ {},
+ ]
+ for item in items:
+ assert not analyzer._validate_news_item(item)
+
+ def test_count_categories_with_all_defaults(self, analyzer):
+ """Items with no category key all map to 'Other'."""
+ items = [{"headline": "A"}, {"headline": "B"}, {"headline": "C"}]
+ result = analyzer._count_categories(items)
+ assert result == {"Other": 3}
+
+ def test_summarize_impact_all_defaults(self, analyzer):
+ """Items with no impact_score all default to 5."""
+ items = [{"headline": "A"}, {"headline": "B"}]
+ result = analyzer._summarize_impact(items)
+ assert result["average"] == 5.0
+ assert result["max"] == 5
+ assert result["min"] == 5
+ assert result["high_impact_count"] == 0
diff --git a/tests/news/test_relevance_service_coverage.py b/tests/news/test_relevance_service_coverage.py
new file mode 100644
index 0000000000..0319c340bd
--- /dev/null
+++ b/tests/news/test_relevance_service_coverage.py
@@ -0,0 +1,678 @@
+"""
+Comprehensive coverage tests for RelevanceService.
+
+Focuses on edge cases, boundary conditions, and scoring combinations
+not covered by existing test files. Tests the actual service methods
+(not reimplementations) to ensure real code coverage.
+"""
+
+import pytest
+from unittest.mock import Mock
+
+from local_deep_research.news.core.relevance_service import (
+ RelevanceService,
+ get_relevance_service,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _card(
+ impact_score=5,
+ category="General",
+ topics=None,
+ interaction=None,
+ viewed=False,
+ *,
+ spec=None,
+):
+ """Build a mock card. Use spec=[] to strip all attrs, or spec=[...] to whitelist."""
+ if spec is not None:
+ card = Mock(spec=spec)
+ # Manually set only the attrs listed in spec
+ for attr in spec:
+ if attr == "impact_score":
+ setattr(card, attr, impact_score)
+ elif attr == "category":
+ setattr(card, attr, category)
+ elif attr == "topics":
+ setattr(card, attr, topics if topics is not None else [])
+ elif attr == "interaction":
+ setattr(
+ card, attr, interaction if interaction is not None else {}
+ )
+ return card
+
+ card = Mock()
+ card.impact_score = impact_score
+ card.category = category
+ card.topics = topics if topics is not None else []
+ card.interaction = (
+ interaction
+ if interaction is not None
+ else {
+ "views": 0,
+ "votes_up": 0,
+ "votes_down": 0,
+ }
+ )
+ if viewed:
+ card.interaction["viewed"] = True
+ return card
+
+
+def svc():
+ return RelevanceService()
+
+
+# ===========================================================================
+# calculate_relevance - scoring arithmetic
+# ===========================================================================
+
+
+class TestCalculateRelevanceArithmetic:
+ """Verify exact numeric outcomes for all factor combinations."""
+
+ def test_no_prefs_none_returns_impact_div_10(self, svc):
+ assert svc.calculate_relevance(
+ _card(impact_score=3), None
+ ) == pytest.approx(0.3)
+
+ def test_no_prefs_empty_dict_is_falsy(self, svc):
+ """Empty dict {} is falsy for `not user_prefs`, so takes the no-prefs path."""
+ # Empty dict -> not {} is True -> returns impact_score / 10
+ assert svc.calculate_relevance(
+ _card(impact_score=5), {}
+ ) == pytest.approx(0.5)
+
+ def test_base_score_is_half(self, svc):
+ """With prefs but no matching attrs the base is 0.5 modified only by impact."""
+ card = _card(impact_score=5, spec=["impact_score"])
+ result = svc.calculate_relevance(card, {"impact_threshold": 5})
+ assert result == pytest.approx(0.6) # 0.5 + 0.1
+
+ def test_liked_category_adds_0_2(self, svc):
+ card = _card(category="AI", impact_score=5)
+ base = svc.calculate_relevance(
+ _card(category="Other", impact_score=5),
+ {"liked_categories": ["AI"], "impact_threshold": 5},
+ )
+ boosted = svc.calculate_relevance(
+ card,
+ {"liked_categories": ["AI"], "impact_threshold": 5},
+ )
+ assert boosted - base == pytest.approx(0.2)
+
+ def test_disliked_category_subtracts_0_2(self, svc):
+ card = _card(category="Spam", impact_score=5)
+ base = svc.calculate_relevance(
+ _card(category="Other", impact_score=5),
+ {"disliked_categories": ["Spam"], "impact_threshold": 5},
+ )
+ penalised = svc.calculate_relevance(
+ card,
+ {"disliked_categories": ["Spam"], "impact_threshold": 5},
+ )
+ assert base - penalised == pytest.approx(0.2)
+
+ def test_impact_above_threshold_adds_0_1(self, svc):
+ prefs = {"impact_threshold": 4}
+ card = _card(impact_score=5)
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.6)
+
+ def test_impact_below_threshold_subtracts_0_1(self, svc):
+ prefs = {"impact_threshold": 6}
+ card = _card(impact_score=5)
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.4)
+
+ def test_impact_equal_threshold_counts_as_above(self, svc):
+ prefs = {"impact_threshold": 5}
+ card = _card(impact_score=5)
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.6)
+
+ def test_topic_match_adds_0_1(self, svc):
+ card = _card(impact_score=5, topics=["deep learning"])
+ prefs = {"liked_topics": ["deep"], "impact_threshold": 5}
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.7)
+
+ def test_all_positive_factors(self, svc):
+ card = _card(impact_score=9, category="Tech", topics=["ai models"])
+ prefs = {
+ "liked_categories": ["Tech"],
+ "impact_threshold": 5,
+ "liked_topics": ["ai"],
+ }
+ # 0.5 + 0.2 + 0.1 + 0.1 = 0.9
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.9)
+
+ def test_all_negative_factors(self, svc):
+ card = _card(impact_score=1, category="Junk", topics=[])
+ prefs = {
+ "disliked_categories": ["Junk"],
+ "impact_threshold": 10,
+ }
+ # 0.5 - 0.2 - 0.1 = 0.2
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.2)
+
+
+class TestCalculateRelevanceClamping:
+ """Ensure clamping to [0, 1] when prefs path is taken."""
+
+ def test_max_clamp(self, svc):
+ """Even with all boosts the score must not exceed 1.0."""
+ card = _card(impact_score=10, category="X", topics=["x"])
+ prefs = {
+ "liked_categories": ["X"],
+ "impact_threshold": 1,
+ "liked_topics": ["x"],
+ }
+ assert svc.calculate_relevance(card, prefs) <= 1.0
+
+ def test_min_clamp(self, svc):
+ """Even with all penalties the score must not go below 0.0."""
+ card = _card(impact_score=0, category="Bad", topics=[])
+ prefs = {
+ "disliked_categories": ["Bad"],
+ "impact_threshold": 100,
+ }
+ assert svc.calculate_relevance(card, prefs) >= 0.0
+
+ def test_no_prefs_path_does_not_clamp(self, svc):
+ """The no-prefs path returns impact/10 directly - no clamping."""
+ assert svc.calculate_relevance(
+ _card(impact_score=-5), None
+ ) == pytest.approx(-0.5)
+ assert svc.calculate_relevance(
+ _card(impact_score=15), None
+ ) == pytest.approx(1.5)
+
+
+class TestCalculateRelevanceMissingAttributes:
+ """Cards missing optional attributes should not raise."""
+
+ def test_no_category_attr(self, svc):
+ card = _card(spec=["impact_score", "topics", "interaction"])
+ card.impact_score = 5
+ card.topics = []
+ card.interaction = {}
+ result = svc.calculate_relevance(card, {"liked_categories": ["Tech"]})
+ assert isinstance(result, float)
+
+ def test_no_impact_score_attr_with_prefs(self, svc):
+ card = _card(spec=["category", "topics", "interaction"])
+ card.category = "Tech"
+ card.topics = []
+ card.interaction = {}
+ result = svc.calculate_relevance(card, {"impact_threshold": 5})
+ # No impact_score attr -> skip impact check -> just base 0.5
+ assert result == pytest.approx(0.5)
+
+ def test_no_topics_attr(self, svc):
+ card = _card(spec=["impact_score", "category", "interaction"])
+ card.impact_score = 5
+ card.category = "Tech"
+ card.interaction = {}
+ result = svc.calculate_relevance(card, {"liked_topics": ["ai"]})
+ assert isinstance(result, float)
+
+ def test_no_impact_score_attr_no_prefs(self, svc):
+ """getattr default of 5 used when card has no impact_score and prefs is None."""
+ card = _card(spec=[])
+ assert svc.calculate_relevance(card, None) == pytest.approx(0.5)
+
+
+class TestCalculateRelevanceTopicEdgeCases:
+ """Topic matching subtleties."""
+
+ def test_partial_substring_match(self, svc):
+ """'art' should match 'artificial'."""
+ card = _card(topics=["Artificial Intelligence"])
+ prefs = {"liked_topics": ["art"], "impact_threshold": 5}
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.7)
+
+ def test_only_first_topic_match_counted(self, svc):
+ """Multiple matching topics still yield only +0.1."""
+ card = _card(topics=["AI News", "AI Research", "AI Updates"])
+ prefs = {"liked_topics": ["ai"], "impact_threshold": 5}
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.7)
+
+ def test_topic_case_insensitive(self, svc):
+ card = _card(topics=["QUANTUM COMPUTING"])
+ prefs = {"liked_topics": ["quantum"], "impact_threshold": 5}
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.7)
+
+ def test_empty_liked_topics_no_boost(self, svc):
+ card = _card(topics=["Something"])
+ prefs = {"liked_topics": [], "impact_threshold": 5}
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.6)
+
+ def test_empty_card_topics_no_boost(self, svc):
+ card = _card(topics=[])
+ prefs = {"liked_topics": ["ai"], "impact_threshold": 5}
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.6)
+
+ def test_no_liked_topics_key_in_prefs(self, svc):
+ """Prefs without 'liked_topics' key -> defaults to empty list."""
+ card = _card(topics=["AI"])
+ prefs = {"impact_threshold": 5}
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.6)
+
+ def test_liked_topic_not_in_card_topics(self, svc):
+ card = _card(topics=["Climate Change"])
+ prefs = {"liked_topics": ["blockchain"], "impact_threshold": 5}
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.6)
+
+
+class TestCalculateRelevanceCategoryPrecedence:
+ """When category is in both liked and disliked, liked wins (checked first)."""
+
+ def test_liked_checked_before_disliked(self, svc):
+ card = _card(category="Tech", impact_score=5, topics=[])
+ prefs = {
+ "liked_categories": ["Tech"],
+ "disliked_categories": ["Tech"],
+ "impact_threshold": 5,
+ }
+ # liked branch matches first due to if/elif -> +0.2
+ assert svc.calculate_relevance(card, prefs) == pytest.approx(0.8)
+
+
+# ===========================================================================
+# calculate_trending_score
+# ===========================================================================
+
+
+class TestCalculateTrendingScoreEdgeCases:
+ """Edge cases for trending score calculation."""
+
+ def test_no_impact_score_returns_zero(self, svc):
+ card = Mock(spec=[])
+ assert svc.calculate_trending_score(card) == 0.0
+
+ def test_zero_everything(self, svc):
+ card = _card(
+ impact_score=0,
+ interaction={"views": 0, "votes_up": 0, "votes_down": 0},
+ )
+ assert svc.calculate_trending_score(card) == 0.0
+
+ def test_exact_formula(self, svc):
+ card = _card(
+ impact_score=6,
+ interaction={"views": 30, "votes_up": 15, "votes_down": 3},
+ )
+ # engagement = 30 + 15*2 - 3 = 57
+ # trending = 6 + 57/10 = 11.7
+ assert svc.calculate_trending_score(card) == pytest.approx(11.7)
+
+ def test_negative_net_engagement(self, svc):
+ card = _card(
+ impact_score=5,
+ interaction={"views": 0, "votes_up": 0, "votes_down": 100},
+ )
+ # 5 + (-100)/10 = -5.0
+ assert svc.calculate_trending_score(card) == pytest.approx(-5.0)
+
+ def test_missing_interaction_keys_default_zero(self, svc):
+ card = _card(impact_score=4, interaction={})
+ assert svc.calculate_trending_score(card) == pytest.approx(4.0)
+
+ def test_partial_interaction_keys(self, svc):
+ card = _card(impact_score=3, interaction={"views": 20})
+ # votes_up=0, votes_down=0 via .get defaults
+ assert svc.calculate_trending_score(card) == pytest.approx(5.0)
+
+ def test_upvotes_weighted_double(self, svc):
+ card = _card(
+ impact_score=0,
+ interaction={"views": 0, "votes_up": 10, "votes_down": 0},
+ )
+ # 0 + (0 + 20 - 0)/10 = 2.0
+ assert svc.calculate_trending_score(card) == pytest.approx(2.0)
+
+ def test_large_values(self, svc):
+ card = _card(
+ impact_score=10,
+ interaction={
+ "views": 1_000_000,
+ "votes_up": 500_000,
+ "votes_down": 50_000,
+ },
+ )
+ expected = 10 + (1_000_000 + 500_000 * 2 - 50_000) / 10
+ assert svc.calculate_trending_score(card) == pytest.approx(expected)
+
+
+# ===========================================================================
+# filter_trending
+# ===========================================================================
+
+
+class TestFilterTrendingComprehensive:
+ """Comprehensive filter_trending tests."""
+
+ def test_empty_list(self, svc):
+ assert svc.filter_trending([]) == []
+
+ def test_all_below_min_impact(self, svc):
+ cards = [_card(impact_score=i) for i in range(1, 7)]
+ assert svc.filter_trending(cards, min_impact=7) == []
+
+ def test_all_above_min_impact(self, svc):
+ cards = [_card(impact_score=i) for i in range(8, 11)]
+ result = svc.filter_trending(cards, min_impact=7)
+ assert len(result) == 3
+
+ def test_exact_min_impact_included(self, svc):
+ card = _card(impact_score=7)
+ result = svc.filter_trending([card], min_impact=7)
+ assert len(result) == 1
+
+ def test_one_below_min_impact_excluded(self, svc):
+ card = _card(impact_score=6)
+ result = svc.filter_trending([card], min_impact=7)
+ assert len(result) == 0
+
+ def test_sorted_descending_by_trending(self, svc):
+ c_low = _card(
+ impact_score=7,
+ interaction={"views": 0, "votes_up": 0, "votes_down": 0},
+ )
+ c_mid = _card(
+ impact_score=8,
+ interaction={"views": 10, "votes_up": 0, "votes_down": 0},
+ )
+ c_high = _card(
+ impact_score=9,
+ interaction={"views": 50, "votes_up": 10, "votes_down": 0},
+ )
+ result = svc.filter_trending([c_low, c_high, c_mid], min_impact=7)
+ scores = [c.trending_score for c in result]
+ assert scores == sorted(scores, reverse=True)
+
+ def test_limit_truncates(self, svc):
+ cards = [_card(impact_score=8) for _ in range(20)]
+ assert len(svc.filter_trending(cards, min_impact=7, limit=5)) == 5
+
+ def test_limit_zero_returns_empty(self, svc):
+ card = _card(impact_score=10)
+ assert svc.filter_trending([card], min_impact=7, limit=0) == []
+
+ def test_limit_larger_than_results(self, svc):
+ cards = [_card(impact_score=8) for _ in range(3)]
+ result = svc.filter_trending(cards, min_impact=7, limit=100)
+ assert len(result) == 3
+
+ def test_default_min_impact_is_7(self, svc):
+ card6 = _card(impact_score=6)
+ card7 = _card(impact_score=7)
+ result = svc.filter_trending([card6, card7])
+ assert card7 in [r for r in result]
+ assert card6 not in [r for r in result]
+
+ def test_default_limit_is_10(self, svc):
+ cards = [_card(impact_score=9) for _ in range(15)]
+ assert len(svc.filter_trending(cards)) == 10
+
+ def test_trending_score_attribute_set(self, svc):
+ card = _card(
+ impact_score=8,
+ interaction={"views": 5, "votes_up": 1, "votes_down": 0},
+ )
+ result = svc.filter_trending([card], min_impact=7)
+ assert hasattr(result[0], "trending_score")
+ # 8 + (5 + 2 - 0)/10 = 8.7
+ assert result[0].trending_score == pytest.approx(8.7)
+
+ def test_cards_without_impact_score_excluded(self, svc):
+ card_with = _card(impact_score=9)
+ card_without = Mock(spec=[]) # no impact_score
+ result = svc.filter_trending([card_with, card_without], min_impact=7)
+ assert len(result) == 1
+ assert result[0] is card_with
+
+ def test_min_impact_zero_includes_all(self, svc):
+ cards = [_card(impact_score=i) for i in range(0, 5)]
+ result = svc.filter_trending(cards, min_impact=0, limit=100)
+ assert len(result) == 5
+
+ def test_mixed_impact_scores_correct_filter(self, svc):
+ scores = [10, 7, 3, 8, 6, 9, 7, 1]
+ cards = [_card(impact_score=s) for s in scores]
+ result = svc.filter_trending(cards, min_impact=7)
+ for c in result:
+ assert c.impact_score >= 7
+ assert len(result) == 5 # 10, 7, 8, 9, 7
+
+ def test_stable_order_for_equal_trending_scores(self, svc):
+ """All cards with same trending score still return correct count."""
+ cards = [
+ _card(
+ impact_score=8,
+ interaction={"views": 0, "votes_up": 0, "votes_down": 0},
+ )
+ for _ in range(5)
+ ]
+ result = svc.filter_trending(cards, min_impact=7, limit=3)
+ assert len(result) == 3
+ assert all(c.trending_score == result[0].trending_score for c in result)
+
+
+# ===========================================================================
+# personalize_feed
+# ===========================================================================
+
+
+class TestPersonalizeFeedComprehensive:
+ """Comprehensive personalize_feed tests."""
+
+ def test_empty_cards(self, svc):
+ assert svc.personalize_feed([], None) == []
+
+ def test_empty_cards_with_prefs(self, svc):
+ assert svc.personalize_feed([], {"liked_categories": ["Tech"]}) == []
+
+ def test_sets_relevance_score_attr(self, svc):
+ card = _card(impact_score=7)
+ result = svc.personalize_feed([card], None)
+ assert result[0].relevance_score == pytest.approx(0.7)
+
+ def test_sorted_by_relevance_descending(self, svc):
+ c1 = _card(impact_score=3)
+ c2 = _card(impact_score=9)
+ c3 = _card(impact_score=6)
+ result = svc.personalize_feed([c1, c2, c3], None)
+ scores = [c.relevance_score for c in result]
+ assert scores == sorted(scores, reverse=True)
+
+ def test_include_seen_true_keeps_viewed(self, svc):
+ seen = _card(impact_score=5, viewed=True)
+ unseen = _card(impact_score=5)
+ result = svc.personalize_feed([seen, unseen], None, include_seen=True)
+ assert len(result) == 2
+
+ def test_include_seen_false_removes_viewed(self, svc):
+ seen = _card(impact_score=5, viewed=True)
+ unseen = _card(impact_score=5)
+ result = svc.personalize_feed([seen, unseen], None, include_seen=False)
+ assert len(result) == 1
+ assert result[0] is unseen
+
+ def test_all_seen_excluded_returns_empty(self, svc):
+ cards = [_card(impact_score=5, viewed=True) for _ in range(3)]
+ result = svc.personalize_feed(cards, None, include_seen=False)
+ assert result == []
+
+ def test_default_include_seen_is_true(self, svc):
+ seen = _card(impact_score=5, viewed=True)
+ result = svc.personalize_feed([seen], None)
+ assert len(result) == 1
+
+ def test_viewed_key_missing_card_included(self, svc):
+ """Cards without 'viewed' key should be included even with include_seen=False."""
+ card = _card(impact_score=5, interaction={"views": 10})
+ result = svc.personalize_feed([card], None, include_seen=False)
+ assert len(result) == 1
+
+ def test_viewed_false_card_included(self, svc):
+ card = _card(impact_score=5, interaction={"viewed": False})
+ result = svc.personalize_feed([card], None, include_seen=False)
+ assert len(result) == 1
+
+ def test_viewed_none_card_included(self, svc):
+ """viewed=None is falsy, so card is included."""
+ card = _card(impact_score=5, interaction={"viewed": None})
+ result = svc.personalize_feed([card], None, include_seen=False)
+ assert len(result) == 1
+
+ def test_viewed_zero_card_included(self, svc):
+ """viewed=0 is falsy, so card is included."""
+ card = _card(impact_score=5, interaction={"viewed": 0})
+ result = svc.personalize_feed([card], None, include_seen=False)
+ assert len(result) == 1
+
+ def test_preserves_card_identity(self, svc):
+ card = _card(impact_score=7)
+ result = svc.personalize_feed([card], None)
+ assert result[0] is card
+
+ def test_with_prefs_sorts_correctly(self, svc):
+ liked = _card(category="Tech", impact_score=5, topics=[])
+ disliked = _card(category="Sports", impact_score=5, topics=[])
+ neutral = _card(category="Science", impact_score=5, topics=[])
+ prefs = {
+ "liked_categories": ["Tech"],
+ "disliked_categories": ["Sports"],
+ "impact_threshold": 5,
+ }
+ result = svc.personalize_feed([disliked, neutral, liked], prefs)
+ assert result[0] is liked
+ assert result[-1] is disliked
+
+ def test_relevance_set_before_filtering(self, svc):
+ """Even seen cards get relevance_score set (just filtered from output)."""
+ seen = _card(impact_score=8, viewed=True)
+ svc.personalize_feed([seen], None, include_seen=False)
+ # The card still got its relevance_score set before the filter check
+ assert seen.relevance_score == pytest.approx(0.8)
+
+ def test_single_card_no_prefs(self, svc):
+ card = _card(impact_score=10)
+ result = svc.personalize_feed([card], None)
+ assert len(result) == 1
+ assert result[0].relevance_score == pytest.approx(1.0)
+
+ def test_many_cards_sorted(self, svc):
+ cards = [_card(impact_score=i) for i in range(1, 11)]
+ result = svc.personalize_feed(cards, None)
+ scores = [c.relevance_score for c in result]
+ assert scores == sorted(scores, reverse=True)
+
+ def test_prefs_none_and_empty_dict_same_path(self, svc):
+ """Both None and {} are falsy, so both use impact/10 path."""
+ card1 = _card(impact_score=6)
+ card2 = _card(impact_score=6)
+ svc.personalize_feed([card1], None)
+ svc.personalize_feed([card2], {})
+ assert card1.relevance_score == pytest.approx(0.6)
+ assert card2.relevance_score == pytest.approx(0.6)
+
+ def test_prefs_with_content_uses_prefs_path(self, svc):
+ """Non-empty prefs dict uses the prefs scoring path."""
+ card = _card(impact_score=6)
+ svc.personalize_feed([card], {"impact_threshold": 5})
+ # prefs path: 0.5 base + 0.1 (6 >= 5) = 0.6
+ assert card.relevance_score == pytest.approx(0.6)
+
+
+# ===========================================================================
+# Singleton
+# ===========================================================================
+
+
+class TestGetRelevanceServiceSingleton:
+ """Tests for the module-level singleton."""
+
+ def test_returns_instance(self):
+ svc = get_relevance_service()
+ assert isinstance(svc, RelevanceService)
+
+ def test_returns_same_instance(self):
+ s1 = get_relevance_service()
+ s2 = get_relevance_service()
+ assert s1 is s2
+
+ def test_singleton_reset(self):
+ """After resetting the module global, a new instance is created."""
+ import local_deep_research.news.core.relevance_service as mod
+
+ old = mod._relevance_service
+ mod._relevance_service = None
+ try:
+ new = mod.get_relevance_service()
+ assert isinstance(new, RelevanceService)
+ # If old existed, new might differ (depends on prior tests)
+ finally:
+ # Restore to avoid cross-test pollution
+ mod._relevance_service = old
+
+
+# ===========================================================================
+# Integration-style: combinations of methods
+# ===========================================================================
+
+
+class TestMethodInteractions:
+ """Test interactions between methods."""
+
+ def test_filter_then_personalize(self, svc):
+ """filter_trending output can be fed to personalize_feed."""
+ cards = [
+ _card(
+ impact_score=9,
+ interaction={"views": 100, "votes_up": 10, "votes_down": 0},
+ ),
+ _card(
+ impact_score=8,
+ interaction={"views": 50, "votes_up": 5, "votes_down": 0},
+ ),
+ _card(
+ impact_score=3,
+ interaction={"views": 200, "votes_up": 20, "votes_down": 0},
+ ),
+ ]
+ trending = svc.filter_trending(cards, min_impact=7)
+ assert len(trending) == 2 # only impact 9 and 8
+
+ personalized = svc.personalize_feed(trending, None)
+ assert len(personalized) == 2
+ # Sorted by relevance (impact/10)
+ assert (
+ personalized[0].relevance_score >= personalized[1].relevance_score
+ )
+
+ def test_trending_score_is_consistent_with_calculate(self, svc):
+ """filter_trending sets trending_score using calculate_trending_score."""
+ card = _card(
+ impact_score=8,
+ interaction={"views": 30, "votes_up": 5, "votes_down": 2},
+ )
+ svc.filter_trending([card], min_impact=7)
+ expected = svc.calculate_trending_score(card)
+ assert card.trending_score == pytest.approx(expected)
+
+ def test_personalize_uses_calculate_relevance(self, svc):
+ """personalize_feed sets relevance_score using calculate_relevance."""
+ card = _card(impact_score=7, category="Tech", topics=["ai"])
+ prefs = {
+ "liked_categories": ["Tech"],
+ "liked_topics": ["ai"],
+ "impact_threshold": 5,
+ }
+ svc.personalize_feed([card], prefs)
+ expected = svc.calculate_relevance(card, prefs)
+ assert card.relevance_score == pytest.approx(expected)
diff --git a/tests/news/test_topic_generator_coverage.py b/tests/news/test_topic_generator_coverage.py
new file mode 100644
index 0000000000..8e72165a60
--- /dev/null
+++ b/tests/news/test_topic_generator_coverage.py
@@ -0,0 +1,394 @@
+"""
+Comprehensive coverage tests for topic_generator.py.
+
+Focuses on areas with insufficient coverage in existing test files:
+- _generate_with_llm prompt construction and truncation logic
+- _generate_with_llm response cleaning pipeline (non-string filtering, length cap)
+- _generate_with_llm comma-separated text fallback path
+- _generate_with_llm close_llm always called (finally block)
+- generate_topics orchestration with real _validate_topics (no double-mock)
+- _validate_topics boundary and ordering edge cases
+"""
+
+from unittest.mock import Mock, patch
+
+
+from local_deep_research.news.utils.topic_generator import (
+ _generate_with_llm,
+ _validate_topics,
+ generate_topics,
+)
+
+
+# ---------------------------------------------------------------------------
+# _generate_with_llm – prompt construction
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateWithLLMPromptConstruction:
+ """Verify the prompt fed to the LLM is built correctly."""
+
+ def _invoke_and_capture_prompt(
+ self, query="q", findings="", category="", max_topics=5
+ ):
+ """Helper: call _generate_with_llm with a mock LLM and return the prompt string."""
+ mock_llm = Mock()
+ mock_llm.invoke.return_value = Mock(content='["tag"]')
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.get_llm",
+ return_value=mock_llm,
+ ),
+ patch("local_deep_research.utilities.llm_utils.close_llm"),
+ ):
+ _generate_with_llm(query, findings, category, max_topics)
+
+ prompt = mock_llm.invoke.call_args[0][0]
+ return prompt
+
+ def test_prompt_contains_query(self):
+ prompt = self._invoke_and_capture_prompt(query="climate crisis")
+ assert "climate crisis" in prompt
+
+ def test_query_truncated_at_500(self):
+ long_query = "x" * 600
+ prompt = self._invoke_and_capture_prompt(query=long_query)
+ assert "x" * 500 in prompt
+ assert "x" * 501 not in prompt
+
+ def test_query_not_truncated_when_short(self):
+ prompt = self._invoke_and_capture_prompt(query="short")
+ assert "short" in prompt
+
+ def test_findings_included_when_present(self):
+ prompt = self._invoke_and_capture_prompt(findings="some findings text")
+ assert "some findings text" in prompt
+
+ def test_findings_truncated_at_1000(self):
+ long_findings = "f" * 1500
+ prompt = self._invoke_and_capture_prompt(findings=long_findings)
+ assert "f" * 1000 in prompt
+ assert "f" * 1001 not in prompt
+
+ def test_findings_omitted_when_empty(self):
+ prompt = self._invoke_and_capture_prompt(findings="")
+ assert "Content:" not in prompt
+
+ def test_category_included_when_present(self):
+ prompt = self._invoke_and_capture_prompt(category="Technology")
+ assert "Category: Technology" in prompt
+
+ def test_category_omitted_when_empty(self):
+ prompt = self._invoke_and_capture_prompt(category="")
+ assert "Category:" not in prompt
+
+ def test_max_topics_in_prompt(self):
+ prompt = self._invoke_and_capture_prompt(max_topics=7)
+ assert "7" in prompt
+
+
+# ---------------------------------------------------------------------------
+# _generate_with_llm – response cleaning
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateWithLLMResponseCleaning:
+ """Verify the cleaning pipeline inside _generate_with_llm."""
+
+ def _run_with_llm_content(self, content, max_topics=5):
+ """Helper: mock LLM returning `content` and return the result list."""
+ mock_llm = Mock()
+ mock_llm.invoke.return_value = Mock(content=content)
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.get_llm",
+ return_value=mock_llm,
+ ),
+ patch("local_deep_research.utilities.llm_utils.close_llm"),
+ ):
+ return _generate_with_llm("q", "f", "", max_topics)
+
+ def test_valid_json_array_parsed(self):
+ result = self._run_with_llm_content('["AI", "Climate"]')
+ assert result == ["AI", "Climate"]
+
+ def test_non_string_items_filtered(self):
+ """Items that are not strings should be removed."""
+ result = self._run_with_llm_content('[123, "Valid", null, true]')
+ assert result == ["Valid"]
+
+ def test_empty_string_items_filtered(self):
+ result = self._run_with_llm_content('["", "Valid", " "]')
+ # empty and whitespace-only are filtered (strip then falsy check)
+ assert result == ["Valid"]
+
+ def test_items_over_30_chars_filtered(self):
+ long = "a" * 31
+ result = self._run_with_llm_content(f'["{long}", "short"]')
+ assert result == ["short"]
+
+ def test_exactly_30_char_item_kept(self):
+ item = "a" * 30
+ result = self._run_with_llm_content(f'["{item}"]')
+ assert result == [item]
+
+ def test_max_topics_limits_json_result(self):
+ result = self._run_with_llm_content(
+ '["a1", "b2", "c3", "d4", "e5"]', max_topics=2
+ )
+ assert len(result) == 2
+ assert result == ["a1", "b2"]
+
+ def test_items_are_stripped(self):
+ result = self._run_with_llm_content('[" padded "]')
+ assert result == ["padded"]
+
+
+# ---------------------------------------------------------------------------
+# _generate_with_llm – comma-separated fallback
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateWithLLMCommaFallback:
+ """When extract_json returns None but content has commas, split on comma."""
+
+ def _run_with_non_json(self, content, max_topics=5):
+ mock_llm = Mock()
+ mock_llm.invoke.return_value = Mock(content=content)
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.get_llm",
+ return_value=mock_llm,
+ ),
+ patch("local_deep_research.utilities.llm_utils.close_llm"),
+ patch(
+ "local_deep_research.news.utils.topic_generator.extract_json",
+ return_value=None,
+ ),
+ ):
+ return _generate_with_llm("q", "f", "", max_topics)
+
+ def test_comma_separated_parsed(self):
+ result = self._run_with_non_json("AI, Climate, Economy")
+ assert "AI" in result
+ assert "Climate" in result
+ assert "Economy" in result
+
+ def test_quotes_stripped_from_comma_items(self):
+ result = self._run_with_non_json('"AI", "Climate"')
+ assert "AI" in result
+ assert "Climate" in result
+
+ def test_long_items_filtered_in_comma_path(self):
+ long = "z" * 31
+ result = self._run_with_non_json(f"valid, {long}")
+ assert "valid" in result
+ assert long not in result
+
+ def test_empty_items_filtered_in_comma_path(self):
+ result = self._run_with_non_json("AI, , , Climate")
+ assert "" not in result
+ assert len(result) == 2
+
+ def test_max_topics_applied_in_comma_path(self):
+ result = self._run_with_non_json("aa, bb, cc, dd, ee", max_topics=2)
+ assert len(result) == 2
+
+ def test_no_comma_returns_empty_list(self):
+ """If content has no comma and JSON parsing failed, function returns []."""
+ mock_llm = Mock()
+ mock_llm.invoke.return_value = Mock(content="just plain text")
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.get_llm",
+ return_value=mock_llm,
+ ),
+ patch("local_deep_research.utilities.llm_utils.close_llm"),
+ patch(
+ "local_deep_research.news.utils.topic_generator.extract_json",
+ return_value=None,
+ ),
+ ):
+ result = _generate_with_llm("q", "f", "", 5)
+
+ # Function falls through the try block without explicit return,
+ # then the outer except catches the implicit None and returns []
+ assert result == []
+
+
+# ---------------------------------------------------------------------------
+# _generate_with_llm – error handling and resource cleanup
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateWithLLMErrorHandling:
+ """Verify error handling and LLM cleanup."""
+
+ def test_returns_empty_list_on_get_llm_failure(self):
+ with patch(
+ "local_deep_research.config.llm_config.get_llm",
+ side_effect=Exception("no LLM"),
+ ):
+ result = _generate_with_llm("q", "f", "", 5)
+ assert result == []
+
+ def test_returns_empty_list_on_invoke_failure(self):
+ mock_llm = Mock()
+ mock_llm.invoke.side_effect = RuntimeError("invoke boom")
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.get_llm",
+ return_value=mock_llm,
+ ),
+ patch(
+ "local_deep_research.utilities.llm_utils.close_llm"
+ ) as mock_close,
+ ):
+ result = _generate_with_llm("q", "f", "", 5)
+
+ assert result == []
+ # close_llm should still be called (finally block)
+ mock_close.assert_called_once_with(mock_llm)
+
+ def test_close_llm_called_on_success(self):
+ mock_llm = Mock()
+ mock_llm.invoke.return_value = Mock(content='["tag"]')
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.get_llm",
+ return_value=mock_llm,
+ ),
+ patch(
+ "local_deep_research.utilities.llm_utils.close_llm"
+ ) as mock_close,
+ ):
+ _generate_with_llm("q", "f", "", 5)
+
+ mock_close.assert_called_once_with(mock_llm)
+
+
+# ---------------------------------------------------------------------------
+# generate_topics – orchestration (uses real _validate_topics)
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateTopicsOrchestration:
+ """Test generate_topics with real _validate_topics (only mock _generate_with_llm)."""
+
+ @patch("local_deep_research.news.utils.topic_generator._generate_with_llm")
+ def test_llm_topics_validated_and_lowercased(self, mock_llm):
+ mock_llm.return_value = ["AI", "Climate Change", "AI"]
+ result = generate_topics("query")
+ # Duplicates removed, lowercased
+ assert result == ["ai", "climate change"]
+
+ @patch("local_deep_research.news.utils.topic_generator._generate_with_llm")
+ def test_llm_empty_gives_failure_marker(self, mock_llm):
+ mock_llm.return_value = []
+ result = generate_topics("query")
+ # "[Topic generation failed]" goes through _validate_topics
+ # It is 25 chars, >= 2, so it passes through as lowercase
+ assert result == ["[topic generation failed]"]
+
+ @patch("local_deep_research.news.utils.topic_generator._generate_with_llm")
+ def test_llm_returns_all_invalid_gives_no_valid(self, mock_llm):
+ mock_llm.return_value = ["a", ""] # all too short or empty
+ result = generate_topics("query")
+ assert result == ["[No valid topics]"]
+
+ @patch("local_deep_research.news.utils.topic_generator._generate_with_llm")
+ def test_max_topics_forwarded_to_llm(self, mock_llm):
+ mock_llm.return_value = ["aa", "bb", "cc"]
+ generate_topics("q", max_topics=7)
+ assert mock_llm.call_args[0][3] == 7
+
+ @patch("local_deep_research.news.utils.topic_generator._generate_with_llm")
+ def test_category_forwarded_to_llm(self, mock_llm):
+ mock_llm.return_value = ["tag"]
+ generate_topics("q", category="Sports")
+ assert mock_llm.call_args[0][2] == "Sports"
+
+ @patch("local_deep_research.news.utils.topic_generator._generate_with_llm")
+ def test_findings_forwarded_to_llm(self, mock_llm):
+ mock_llm.return_value = ["tag"]
+ generate_topics("q", findings="some findings")
+ assert mock_llm.call_args[0][1] == "some findings"
+
+ @patch("local_deep_research.news.utils.topic_generator._generate_with_llm")
+ def test_default_parameters(self, mock_llm):
+ mock_llm.return_value = []
+ generate_topics("q")
+ # (query, findings, category, max_topics)
+ args = mock_llm.call_args[0]
+ assert args == ("q", "", "", 5)
+
+
+# ---------------------------------------------------------------------------
+# _validate_topics – additional boundary / ordering tests
+# ---------------------------------------------------------------------------
+
+
+class TestValidateTopicsAdditional:
+ """Cover edge cases not well-tested elsewhere."""
+
+ def test_whitespace_after_strip_becomes_too_short(self):
+ """A topic that is long enough pre-strip but too short after."""
+ result = _validate_topics([" x "], max_topics=5)
+ # "x" is 1 char after strip -> filtered
+ assert result == ["[No valid topics]"]
+
+ def test_dedup_happens_after_strip(self):
+ """' AI ' and 'AI' should be treated as duplicates after stripping."""
+ result = _validate_topics([" AI ", "AI"], max_topics=5)
+ assert result == ["ai"]
+
+ def test_max_topics_zero_still_returns_one(self):
+ """max_topics=0 is a degenerate case: the >= check means one topic
+ gets appended before the break triggers, so we get exactly one."""
+ result = _validate_topics(["valid", "topic"], max_topics=0)
+ assert result == ["valid"]
+
+ def test_large_number_of_topics(self):
+ topics = [f"topic{i:04d}" for i in range(200)]
+ result = _validate_topics(topics, max_topics=10)
+ assert len(result) == 10
+ assert result[0] == "topic0000"
+
+ def test_preserves_internal_whitespace(self):
+ """Internal spaces in multi-word topics should be preserved."""
+ result = _validate_topics(["climate change"], max_topics=5)
+ assert result == ["climate change"]
+
+ def test_tab_and_newline_stripped(self):
+ result = _validate_topics(["\tAI\n"], max_topics=5)
+ assert result == ["ai"]
+
+ def test_failure_marker_from_llm_passes_through(self):
+ """The '[Topic generation failed]' marker should survive validation."""
+ result = _validate_topics(["[Topic generation failed]"], max_topics=5)
+ assert result == ["[topic generation failed]"]
+
+ def test_special_chars_preserved(self):
+ result = _validate_topics(["COVID-19", "AI/ML"], max_topics=5)
+ assert "covid-19" in result
+ assert "ai/ml" in result
+
+ def test_unicode_topics_preserved(self):
+ result = _validate_topics(["klima", "umwelt"], max_topics=5)
+ assert result == ["klima", "umwelt"]
+
+ def test_exactly_boundary_lengths(self):
+ """2-char kept, 1-char dropped, 30-char kept, 31-char dropped."""
+ result = _validate_topics(
+ ["ab", "a", "c" * 30, "d" * 31], max_topics=10
+ )
+ assert "ab" in result
+ assert "a" not in result
+ assert "c" * 30 in result
+ assert "d" * 31 not in result
diff --git a/tests/research_library/downloaders/test_openalex_coverage.py b/tests/research_library/downloaders/test_openalex_coverage.py
new file mode 100644
index 0000000000..20f193eb2f
--- /dev/null
+++ b/tests/research_library/downloaders/test_openalex_coverage.py
@@ -0,0 +1,479 @@
+"""Comprehensive tests for OpenAlexDownloader to increase coverage."""
+
+from unittest.mock import Mock, patch, MagicMock
+
+import pytest
+import requests
+
+from local_deep_research.research_library.downloaders.base import (
+ ContentType,
+ DownloadResult,
+)
+from local_deep_research.research_library.downloaders.openalex import (
+ OpenAlexDownloader,
+)
+
+
+# ============== Fixtures ==============
+
+
+def downloader():
+ """Create an OpenAlexDownloader with mocked session/rate_tracker."""
+ d = OpenAlexDownloader.__new__(OpenAlexDownloader)
+ d.timeout = 30
+ d.polite_pool_email = None
+ d.base_api_url = "https://api.openalex.org"
+ d.session = MagicMock()
+ d.session.headers = {"User-Agent": "Test"}
+ d.rate_tracker = MagicMock()
+ d.rate_tracker.apply_rate_limit.return_value = 0.0
+ return d
+
+
+def pdf_bytes():
+ """Minimal PDF content."""
+ return b"%PDF-1.4 minimal test content"
+
+
+# ============== can_handle ==============
+
+
+class TestCanHandle:
+ def test_openalex_org(self, downloader):
+ assert downloader.can_handle("https://openalex.org/W123456789") is True
+
+ def test_subdomain(self, downloader):
+ assert (
+ downloader.can_handle("https://api.openalex.org/works/W123") is True
+ )
+
+ def test_http_scheme(self, downloader):
+ assert downloader.can_handle("http://openalex.org/W999") is True
+
+ def test_with_query_string(self, downloader):
+ assert (
+ downloader.can_handle("https://openalex.org/W1?select=id") is True
+ )
+
+ def test_rejects_arxiv(self, downloader):
+ assert downloader.can_handle("https://arxiv.org/abs/1234.5678") is False
+
+ def test_rejects_example(self, downloader):
+ assert downloader.can_handle("https://example.com/openalex") is False
+
+ def test_rejects_empty(self, downloader):
+ assert downloader.can_handle("") is False
+
+ def test_rejects_none(self, downloader):
+ assert downloader.can_handle(None) is False
+
+ def test_rejects_not_a_url(self, downloader):
+ assert downloader.can_handle("just some text") is False
+
+ def test_rejects_similar_domain(self, downloader):
+ assert downloader.can_handle("https://notopenalex.org/W123") is False
+
+ def test_rejects_openalex_in_path(self, downloader):
+ assert (
+ downloader.can_handle("https://example.com/openalex.org/W1")
+ is False
+ )
+
+
+# ============== _extract_work_id ==============
+
+
+class TestExtractWorkId:
+ def test_direct_work_url(self, downloader):
+ assert (
+ downloader._extract_work_id("https://openalex.org/W1234567890")
+ == "W1234567890"
+ )
+
+ def test_works_path(self, downloader):
+ assert (
+ downloader._extract_work_id("https://openalex.org/works/W9999")
+ == "W9999"
+ )
+
+ def test_api_subdomain(self, downloader):
+ assert (
+ downloader._extract_work_id("https://api.openalex.org/works/W42")
+ == "W42"
+ )
+
+ def test_with_trailing_slash(self, downloader):
+ assert (
+ downloader._extract_work_id("https://openalex.org/W100/") == "W100"
+ )
+
+ def test_with_query_params(self, downloader):
+ assert (
+ downloader._extract_work_id("https://openalex.org/W55?select=id")
+ == "W55"
+ )
+
+ def test_with_fragment(self, downloader):
+ assert (
+ downloader._extract_work_id("https://openalex.org/W77#section")
+ == "W77"
+ )
+
+ def test_non_openalex_domain(self, downloader):
+ assert downloader._extract_work_id("https://example.com/W123") is None
+
+ def test_no_work_id_in_path(self, downloader):
+ assert (
+ downloader._extract_work_id("https://openalex.org/authors/A123")
+ is None
+ )
+
+ def test_empty_string(self, downloader):
+ assert downloader._extract_work_id("") is None
+
+ def test_invalid_url(self, downloader):
+ assert downloader._extract_work_id("not-a-url") is None
+
+
+# ============== _get_pdf_url ==============
+
+
+class TestGetPdfUrl:
+ def test_returns_pdf_url_when_oa_with_pdf(self, downloader):
+ """Open access work with pdf_url in best_oa_location."""
+ resp = Mock()
+ resp.status_code = 200
+ resp.json.return_value = {
+ "open_access": {"is_oa": True},
+ "best_oa_location": {
+ "pdf_url": "https://example.com/paper.pdf",
+ "landing_page_url": "https://example.com/paper",
+ },
+ }
+ downloader.session.get.return_value = resp
+
+ result = downloader._get_pdf_url("W123")
+ assert result == "https://example.com/paper.pdf"
+
+ def test_returns_none_when_not_oa(self, downloader):
+ """Work is not open access."""
+ resp = Mock()
+ resp.status_code = 200
+ resp.json.return_value = {
+ "open_access": {"is_oa": False},
+ "best_oa_location": None,
+ }
+ downloader.session.get.return_value = resp
+
+ assert downloader._get_pdf_url("W123") is None
+
+ def test_returns_landing_url_when_pdf_content_type(self, downloader):
+ """No pdf_url but landing_page_url serves a PDF."""
+ api_resp = Mock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {
+ "open_access": {"is_oa": True},
+ "best_oa_location": {
+ "pdf_url": None,
+ "landing_page_url": "https://example.com/landing",
+ },
+ }
+
+ head_resp = Mock()
+ head_resp.headers = {"Content-Type": "application/pdf"}
+
+ downloader.session.get.return_value = api_resp
+ downloader.session.head.return_value = head_resp
+
+ result = downloader._get_pdf_url("W123")
+ assert result == "https://example.com/landing"
+
+ def test_skips_landing_url_when_not_pdf(self, downloader):
+ """Landing page is HTML, not PDF."""
+ api_resp = Mock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {
+ "open_access": {"is_oa": True},
+ "best_oa_location": {
+ "pdf_url": None,
+ "landing_page_url": "https://example.com/landing",
+ },
+ }
+
+ head_resp = Mock()
+ head_resp.headers = {"Content-Type": "text/html; charset=utf-8"}
+
+ downloader.session.get.return_value = api_resp
+ downloader.session.head.return_value = head_resp
+
+ assert downloader._get_pdf_url("W123") is None
+
+ def test_landing_url_head_request_fails(self, downloader):
+ """HEAD request for landing page raises an exception."""
+ api_resp = Mock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {
+ "open_access": {"is_oa": True},
+ "best_oa_location": {
+ "pdf_url": None,
+ "landing_page_url": "https://example.com/landing",
+ },
+ }
+
+ downloader.session.get.return_value = api_resp
+ downloader.session.head.side_effect = (
+ requests.exceptions.ConnectionError("fail")
+ )
+
+ assert downloader._get_pdf_url("W123") is None
+
+ def test_no_best_oa_location(self, downloader):
+ """Open access but best_oa_location is empty/None."""
+ resp = Mock()
+ resp.status_code = 200
+ resp.json.return_value = {
+ "open_access": {"is_oa": True},
+ "best_oa_location": None,
+ }
+ downloader.session.get.return_value = resp
+
+ assert downloader._get_pdf_url("W123") is None
+
+ def test_oa_location_empty_dict(self, downloader):
+ """best_oa_location is an empty dict (no pdf_url, no landing_page_url)."""
+ resp = Mock()
+ resp.status_code = 200
+ resp.json.return_value = {
+ "open_access": {"is_oa": True},
+ "best_oa_location": {},
+ }
+ downloader.session.get.return_value = resp
+
+ assert downloader._get_pdf_url("W123") is None
+
+ def test_404_response(self, downloader):
+ """API returns 404."""
+ resp = Mock()
+ resp.status_code = 404
+ downloader.session.get.return_value = resp
+
+ assert downloader._get_pdf_url("W999") is None
+
+ def test_500_response(self, downloader):
+ """API returns 500 server error."""
+ resp = Mock()
+ resp.status_code = 500
+ downloader.session.get.return_value = resp
+
+ assert downloader._get_pdf_url("W999") is None
+
+ def test_request_exception(self, downloader):
+ """Network error during API call."""
+ downloader.session.get.side_effect = (
+ requests.exceptions.ConnectionError("timeout")
+ )
+
+ assert downloader._get_pdf_url("W123") is None
+
+ def test_json_decode_error(self, downloader):
+ """API returns invalid JSON."""
+ resp = Mock()
+ resp.status_code = 200
+ resp.json.side_effect = ValueError("No JSON object")
+ downloader.session.get.return_value = resp
+
+ assert downloader._get_pdf_url("W123") is None
+
+ def test_polite_pool_email_in_header(self, downloader):
+ """When polite_pool_email is set, User-Agent header is sent."""
+ downloader.polite_pool_email = "[email protected]"
+
+ resp = Mock()
+ resp.status_code = 404
+ downloader.session.get.return_value = resp
+
+ downloader._get_pdf_url("W123")
+
+ call_kwargs = downloader.session.get.call_args
+ headers = (
+ call_kwargs[1]["headers"]
+ if "headers" in call_kwargs[1]
+ else call_kwargs.kwargs["headers"]
+ )
+ assert "mailto:[email protected]" in headers.get("User-Agent", "")
+
+ def test_no_polite_pool_email_empty_headers(self, downloader):
+ """When polite_pool_email is None, no User-Agent override."""
+ resp = Mock()
+ resp.status_code = 404
+ downloader.session.get.return_value = resp
+
+ downloader._get_pdf_url("W123")
+
+ call_kwargs = downloader.session.get.call_args
+ headers = call_kwargs[1].get(
+ "headers", call_kwargs.kwargs.get("headers", {})
+ )
+ assert headers == {}
+
+ def test_missing_open_access_key(self, downloader):
+ """Response JSON has no open_access key at all."""
+ resp = Mock()
+ resp.status_code = 200
+ resp.json.return_value = {
+ "best_oa_location": {"pdf_url": "https://x.com/a.pdf"},
+ }
+ downloader.session.get.return_value = resp
+
+ # is_oa defaults to False because open_access is empty dict
+ assert downloader._get_pdf_url("W123") is None
+
+
+# ============== download_with_result ==============
+
+
+class TestDownloadWithResult:
+ def test_non_pdf_content_type_returns_skip(self, downloader):
+ """Requesting TEXT content type returns skip reason."""
+ result = downloader.download_with_result(
+ "https://openalex.org/W123", content_type=ContentType.TEXT
+ )
+ assert result.is_success is False
+ assert (
+ "not yet supported" in result.skip_reason.lower()
+ or "Text extraction" in result.skip_reason
+ )
+
+ def test_invalid_url_returns_skip(self, downloader):
+ """URL that doesn't contain a work ID returns skip."""
+ result = downloader.download_with_result(
+ "https://openalex.org/authors/A1"
+ )
+ assert result.is_success is False
+ assert "work ID" in result.skip_reason
+
+ def test_no_pdf_url_returns_skip(self, downloader):
+ """When _get_pdf_url returns None, skip reason mentions not open access."""
+ with patch.object(downloader, "_get_pdf_url", return_value=None):
+ result = downloader.download_with_result(
+ "https://openalex.org/W123"
+ )
+ assert result.is_success is False
+ assert (
+ "not open access" in result.skip_reason.lower()
+ or "no free PDF" in result.skip_reason
+ )
+
+ def test_successful_download(self, downloader, pdf_bytes):
+ """Full successful flow: extract ID -> get PDF URL -> download PDF."""
+ with patch.object(
+ downloader,
+ "_get_pdf_url",
+ return_value="https://example.com/paper.pdf",
+ ):
+ with patch(
+ "local_deep_research.research_library.downloaders.base.BaseDownloader._download_pdf",
+ return_value=pdf_bytes,
+ ) as mock_dl:
+ result = downloader.download_with_result(
+ "https://openalex.org/W123"
+ )
+
+ assert result.is_success is True
+ assert result.content == pdf_bytes
+ mock_dl.assert_called_once_with("https://example.com/paper.pdf")
+
+ def test_pdf_download_fails(self, downloader):
+ """PDF URL found but actual download returns None."""
+ with patch.object(
+ downloader,
+ "_get_pdf_url",
+ return_value="https://example.com/paper.pdf",
+ ):
+ with patch(
+ "local_deep_research.research_library.downloaders.base.BaseDownloader._download_pdf",
+ return_value=None,
+ ):
+ result = downloader.download_with_result(
+ "https://openalex.org/W123"
+ )
+
+ assert result.is_success is False
+ assert "download failed" in result.skip_reason.lower()
+
+
+# ============== download ==============
+
+
+class TestDownload:
+ def test_returns_bytes_on_success(self, downloader, pdf_bytes):
+ """download() returns content bytes when successful."""
+ with patch.object(
+ downloader,
+ "download_with_result",
+ return_value=DownloadResult(content=pdf_bytes, is_success=True),
+ ):
+ result = downloader.download("https://openalex.org/W123")
+ assert result == pdf_bytes
+
+ def test_returns_none_on_failure(self, downloader):
+ """download() returns None when download_with_result fails."""
+ with patch.object(
+ downloader,
+ "download_with_result",
+ return_value=DownloadResult(skip_reason="No PDF"),
+ ):
+ result = downloader.download("https://openalex.org/W123")
+ assert result is None
+
+ def test_passes_content_type(self, downloader):
+ """download() passes content_type through to download_with_result."""
+ with patch.object(
+ downloader,
+ "download_with_result",
+ return_value=DownloadResult(skip_reason="unsupported"),
+ ) as mock_dwr:
+ downloader.download(
+ "https://openalex.org/W123", content_type=ContentType.TEXT
+ )
+
+ mock_dwr.assert_called_once_with(
+ "https://openalex.org/W123", ContentType.TEXT
+ )
+
+
+# ============== __init__ ==============
+
+
+class TestInit:
+ def test_default_timeout(self):
+ """Default timeout is 30."""
+ d = OpenAlexDownloader()
+ assert d.timeout == 30
+
+ def test_custom_timeout(self):
+ """Custom timeout is respected."""
+ d = OpenAlexDownloader(timeout=60)
+ assert d.timeout == 60
+
+ def test_polite_pool_email(self):
+ """Polite pool email is stored."""
+ d = OpenAlexDownloader(polite_pool_email="[email protected]")
+ assert d.polite_pool_email == "[email protected]"
+
+ def test_polite_pool_default_none(self):
+ """Polite pool email defaults to None."""
+ d = OpenAlexDownloader()
+ assert d.polite_pool_email is None
+
+ def test_base_api_url(self):
+ """Base API URL is set correctly."""
+ d = OpenAlexDownloader()
+ assert d.base_api_url == "https://api.openalex.org"
+
+ def test_session_created(self):
+ """Session is created."""
+ d = OpenAlexDownloader()
+ assert d.session is not None
diff --git a/tests/research_library/downloaders/test_pubmed_coverage.py b/tests/research_library/downloaders/test_pubmed_coverage.py
new file mode 100644
index 0000000000..a4acb1b7b3
--- /dev/null
+++ b/tests/research_library/downloaders/test_pubmed_coverage.py
@@ -0,0 +1,1204 @@
+"""
+Comprehensive coverage tests for research_library/downloaders/pubmed.py
+
+Focuses on:
+- can_handle() URL hostname checking for pubmed/ncbi/pmc
+- _apply_rate_limit() time-based rate limiting
+- _download_pdf_with_result() full download flow with various URL patterns
+- _download_text() and _fetch_text_from_europe_pmc() metadata/text extraction
+- Error handling and edge cases across all code paths
+"""
+
+import time
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.research_library.downloaders.pubmed import (
+ PubMedDownloader,
+)
+from local_deep_research.research_library.downloaders.base import (
+ ContentType,
+ DownloadResult,
+)
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def downloader():
+ """Create a PubMedDownloader with rate limiting disabled."""
+ dl = PubMedDownloader(rate_limit_delay=0.0)
+ dl.last_request_time = 0
+ return dl
+
+
+def downloader_with_rate_limit():
+ """Create a PubMedDownloader with a short rate limit for testing."""
+ return PubMedDownloader(rate_limit_delay=0.15)
+
+
+# ---------------------------------------------------------------------------
+# can_handle – URL hostname checking
+# ---------------------------------------------------------------------------
+
+
+class TestCanHandleURLPatterns:
+ """Thorough URL pattern matching for can_handle()."""
+
+ def test_pubmed_standard_url(self, downloader):
+ assert (
+ downloader.can_handle("https://pubmed.ncbi.nlm.nih.gov/12345678")
+ is True
+ )
+
+ def test_pubmed_trailing_slash(self, downloader):
+ assert (
+ downloader.can_handle("https://pubmed.ncbi.nlm.nih.gov/12345678/")
+ is True
+ )
+
+ def test_pubmed_with_query_params(self, downloader):
+ assert (
+ downloader.can_handle(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678?from=search"
+ )
+ is True
+ )
+
+ def test_pubmed_with_fragment(self, downloader):
+ assert (
+ downloader.can_handle(
+ "https://pubmed.ncbi.nlm.nih.gov/12345678#abstract"
+ )
+ is True
+ )
+
+ def test_pubmed_http_scheme(self, downloader):
+ assert (
+ downloader.can_handle("http://pubmed.ncbi.nlm.nih.gov/12345678")
+ is True
+ )
+
+ def test_pubmed_no_article_id(self, downloader):
+ """Even the root pubmed URL should match (hostname check only)."""
+ assert downloader.can_handle("https://pubmed.ncbi.nlm.nih.gov/") is True
+
+ def test_ncbi_pmc_url(self, downloader):
+ assert (
+ downloader.can_handle(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC1234567"
+ )
+ is True
+ )
+
+ def test_ncbi_pmc_trailing_slash(self, downloader):
+ assert (
+ downloader.can_handle(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC1234567/"
+ )
+ is True
+ )
+
+ def test_ncbi_without_pmc_path_rejected(self, downloader):
+ """ncbi.nlm.nih.gov without /pmc in path must be rejected."""
+ assert (
+ downloader.can_handle("https://ncbi.nlm.nih.gov/gene/12345")
+ is False
+ )
+
+ def test_ncbi_pmc_nested_path(self, downloader):
+ assert (
+ downloader.can_handle(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC9999/pdf/"
+ )
+ is True
+ )
+
+ def test_europe_pmc_bare_domain(self, downloader):
+ assert (
+ downloader.can_handle("https://europepmc.org/article/PMC/1234567")
+ is True
+ )
+
+ def test_europe_pmc_www_subdomain(self, downloader):
+ assert (
+ downloader.can_handle(
+ "https://www.europepmc.org/article/PMC/1234567"
+ )
+ is True
+ )
+
+ def test_europe_pmc_other_subdomain(self, downloader):
+ """Any subdomain of europepmc.org should be accepted."""
+ assert downloader.can_handle("https://api.europepmc.org/search") is True
+
+ def test_reject_google(self, downloader):
+ assert downloader.can_handle("https://google.com") is False
+
+ def test_reject_arxiv(self, downloader):
+ assert (
+ downloader.can_handle("https://arxiv.org/abs/2101.00001") is False
+ )
+
+ def test_reject_nature(self, downloader):
+ assert (
+ downloader.can_handle("https://nature.com/articles/s123") is False
+ )
+
+ def test_reject_empty_string(self, downloader):
+ assert downloader.can_handle("") is False
+
+ def test_reject_plain_text(self, downloader):
+ assert downloader.can_handle("not a url at all") is False
+
+ def test_reject_none_hostname(self, downloader):
+ """URL with no hostname parsed returns False."""
+ assert downloader.can_handle("://") is False
+
+ def test_reject_similar_domain(self, downloader):
+ """Domains that contain 'pubmed' but are not the real one."""
+ assert (
+ downloader.can_handle("https://fakepubmed.ncbi.nlm.nih.gov/123")
+ is False
+ )
+
+ def test_reject_europepmc_in_different_tld(self, downloader):
+ assert (
+ downloader.can_handle("https://europepmc.com/article/PMC/123")
+ is False
+ )
+
+ def test_ncbi_with_www_prefix_no_pmc(self, downloader):
+ """www.ncbi.nlm.nih.gov is not the same hostname as ncbi.nlm.nih.gov."""
+ # The code checks hostname == "ncbi.nlm.nih.gov" exactly
+ assert (
+ downloader.can_handle(
+ "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC123"
+ )
+ is False
+ )
+
+
+# ---------------------------------------------------------------------------
+# _apply_rate_limit – time-based rate limiting
+# ---------------------------------------------------------------------------
+
+
+class TestApplyRateLimit:
+ """Test _apply_rate_limit() behaviour with mocked time."""
+
+ def test_first_request_no_sleep(self, downloader):
+ """First request (last_request_time=0) should not sleep."""
+ with patch(
+ "local_deep_research.research_library.downloaders.pubmed.time"
+ ) as mock_time:
+ mock_time.time.return_value = 1000.0
+ downloader.last_request_time = 0
+ downloader.rate_limit_delay = 1.0
+ downloader._apply_rate_limit()
+ mock_time.sleep.assert_not_called()
+ assert downloader.last_request_time == 1000.0
+
+ def test_rapid_request_sleeps(self, downloader):
+ """Second request within the delay window should sleep."""
+ with patch(
+ "local_deep_research.research_library.downloaders.pubmed.time"
+ ) as mock_time:
+ mock_time.time.return_value = 1000.5
+ downloader.last_request_time = 1000.0
+ downloader.rate_limit_delay = 1.0
+ downloader._apply_rate_limit()
+ mock_time.sleep.assert_called_once_with(
+ pytest.approx(0.5, abs=0.01)
+ )
+
+ def test_sufficient_gap_no_sleep(self, downloader):
+ """Request after the delay window should not sleep."""
+ with patch(
+ "local_deep_research.research_library.downloaders.pubmed.time"
+ ) as mock_time:
+ mock_time.time.return_value = 1005.0
+ downloader.last_request_time = 1000.0
+ downloader.rate_limit_delay = 1.0
+ downloader._apply_rate_limit()
+ mock_time.sleep.assert_not_called()
+
+ def test_updates_last_request_time(self, downloader):
+ """_apply_rate_limit must update last_request_time after sleeping."""
+ with patch(
+ "local_deep_research.research_library.downloaders.pubmed.time"
+ ) as mock_time:
+ # First call to time.time() is for current_time, second is after sleep
+ mock_time.time.side_effect = [1000.5, 1001.0]
+ downloader.last_request_time = 1000.0
+ downloader.rate_limit_delay = 1.0
+ downloader._apply_rate_limit()
+ assert downloader.last_request_time == 1001.0
+
+ def test_real_timing_delay(self, downloader_with_rate_limit):
+ """Integration-style test: real time.sleep with short delay."""
+ dl = downloader_with_rate_limit
+ dl._apply_rate_limit()
+ start = time.time()
+ dl._apply_rate_limit()
+ elapsed = time.time() - start
+ assert elapsed >= 0.1 # at least most of 0.15s delay
+
+ def test_zero_delay_no_sleep(self):
+ """When rate_limit_delay=0, should never sleep."""
+ dl = PubMedDownloader(rate_limit_delay=0.0)
+ dl._apply_rate_limit()
+ start = time.time()
+ dl._apply_rate_limit()
+ elapsed = time.time() - start
+ assert elapsed < 0.05
+
+
+# ---------------------------------------------------------------------------
+# _download_pdf_with_result – full download flow
+# ---------------------------------------------------------------------------
+
+
+class TestDownloadPdfWithResult:
+ """Tests for _download_pdf_with_result covering all three URL branches."""
+
+ # -- PMC URL branch --
+
+ def test_pmc_url_invalid_format_no_digits(self, downloader):
+ """PMC URL with PMC prefix but no digits returns invalid format."""
+ result = downloader._download_pdf_with_result(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC/"
+ )
+ assert result.is_success is False
+ assert "Invalid PMC URL format" in result.skip_reason
+
+ def test_pmc_url_no_pmc_prefix(self, downloader):
+ """PMC URL without PMC prefix falls to unsupported branch."""
+ result = downloader._download_pdf_with_result(
+ "https://ncbi.nlm.nih.gov/pmc/articles/"
+ )
+ assert result.is_success is False
+ assert result.skip_reason is not None
+
+ def test_pmc_url_europe_pmc_success(self, downloader):
+ """PMC URL: Europe PMC succeeds on first try."""
+ with patch.object(
+ downloader, "_download_via_europe_pmc", return_value=b"%PDF"
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC1234567/"
+ )
+ assert result.is_success is True
+ assert result.content == b"%PDF"
+
+ def test_pmc_url_fallback_to_ncbi(self, downloader):
+ """PMC URL: Europe PMC fails, NCBI PMC succeeds."""
+ with (
+ patch.object(
+ downloader, "_download_via_europe_pmc", return_value=None
+ ),
+ patch.object(
+ downloader, "_download_via_ncbi_pmc", return_value=b"%PDF-ncbi"
+ ),
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC1234567/"
+ )
+ assert result.is_success is True
+ assert result.content == b"%PDF-ncbi"
+
+ def test_pmc_url_both_fail(self, downloader):
+ """PMC URL: both sources fail gives descriptive skip reason."""
+ with (
+ patch.object(
+ downloader, "_download_via_europe_pmc", return_value=None
+ ),
+ patch.object(
+ downloader, "_download_via_ncbi_pmc", return_value=None
+ ),
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC1234567/"
+ )
+ assert result.is_success is False
+ assert "PMC1234567" in result.skip_reason
+ assert (
+ "retracted" in result.skip_reason
+ or "embargoed" in result.skip_reason
+ )
+
+ # -- PubMed URL branch --
+
+ def test_pubmed_url_invalid_format(self, downloader):
+ """PubMed URL without PMID returns skip reason."""
+ result = downloader._download_pdf_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/"
+ )
+ assert result.is_success is False
+ assert "Invalid PubMed URL format" in result.skip_reason
+
+ def test_pubmed_url_not_open_access(self, downloader):
+ """PubMed article that is not open access returns subscription skip."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {
+ "resultList": {
+ "result": [
+ {
+ "isOpenAccess": "N",
+ "journalTitle": "Nature Medicine",
+ }
+ ]
+ }
+ }
+ with patch.object(downloader.session, "get", return_value=mock_resp):
+ result = downloader._download_pdf_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/99999999/"
+ )
+ assert result.is_success is False
+ assert "subscription" in result.skip_reason.lower()
+ assert "Nature Medicine" in result.skip_reason
+
+ def test_pubmed_url_no_pdf_available(self, downloader):
+ """PubMed article is open access but has no PDF."""
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.json.return_value = {
+ "resultList": {
+ "result": [
+ {
+ "isOpenAccess": "Y",
+ "hasPDF": "N",
+ }
+ ]
+ }
+ }
+ with patch.object(downloader.session, "get", return_value=mock_resp):
+ result = downloader._download_pdf_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/99999999/"
+ )
+ assert result.is_success is False
+ assert "No PDF" in result.skip_reason
+
+ def test_pubmed_url_open_access_with_pdf(self, downloader):
+ """PubMed open access article with PDF available and PMCID."""
+ api_resp = MagicMock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {
+ "resultList": {
+ "result": [
+ {
+ "isOpenAccess": "Y",
+ "hasPDF": "Y",
+ "pmcid": "PMC555",
+ }
+ ]
+ }
+ }
+ with (
+ patch.object(downloader.session, "get", return_value=api_resp),
+ patch.object(
+ downloader, "_download_via_europe_pmc", return_value=b"%PDF-ok"
+ ),
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/99999999/"
+ )
+ assert result.is_success is True
+ assert result.content == b"%PDF-ok"
+
+ def test_pubmed_url_not_found_in_europe_pmc(self, downloader):
+ """PMID not found in Europe PMC database."""
+ api_resp = MagicMock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {"resultList": {"result": []}}
+ # Also mock the fallback _get_pmc_id_from_pmid
+ with (
+ patch.object(downloader.session, "get", return_value=api_resp),
+ patch.object(
+ downloader, "_get_pmc_id_from_pmid", return_value=None
+ ),
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/99999999/"
+ )
+ assert result.is_success is False
+ assert "not found" in result.skip_reason.lower()
+
+ def test_pubmed_url_api_exception_fallback_to_ncbi(self, downloader):
+ """Europe PMC API throws, fallback to NCBI PMC ID lookup succeeds."""
+ with (
+ patch.object(
+ downloader.session, "get", side_effect=Exception("timeout")
+ ),
+ patch.object(
+ downloader, "_get_pmc_id_from_pmid", return_value="PMC777"
+ ),
+ patch.object(
+ downloader, "_download_via_europe_pmc", return_value=b"%PDF-fb"
+ ),
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/99999999/"
+ )
+ assert result.is_success is True
+
+ def test_pubmed_url_ncbi_pmc_id_found_but_pdf_fails(self, downloader):
+ """PMC ID found via NCBI but PDF download from both sources fails."""
+ with (
+ patch.object(
+ downloader.session, "get", side_effect=Exception("err")
+ ),
+ patch.object(
+ downloader, "_get_pmc_id_from_pmid", return_value="PMC888"
+ ),
+ patch.object(
+ downloader, "_download_via_europe_pmc", return_value=None
+ ),
+ patch.object(
+ downloader, "_download_via_ncbi_pmc", return_value=None
+ ),
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/99999999/"
+ )
+ assert result.is_success is False
+ assert "PMC888" in result.skip_reason
+
+ def test_pubmed_url_no_pmc_id_paywalled(self, downloader):
+ """No PMC ID available at all — article is paywalled."""
+ with (
+ patch.object(
+ downloader.session, "get", side_effect=Exception("err")
+ ),
+ patch.object(
+ downloader, "_get_pmc_id_from_pmid", return_value=None
+ ),
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/99999999/"
+ )
+ assert result.is_success is False
+ assert "paywalled" in result.skip_reason.lower()
+
+ # -- Europe PMC URL branch --
+
+ def test_europe_pmc_url_success(self, downloader):
+ """Europe PMC URL with valid PMC ID succeeds."""
+ with patch.object(
+ downloader, "_download_via_europe_pmc", return_value=b"%PDF-eu"
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://europepmc.org/article/PMC7654321"
+ )
+ assert result.is_success is True
+ assert result.content == b"%PDF-eu"
+
+ def test_europe_pmc_url_download_fails(self, downloader):
+ """Europe PMC URL with valid PMC ID but download fails."""
+ with patch.object(
+ downloader, "_download_via_europe_pmc", return_value=None
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://europepmc.org/article/PMC7654321"
+ )
+ assert result.is_success is False
+ assert "PMC7654321" in result.skip_reason
+
+ def test_europe_pmc_url_no_pmc_id(self, downloader):
+ """Europe PMC URL without PMC ID in URL."""
+ result = downloader._download_pdf_with_result(
+ "https://europepmc.org/article/invalid-path"
+ )
+ assert result.is_success is False
+ assert "Invalid Europe PMC URL format" in result.skip_reason
+
+ def test_europe_pmc_subdomain_url(self, downloader):
+ """Europe PMC with www subdomain."""
+ with patch.object(
+ downloader, "_download_via_europe_pmc", return_value=b"%PDF"
+ ):
+ result = downloader._download_pdf_with_result(
+ "https://www.europepmc.org/article/PMC1111"
+ )
+ assert result.is_success is True
+
+ # -- Unsupported URL branch --
+
+ def test_unsupported_url_format(self, downloader):
+ """URL that matches none of the branches."""
+ result = downloader._download_pdf_with_result(
+ "https://example.com/something"
+ )
+ assert result.is_success is False
+ assert "Unsupported" in result.skip_reason
+
+
+# ---------------------------------------------------------------------------
+# download_with_result – public API
+# ---------------------------------------------------------------------------
+
+
+class TestDownloadWithResult:
+ """Test the public download_with_result() method."""
+
+ def test_text_success(self, downloader):
+ with patch.object(
+ downloader, "_download_text", return_value=b"some text"
+ ):
+ result = downloader.download_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/123/", ContentType.TEXT
+ )
+ assert result.is_success is True
+ assert result.content == b"some text"
+
+ def test_text_failure(self, downloader):
+ with patch.object(downloader, "_download_text", return_value=None):
+ result = downloader.download_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/123/", ContentType.TEXT
+ )
+ assert result.is_success is False
+ assert "subscription" in result.skip_reason.lower()
+
+ def test_pdf_delegates_to_download_pdf_with_result(self, downloader):
+ expected = DownloadResult(content=b"%PDF", is_success=True)
+ with patch.object(
+ downloader, "_download_pdf_with_result", return_value=expected
+ ):
+ result = downloader.download_with_result(
+ "https://pubmed.ncbi.nlm.nih.gov/123/", ContentType.PDF
+ )
+ assert result.is_success is True
+
+
+# ---------------------------------------------------------------------------
+# download – public API
+# ---------------------------------------------------------------------------
+
+
+class TestDownload:
+ """Test the public download() method."""
+
+ def test_pdf_calls_download_pdf_content(self, downloader):
+ with patch.object(
+ downloader, "_download_pdf_content", return_value=b"%PDF"
+ ) as mock_dl:
+ result = downloader.download(
+ "https://pubmed.ncbi.nlm.nih.gov/123/", ContentType.PDF
+ )
+ assert result == b"%PDF"
+ mock_dl.assert_called_once()
+
+ def test_text_calls_download_text(self, downloader):
+ with patch.object(
+ downloader, "_download_text", return_value=b"text"
+ ) as mock_dl:
+ result = downloader.download(
+ "https://pubmed.ncbi.nlm.nih.gov/123/", ContentType.TEXT
+ )
+ assert result == b"text"
+ mock_dl.assert_called_once()
+
+
+# ---------------------------------------------------------------------------
+# _download_pdf_content – URL routing
+# ---------------------------------------------------------------------------
+
+
+class TestDownloadPdfContentRouting:
+ """Test _download_pdf_content routes to the correct handler."""
+
+ def test_routes_pmc_url(self, downloader):
+ with patch.object(
+ downloader, "_download_pmc_direct", return_value=b"pmc"
+ ) as mock_dl:
+ result = downloader._download_pdf_content(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC123/"
+ )
+ assert result == b"pmc"
+ mock_dl.assert_called_once()
+
+ def test_routes_pubmed_url(self, downloader):
+ with patch.object(
+ downloader, "_download_pubmed", return_value=b"pm"
+ ) as mock_dl:
+ result = downloader._download_pdf_content(
+ "https://pubmed.ncbi.nlm.nih.gov/123/"
+ )
+ assert result == b"pm"
+ mock_dl.assert_called_once()
+
+ def test_routes_europe_pmc_url(self, downloader):
+ with patch.object(
+ downloader, "_download_europe_pmc", return_value=b"eu"
+ ) as mock_dl:
+ result = downloader._download_pdf_content(
+ "https://europepmc.org/article/PMC123"
+ )
+ assert result == b"eu"
+ mock_dl.assert_called_once()
+
+ def test_routes_europe_pmc_subdomain(self, downloader):
+ with patch.object(
+ downloader, "_download_europe_pmc", return_value=b"eu"
+ ):
+ result = downloader._download_pdf_content(
+ "https://www.europepmc.org/article/PMC123"
+ )
+ assert result == b"eu"
+
+ def test_unrecognised_url_returns_none(self, downloader):
+ result = downloader._download_pdf_content("https://example.com/foo.pdf")
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# _download_pmc_direct
+# ---------------------------------------------------------------------------
+
+
+class TestDownloadPmcDirect:
+ """Test _download_pmc_direct."""
+
+ def test_no_pmc_id_returns_none(self, downloader):
+ result = downloader._download_pmc_direct(
+ "https://ncbi.nlm.nih.gov/pmc/articles/"
+ )
+ assert result is None
+
+ def test_europe_pmc_succeeds(self, downloader):
+ with patch.object(
+ downloader, "_download_via_europe_pmc", return_value=b"ok"
+ ):
+ result = downloader._download_pmc_direct(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC999/"
+ )
+ assert result == b"ok"
+
+ def test_europe_pmc_fails_ncbi_succeeds(self, downloader):
+ with (
+ patch.object(
+ downloader, "_download_via_europe_pmc", return_value=None
+ ),
+ patch.object(
+ downloader, "_download_via_ncbi_pmc", return_value=b"ncbi"
+ ),
+ ):
+ result = downloader._download_pmc_direct(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC999/"
+ )
+ assert result == b"ncbi"
+
+
+# ---------------------------------------------------------------------------
+# _download_pubmed
+# ---------------------------------------------------------------------------
+
+
+class TestDownloadPubmed:
+ def test_no_pmid_returns_none(self, downloader):
+ result = downloader._download_pubmed("https://pubmed.ncbi.nlm.nih.gov/")
+ assert result is None
+
+ def test_europe_pmc_api_success(self, downloader):
+ with patch.object(
+ downloader, "_try_europe_pmc_api", return_value=b"pdf"
+ ):
+ result = downloader._download_pubmed(
+ "https://pubmed.ncbi.nlm.nih.gov/12345/"
+ )
+ assert result == b"pdf"
+
+ def test_europe_pmc_api_fails_ncbi_fallback(self, downloader):
+ with (
+ patch.object(downloader, "_try_europe_pmc_api", return_value=None),
+ patch.object(
+ downloader, "_get_pmc_id_from_pmid", return_value="PMC111"
+ ),
+ patch.object(
+ downloader, "_download_via_europe_pmc", return_value=b"via-eu"
+ ),
+ ):
+ result = downloader._download_pubmed(
+ "https://pubmed.ncbi.nlm.nih.gov/12345/"
+ )
+ assert result == b"via-eu"
+
+ def test_no_pmc_id_returns_none(self, downloader):
+ with (
+ patch.object(downloader, "_try_europe_pmc_api", return_value=None),
+ patch.object(
+ downloader, "_get_pmc_id_from_pmid", return_value=None
+ ),
+ ):
+ result = downloader._download_pubmed(
+ "https://pubmed.ncbi.nlm.nih.gov/12345/"
+ )
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# _try_europe_pmc_api
+# ---------------------------------------------------------------------------
+
+
+class TestTryEuropePmcApi:
+ def test_open_access_with_pdf_and_pmcid(self, downloader):
+ api_resp = MagicMock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {
+ "resultList": {
+ "result": [
+ {"isOpenAccess": "Y", "hasPDF": "Y", "pmcid": "PMC42"}
+ ]
+ }
+ }
+ with (
+ patch.object(downloader.session, "get", return_value=api_resp),
+ patch.object(
+ downloader, "_download_via_europe_pmc", return_value=b"ok"
+ ) as mock_dl,
+ ):
+ result = downloader._try_europe_pmc_api("12345")
+ assert result == b"ok"
+ mock_dl.assert_called_once_with("PMC42")
+
+ def test_not_open_access(self, downloader):
+ api_resp = MagicMock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {
+ "resultList": {"result": [{"isOpenAccess": "N"}]}
+ }
+ with patch.object(downloader.session, "get", return_value=api_resp):
+ result = downloader._try_europe_pmc_api("12345")
+ assert result is None
+
+ def test_open_access_no_pdf(self, downloader):
+ api_resp = MagicMock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {
+ "resultList": {"result": [{"isOpenAccess": "Y", "hasPDF": "N"}]}
+ }
+ with patch.object(downloader.session, "get", return_value=api_resp):
+ result = downloader._try_europe_pmc_api("12345")
+ assert result is None
+
+ def test_no_pmcid(self, downloader):
+ api_resp = MagicMock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {
+ "resultList": {"result": [{"isOpenAccess": "Y", "hasPDF": "Y"}]}
+ }
+ with patch.object(downloader.session, "get", return_value=api_resp):
+ result = downloader._try_europe_pmc_api("12345")
+ assert result is None
+
+ def test_empty_results(self, downloader):
+ api_resp = MagicMock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {"resultList": {"result": []}}
+ with patch.object(downloader.session, "get", return_value=api_resp):
+ result = downloader._try_europe_pmc_api("12345")
+ assert result is None
+
+ def test_non_200_status(self, downloader):
+ api_resp = MagicMock()
+ api_resp.status_code = 500
+ with patch.object(downloader.session, "get", return_value=api_resp):
+ result = downloader._try_europe_pmc_api("12345")
+ assert result is None
+
+ def test_network_exception(self, downloader):
+ with patch.object(
+ downloader.session, "get", side_effect=Exception("fail")
+ ):
+ result = downloader._try_europe_pmc_api("12345")
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# _get_pmc_id_from_pmid
+# ---------------------------------------------------------------------------
+
+
+class TestGetPmcIdFromPmid:
+ def test_success(self, downloader):
+ resp = MagicMock()
+ resp.status_code = 200
+ resp.json.return_value = {
+ "linksets": [{"linksetdbs": [{"dbto": "pmc", "links": [7654321]}]}]
+ }
+ with patch.object(downloader.session, "get", return_value=resp):
+ assert downloader._get_pmc_id_from_pmid("123") == "PMC7654321"
+
+ def test_no_linksetdbs(self, downloader):
+ resp = MagicMock()
+ resp.status_code = 200
+ resp.json.return_value = {"linksets": [{}]}
+ # Also need to handle fallback scraping
+ scrape_resp = MagicMock()
+ scrape_resp.status_code = 404
+ with patch.object(
+ downloader.session, "get", side_effect=[resp, scrape_resp]
+ ):
+ assert downloader._get_pmc_id_from_pmid("123") is None
+
+ def test_linksetdbs_wrong_db(self, downloader):
+ resp = MagicMock()
+ resp.status_code = 200
+ resp.json.return_value = {
+ "linksets": [{"linksetdbs": [{"dbto": "gene", "links": [999]}]}]
+ }
+ scrape_resp = MagicMock()
+ scrape_resp.status_code = 404
+ with patch.object(
+ downloader.session, "get", side_effect=[resp, scrape_resp]
+ ):
+ assert downloader._get_pmc_id_from_pmid("123") is None
+
+ def test_empty_links(self, downloader):
+ resp = MagicMock()
+ resp.status_code = 200
+ resp.json.return_value = {
+ "linksets": [{"linksetdbs": [{"dbto": "pmc", "links": []}]}]
+ }
+ scrape_resp = MagicMock()
+ scrape_resp.status_code = 404
+ with patch.object(
+ downloader.session, "get", side_effect=[resp, scrape_resp]
+ ):
+ assert downloader._get_pmc_id_from_pmid("123") is None
+
+ def test_api_fails_scrape_succeeds(self, downloader):
+ """When E-utilities fails, fallback to scraping the PubMed page."""
+ scrape_resp = MagicMock()
+ scrape_resp.status_code = 200
+ scrape_resp.text = (
+ '<a href="/pmc/articles/PMC8888/">Free PMC article</a>'
+ )
+ with patch.object(
+ downloader.session,
+ "get",
+ side_effect=[Exception("timeout"), scrape_resp],
+ ):
+ assert downloader._get_pmc_id_from_pmid("123") == "PMC8888"
+
+ def test_both_fail(self, downloader):
+ with patch.object(
+ downloader.session, "get", side_effect=Exception("fail")
+ ):
+ assert downloader._get_pmc_id_from_pmid("123") is None
+
+
+# ---------------------------------------------------------------------------
+# _download_via_europe_pmc / _download_via_ncbi_pmc
+# ---------------------------------------------------------------------------
+
+
+class TestDownloadViaMethods:
+ def test_europe_pmc_constructs_correct_url(self, downloader):
+ with patch.object(downloader, "_download_pdf") as mock_dl:
+ mock_dl.return_value = b"pdf"
+ downloader._download_via_europe_pmc("PMC555")
+ mock_dl.assert_called_once_with(
+ "https://europepmc.org/backend/ptpmcrender.fcgi?accid=PMC555&blobtype=pdf"
+ )
+
+ def test_europe_pmc_returns_none_on_failure(self, downloader):
+ with patch.object(downloader, "_download_pdf", return_value=None):
+ assert downloader._download_via_europe_pmc("PMC555") is None
+
+ def test_ncbi_pmc_tries_two_urls(self, downloader):
+ """NCBI PMC should try /pdf/ then /pdf/main.pdf."""
+ with patch.object(
+ downloader, "_download_pdf", side_effect=[None, b"pdf2"]
+ ) as mock_dl:
+ result = downloader._download_via_ncbi_pmc("PMC999")
+ assert result == b"pdf2"
+ assert mock_dl.call_count == 2
+
+ def test_ncbi_pmc_first_url_succeeds(self, downloader):
+ with patch.object(
+ downloader, "_download_pdf", return_value=b"pdf1"
+ ) as mock_dl:
+ result = downloader._download_via_ncbi_pmc("PMC999")
+ assert result == b"pdf1"
+ assert mock_dl.call_count == 1
+
+ def test_ncbi_pmc_both_fail(self, downloader):
+ with patch.object(downloader, "_download_pdf", return_value=None):
+ assert downloader._download_via_ncbi_pmc("PMC999") is None
+
+
+# ---------------------------------------------------------------------------
+# _download_europe_pmc
+# ---------------------------------------------------------------------------
+
+
+class TestDownloadEuropePmc:
+ def test_extracts_pmc_id_and_downloads(self, downloader):
+ with patch.object(
+ downloader, "_download_via_europe_pmc", return_value=b"ok"
+ ) as mock_dl:
+ result = downloader._download_europe_pmc(
+ "https://europepmc.org/article/PMC123"
+ )
+ mock_dl.assert_called_once_with("PMC123")
+ assert result == b"ok"
+
+ def test_no_pmc_id_returns_none(self, downloader):
+ result = downloader._download_europe_pmc(
+ "https://europepmc.org/article/invalid"
+ )
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# _fetch_text_from_europe_pmc
+# ---------------------------------------------------------------------------
+
+
+class TestFetchTextFromEuropePmc:
+ def test_no_identifiers_returns_none(self, downloader):
+ assert downloader._fetch_text_from_europe_pmc(None, None) is None
+
+ def test_pmcid_query_construction(self, downloader):
+ """When pmc_id provided, query should use PMC: prefix."""
+ api_resp = MagicMock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {"resultList": {"result": []}}
+ with patch.object(
+ downloader.session, "get", return_value=api_resp
+ ) as mock_get:
+ downloader._fetch_text_from_europe_pmc(None, "PMC123")
+ call_kwargs = mock_get.call_args
+ assert call_kwargs[1]["params"]["query"] == "PMC:123"
+
+ def test_pmid_query_construction(self, downloader):
+ """When only pmid provided, query should use EXT_ID: prefix."""
+ api_resp = MagicMock()
+ api_resp.status_code = 200
+ api_resp.json.return_value = {"resultList": {"result": []}}
+ with patch.object(
+ downloader.session, "get", return_value=api_resp
+ ) as mock_get:
+ downloader._fetch_text_from_europe_pmc("56789", None)
+ call_kwargs = mock_get.call_args
+ assert call_kwargs[1]["params"]["query"] == "EXT_ID:56789"
+
+ def test_open_access_with_full_text(self, downloader):
+ meta_resp = MagicMock()
+ meta_resp.status_code = 200
+ meta_resp.json.return_value = {
+ "resultList": {"result": [{"isOpenAccess": "Y", "pmcid": "PMC42"}]}
+ }
+ xml_resp = MagicMock()
+ xml_resp.status_code = 200
+ xml_resp.text = "<article><body><p>Hello world</p></body></article>"
+
+ with patch.object(
+ downloader.session, "get", side_effect=[meta_resp, xml_resp]
+ ):
+ result = downloader._fetch_text_from_europe_pmc("123", None)
+ assert result is not None
+ assert "Hello world" in result
+
+ def test_xml_tags_stripped(self, downloader):
+ meta_resp = MagicMock()
+ meta_resp.status_code = 200
+ meta_resp.json.return_value = {
+ "resultList": {"result": [{"isOpenAccess": "Y", "pmcid": "PMC42"}]}
+ }
+ xml_resp = MagicMock()
+ xml_resp.status_code = 200
+ xml_resp.text = "<root><a>one</a><b>two</b></root>"
+
+ with patch.object(
+ downloader.session, "get", side_effect=[meta_resp, xml_resp]
+ ):
+ result = downloader._fetch_text_from_europe_pmc("123", None)
+ assert "<" not in result
+ assert "one" in result and "two" in result
+
+ def test_not_open_access_returns_none(self, downloader):
+ meta_resp = MagicMock()
+ meta_resp.status_code = 200
+ meta_resp.json.return_value = {
+ "resultList": {"result": [{"isOpenAccess": "N"}]}
+ }
+ with patch.object(downloader.session, "get", return_value=meta_resp):
+ assert downloader._fetch_text_from_europe_pmc("123", None) is None
+
+ def test_no_pmcid_in_result(self, downloader):
+ meta_resp = MagicMock()
+ meta_resp.status_code = 200
+ meta_resp.json.return_value = {
+ "resultList": {"result": [{"isOpenAccess": "Y"}]}
+ }
+ with patch.object(downloader.session, "get", return_value=meta_resp):
+ assert downloader._fetch_text_from_europe_pmc("123", None) is None
+
+ def test_xml_fetch_non_200(self, downloader):
+ meta_resp = MagicMock()
+ meta_resp.status_code = 200
+ meta_resp.json.return_value = {
+ "resultList": {"result": [{"isOpenAccess": "Y", "pmcid": "PMC42"}]}
+ }
+ xml_resp = MagicMock()
+ xml_resp.status_code = 500
+
+ with patch.object(
+ downloader.session, "get", side_effect=[meta_resp, xml_resp]
+ ):
+ assert downloader._fetch_text_from_europe_pmc("123", None) is None
+
+ def test_network_exception_returns_none(self, downloader):
+ with patch.object(
+ downloader.session, "get", side_effect=Exception("fail")
+ ):
+ assert downloader._fetch_text_from_europe_pmc("123", None) is None
+
+ def test_empty_xml_returns_none(self, downloader):
+ meta_resp = MagicMock()
+ meta_resp.status_code = 200
+ meta_resp.json.return_value = {
+ "resultList": {"result": [{"isOpenAccess": "Y", "pmcid": "PMC42"}]}
+ }
+ xml_resp = MagicMock()
+ xml_resp.status_code = 200
+ xml_resp.text = ""
+
+ with patch.object(
+ downloader.session, "get", side_effect=[meta_resp, xml_resp]
+ ):
+ assert downloader._fetch_text_from_europe_pmc("123", None) is None
+
+
+# ---------------------------------------------------------------------------
+# _download_text
+# ---------------------------------------------------------------------------
+
+
+class TestDownloadText:
+ def test_pubmed_url_extracts_pmid(self, downloader):
+ with patch.object(
+ downloader, "_fetch_text_from_europe_pmc", return_value="text"
+ ) as mock_dl:
+ result = downloader._download_text(
+ "https://pubmed.ncbi.nlm.nih.gov/55555/"
+ )
+ assert result == b"text"
+ mock_dl.assert_called_once_with("55555", None)
+
+ def test_pmc_url_extracts_pmc_id(self, downloader):
+ with patch.object(
+ downloader, "_fetch_text_from_europe_pmc", return_value="text"
+ ) as mock_dl:
+ result = downloader._download_text(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC7777/"
+ )
+ assert result == b"text"
+ mock_dl.assert_called_once_with(None, "PMC7777")
+
+ def test_text_not_available_fallback_to_pdf(self, downloader):
+ """When text API fails, tries PDF extraction."""
+ with (
+ patch.object(
+ downloader, "_fetch_text_from_europe_pmc", return_value=None
+ ),
+ patch.object(
+ downloader, "_download_pdf_content", return_value=b"fakepdf"
+ ),
+ patch.object(
+ downloader, "extract_text_from_pdf", return_value="extracted"
+ ),
+ ):
+ result = downloader._download_text(
+ "https://pubmed.ncbi.nlm.nih.gov/123/"
+ )
+ assert result == b"extracted"
+
+ def test_text_and_pdf_both_fail(self, downloader):
+ with (
+ patch.object(
+ downloader, "_fetch_text_from_europe_pmc", return_value=None
+ ),
+ patch.object(
+ downloader, "_download_pdf_content", return_value=None
+ ),
+ ):
+ assert (
+ downloader._download_text(
+ "https://pubmed.ncbi.nlm.nih.gov/123/"
+ )
+ is None
+ )
+
+ def test_pdf_extraction_returns_none(self, downloader):
+ with (
+ patch.object(
+ downloader, "_fetch_text_from_europe_pmc", return_value=None
+ ),
+ patch.object(
+ downloader, "_download_pdf_content", return_value=b"pdf"
+ ),
+ patch.object(
+ downloader, "extract_text_from_pdf", return_value=None
+ ),
+ ):
+ assert (
+ downloader._download_text(
+ "https://pubmed.ncbi.nlm.nih.gov/123/"
+ )
+ is None
+ )
+
+ def test_unrecognised_url_no_ids(self, downloader):
+ """URL that yields neither pmid nor pmc_id still tries PDF fallback."""
+ with (
+ patch.object(
+ downloader, "_fetch_text_from_europe_pmc"
+ ) as mock_fetch,
+ patch.object(
+ downloader, "_download_pdf_content", return_value=None
+ ),
+ ):
+ result = downloader._download_text("https://example.com/something")
+ # _fetch_text_from_europe_pmc should not be called since both are None
+ mock_fetch.assert_not_called()
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# Initialization
+# ---------------------------------------------------------------------------
+
+
+class TestInit:
+ def test_defaults(self):
+ dl = PubMedDownloader()
+ assert dl.timeout == 30
+ assert dl.rate_limit_delay == 1.0
+ assert dl.last_request_time == 0
+
+ def test_custom_params(self):
+ dl = PubMedDownloader(timeout=60, rate_limit_delay=2.5)
+ assert dl.timeout == 60
+ assert dl.rate_limit_delay == 2.5
+
+ def test_has_session(self):
+ dl = PubMedDownloader()
+ assert hasattr(dl, "session")
+
+ def test_inherits_base_downloader(self):
+ from local_deep_research.research_library.downloaders.base import (
+ BaseDownloader,
+ )
+
+ dl = PubMedDownloader()
+ assert isinstance(dl, BaseDownloader)
diff --git a/tests/research_library/services/test_pdf_storage_manager_coverage.py b/tests/research_library/services/test_pdf_storage_manager_coverage.py
new file mode 100644
index 0000000000..8b4ce0f5d2
--- /dev/null
+++ b/tests/research_library/services/test_pdf_storage_manager_coverage.py
@@ -0,0 +1,490 @@
+"""
+Comprehensive tests for PDFStorageManager helper methods.
+
+Focuses on:
+- _get_safe_file_path(): Path traversal prevention (security-critical)
+- _infer_storage_mode(): Storage detection logic
+- _generate_filename(): URL-to-filename conversion
+"""
+
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.constants import (
+ FILE_PATH_BLOB_DELETED,
+ FILE_PATH_METADATA_ONLY,
+ FILE_PATH_SENTINELS,
+ FILE_PATH_TEXT_ONLY,
+)
+from local_deep_research.research_library.services.pdf_storage_manager import (
+ PDFStorageManager,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _mgr(tmp_path, mode="filesystem"):
+ """Shortcut to create a PDFStorageManager rooted at tmp_path."""
+ return PDFStorageManager(tmp_path, mode)
+
+
+# ===========================================================================
+# _get_safe_file_path -- SECURITY-CRITICAL
+# ===========================================================================
+
+
+class TestGetSafeFilePath:
+ """Path traversal prevention tests for _get_safe_file_path."""
+
+ # -- Valid paths --
+
+ def test_simple_relative_path(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ result = mgr._get_safe_file_path("pdfs/paper.pdf")
+ assert result is not None
+ assert result == tmp_path / "pdfs" / "paper.pdf"
+
+ def test_nested_relative_path(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ result = mgr._get_safe_file_path("pdfs/2024/01/paper.pdf")
+ assert result is not None
+ assert str(result).startswith(str(tmp_path))
+
+ def test_filename_only(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ result = mgr._get_safe_file_path("paper.pdf")
+ assert result is not None
+ assert result == tmp_path / "paper.pdf"
+
+ # -- Empty / sentinel inputs → None --
+
+ def test_empty_string_returns_none(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path("") is None
+
+ def test_none_returns_none(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path(None) is None
+
+ @pytest.mark.parametrize("sentinel", list(FILE_PATH_SENTINELS))
+ def test_sentinels_return_none(self, tmp_path, sentinel):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path(sentinel) is None
+
+ def test_metadata_only_sentinel(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path(FILE_PATH_METADATA_ONLY) is None
+
+ def test_text_only_sentinel(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path(FILE_PATH_TEXT_ONLY) is None
+
+ def test_blob_deleted_sentinel(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path(FILE_PATH_BLOB_DELETED) is None
+
+ # -- Path traversal attacks → None --
+
+ def test_dot_dot_simple(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path("../etc/passwd") is None
+
+ def test_dot_dot_deep(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path("../../../../../../etc/shadow") is None
+
+ def test_dot_dot_in_middle(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path("pdfs/../../etc/passwd") is None
+
+ def test_dot_dot_encoded_slash(self, tmp_path):
+ """URL-encoded slashes should not bypass the check."""
+ mgr = _mgr(tmp_path)
+ # Even if someone encodes slashes, PathValidator should catch it
+ assert mgr._get_safe_file_path("..%2F..%2Fetc%2Fpasswd") is None or str(
+ mgr._get_safe_file_path("..%2F..%2Fetc%2Fpasswd")
+ ).startswith(str(tmp_path))
+
+ def test_backslash_traversal(self, tmp_path):
+ """Backslash-based traversal (Windows-style)."""
+ mgr = _mgr(tmp_path)
+ result = mgr._get_safe_file_path("..\\..\\etc\\passwd")
+ # Should either be None or safely contained within library_root
+ if result is not None:
+ assert str(result.resolve()).startswith(str(tmp_path))
+
+ def test_absolute_path_rejected(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ result = mgr._get_safe_file_path("/etc/passwd")
+ # Absolute paths outside library_root must be blocked
+ if result is not None:
+ assert str(result.resolve()).startswith(str(tmp_path))
+
+ def test_null_byte_injection(self, tmp_path):
+ """Null bytes must not bypass validation."""
+ mgr = _mgr(tmp_path)
+ result = mgr._get_safe_file_path("pdfs/paper.pdf\x00.txt")
+ # Should be blocked (None) or safely contained
+ if result is not None:
+ assert str(result.resolve()).startswith(str(tmp_path))
+
+ def test_dot_dot_with_trailing_slash(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ assert mgr._get_safe_file_path("../") is None
+
+ def test_current_dir_reference(self, tmp_path):
+ """Single dot should still resolve within library root."""
+ mgr = _mgr(tmp_path)
+ result = mgr._get_safe_file_path("./pdfs/paper.pdf")
+ # This is actually safe, but PathValidator may reject it
+ if result is not None:
+ assert str(result.resolve()).startswith(str(tmp_path))
+
+ def test_double_dot_slash_variations(self, tmp_path):
+ """Various .. patterns that attackers try."""
+ mgr = _mgr(tmp_path)
+ attacks = [
+ "../",
+ "..\\",
+ "../../../etc/passwd",
+ "pdfs/../../../etc/passwd",
+ "pdfs/./../../etc/passwd",
+ "....//....//etc/passwd",
+ ]
+ for attack in attacks:
+ result = mgr._get_safe_file_path(attack)
+ if result is not None:
+ assert str(result.resolve()).startswith(str(tmp_path)), (
+ f"Attack '{attack}' escaped library root to {result}"
+ )
+
+ def test_symlink_blocked(self, tmp_path):
+ """Symlinks pointing outside library root should be blocked."""
+ # Create a symlink inside tmp_path that points to /etc
+ link_path = tmp_path / "pdfs"
+ link_path.mkdir(parents=True, exist_ok=True)
+ symlink = tmp_path / "pdfs" / "evil.pdf"
+ try:
+ symlink.symlink_to("/etc/passwd")
+ except (OSError, PermissionError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ mgr = _mgr(tmp_path)
+ result = mgr._get_safe_file_path("pdfs/evil.pdf")
+ assert result is None, "Symlinks must be blocked"
+
+ def test_long_path_with_valid_characters(self, tmp_path):
+ """Very long but valid relative paths should work."""
+ mgr = _mgr(tmp_path)
+ long_path = "pdfs/" + "a" * 200 + ".pdf"
+ result = mgr._get_safe_file_path(long_path)
+ # Should succeed if the path is within library root
+ if result is not None:
+ assert str(result).startswith(str(tmp_path))
+
+
+# ===========================================================================
+# _infer_storage_mode
+# ===========================================================================
+
+
+class TestInferStorageMode:
+ """Tests for backward-compatible storage mode inference."""
+
+ def test_blob_present_means_database(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ doc = Mock()
+ doc.blob = Mock() # truthy blob
+ doc.file_path = "pdfs/test.pdf"
+ assert mgr._infer_storage_mode(doc) == "database"
+
+ def test_blob_none_with_file_path_means_filesystem(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ doc = Mock()
+ doc.blob = None
+ doc.file_path = "pdfs/test.pdf"
+ assert mgr._infer_storage_mode(doc) == "filesystem"
+
+ def test_blob_none_with_no_file_path_means_none(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ doc = Mock()
+ doc.blob = None
+ doc.file_path = None
+ assert mgr._infer_storage_mode(doc) == "none"
+
+ def test_blob_none_with_empty_file_path_means_none(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ doc = Mock()
+ doc.blob = None
+ doc.file_path = ""
+ assert mgr._infer_storage_mode(doc) == "none"
+
+ @pytest.mark.parametrize("sentinel", list(FILE_PATH_SENTINELS))
+ def test_sentinels_infer_as_none(self, tmp_path, sentinel):
+ """All sentinel values should infer as 'none' storage."""
+ mgr = _mgr(tmp_path)
+ doc = Mock()
+ doc.blob = None
+ doc.file_path = sentinel
+ assert mgr._infer_storage_mode(doc) == "none"
+
+ def test_blob_takes_precedence_over_sentinel(self, tmp_path):
+ """If blob is present AND file_path is sentinel, blob wins."""
+ mgr = _mgr(tmp_path)
+ doc = Mock()
+ doc.blob = Mock()
+ doc.file_path = FILE_PATH_METADATA_ONLY
+ assert mgr._infer_storage_mode(doc) == "database"
+
+ def test_blob_takes_precedence_over_file_path(self, tmp_path):
+ """If both blob and file_path exist, blob (database) wins."""
+ mgr = _mgr(tmp_path)
+ doc = Mock()
+ doc.blob = Mock()
+ doc.file_path = "pdfs/test.pdf"
+ assert mgr._infer_storage_mode(doc) == "database"
+
+ def test_no_blob_attribute_means_no_database(self, tmp_path):
+ """Document without blob attribute at all should not be 'database'."""
+ mgr = _mgr(tmp_path)
+ doc = Mock(spec=["file_path"]) # no blob attribute
+ doc.file_path = "pdfs/test.pdf"
+ assert mgr._infer_storage_mode(doc) == "filesystem"
+
+ def test_no_blob_no_file_path_attribute(self, tmp_path):
+ """Document with neither blob nor file_path should be 'none'."""
+ mgr = _mgr(tmp_path)
+ doc = Mock(spec=["file_path"])
+ doc.file_path = None
+ assert mgr._infer_storage_mode(doc) == "none"
+
+ def test_empty_blob_is_falsy(self, tmp_path):
+ """An empty/falsy blob should not count as database storage."""
+ mgr = _mgr(tmp_path)
+ doc = Mock()
+ doc.blob = [] # falsy
+ doc.file_path = "pdfs/paper.pdf"
+ assert mgr._infer_storage_mode(doc) == "filesystem"
+
+ def test_blob_false_is_falsy(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ doc = Mock()
+ doc.blob = False
+ doc.file_path = "pdfs/paper.pdf"
+ assert mgr._infer_storage_mode(doc) == "filesystem"
+
+
+# ===========================================================================
+# _generate_filename
+# ===========================================================================
+
+
+class TestGenerateFilename:
+ """URL-to-filename conversion tests."""
+
+ # -- arXiv --
+
+ def test_arxiv_standard_url(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://arxiv.org/pdf/2401.12345.pdf", None, "fallback.pdf"
+ )
+ assert fn == "arxiv_2401.12345.pdf"
+
+ def test_arxiv_abs_url(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://arxiv.org/abs/2301.1234", 42, "fallback.pdf"
+ )
+ assert fn == "arxiv_2301.1234.pdf"
+
+ def test_arxiv_4digit_id(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://arxiv.org/abs/2301.1234", None, "fallback.pdf"
+ )
+ assert "2301.1234" in fn
+ assert fn.startswith("arxiv_")
+ assert fn.endswith(".pdf")
+
+ def test_arxiv_5digit_id(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://arxiv.org/pdf/2401.12345v2", None, "fallback.pdf"
+ )
+ assert "2401.12345" in fn
+
+ def test_arxiv_subdomain(self, tmp_path):
+ """export.arxiv.org should be recognized as arXiv."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://export.arxiv.org/pdf/2301.54321", 5, "fallback.pdf"
+ )
+ assert fn == "arxiv_2301.54321.pdf"
+
+ def test_arxiv_no_id_in_url(self, tmp_path):
+ """arXiv URL without recognizable ID falls back to timestamp."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://arxiv.org/some/other/path", 99, "fallback.pdf"
+ )
+ assert fn.startswith("arxiv_")
+ assert fn.endswith(".pdf")
+ assert "99" in fn # resource_id used
+
+ def test_arxiv_no_id_no_resource_id(self, tmp_path):
+ """arXiv URL without ID and no resource_id uses 'unknown'."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://arxiv.org/some/other/path", None, "fallback.pdf"
+ )
+ assert "unknown" in fn
+ assert fn.startswith("arxiv_")
+
+ # -- PubMed / PMC --
+
+ def test_pmc_standard_url(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC1234567/pdf/",
+ None,
+ "fallback.pdf",
+ )
+ assert fn == "pmc_PMC1234567.pdf"
+
+ def test_pmc_with_resource_id(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC9876543/",
+ 42,
+ "fallback.pdf",
+ )
+ assert fn == "pmc_PMC9876543.pdf"
+
+ def test_pmc_no_id_in_url(self, tmp_path):
+ """PMC URL without recognizable PMC ID falls back to timestamp."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://ncbi.nlm.nih.gov/pmc/about/", 10, "fallback.pdf"
+ )
+ assert fn.startswith("pubmed_")
+ assert fn.endswith(".pdf")
+ assert "10" in fn
+
+ def test_pmc_no_id_no_resource_id(self, tmp_path):
+ """PMC URL without ID and no resource_id uses 'unknown'."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://ncbi.nlm.nih.gov/pmc/about/", None, "fallback.pdf"
+ )
+ assert "unknown" in fn
+ assert fn.startswith("pubmed_")
+
+ def test_ncbi_non_pmc_path_uses_fallback(self, tmp_path):
+ """NCBI URL without /pmc in path should use fallback."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://ncbi.nlm.nih.gov/pubmed/12345678",
+ None,
+ "my_paper.pdf",
+ )
+ assert fn == "my_paper.pdf"
+
+ # -- Fallback --
+
+ def test_unknown_url_uses_fallback(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://example.com/paper.pdf", None, "my_paper.pdf"
+ )
+ assert fn == "my_paper.pdf"
+
+ def test_unknown_url_preserves_fallback_exactly(self, tmp_path):
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://nature.com/articles/12345/download",
+ 100,
+ "document_20240101.pdf",
+ )
+ assert fn == "document_20240101.pdf"
+
+ def test_fallback_with_special_characters(self, tmp_path):
+ """Fallback filename with special chars is returned as-is."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://example.com/", None, "a file (1).pdf"
+ )
+ assert fn == "a file (1).pdf"
+
+ # -- Edge cases --
+
+ def test_empty_url_uses_fallback(self, tmp_path):
+ """Empty URL should use fallback filename."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename("", None, "fallback.pdf")
+ assert fn == "fallback.pdf"
+
+ def test_url_with_no_hostname(self, tmp_path):
+ """URL with no hostname should use fallback."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "file:///local/paper.pdf", None, "fallback.pdf"
+ )
+ assert fn == "fallback.pdf"
+
+ def test_http_vs_https_arxiv(self, tmp_path):
+ """Both http and https arXiv URLs should work."""
+ mgr = _mgr(tmp_path)
+ fn_http = mgr._generate_filename(
+ "http://arxiv.org/abs/2301.12345", None, "fallback.pdf"
+ )
+ fn_https = mgr._generate_filename(
+ "https://arxiv.org/abs/2301.12345", None, "fallback.pdf"
+ )
+ assert fn_http == fn_https == "arxiv_2301.12345.pdf"
+
+ def test_arxiv_with_query_params(self, tmp_path):
+ """arXiv URL with query params should still extract ID."""
+ mgr = _mgr(tmp_path)
+ fn = mgr._generate_filename(
+ "https://arxiv.org/pdf/2301.12345?download=true",
+ None,
+ "fallback.pdf",
+ )
+ assert "2301.12345" in fn
+
+
+# ===========================================================================
+# __init__ validation
+# ===========================================================================
+
+
+class TestInitValidation:
+ """Verify constructor handles edge cases."""
+
+ def test_unknown_mode_defaults_to_none(self, tmp_path):
+ mgr = PDFStorageManager(tmp_path, "s3")
+ assert mgr.storage_mode == "none"
+
+ def test_empty_string_mode_defaults_to_none(self, tmp_path):
+ mgr = PDFStorageManager(tmp_path, "")
+ assert mgr.storage_mode == "none"
+
+ def test_library_root_is_resolved(self, tmp_path):
+ relative = tmp_path / "sub" / ".." / "sub"
+ relative.mkdir(parents=True, exist_ok=True)
+ mgr = PDFStorageManager(relative, "filesystem")
+ # Should be resolved (no ..)
+ assert ".." not in str(mgr.library_root)
+
+ def test_max_size_calculation(self, tmp_path):
+ mgr = PDFStorageManager(tmp_path, "none", max_pdf_size_mb=50)
+ assert mgr.max_pdf_size_bytes == 50 * 1024 * 1024
+
+ def test_default_max_size(self, tmp_path):
+ mgr = PDFStorageManager(tmp_path, "none")
+ assert mgr.max_pdf_size_bytes == 100 * 1024 * 1024
diff --git a/tests/security/test_data_sanitizer_coverage.py b/tests/security/test_data_sanitizer_coverage.py
new file mode 100644
index 0000000000..acf71162e9
--- /dev/null
+++ b/tests/security/test_data_sanitizer_coverage.py
@@ -0,0 +1,628 @@
+"""
+Comprehensive coverage tests for data_sanitizer.py.
+
+Targets gaps not covered by existing test suites:
+- Tuple and set inputs (non-list iterables)
+- sanitize/redact with dict values that are lists of lists
+- redact on deeply nested structures with custom keys + custom text combined
+- filter_research_metadata with truthy/falsy edge values (0, empty string, empty list)
+- strip_settings_snapshot preserving complex nested values
+- Ensuring bool coercion in filter_research_metadata for various truthy types
+- sanitize/redact on dicts where values are themselves sensitive-key dicts
+- Mixed list containing nested lists and dicts
+- redact with empty string redaction_text
+- Large flat dict with only sensitive keys
+- Key collision: same key different cases in one dict
+- Convenience functions with all optional params
+- strip_settings_snapshot with empty string input
+- filter_research_metadata with empty string input
+- Numeric and boolean JSON strings for metadata functions
+"""
+
+import json
+
+import pytest
+
+from local_deep_research.security.data_sanitizer import (
+ DataSanitizer,
+ filter_research_metadata,
+ redact_data,
+ sanitize_data,
+ strip_settings_snapshot,
+)
+
+
+# ---------------------------------------------------------------------------
+# sanitize() -- additional coverage
+# ---------------------------------------------------------------------------
+
+
+class TestSanitizeTupleAndUnusualTypes:
+ """Sanitize behavior with tuple, set, and other non-list/dict types."""
+
+ def test_tuple_returned_as_is(self):
+ """Tuples are primitives from sanitize's perspective -- returned unchanged."""
+ data = (1, 2, 3)
+ result = DataSanitizer.sanitize(data)
+ assert result == (1, 2, 3)
+
+ def test_set_returned_as_is(self):
+ """Sets are not traversed -- returned unchanged."""
+ data = {1, 2, 3}
+ result = DataSanitizer.sanitize(data)
+ assert result == {1, 2, 3}
+
+ def test_float_returned_as_is(self):
+ """Float primitives pass through."""
+ assert DataSanitizer.sanitize(3.14) == 3.14
+
+ def test_bytes_returned_as_is(self):
+ """Bytes are treated as a primitive."""
+ data = b"hello"
+ assert DataSanitizer.sanitize(data) == b"hello"
+
+ def test_zero_returned_as_is(self):
+ """Zero (falsy int) passes through unchanged."""
+ assert DataSanitizer.sanitize(0) == 0
+
+ def test_empty_string_returned_as_is(self):
+ """Empty string (falsy) passes through unchanged."""
+ assert DataSanitizer.sanitize("") == ""
+
+ def test_false_returned_as_is(self):
+ """False (falsy bool) passes through unchanged."""
+ assert DataSanitizer.sanitize(False) is False
+
+
+class TestSanitizeNestedListsOfLists:
+ """Sanitize handles nested list structures."""
+
+ def test_list_of_lists_with_dicts(self):
+ """Nested list of lists containing dicts are sanitized."""
+ data = [[{"api_key": "k1", "val": 1}], [{"password": "p1", "val": 2}]]
+ result = DataSanitizer.sanitize(data)
+ assert result == [[{"val": 1}], [{"val": 2}]]
+
+ def test_list_of_mixed_nested(self):
+ """Mixed list containing dicts, lists, and primitives."""
+ data = [
+ {"secret": "s", "ok": True},
+ [{"access_token": "t"}, 42],
+ "plain",
+ ]
+ result = DataSanitizer.sanitize(data)
+ assert result[0] == {"ok": True}
+ assert result[1] == [{}, 42]
+ assert result[2] == "plain"
+
+
+class TestSanitizeValueTypes:
+ """Sanitize removes keys regardless of the value type."""
+
+ def test_sensitive_key_with_list_value(self):
+ """A sensitive key whose value is a list is still removed entirely."""
+ data = {"api_key": [1, 2, 3], "name": "ok"}
+ result = DataSanitizer.sanitize(data)
+ assert "api_key" not in result
+ assert result == {"name": "ok"}
+
+ def test_sensitive_key_with_dict_value(self):
+ """A sensitive key whose value is a dict is still removed entirely."""
+ data = {"password": {"nested": "data"}, "name": "ok"}
+ result = DataSanitizer.sanitize(data)
+ assert "password" not in result
+ assert result == {"name": "ok"}
+
+ def test_sensitive_key_with_none_value(self):
+ """A sensitive key with None value is still removed."""
+ data = {"secret": None, "name": "ok"}
+ result = DataSanitizer.sanitize(data)
+ assert "secret" not in result
+
+ def test_sensitive_key_with_bool_value(self):
+ """A sensitive key with boolean value is still removed."""
+ data = {"csrf_token": True, "name": "ok"}
+ result = DataSanitizer.sanitize(data)
+ assert "csrf_token" not in result
+
+ def test_sensitive_key_with_numeric_value(self):
+ """A sensitive key with numeric value is still removed."""
+ data = {"auth_token": 12345, "name": "ok"}
+ result = DataSanitizer.sanitize(data)
+ assert "auth_token" not in result
+
+
+class TestSanitizeAllKeySensitive:
+ """When every key in a dict is sensitive."""
+
+ def test_all_keys_removed_returns_empty_dict(self):
+ data = {
+ "api_key": "1",
+ "password": "2",
+ "secret": "3",
+ }
+ result = DataSanitizer.sanitize(data)
+ assert result == {}
+
+ def test_large_dict_all_sensitive(self):
+ """All 10 default sensitive keys in one dict."""
+ data = {
+ k: f"val_{i}"
+ for i, k in enumerate(DataSanitizer.DEFAULT_SENSITIVE_KEYS)
+ }
+ result = DataSanitizer.sanitize(data)
+ assert result == {}
+
+
+class TestSanitizeReturnTypeSame:
+ """Sanitize returns the same container type."""
+
+ def test_dict_returns_dict(self):
+ result = DataSanitizer.sanitize({"a": 1})
+ assert isinstance(result, dict)
+
+ def test_list_returns_list(self):
+ result = DataSanitizer.sanitize([1, 2])
+ assert isinstance(result, list)
+
+
+# ---------------------------------------------------------------------------
+# redact() -- additional coverage
+# ---------------------------------------------------------------------------
+
+
+class TestRedactTupleAndUnusualTypes:
+ """Redact behavior with non-list/dict types."""
+
+ def test_tuple_returned_as_is(self):
+ data = (1, 2, 3)
+ assert DataSanitizer.redact(data) == (1, 2, 3)
+
+ def test_set_returned_as_is(self):
+ data = {1, 2, 3}
+ assert DataSanitizer.redact(data) == {1, 2, 3}
+
+ def test_bytes_returned_as_is(self):
+ assert DataSanitizer.redact(b"data") == b"data"
+
+ def test_zero_returned_as_is(self):
+ assert DataSanitizer.redact(0) == 0
+
+ def test_empty_string_returned_as_is(self):
+ assert DataSanitizer.redact("") == ""
+
+
+class TestRedactNestedListsOfLists:
+ """Redact handles nested list structures."""
+
+ def test_list_of_lists_with_dicts(self):
+ data = [[{"api_key": "k1", "val": 1}], [{"password": "p1", "val": 2}]]
+ result = DataSanitizer.redact(data)
+ assert result == [
+ [{"api_key": "[REDACTED]", "val": 1}],
+ [{"password": "[REDACTED]", "val": 2}],
+ ]
+
+
+class TestRedactCombinedCustomKeysAndText:
+ """Redact with both custom keys and custom redaction text."""
+
+ def test_custom_keys_and_custom_text(self):
+ data = {"my_secret": "val", "api_key": "keep", "name": "ok"}
+ result = DataSanitizer.redact(
+ data, sensitive_keys={"my_secret"}, redaction_text="<REMOVED>"
+ )
+ assert result["my_secret"] == "<REMOVED>"
+ assert result["api_key"] == "keep"
+ assert result["name"] == "ok"
+
+ def test_custom_keys_and_empty_text(self):
+ data = {"password": "keep_default", "custom": "hide"}
+ result = DataSanitizer.redact(
+ data, sensitive_keys={"custom"}, redaction_text=""
+ )
+ assert result["custom"] == ""
+ assert result["password"] == "keep_default"
+
+
+class TestRedactAllKeysSensitive:
+ """When every key in a dict is sensitive, all values are redacted."""
+
+ def test_all_keys_redacted(self):
+ data = {"api_key": "1", "password": "2", "secret": "3"}
+ result = DataSanitizer.redact(data)
+ assert all(v == "[REDACTED]" for v in result.values())
+ assert len(result) == 3
+
+ def test_large_dict_all_redacted(self):
+ data = {
+ k: f"val_{i}"
+ for i, k in enumerate(DataSanitizer.DEFAULT_SENSITIVE_KEYS)
+ }
+ result = DataSanitizer.redact(data)
+ assert all(v == "[REDACTED]" for v in result.values())
+ assert len(result) == len(DataSanitizer.DEFAULT_SENSITIVE_KEYS)
+
+
+class TestRedactDeeplyNestedCustom:
+ """Redact with custom keys in deeply nested structures."""
+
+ def test_deeply_nested_custom_key(self):
+ data = {"a": {"b": {"c": {"my_field": "secret", "val": 1}}}}
+ result = DataSanitizer.redact(data, sensitive_keys={"my_field"})
+ assert result["a"]["b"]["c"]["my_field"] == "[REDACTED]"
+ assert result["a"]["b"]["c"]["val"] == 1
+
+ def test_list_nested_in_dict_custom_key(self):
+ data = {"items": [{"token": "t1", "id": 1}, {"token": "t2", "id": 2}]}
+ result = DataSanitizer.redact(data, sensitive_keys={"token"})
+ assert result["items"][0]["token"] == "[REDACTED]"
+ assert result["items"][0]["id"] == 1
+ assert result["items"][1]["token"] == "[REDACTED]"
+
+
+class TestRedactDoesNotMutateNested:
+ """Redact does not mutate nested original data."""
+
+ def test_nested_dict_original_unchanged(self):
+ inner = {"password": "secret", "val": 1}
+ outer = {"config": inner}
+ DataSanitizer.redact(outer)
+ assert inner["password"] == "secret"
+
+ def test_list_original_unchanged(self):
+ item = {"api_key": "k", "id": 1}
+ data = [item]
+ DataSanitizer.redact(data)
+ assert item["api_key"] == "k"
+
+
+# ---------------------------------------------------------------------------
+# Convenience functions -- additional coverage
+# ---------------------------------------------------------------------------
+
+
+class TestConvenienceFunctionsExtended:
+ """Additional convenience function tests."""
+
+ def test_sanitize_data_with_none_keys(self):
+ """sanitize_data with explicit None uses defaults."""
+ data = {"api_key": "k", "name": "n"}
+ result = sanitize_data(data, sensitive_keys=None)
+ assert "api_key" not in result
+ assert result == {"name": "n"}
+
+ def test_redact_data_with_none_keys(self):
+ """redact_data with explicit None uses defaults."""
+ data = {"password": "p", "name": "n"}
+ result = redact_data(data, sensitive_keys=None)
+ assert result["password"] == "[REDACTED]"
+ assert result["name"] == "n"
+
+ def test_redact_data_custom_keys_and_text(self):
+ """redact_data with both custom keys and custom text."""
+ data = {"my_field": "val", "api_key": "keep"}
+ result = redact_data(
+ data, sensitive_keys={"my_field"}, redaction_text="XXX"
+ )
+ assert result["my_field"] == "XXX"
+ assert result["api_key"] == "keep"
+
+ def test_sanitize_data_list_input(self):
+ """sanitize_data works with list input."""
+ data = [{"api_key": "k", "id": 1}]
+ result = sanitize_data(data)
+ assert result == [{"id": 1}]
+
+ def test_redact_data_list_input(self):
+ """redact_data works with list input."""
+ data = [{"password": "p", "id": 1}]
+ result = redact_data(data)
+ assert result == [{"password": "[REDACTED]", "id": 1}]
+
+ def test_sanitize_data_primitive(self):
+ """sanitize_data passes through primitives."""
+ assert sanitize_data("hello") == "hello"
+ assert sanitize_data(42) == 42
+ assert sanitize_data(None) is None
+
+ def test_redact_data_primitive(self):
+ """redact_data passes through primitives."""
+ assert redact_data("hello") == "hello"
+ assert redact_data(42) == 42
+ assert redact_data(None) is None
+
+
+# ---------------------------------------------------------------------------
+# filter_research_metadata() -- additional coverage
+# ---------------------------------------------------------------------------
+
+
+class TestFilterResearchMetadataExtended:
+ """Additional edge cases for filter_research_metadata."""
+
+ def test_is_news_search_zero_coerced_to_false(self):
+ """0 is falsy, coerced to False."""
+ result = filter_research_metadata({"is_news_search": 0})
+ assert result == {"is_news_search": False}
+ assert type(result["is_news_search"]) is bool
+
+ def test_is_news_search_empty_string_coerced_to_false(self):
+ """Empty string is falsy, coerced to False."""
+ result = filter_research_metadata({"is_news_search": ""})
+ assert result == {"is_news_search": False}
+ assert type(result["is_news_search"]) is bool
+
+ def test_is_news_search_empty_list_coerced_to_false(self):
+ """Empty list is falsy, coerced to False."""
+ result = filter_research_metadata({"is_news_search": []})
+ assert result == {"is_news_search": False}
+
+ def test_is_news_search_nonempty_list_coerced_to_true(self):
+ """Non-empty list is truthy, coerced to True."""
+ result = filter_research_metadata({"is_news_search": [1]})
+ assert result == {"is_news_search": True}
+
+ def test_is_news_search_none_coerced_to_false(self):
+ """None is falsy, coerced to False."""
+ result = filter_research_metadata({"is_news_search": None})
+ assert result == {"is_news_search": False}
+
+ def test_empty_string_input(self):
+ """Empty string input (falsy) returns default."""
+ result = filter_research_metadata("")
+ assert result == {"is_news_search": False}
+
+ def test_json_string_with_extra_fields_stripped(self):
+ """JSON string with extra fields returns only is_news_search."""
+ meta_json = json.dumps(
+ {
+ "is_news_search": True,
+ "settings_snapshot": {"api_key": "secret"},
+ "phase": "complete",
+ }
+ )
+ result = filter_research_metadata(meta_json)
+ assert result == {"is_news_search": True}
+ assert "settings_snapshot" not in result
+ assert "phase" not in result
+
+ def test_dict_with_only_settings_snapshot(self):
+ """Dict with only settings_snapshot but no is_news_search."""
+ result = filter_research_metadata({"settings_snapshot": {"key": "val"}})
+ assert result == {"is_news_search": False}
+
+ def test_boolean_input(self):
+ """Boolean input (not a dict/str) returns default."""
+ result = filter_research_metadata(True)
+ assert result == {"is_news_search": False}
+
+ def test_float_input(self):
+ """Float input returns default."""
+ result = filter_research_metadata(3.14)
+ assert result == {"is_news_search": False}
+
+ def test_list_input(self):
+ """List input (non-dict) returns default."""
+ result = filter_research_metadata([{"is_news_search": True}])
+ assert result == {"is_news_search": False}
+
+ def test_json_number_string(self):
+ """JSON string that parses to a number returns default."""
+ result = filter_research_metadata("42")
+ assert result == {"is_news_search": False}
+
+ def test_json_boolean_string(self):
+ """JSON string that parses to a boolean returns default."""
+ result = filter_research_metadata("true")
+ assert result == {"is_news_search": False}
+
+ def test_json_null_string(self):
+ """JSON string 'null' parses to None, then `meta or {}` gives {}."""
+ result = filter_research_metadata("null")
+ assert result == {"is_news_search": False}
+
+
+# ---------------------------------------------------------------------------
+# strip_settings_snapshot() -- additional coverage
+# ---------------------------------------------------------------------------
+
+
+class TestStripSettingsSnapshotExtended:
+ """Additional edge cases for strip_settings_snapshot."""
+
+ def test_empty_string_input(self):
+ """Empty string (falsy) returns empty dict."""
+ result = strip_settings_snapshot("")
+ assert result == {}
+
+ def test_preserves_all_non_snapshot_keys(self):
+ """All keys except settings_snapshot are preserved."""
+ meta = {
+ "phase": "complete",
+ "error_type": None,
+ "processed_query": "test query",
+ "mode": "quick",
+ "duration": 12.5,
+ "is_news_search": True,
+ "settings_snapshot": {"api_key": "secret"},
+ }
+ result = strip_settings_snapshot(meta)
+ assert "settings_snapshot" not in result
+ assert result["phase"] == "complete"
+ assert result["error_type"] is None
+ assert result["processed_query"] == "test query"
+ assert result["mode"] == "quick"
+ assert result["duration"] == 12.5
+ assert result["is_news_search"] is True
+
+ def test_preserves_nested_complex_values(self):
+ """Nested complex values (lists, dicts) are preserved."""
+ meta = {
+ "results": [{"title": "a"}, {"title": "b"}],
+ "config": {"depth": 3},
+ "settings_snapshot": {},
+ }
+ result = strip_settings_snapshot(meta)
+ assert result["results"] == [{"title": "a"}, {"title": "b"}]
+ assert result["config"] == {"depth": 3}
+
+ def test_boolean_input(self):
+ """Boolean input returns empty dict."""
+ assert strip_settings_snapshot(True) == {}
+ assert strip_settings_snapshot(False) == {}
+
+ def test_float_input(self):
+ """Float input returns empty dict."""
+ assert strip_settings_snapshot(3.14) == {}
+
+ def test_list_input(self):
+ """List input returns empty dict."""
+ assert strip_settings_snapshot([1, 2, 3]) == {}
+
+ def test_json_number_string(self):
+ """JSON number string returns empty dict (not a dict)."""
+ assert strip_settings_snapshot("42") == {}
+
+ def test_json_null_string(self):
+ """JSON 'null' string returns empty dict."""
+ assert strip_settings_snapshot("null") == {}
+
+ def test_json_boolean_string(self):
+ """JSON 'true' string returns empty dict."""
+ assert strip_settings_snapshot("true") == {}
+
+ def test_json_array_string(self):
+ """JSON array string returns empty dict."""
+ assert strip_settings_snapshot("[1, 2]") == {}
+
+ def test_does_not_strip_similar_key_names(self):
+ """Keys like 'settings_snapshot_v2' are NOT stripped."""
+ meta = {"settings_snapshot_v2": "data", "settings_snapshot": "secret"}
+ result = strip_settings_snapshot(meta)
+ assert "settings_snapshot_v2" in result
+ assert "settings_snapshot" not in result
+
+ def test_settings_snapshot_with_large_value(self):
+ """Large settings_snapshot value is stripped cleanly."""
+ snapshot = {f"key_{i}": f"value_{i}" for i in range(100)}
+ meta = {"phase": "done", "settings_snapshot": snapshot}
+ result = strip_settings_snapshot(meta)
+ assert result == {"phase": "done"}
+
+ def test_json_string_preserves_value_types(self):
+ """JSON string input preserves value types after parsing."""
+ meta_json = json.dumps(
+ {
+ "phase": "done",
+ "count": 42,
+ "active": True,
+ "settings_snapshot": {},
+ }
+ )
+ result = strip_settings_snapshot(meta_json)
+ assert result == {"phase": "done", "count": 42, "active": True}
+
+ def test_original_dict_not_mutated(self):
+ """strip_settings_snapshot does not mutate the original dict."""
+ meta = {"phase": "done", "settings_snapshot": {"api_key": "secret"}}
+ strip_settings_snapshot(meta)
+ assert "settings_snapshot" in meta
+
+
+# ---------------------------------------------------------------------------
+# DEFAULT_SENSITIVE_KEYS -- exhaustive membership
+# ---------------------------------------------------------------------------
+
+
+class TestDefaultSensitiveKeysComplete:
+ """Verify exact membership of DEFAULT_SENSITIVE_KEYS."""
+
+ def test_exact_set(self):
+ expected = {
+ "api_key",
+ "apikey",
+ "password",
+ "secret",
+ "access_token",
+ "refresh_token",
+ "private_key",
+ "auth_token",
+ "session_token",
+ "csrf_token",
+ }
+ assert DataSanitizer.DEFAULT_SENSITIVE_KEYS == expected
+
+ def test_count(self):
+ assert len(DataSanitizer.DEFAULT_SENSITIVE_KEYS) == 10
+
+ def test_all_lowercase(self):
+ """All default keys are stored in lowercase."""
+ for key in DataSanitizer.DEFAULT_SENSITIVE_KEYS:
+ assert key == key.lower(), f"Key {key!r} is not lowercase"
+
+
+# ---------------------------------------------------------------------------
+# Cross-method consistency
+# ---------------------------------------------------------------------------
+
+
+class TestSanitizeRedactConsistency:
+ """Sanitize and redact should agree on which keys are sensitive."""
+
+ @pytest.mark.parametrize(
+ "key", sorted(DataSanitizer.DEFAULT_SENSITIVE_KEYS)
+ )
+ def test_sanitize_removes_what_redact_replaces(self, key):
+ """For each default key, sanitize removes it and redact replaces it."""
+ data = {key: "value", "safe": "keep"}
+ sanitized = DataSanitizer.sanitize(data)
+ redacted = DataSanitizer.redact(data)
+ assert key not in sanitized
+ assert redacted[key] == "[REDACTED]"
+ assert sanitized["safe"] == "keep"
+ assert redacted["safe"] == "keep"
+
+ def test_sanitize_and_redact_same_custom_keys(self):
+ """Both methods respect the same custom keys set."""
+ custom = {"my_token", "my_secret"}
+ data = {"my_token": "t", "my_secret": "s", "name": "n", "api_key": "k"}
+ sanitized = DataSanitizer.sanitize(data, sensitive_keys=custom)
+ redacted = DataSanitizer.redact(data, sensitive_keys=custom)
+
+ assert "my_token" not in sanitized
+ assert "my_secret" not in sanitized
+ assert "api_key" in sanitized # not in custom set
+
+ assert redacted["my_token"] == "[REDACTED]"
+ assert redacted["my_secret"] == "[REDACTED]"
+ assert redacted["api_key"] == "k" # not in custom set
+
+
+# ---------------------------------------------------------------------------
+# Sanitize/redact with dict containing duplicate-ish case keys
+# ---------------------------------------------------------------------------
+
+
+class TestCaseVariantKeys:
+ """Dict keys that differ only in case."""
+
+ def test_sanitize_removes_all_case_variants(self):
+ """All case variants of a sensitive key are removed."""
+ data = {"Api_Key": "v1", "API_KEY": "v2", "api_key": "v3", "name": "ok"}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"name": "ok"}
+
+ def test_redact_replaces_all_case_variants(self):
+ """All case variants of a sensitive key are redacted."""
+ data = {
+ "Password": "p1",
+ "PASSWORD": "p2",
+ "password": "p3",
+ "name": "ok",
+ }
+ result = DataSanitizer.redact(data)
+ assert result["Password"] == "[REDACTED]"
+ assert result["PASSWORD"] == "[REDACTED]"
+ assert result["password"] == "[REDACTED]"
+ assert result["name"] == "ok"
diff --git a/tests/storage/test_base_storage_coverage.py b/tests/storage/test_base_storage_coverage.py
new file mode 100644
index 0000000000..ec8a796533
--- /dev/null
+++ b/tests/storage/test_base_storage_coverage.py
@@ -0,0 +1,473 @@
+"""Comprehensive tests for the ReportStorage abstract base class in storage/base.py.
+
+Tests cover:
+- Abstract class cannot be instantiated directly
+- Subclass must implement all abstract methods
+- Partial implementations raise TypeError
+- A complete concrete implementation works correctly
+- Method signatures and return types
+- Edge cases: empty strings, None metadata, special characters in IDs
+"""
+
+import pytest
+from abc import ABC
+from typing import Dict, Any, Optional
+
+from local_deep_research.storage.base import ReportStorage
+
+
+# ---------------------------------------------------------------------------
+# 1. ABC contract tests
+# ---------------------------------------------------------------------------
+
+
+class TestReportStorageIsAbstract:
+ """Verify that ReportStorage behaves as a proper abstract base class."""
+
+ def test_cannot_instantiate_directly(self):
+ """ReportStorage cannot be instantiated because it has abstract methods."""
+ with pytest.raises(TypeError):
+ ReportStorage()
+
+ def test_is_subclass_of_abc(self):
+ """ReportStorage inherits from ABC."""
+ assert issubclass(ReportStorage, ABC)
+
+ def test_has_five_abstract_methods(self):
+ """All five public methods are declared abstract."""
+ expected = {
+ "save_report",
+ "get_report",
+ "get_report_with_metadata",
+ "delete_report",
+ "report_exists",
+ }
+ assert ReportStorage.__abstractmethods__ == expected
+
+
+# ---------------------------------------------------------------------------
+# 2. Partial implementation tests
+# ---------------------------------------------------------------------------
+
+
+class TestPartialImplementationRaisesTypeError:
+ """A subclass that skips any single abstract method cannot be instantiated."""
+
+ def test_missing_save_report(self):
+ class Incomplete(ReportStorage):
+ def get_report(self, research_id, username=None):
+ return None
+
+ def get_report_with_metadata(self, research_id, username=None):
+ return None
+
+ def delete_report(self, research_id, username=None):
+ return False
+
+ def report_exists(self, research_id, username=None):
+ return False
+
+ with pytest.raises(TypeError):
+ Incomplete()
+
+ def test_missing_get_report(self):
+ class Incomplete(ReportStorage):
+ def save_report(
+ self, research_id, content, metadata=None, username=None
+ ):
+ return True
+
+ def get_report_with_metadata(self, research_id, username=None):
+ return None
+
+ def delete_report(self, research_id, username=None):
+ return False
+
+ def report_exists(self, research_id, username=None):
+ return False
+
+ with pytest.raises(TypeError):
+ Incomplete()
+
+ def test_missing_get_report_with_metadata(self):
+ class Incomplete(ReportStorage):
+ def save_report(
+ self, research_id, content, metadata=None, username=None
+ ):
+ return True
+
+ def get_report(self, research_id, username=None):
+ return None
+
+ def delete_report(self, research_id, username=None):
+ return False
+
+ def report_exists(self, research_id, username=None):
+ return False
+
+ with pytest.raises(TypeError):
+ Incomplete()
+
+ def test_missing_delete_report(self):
+ class Incomplete(ReportStorage):
+ def save_report(
+ self, research_id, content, metadata=None, username=None
+ ):
+ return True
+
+ def get_report(self, research_id, username=None):
+ return None
+
+ def get_report_with_metadata(self, research_id, username=None):
+ return None
+
+ def report_exists(self, research_id, username=None):
+ return False
+
+ with pytest.raises(TypeError):
+ Incomplete()
+
+ def test_missing_report_exists(self):
+ class Incomplete(ReportStorage):
+ def save_report(
+ self, research_id, content, metadata=None, username=None
+ ):
+ return True
+
+ def get_report(self, research_id, username=None):
+ return None
+
+ def get_report_with_metadata(self, research_id, username=None):
+ return None
+
+ def delete_report(self, research_id, username=None):
+ return False
+
+ with pytest.raises(TypeError):
+ Incomplete()
+
+
+# ---------------------------------------------------------------------------
+# 3. In-memory concrete implementation used for functional tests
+# ---------------------------------------------------------------------------
+
+
+class InMemoryReportStorage(ReportStorage):
+ """Minimal concrete implementation for testing the abstract interface."""
+
+ def __init__(self):
+ self._reports: Dict[str, Dict[str, Any]] = {}
+
+ def _key(self, research_id: str, username: Optional[str] = None) -> str:
+ return f"{username or ''}::{research_id}"
+
+ def save_report(
+ self,
+ research_id: str,
+ content: str,
+ metadata: Optional[Dict[str, Any]] = None,
+ username: Optional[str] = None,
+ ) -> bool:
+ self._reports[self._key(research_id, username)] = {
+ "content": content,
+ "metadata": metadata or {},
+ }
+ return True
+
+ def get_report(
+ self, research_id: str, username: Optional[str] = None
+ ) -> Optional[str]:
+ entry = self._reports.get(self._key(research_id, username))
+ return entry["content"] if entry else None
+
+ def get_report_with_metadata(
+ self, research_id: str, username: Optional[str] = None
+ ) -> Optional[Dict[str, Any]]:
+ entry = self._reports.get(self._key(research_id, username))
+ if entry is None:
+ return None
+ return {"content": entry["content"], "metadata": entry["metadata"]}
+
+ def delete_report(
+ self, research_id: str, username: Optional[str] = None
+ ) -> bool:
+ key = self._key(research_id, username)
+ if key in self._reports:
+ del self._reports[key]
+ return True
+ return False
+
+ def report_exists(
+ self, research_id: str, username: Optional[str] = None
+ ) -> bool:
+ return self._key(research_id, username) in self._reports
+
+
+def storage():
+ return InMemoryReportStorage()
+
+
+# ---------------------------------------------------------------------------
+# 4. Concrete implementation isinstance / subclass checks
+# ---------------------------------------------------------------------------
+
+
+class TestConcreteIsInstance:
+ def test_isinstance_of_report_storage(self, storage):
+ assert isinstance(storage, ReportStorage)
+
+ def test_issubclass_of_report_storage(self):
+ assert issubclass(InMemoryReportStorage, ReportStorage)
+
+
+# ---------------------------------------------------------------------------
+# 5. Functional tests via the in-memory implementation
+# ---------------------------------------------------------------------------
+
+
+class TestSaveReport:
+ def test_save_returns_true(self, storage):
+ assert storage.save_report("r1", "content") is True
+
+ def test_save_with_metadata(self, storage):
+ meta = {"key": "val"}
+ assert storage.save_report("r1", "content", metadata=meta) is True
+
+ def test_save_with_username(self, storage):
+ assert storage.save_report("r1", "c", username="alice") is True
+
+ def test_save_with_all_params(self, storage):
+ assert storage.save_report("r1", "c", {"k": "v"}, "alice") is True
+
+ def test_save_empty_content(self, storage):
+ """Empty string is a valid report content."""
+ assert storage.save_report("r1", "") is True
+ assert storage.get_report("r1") == ""
+
+ def test_save_overwrites_existing(self, storage):
+ storage.save_report("r1", "v1")
+ storage.save_report("r1", "v2")
+ assert storage.get_report("r1") == "v2"
+
+
+class TestGetReport:
+ def test_get_existing(self, storage):
+ storage.save_report("r1", "hello")
+ assert storage.get_report("r1") == "hello"
+
+ def test_get_nonexistent_returns_none(self, storage):
+ assert storage.get_report("no-such-id") is None
+
+ def test_get_with_username(self, storage):
+ storage.save_report("r1", "alice-report", username="alice")
+ assert storage.get_report("r1", username="alice") == "alice-report"
+ # Without username should not find it
+ assert storage.get_report("r1") is None
+
+ def test_get_preserves_content_exactly(self, storage):
+ content = (
+ "# Title\n\n- bullet\n- bullet 2\n\n```python\nprint('hi')\n```"
+ )
+ storage.save_report("r1", content)
+ assert storage.get_report("r1") == content
+
+
+class TestGetReportWithMetadata:
+ def test_returns_dict_with_content_and_metadata(self, storage):
+ meta = {"source": "web"}
+ storage.save_report("r1", "text", metadata=meta)
+ result = storage.get_report_with_metadata("r1")
+ assert result is not None
+ assert result["content"] == "text"
+ assert result["metadata"] == {"source": "web"}
+
+ def test_returns_none_for_nonexistent(self, storage):
+ assert storage.get_report_with_metadata("nope") is None
+
+ def test_empty_metadata_when_none_provided(self, storage):
+ storage.save_report("r1", "text")
+ result = storage.get_report_with_metadata("r1")
+ assert result["metadata"] == {}
+
+ def test_with_username(self, storage):
+ storage.save_report("r1", "u-text", {"k": 1}, username="bob")
+ result = storage.get_report_with_metadata("r1", username="bob")
+ assert result is not None
+ assert result["content"] == "u-text"
+
+
+class TestDeleteReport:
+ def test_delete_existing_returns_true(self, storage):
+ storage.save_report("r1", "data")
+ assert storage.delete_report("r1") is True
+
+ def test_delete_removes_report(self, storage):
+ storage.save_report("r1", "data")
+ storage.delete_report("r1")
+ assert storage.get_report("r1") is None
+
+ def test_delete_nonexistent_returns_false(self, storage):
+ assert storage.delete_report("no-such") is False
+
+ def test_delete_with_username(self, storage):
+ storage.save_report("r1", "data", username="alice")
+ assert storage.delete_report("r1", username="alice") is True
+ assert storage.report_exists("r1", username="alice") is False
+
+ def test_delete_one_user_does_not_affect_another(self, storage):
+ storage.save_report("r1", "alice-data", username="alice")
+ storage.save_report("r1", "bob-data", username="bob")
+ storage.delete_report("r1", username="alice")
+ assert storage.report_exists("r1", username="bob") is True
+ assert storage.get_report("r1", username="bob") == "bob-data"
+
+
+class TestReportExists:
+ def test_exists_after_save(self, storage):
+ storage.save_report("r1", "data")
+ assert storage.report_exists("r1") is True
+
+ def test_not_exists_before_save(self, storage):
+ assert storage.report_exists("r1") is False
+
+ def test_not_exists_after_delete(self, storage):
+ storage.save_report("r1", "data")
+ storage.delete_report("r1")
+ assert storage.report_exists("r1") is False
+
+ def test_exists_with_username(self, storage):
+ storage.save_report("r1", "data", username="alice")
+ assert storage.report_exists("r1", username="alice") is True
+ assert storage.report_exists("r1") is False
+
+
+# ---------------------------------------------------------------------------
+# 6. Edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestEdgeCases:
+ def test_special_characters_in_research_id(self, storage):
+ rid = "report/2024-01-01/some:id#1"
+ storage.save_report(rid, "content")
+ assert storage.get_report(rid) == "content"
+ assert storage.report_exists(rid) is True
+
+ def test_unicode_content(self, storage):
+ content = "Zusammenfassung der Forschung: Ergebnis"
+ storage.save_report("r1", content)
+ assert storage.get_report("r1") == content
+
+ def test_very_long_content(self, storage):
+ content = "x" * 100_000
+ storage.save_report("r1", content)
+ assert storage.get_report("r1") == content
+ assert len(storage.get_report("r1")) == 100_000
+
+ def test_metadata_with_nested_dicts(self, storage):
+ meta = {"a": {"b": {"c": [1, 2, 3]}}}
+ storage.save_report("r1", "text", metadata=meta)
+ result = storage.get_report_with_metadata("r1")
+ assert result["metadata"]["a"]["b"]["c"] == [1, 2, 3]
+
+ def test_multiple_reports_independent(self, storage):
+ storage.save_report("r1", "content1")
+ storage.save_report("r2", "content2")
+ storage.save_report("r3", "content3")
+ assert storage.get_report("r1") == "content1"
+ assert storage.get_report("r2") == "content2"
+ assert storage.get_report("r3") == "content3"
+ storage.delete_report("r2")
+ assert storage.report_exists("r1") is True
+ assert storage.report_exists("r2") is False
+ assert storage.report_exists("r3") is True
+
+ def test_same_id_different_users_are_separate(self, storage):
+ storage.save_report("r1", "alice", username="alice")
+ storage.save_report("r1", "bob", username="bob")
+ assert storage.get_report("r1", username="alice") == "alice"
+ assert storage.get_report("r1", username="bob") == "bob"
+
+ def test_metadata_none_explicit(self, storage):
+ """Passing metadata=None explicitly should not cause errors."""
+ assert storage.save_report("r1", "text", metadata=None) is True
+ result = storage.get_report_with_metadata("r1")
+ assert result["metadata"] == {}
+
+ def test_username_none_explicit(self, storage):
+ """Passing username=None explicitly should behave like omitting it."""
+ storage.save_report("r1", "text", username=None)
+ assert storage.get_report("r1", username=None) == "text"
+ assert storage.report_exists("r1", username=None) is True
+
+
+# ---------------------------------------------------------------------------
+# 7. Method signature tests
+# ---------------------------------------------------------------------------
+
+
+class TestMethodSignatures:
+ """Verify that the abstract methods accept the documented parameters."""
+
+ def test_save_report_accepts_keyword_args(self, storage):
+ result = storage.save_report(
+ research_id="r1",
+ content="text",
+ metadata={"k": "v"},
+ username="alice",
+ )
+ assert result is True
+
+ def test_get_report_accepts_keyword_args(self, storage):
+ storage.save_report("r1", "text")
+ result = storage.get_report(research_id="r1", username=None)
+ assert result == "text"
+
+ def test_get_report_with_metadata_accepts_keyword_args(self, storage):
+ storage.save_report("r1", "text")
+ result = storage.get_report_with_metadata(
+ research_id="r1", username=None
+ )
+ assert result is not None
+
+ def test_delete_report_accepts_keyword_args(self, storage):
+ storage.save_report("r1", "text")
+ result = storage.delete_report(research_id="r1", username=None)
+ assert result is True
+
+ def test_report_exists_accepts_keyword_args(self, storage):
+ storage.save_report("r1", "text")
+ result = storage.report_exists(research_id="r1", username=None)
+ assert result is True
+
+
+# ---------------------------------------------------------------------------
+# 8. Return type tests
+# ---------------------------------------------------------------------------
+
+
+class TestReturnTypes:
+ def test_save_report_returns_bool(self, storage):
+ result = storage.save_report("r1", "text")
+ assert isinstance(result, bool)
+
+ def test_get_report_returns_str_or_none(self, storage):
+ assert storage.get_report("nope") is None
+ storage.save_report("r1", "text")
+ result = storage.get_report("r1")
+ assert isinstance(result, str)
+
+ def test_get_report_with_metadata_returns_dict_or_none(self, storage):
+ assert storage.get_report_with_metadata("nope") is None
+ storage.save_report("r1", "text", metadata={"a": 1})
+ result = storage.get_report_with_metadata("r1")
+ assert isinstance(result, dict)
+ assert "content" in result
+ assert "metadata" in result
+
+ def test_delete_report_returns_bool(self, storage):
+ assert isinstance(storage.delete_report("nope"), bool)
+
+ def test_report_exists_returns_bool(self, storage):
+ assert isinstance(storage.report_exists("nope"), bool)
diff --git a/tests/test_report_generator_coverage.py b/tests/test_report_generator_coverage.py
new file mode 100644
index 0000000000..5a89dac6ea
--- /dev/null
+++ b/tests/test_report_generator_coverage.py
@@ -0,0 +1,888 @@
+"""Comprehensive tests for report_generator.py targeting uncovered paths.
+
+Focuses on areas with gaps in existing test suites:
+- close() resource cleanup with _owns_llm flag
+- _format_final_report TOC assembly, section ordering, missing sections, metadata
+- _truncate_at_sentence_boundary additional edge cases
+- _build_previous_context boundary conditions
+- _research_and_generate_sections iteration restore on exception, pipe in section name
+- _generate_error_report format
+- generate_report progress callback sequencing
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ DEFAULT_MAX_CONTEXT_CHARS,
+ DEFAULT_MAX_CONTEXT_SECTIONS,
+)
+
+MODULE = "local_deep_research.report_generator"
+
+
+# ---------------------------------------------------------------------------
+# Shared fixtures
+# ---------------------------------------------------------------------------
+
+
+def mock_search_system():
+ """Minimal mock search system with strategy."""
+ system = MagicMock()
+ system.strategy = MagicMock()
+ system.strategy.settings_snapshot = {"search.iterations": 3}
+ system.strategy.max_iterations = 3
+ system.all_links_of_system = []
+ system.analyze_topic.return_value = {"current_knowledge": "mock content"}
+ return system
+
+
+def mock_model():
+ """Minimal mock LLM."""
+ model = MagicMock()
+ model.invoke.return_value = MagicMock(content="STRUCTURE\nEND_STRUCTURE")
+ return model
+
+
+def generator(mock_search_system, mock_model):
+ """IntegratedReportGenerator with all deps mocked via __new__."""
+ gen = IntegratedReportGenerator.__new__(IntegratedReportGenerator)
+ gen.search_system = mock_search_system
+ gen.model = mock_model
+ gen.searches_per_section = 2
+ gen.max_context_sections = DEFAULT_MAX_CONTEXT_SECTIONS
+ gen.max_context_chars = DEFAULT_MAX_CONTEXT_CHARS
+ gen._owns_llm = False
+ return gen
+
+
+# ---------------------------------------------------------------------------
+# close() -- resource cleanup
+# ---------------------------------------------------------------------------
+
+
+class TestClose:
+ """Tests for close() method and _owns_llm lifecycle."""
+
+ def test_close_when_owns_llm_calls_close_llm(self, generator, mock_model):
+ """When _owns_llm is True, close() delegates to close_llm."""
+ generator._owns_llm = True
+ generator.model = mock_model
+
+ with patch(f"{MODULE}.close_llm") as mock_close:
+ generator.close()
+ mock_close.assert_called_once_with(mock_model)
+
+ def test_close_when_not_owns_llm_does_nothing(self, generator, mock_model):
+ """When _owns_llm is False, close() must not call close_llm."""
+ generator._owns_llm = False
+ generator.model = mock_model
+
+ with patch(f"{MODULE}.close_llm") as mock_close:
+ generator.close()
+ mock_close.assert_not_called()
+
+ def test_close_when_model_is_none(self, generator):
+ """When model is None (regardless of _owns_llm), close() is safe."""
+ generator._owns_llm = True
+ generator.model = None
+
+ with patch(f"{MODULE}.close_llm") as mock_close:
+ generator.close()
+ mock_close.assert_not_called()
+
+ def test_owns_llm_set_true_when_no_search_system_or_llm(self):
+ """Constructor sets _owns_llm=True when neither search_system nor llm given."""
+ with (
+ patch(f"{MODULE}.get_llm") as mock_get_llm,
+ patch(f"{MODULE}.AdvancedSearchSystem"),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ side_effect=lambda k,
+ default=None,
+ settings_snapshot=None: default,
+ ),
+ ):
+ mock_get_llm.return_value = MagicMock()
+ gen = IntegratedReportGenerator()
+ assert gen._owns_llm is True
+
+ def test_owns_llm_set_false_when_search_system_provided(
+ self, mock_search_system
+ ):
+ """Constructor sets _owns_llm=False when search_system is provided."""
+ mock_search_system.model = MagicMock()
+ with patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ side_effect=lambda k, default=None, settings_snapshot=None: default,
+ ):
+ gen = IntegratedReportGenerator(search_system=mock_search_system)
+ assert gen._owns_llm is False
+
+ def test_owns_llm_set_false_when_llm_provided(self):
+ """Constructor sets _owns_llm=False when llm is provided."""
+ with (
+ patch(f"{MODULE}.AdvancedSearchSystem"),
+ patch(
+ f"{MODULE}.get_setting_from_snapshot",
+ side_effect=lambda k,
+ default=None,
+ settings_snapshot=None: default,
+ ),
+ ):
+ gen = IntegratedReportGenerator(llm=MagicMock())
+ assert gen._owns_llm is False
+
+
+# ---------------------------------------------------------------------------
+# _format_final_report -- detailed TOC and assembly
+# ---------------------------------------------------------------------------
+
+
+class TestFormatFinalReportDetailed:
+ """Detailed tests for _format_final_report output structure."""
+
+ @pytest.fixture
+ def _patch_importlib(self):
+ """Patch importlib.import_module to return a mock with format_links_to_markdown."""
+ with patch(f"{MODULE}.importlib") as mock_imp:
+ mock_utils = MagicMock()
+ mock_utils.search_utilities.format_links_to_markdown.return_value = "- [Link1](http://a.com)"
+ mock_imp.import_module.return_value = mock_utils
+ yield mock_imp
+
+ def test_toc_numbering_matches_structure_order(
+ self, generator, _patch_importlib
+ ):
+ """TOC entries use 1-based numbering matching structure list order."""
+ structure = [
+ {"name": "Alpha", "subsections": [{"name": "A1", "purpose": "p1"}]},
+ {"name": "Beta", "subsections": [{"name": "B1", "purpose": "p2"}]},
+ {"name": "Gamma", "subsections": [{"name": "G1", "purpose": "p3"}]},
+ ]
+ sections = {
+ "Alpha": "Alpha content",
+ "Beta": "Beta content",
+ "Gamma": "Gamma content",
+ }
+
+ report = generator._format_final_report(sections, structure, "q")
+ content = report["content"]
+
+ assert "1. **Alpha**" in content
+ assert "2. **Beta**" in content
+ assert "3. **Gamma**" in content
+
+ def test_toc_subsection_numbering(self, generator, _patch_importlib):
+ """Subsections use i.j numbering format."""
+ structure = [
+ {
+ "name": "Section",
+ "subsections": [
+ {"name": "Sub1", "purpose": "first"},
+ {"name": "Sub2", "purpose": "second"},
+ {"name": "Sub3", "purpose": "third"},
+ ],
+ }
+ ]
+ sections = {"Section": "content"}
+
+ report = generator._format_final_report(sections, structure, "q")
+ content = report["content"]
+
+ assert "1.1 Sub1" in content
+ assert "1.2 Sub2" in content
+ assert "1.3 Sub3" in content
+
+ def test_toc_subsection_includes_purpose_in_italics(
+ self, generator, _patch_importlib
+ ):
+ """Subsection TOC entries include purpose in italics after pipe."""
+ structure = [
+ {
+ "name": "S",
+ "subsections": [
+ {"name": "Detail", "purpose": "explain details"}
+ ],
+ }
+ ]
+ sections = {"S": "content"}
+
+ report = generator._format_final_report(sections, structure, "q")
+ content = report["content"]
+
+ assert "_explain details_" in content
+
+ def test_section_content_appears_in_structure_order(
+ self, generator, _patch_importlib
+ ):
+ """Section content is emitted in the order defined by structure, not dict order."""
+ structure = [
+ {"name": "Zebra", "subsections": []},
+ {"name": "Apple", "subsections": []},
+ ]
+ sections = {
+ "Apple": "Apple body text",
+ "Zebra": "Zebra body text",
+ }
+
+ report = generator._format_final_report(sections, structure, "q")
+ content = report["content"]
+
+ zebra_pos = content.index("Zebra body text")
+ apple_pos = content.index("Apple body text")
+ assert zebra_pos < apple_pos, "Sections must appear in structure order"
+
+ def test_missing_section_content_omitted_gracefully(
+ self, generator, _patch_importlib
+ ):
+ """If a section name is in structure but not in sections dict, it is skipped."""
+ structure = [
+ {"name": "Present", "subsections": []},
+ {"name": "Missing", "subsections": []},
+ ]
+ sections = {"Present": "Present content"}
+
+ report = generator._format_final_report(sections, structure, "q")
+ content = report["content"]
+
+ assert "Present content" in content
+
+ def test_sources_section_appended_at_end(self, generator, _patch_importlib):
+ """Final report ends with ## Sources followed by formatted links."""
+ structure = [{"name": "A", "subsections": []}]
+ sections = {"A": "body"}
+
+ report = generator._format_final_report(sections, structure, "q")
+ content = report["content"]
+
+ assert content.rstrip().endswith("- [Link1](http://a.com)")
+
+ def test_research_summary_present(self, generator, _patch_importlib):
+ """Report contains '# Research Summary' section."""
+ structure = [{"name": "A", "subsections": []}]
+ sections = {"A": "body"}
+
+ report = generator._format_final_report(sections, structure, "q")
+ assert "# Research Summary" in report["content"]
+
+ def test_metadata_searches_per_section(self, generator, _patch_importlib):
+ """Metadata includes searches_per_section value."""
+ generator.searches_per_section = 7
+ structure = [{"name": "A", "subsections": []}]
+ sections = {"A": "body"}
+
+ report = generator._format_final_report(sections, structure, "q")
+ assert report["metadata"]["searches_per_section"] == 7
+
+ def test_metadata_initial_sources_counts_links(
+ self, generator, _patch_importlib
+ ):
+ """Metadata initial_sources equals len(all_links_of_system)."""
+ generator.search_system.all_links_of_system = [
+ {"link": "a"},
+ {"link": "b"},
+ {"link": "c"},
+ ]
+ structure = []
+ sections = {}
+
+ report = generator._format_final_report(sections, structure, "q")
+ assert report["metadata"]["initial_sources"] == 3
+
+ def test_metadata_generated_at_is_iso_format(
+ self, generator, _patch_importlib
+ ):
+ """generated_at is a valid ISO 8601 string."""
+ from datetime import datetime
+
+ structure = []
+ sections = {}
+
+ report = generator._format_final_report(sections, structure, "q")
+ # Should not raise
+ datetime.fromisoformat(report["metadata"]["generated_at"])
+
+ def test_empty_structure_produces_valid_report(
+ self, generator, _patch_importlib
+ ):
+ """Empty structure list still produces a report with TOC header and sources."""
+ report = generator._format_final_report({}, [], "q")
+ assert "Table of Contents" in report["content"]
+ assert "## Sources" in report["content"]
+ assert report["metadata"]["sections_researched"] == 0
+
+
+# ---------------------------------------------------------------------------
+# _truncate_at_sentence_boundary -- additional edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestTruncateEdgeCases:
+ """Additional edge cases for _truncate_at_sentence_boundary."""
+
+ def test_text_with_only_punctuation(self, generator):
+ """Text like '...' should not crash."""
+ result = generator._truncate_at_sentence_boundary("...", 2)
+ assert result == "..\n[...truncated]"
+
+ def test_sentence_ending_at_exactly_max_chars(self, generator):
+ """When sentence ends exactly at max_chars, use that boundary."""
+ text = "Hello. World."
+ # max_chars=6: truncated = "Hello." -> period at index 5 followed by end
+ result = generator._truncate_at_sentence_boundary(text, 6)
+ assert result.startswith("Hello.")
+ assert "[...truncated]" in result
+
+ def test_max_chars_one(self, generator):
+ """max_chars=1 with longer text."""
+ result = generator._truncate_at_sentence_boundary("ab", 1)
+ assert result == "a\n[...truncated]"
+
+ def test_exclamation_at_end_of_truncated_region(self, generator):
+ """Exclamation mark at very end of truncated region is a valid boundary."""
+ text = "Stop! More text follows here and keeps going."
+ # "Stop!" is 5 chars, max_chars=5: truncated = "Stop!"
+ result = generator._truncate_at_sentence_boundary(text, 5)
+ assert "Stop!" in result
+ assert "[...truncated]" in result
+
+ def test_mixed_sentence_endings(self, generator):
+ """Text with mixed .!? picks last valid one before limit."""
+ text = "First. Second! Third? Fourth sentence that is very very long."
+ # max_chars=25: truncated = "First. Second! Third? Fou"
+ result = generator._truncate_at_sentence_boundary(text, 25)
+ # Last valid boundary: "?" at index 20, followed by " ", 21 > 20 (80% of 25)
+ assert "Third?" in result
+ assert "[...truncated]" in result
+
+ def test_newline_after_period_is_valid_boundary(self, generator):
+ """Period followed by newline counts as sentence boundary."""
+ text = (
+ "Done.\nMore text that extends beyond the character limit by a lot."
+ )
+ result = generator._truncate_at_sentence_boundary(text, 10)
+ assert "Done." in result
+ assert "[...truncated]" in result
+
+ def test_period_in_middle_of_word_not_boundary(self, generator):
+ """Period not followed by space/newline/end is not a boundary."""
+ # "file.txt" has a period but it's followed by 't'
+ text = "file.txt is the name of the file and it is important to know."
+ result = generator._truncate_at_sentence_boundary(text, 12)
+ # "file.txt is " -> period at 4 followed by 't', not space
+ # No valid boundary -> hard truncation
+ assert result == text[:12] + "\n[...truncated]"
+
+ def test_unicode_text_truncation(self, generator):
+ """Unicode characters are handled correctly in truncation."""
+ text = "Bonjour le monde. C'est magnifique! Plus de texte ici."
+ result = generator._truncate_at_sentence_boundary(text, 40)
+ assert "[...truncated]" in result
+
+
+# ---------------------------------------------------------------------------
+# _build_previous_context -- boundary conditions
+# ---------------------------------------------------------------------------
+
+
+class TestBuildPreviousContextBoundary:
+ """Boundary conditions for _build_previous_context."""
+
+ def test_exactly_max_context_sections_findings(self, generator):
+ """When findings count equals max_context_sections, all are included."""
+ generator.max_context_sections = 3
+ findings = ["Finding A", "Finding B", "Finding C"]
+ result = generator._build_previous_context(findings)
+ assert "Finding A" in result
+ assert "Finding B" in result
+ assert "Finding C" in result
+
+ def test_one_more_than_max_drops_oldest(self, generator):
+ """When findings count is max+1, oldest is dropped."""
+ generator.max_context_sections = 2
+ findings = ["Old", "Mid", "New"]
+ result = generator._build_previous_context(findings)
+ assert "Old" not in result
+ assert "Mid" in result
+ assert "New" in result
+
+ def test_context_chars_exactly_at_limit_no_truncation(self, generator):
+ """When context length equals max_context_chars, no truncation marker."""
+ generator.max_context_chars = 20
+ # Single finding exactly 20 chars
+ finding = "x" * 20
+ result = generator._build_previous_context([finding])
+ assert "[...truncated]" not in result
+
+ def test_context_chars_one_over_limit_triggers_truncation(self, generator):
+ """When context length is max_context_chars + 1, truncation happens."""
+ generator.max_context_chars = 20
+ finding = "x" * 21
+ result = generator._build_previous_context([finding])
+ assert "[...truncated]" in result
+
+ def test_max_context_sections_zero_returns_all(self, generator):
+ """max_context_sections=0 -> [-0:] is full list in Python, so all are included."""
+ generator.max_context_sections = 0
+ result = generator._build_previous_context(["A", "B"])
+ # [-0:] == [0:] == full list, so both findings appear
+ assert "A" in result
+ assert "B" in result
+
+ def test_single_finding_with_large_char_limit(self, generator):
+ """Single small finding with huge char limit is not truncated."""
+ generator.max_context_chars = 100000
+ result = generator._build_previous_context(["Small finding."])
+ assert "Small finding." in result
+ assert "[...truncated]" not in result
+
+
+# ---------------------------------------------------------------------------
+# _research_and_generate_sections -- iteration override and restore
+# ---------------------------------------------------------------------------
+
+
+class TestIterationOverrideRestore:
+ """Tests that iteration settings are restored even on exception."""
+
+ def test_settings_restored_after_analyze_topic_exception(
+ self, generator, mock_search_system
+ ):
+ """If analyze_topic raises, iteration settings are still restored."""
+ mock_search_system.strategy.settings_snapshot = {"search.iterations": 5}
+ mock_search_system.strategy.max_iterations = 5
+ mock_search_system.analyze_topic.side_effect = RuntimeError("boom")
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ with pytest.raises(RuntimeError, match="boom"):
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ # Settings must be restored
+ assert (
+ mock_search_system.strategy.settings_snapshot["search.iterations"]
+ == 5
+ )
+ assert mock_search_system.strategy.max_iterations == 5
+
+ def test_settings_restored_when_key_not_originally_present(
+ self, generator, mock_search_system
+ ):
+ """If search.iterations was not in snapshot originally, it is removed after."""
+ mock_search_system.strategy.settings_snapshot = {} # no key
+ mock_search_system.strategy.max_iterations = 3
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "ok"
+ }
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ # Key should be removed since it was not originally present
+ assert (
+ "search.iterations"
+ not in mock_search_system.strategy.settings_snapshot
+ )
+
+ def test_iteration_set_to_one_during_analyze_topic(
+ self, generator, mock_search_system
+ ):
+ """During analyze_topic, search.iterations should be 1."""
+ captured_value = {}
+
+ def capture_settings(query):
+ captured_value["iterations"] = (
+ mock_search_system.strategy.settings_snapshot.get(
+ "search.iterations"
+ )
+ )
+ captured_value["max_iterations"] = (
+ mock_search_system.strategy.max_iterations
+ )
+ return {"current_knowledge": "content"}
+
+ mock_search_system.analyze_topic.side_effect = capture_settings
+ mock_search_system.strategy.settings_snapshot = {"search.iterations": 5}
+ mock_search_system.strategy.max_iterations = 5
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert captured_value["iterations"] == 1
+ assert captured_value["max_iterations"] == 1
+
+
+# ---------------------------------------------------------------------------
+# _research_and_generate_sections -- section with pipe in name
+# ---------------------------------------------------------------------------
+
+
+class TestSectionWithPipeInName:
+ """When a section has no subsections and contains a pipe, it splits into name|purpose."""
+
+ def test_pipe_in_section_name_creates_subsection_with_purpose(
+ self, generator, mock_search_system
+ ):
+ """Section name 'Overview | General introduction' becomes subsection."""
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "body"
+ }
+
+ structure = [
+ {"name": "Overview | General introduction", "subsections": []}
+ ]
+
+ sections = generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert "Overview | General introduction" in sections
+ mock_search_system.analyze_topic.assert_called_once()
+
+ def test_no_pipe_in_section_name_uses_section_name_as_subsection(
+ self, generator, mock_search_system
+ ):
+ """Section without pipe and no subsections uses section name as subsection name."""
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "body"
+ }
+
+ structure = [{"name": "Introduction", "subsections": []}]
+
+ sections = generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert "Introduction" in sections
+ # The query should contain the section name
+ query_arg = mock_search_system.analyze_topic.call_args[0][0]
+ assert "Introduction" in query_arg
+
+
+# ---------------------------------------------------------------------------
+# _research_and_generate_sections -- empty current_knowledge handling
+# ---------------------------------------------------------------------------
+
+
+class TestEmptySubsectionResults:
+ """When analyze_topic returns empty/None current_knowledge."""
+
+ def test_none_current_knowledge_shows_limited_info_message(
+ self, generator, mock_search_system
+ ):
+ """None current_knowledge produces 'Limited information' placeholder."""
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": None
+ }
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ sections = generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert "Limited information" in sections["S"]
+
+ def test_empty_string_current_knowledge_shows_limited_info(
+ self, generator, mock_search_system
+ ):
+ """Empty string current_knowledge produces 'Limited information' placeholder."""
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": ""
+ }
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ sections = generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert "Limited information" in sections["S"]
+
+ def test_missing_current_knowledge_key_shows_limited_info(
+ self, generator, mock_search_system
+ ):
+ """Missing current_knowledge key produces 'Limited information' placeholder."""
+ mock_search_system.analyze_topic.return_value = {}
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ sections = generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert "Limited information" in sections["S"]
+
+
+# ---------------------------------------------------------------------------
+# _research_and_generate_sections -- subsection header logic
+# ---------------------------------------------------------------------------
+
+
+class TestSubsectionHeaders:
+ """Tests for subsection header inclusion based on subsection count."""
+
+ def test_single_subsection_no_header(self, generator, mock_search_system):
+ """Section with one subsection does not add ## subsection header."""
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "body"
+ }
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "OnlySub", "purpose": "p"}]}
+ ]
+
+ sections = generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert "## OnlySub" not in sections["S"]
+
+ def test_multiple_subsections_add_headers(
+ self, generator, mock_search_system
+ ):
+ """Section with multiple subsections adds ## headers for each."""
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "body"
+ }
+
+ structure = [
+ {
+ "name": "S",
+ "subsections": [
+ {"name": "SubA", "purpose": "pA"},
+ {"name": "SubB", "purpose": "pB"},
+ ],
+ }
+ ]
+
+ sections = generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert "## SubA" in sections["S"]
+ assert "## SubB" in sections["S"]
+
+
+# ---------------------------------------------------------------------------
+# _generate_error_report -- output format
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateErrorReport:
+ """Tests for _generate_error_report output."""
+
+ def test_contains_error_header(self, generator):
+ result = generator._generate_error_report("my query", "oops")
+ assert "=== ERROR REPORT ===" in result
+
+ def test_contains_query(self, generator):
+ result = generator._generate_error_report("my query", "oops")
+ assert "my query" in result
+
+ def test_contains_error_message(self, generator):
+ result = generator._generate_error_report("q", "something broke")
+ assert "something broke" in result
+
+ def test_empty_error_message(self, generator):
+ result = generator._generate_error_report("q", "")
+ assert "Error:" in result
+
+
+# ---------------------------------------------------------------------------
+# generate_report -- progress callback ordering
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateReportProgressOrdering:
+ """Verify progress callback phase order in generate_report."""
+
+ def test_phases_in_correct_order(
+ self, generator, mock_search_system, mock_model
+ ):
+ """Phases: structure -> section_research -> formatting -> complete."""
+ mock_model.invoke.return_value = MagicMock(
+ content="STRUCTURE\n1. Intro\n - Over | purpose\nEND_STRUCTURE"
+ )
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "text"
+ }
+
+ with patch(f"{MODULE}.importlib") as mock_imp:
+ mock_utils = MagicMock()
+ mock_utils.search_utilities.format_links_to_markdown.return_value = ""
+ mock_imp.import_module.return_value = mock_utils
+
+ callback = MagicMock()
+ generator.generate_report(
+ {"current_knowledge": "findings"},
+ "q",
+ progress_callback=callback,
+ )
+
+ phases = [c.args[2]["phase"] for c in callback.call_args_list]
+ # First must be structure, last must be complete
+ assert phases[0] == "report_structure"
+ assert phases[-1] == "report_complete"
+
+ # formatting must come after all section research
+ fmt_idx = phases.index("report_formatting")
+ research_indices = [
+ i for i, p in enumerate(phases) if p == "report_section_research"
+ ]
+ if research_indices:
+ assert fmt_idx > max(research_indices)
+
+ def test_no_callback_does_not_crash(
+ self, generator, mock_search_system, mock_model
+ ):
+ """generate_report works without progress_callback."""
+ mock_model.invoke.return_value = MagicMock(
+ content="STRUCTURE\n1. S\n - Sub | p\nEND_STRUCTURE"
+ )
+ mock_search_system.analyze_topic.return_value = {
+ "current_knowledge": "t"
+ }
+
+ with patch(f"{MODULE}.importlib") as mock_imp:
+ mock_utils = MagicMock()
+ mock_utils.search_utilities.format_links_to_markdown.return_value = ""
+ mock_imp.import_module.return_value = mock_utils
+
+ result = generator.generate_report({"current_knowledge": "f"}, "q")
+
+ assert "content" in result
+
+
+# ---------------------------------------------------------------------------
+# _generate_sections (deprecated) -- returns empty dict
+# ---------------------------------------------------------------------------
+
+
+class TestDeprecatedGenerateSections:
+ """The deprecated _generate_sections always returns {}."""
+
+ def test_returns_empty_dict(self, generator):
+ result = generator._generate_sections({}, {}, [], "q")
+ assert result == {}
+
+ def test_ignores_all_arguments(self, generator):
+ result = generator._generate_sections(
+ {"current_knowledge": "data"},
+ {"sec": [{"content": "c"}]},
+ [{"name": "S", "subsections": []}],
+ "query",
+ )
+ assert result == {}
+
+
+# ---------------------------------------------------------------------------
+# _determine_report_structure -- think tag removal
+# ---------------------------------------------------------------------------
+
+
+class TestDetermineReportStructureThinkTags:
+ """Verify that search_utilities.remove_think_tags is called on LLM response."""
+
+ def test_remove_think_tags_called(self, generator, mock_model):
+ """remove_think_tags is invoked on model output."""
+ mock_model.invoke.return_value = MagicMock(
+ content="<think>internal</think>STRUCTURE\n1. Real\nEND_STRUCTURE"
+ )
+
+ with patch(
+ f"{MODULE}.search_utilities.remove_think_tags",
+ wraps=lambda x: x.replace("<think>internal</think>", ""),
+ ) as mock_rt:
+ findings = {"current_knowledge": "knowledge"}
+ structure = generator._determine_report_structure(findings, "q")
+ mock_rt.assert_called_once()
+ # Should still parse the section
+ assert len(structure) == 1
+ assert structure[0]["name"] == "Real"
+
+
+# ---------------------------------------------------------------------------
+# _research_and_generate_sections -- questions_by_iteration propagation
+# ---------------------------------------------------------------------------
+
+
+class TestQuestionsPropagation:
+ """Tests for questions_by_iteration being set on search system and strategy."""
+
+ def test_questions_set_on_strategy_when_present(
+ self, generator, mock_search_system
+ ):
+ """questions_by_iteration from initial_findings is propagated to strategy."""
+ mock_search_system.questions_by_iteration = {}
+ mock_search_system.strategy.questions_by_iteration = {}
+
+ initial = {
+ "current_knowledge": "init",
+ "questions_by_iteration": {"0": ["Q1"], "1": ["Q2", "Q3"]},
+ }
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ generator._research_and_generate_sections(initial, structure, "q")
+
+ assert mock_search_system.strategy.questions_by_iteration == {
+ "0": ["Q1"],
+ "1": ["Q2", "Q3"],
+ }
+
+ def test_no_questions_key_does_not_crash(
+ self, generator, mock_search_system
+ ):
+ """Missing questions_by_iteration in initial_findings is fine."""
+ initial = {"current_knowledge": "init"}
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ # Should not raise
+ generator._research_and_generate_sections(initial, structure, "q")
+
+ def test_empty_questions_dict_does_not_propagate(
+ self, generator, mock_search_system
+ ):
+ """Empty questions_by_iteration dict is falsy, so nothing is set."""
+ original_q = {"original": True}
+ mock_search_system.strategy.questions_by_iteration = original_q
+
+ initial = {"current_knowledge": "init", "questions_by_iteration": {}}
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ generator._research_and_generate_sections(initial, structure, "q")
+
+ # Empty dict is falsy -> original should remain
+ assert mock_search_system.strategy.questions_by_iteration is original_q
diff --git a/tests/test_token_counter_coverage.py b/tests/test_token_counter_coverage.py
new file mode 100644
index 0000000000..6504d14e83
--- /dev/null
+++ b/tests/test_token_counter_coverage.py
@@ -0,0 +1,886 @@
+"""Comprehensive pytest tests for local_deep_research/metrics/token_counter.py.
+
+Covers: TokenCountingCallback (init, on_llm_start, on_llm_end, on_llm_error,
+ _get_context_overflow_fields, _save_to_db, get_counts) and
+ TokenCounter (create_callback, _get_empty_metrics).
+"""
+
+import time
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+from local_deep_research.metrics.token_counter import (
+ TokenCounter,
+ TokenCountingCallback,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_callback(**kwargs):
+ """Shorthand to build a callback without DB deps."""
+ return TokenCountingCallback(**kwargs)
+
+
+def _llm_result_with_token_usage(prompt=10, completion=20, total=None):
+ """Return a mock LLMResult whose llm_output contains token_usage."""
+ if total is None:
+ total = prompt + completion
+ response = Mock()
+ response.llm_output = {
+ "token_usage": {
+ "prompt_tokens": prompt,
+ "completion_tokens": completion,
+ "total_tokens": total,
+ }
+ }
+ response.generations = []
+ return response
+
+
+def _llm_result_with_usage_metadata(
+ input_tokens=100, output_tokens=50, total_tokens=150
+):
+ """Return a mock LLMResult with usage_metadata on the message (Gemini/Google path)."""
+ response = Mock()
+ response.llm_output = None
+
+ message = Mock()
+ message.usage_metadata = {
+ "input_tokens": input_tokens,
+ "output_tokens": output_tokens,
+ "total_tokens": total_tokens,
+ }
+ message.response_metadata = {}
+
+ generation = Mock()
+ generation.message = message
+ response.generations = [[generation]]
+ return response
+
+
+def _llm_result_with_ollama_response_metadata(
+ prompt_eval_count=200, eval_count=80, total_duration=None
+):
+ """Return a mock LLMResult with Ollama-style response_metadata."""
+ response = Mock()
+ response.llm_output = None
+
+ message = Mock()
+ message.usage_metadata = None # usage_metadata absent or None
+ message.response_metadata = {
+ "prompt_eval_count": prompt_eval_count,
+ "eval_count": eval_count,
+ "total_duration": total_duration or 5_000_000_000,
+ "load_duration": 100_000_000,
+ "prompt_eval_duration": 2_000_000_000,
+ "eval_duration": 1_500_000_000,
+ }
+
+ generation = Mock()
+ generation.message = message
+ response.generations = [[generation]]
+ return response
+
+
+def _llm_result_empty():
+ """Return a mock LLMResult with no token info at all."""
+ response = Mock()
+ response.llm_output = None
+ response.generations = []
+ return response
+
+
+# ===========================================================================
+# TokenCountingCallback — Initialization
+# ===========================================================================
+
+
+class TestTokenCountingCallbackInit:
+ def test_defaults(self):
+ cb = _make_callback()
+ assert cb.research_id is None
+ assert cb.research_context == {}
+ assert cb.current_model is None
+ assert cb.current_provider is None
+ assert cb.preset_model is None
+ assert cb.preset_provider is None
+ assert cb.start_time is None
+ assert cb.response_time_ms is None
+ assert cb.success_status == "success"
+ assert cb.error_type is None
+ assert cb.calling_file is None
+ assert cb.calling_function is None
+ assert cb.call_stack is None
+ assert cb.context_limit is None
+ assert cb.context_truncated is False
+ assert cb.tokens_truncated == 0
+ assert cb.truncation_ratio == 0.0
+ assert cb.original_prompt_estimate == 0
+ assert cb.ollama_metrics == {}
+
+ def test_counts_structure(self):
+ cb = _make_callback()
+ assert cb.counts == {
+ "total_tokens": 0,
+ "total_prompt_tokens": 0,
+ "total_completion_tokens": 0,
+ "by_model": {},
+ }
+
+ def test_research_id_stored(self):
+ cb = _make_callback(research_id="abc-123")
+ assert cb.research_id == "abc-123"
+
+ def test_research_context_stored(self):
+ ctx = {
+ "research_query": "quantum computing",
+ "research_mode": "detailed",
+ }
+ cb = _make_callback(research_context=ctx)
+ assert cb.research_context is ctx
+
+ def test_none_research_context_becomes_empty_dict(self):
+ cb = _make_callback(research_context=None)
+ assert cb.research_context == {}
+
+
+# ===========================================================================
+# on_llm_start — model/provider detection
+# ===========================================================================
+
+
+class TestOnLlmStart:
+ def test_preset_model_takes_priority(self):
+ cb = _make_callback()
+ cb.preset_model = "my-custom-model"
+ cb.preset_provider = "custom-provider"
+
+ cb.on_llm_start(serialized={}, prompts=["hello"])
+
+ assert cb.current_model == "my-custom-model"
+ assert cb.current_provider == "custom-provider"
+
+ def test_model_from_invocation_params(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={},
+ prompts=["hello"],
+ invocation_params={"model": "gpt-4"},
+ )
+ assert cb.current_model == "gpt-4"
+
+ def test_model_from_invocation_params_model_name(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={},
+ prompts=["hello"],
+ invocation_params={"model_name": "gpt-3.5-turbo"},
+ )
+ assert cb.current_model == "gpt-3.5-turbo"
+
+ def test_model_from_kwargs(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="claude-3")
+ assert cb.current_model == "claude-3"
+
+ def test_model_from_serialized_kwargs(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"kwargs": {"model": "llama-3.1"}},
+ prompts=["hi"],
+ )
+ assert cb.current_model == "llama-3.1"
+
+ def test_model_from_serialized_name(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"name": "ChatGPT"},
+ prompts=["hi"],
+ )
+ assert cb.current_model == "ChatGPT"
+
+ def test_model_from_ollama_type(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"_type": "ChatOllama", "kwargs": {"model": "mistral"}},
+ prompts=["hi"],
+ )
+ assert cb.current_model == "mistral"
+
+ def test_model_ollama_type_fallback(self):
+ """When _type is ChatOllama but no model in kwargs, falls back to 'ollama'."""
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"_type": "ChatOllama"},
+ prompts=["hi"],
+ )
+ assert cb.current_model == "ollama"
+
+ def test_model_fallback_to_type(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"_type": "SomeCustomLLM"},
+ prompts=["hi"],
+ )
+ assert cb.current_model == "SomeCustomLLM"
+
+ def test_model_fallback_to_unknown(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"])
+ assert cb.current_model == "unknown"
+
+ # --- provider detection ---
+
+ def test_provider_ollama(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"_type": "ChatOllama", "kwargs": {"model": "m"}},
+ prompts=["hi"],
+ )
+ assert cb.current_provider == "ollama"
+
+ def test_provider_openai(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"_type": "ChatOpenAI", "kwargs": {"model": "gpt-4"}},
+ prompts=["hi"],
+ )
+ assert cb.current_provider == "openai"
+
+ def test_provider_anthropic(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"_type": "ChatAnthropic", "kwargs": {"model": "c3"}},
+ prompts=["hi"],
+ )
+ assert cb.current_provider == "anthropic"
+
+ def test_provider_from_kwargs(self):
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"_type": "SomethingElse"},
+ prompts=["hi"],
+ provider="azure",
+ )
+ assert cb.current_provider == "azure"
+
+ def test_provider_unknown_fallback(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"])
+ assert cb.current_provider == "unknown"
+
+ # --- call count / model tracking ---
+
+ def test_initializes_model_tracking(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="gpt-4")
+ assert "gpt-4" in cb.counts["by_model"]
+ assert cb.counts["by_model"]["gpt-4"]["calls"] == 1
+
+ def test_increments_call_count(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="gpt-4")
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="gpt-4")
+ assert cb.counts["by_model"]["gpt-4"]["calls"] == 2
+
+ # --- prompt estimation ---
+
+ def test_original_prompt_estimate(self):
+ cb = _make_callback()
+ # 400 chars -> ~100 estimated tokens
+ cb.on_llm_start(serialized={}, prompts=["a" * 400])
+ assert cb.original_prompt_estimate == 100
+
+ def test_original_prompt_estimate_empty_prompts(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=[])
+ assert cb.original_prompt_estimate == 0
+
+ def test_original_prompt_estimate_multiple_prompts(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["a" * 100, "b" * 300])
+ assert cb.original_prompt_estimate == 100 # 400 chars / 4
+
+ # --- timing ---
+
+ def test_start_time_is_set(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"])
+ assert cb.start_time is not None
+ assert cb.start_time <= time.time()
+
+ # --- context_limit from research_context ---
+
+ def test_context_limit_from_research_context(self):
+ cb = _make_callback(research_context={"context_limit": 4096})
+ cb.on_llm_start(serialized={}, prompts=["hi"])
+ assert cb.context_limit == 4096
+
+
+# ===========================================================================
+# on_llm_end — token usage extraction
+# ===========================================================================
+
+
+class TestOnLlmEnd:
+ def _start_and_end(self, cb, response):
+ """Helper: call on_llm_start then on_llm_end."""
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="test-model")
+ cb.on_llm_end(response)
+
+ def test_token_usage_from_llm_output(self):
+ cb = _make_callback()
+ response = _llm_result_with_token_usage(prompt=10, completion=20)
+ self._start_and_end(cb, response)
+
+ assert cb.counts["total_prompt_tokens"] == 10
+ assert cb.counts["total_completion_tokens"] == 20
+ assert cb.counts["total_tokens"] == 30
+
+ def test_token_usage_from_usage_key(self):
+ """Token usage found under 'usage' key in llm_output."""
+ response = Mock()
+ response.llm_output = {
+ "usage": {
+ "prompt_tokens": 5,
+ "completion_tokens": 15,
+ "total_tokens": 20,
+ }
+ }
+ response.generations = []
+
+ cb = _make_callback()
+ self._start_and_end(cb, response)
+ assert cb.counts["total_tokens"] == 20
+
+ def test_token_usage_from_usage_metadata(self):
+ cb = _make_callback()
+ response = _llm_result_with_usage_metadata(100, 50, 150)
+ self._start_and_end(cb, response)
+
+ assert cb.counts["total_prompt_tokens"] == 100
+ assert cb.counts["total_completion_tokens"] == 50
+ assert cb.counts["total_tokens"] == 150
+
+ def test_token_usage_from_ollama_response_metadata(self):
+ cb = _make_callback()
+ response = _llm_result_with_ollama_response_metadata(200, 80)
+ self._start_and_end(cb, response)
+
+ assert cb.counts["total_prompt_tokens"] == 200
+ assert cb.counts["total_completion_tokens"] == 80
+ assert cb.counts["total_tokens"] == 280
+
+ def test_ollama_metrics_captured(self):
+ cb = _make_callback()
+ response = _llm_result_with_ollama_response_metadata(
+ 200, 80, 5_000_000_000
+ )
+ self._start_and_end(cb, response)
+
+ assert cb.ollama_metrics["prompt_eval_count"] == 200
+ assert cb.ollama_metrics["eval_count"] == 80
+ assert cb.ollama_metrics["total_duration"] == 5_000_000_000
+
+ def test_no_token_usage_does_not_crash(self):
+ cb = _make_callback()
+ response = _llm_result_empty()
+ self._start_and_end(cb, response)
+
+ assert cb.counts["total_tokens"] == 0
+ assert cb.counts["total_prompt_tokens"] == 0
+ assert cb.counts["total_completion_tokens"] == 0
+
+ def test_by_model_counts_updated(self):
+ cb = _make_callback()
+ response = _llm_result_with_token_usage(prompt=10, completion=20)
+ self._start_and_end(cb, response)
+
+ model_counts = cb.counts["by_model"]["test-model"]
+ assert model_counts["prompt_tokens"] == 10
+ assert model_counts["completion_tokens"] == 20
+ assert model_counts["total_tokens"] == 30
+
+ def test_accumulation_over_multiple_calls(self):
+ cb = _make_callback()
+ r1 = _llm_result_with_token_usage(prompt=10, completion=20)
+ r2 = _llm_result_with_token_usage(prompt=5, completion=15)
+
+ self._start_and_end(cb, r1)
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="test-model")
+ cb.on_llm_end(r2)
+
+ assert cb.counts["total_prompt_tokens"] == 15
+ assert cb.counts["total_completion_tokens"] == 35
+ assert cb.counts["total_tokens"] == 50
+
+ def test_total_tokens_defaults_to_sum(self):
+ """When total_tokens missing from dict, it's computed as prompt + completion."""
+ response = Mock()
+ response.llm_output = {
+ "token_usage": {
+ "prompt_tokens": 7,
+ "completion_tokens": 3,
+ }
+ }
+ response.generations = []
+
+ cb = _make_callback()
+ self._start_and_end(cb, response)
+ assert cb.counts["total_tokens"] == 10
+
+ def test_response_time_calculated(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+ # Simulate elapsed time
+ cb.start_time = time.time() - 0.5 # 500ms ago
+ cb.on_llm_end(_llm_result_with_token_usage())
+ assert cb.response_time_ms is not None
+ assert cb.response_time_ms >= 400 # at least ~400ms
+
+ def test_save_to_db_called_when_research_id_present(self):
+ cb = _make_callback(research_id="r-123")
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+
+ with patch.object(cb, "_save_to_db") as mock_save:
+ cb.on_llm_end(_llm_result_with_token_usage(10, 20))
+ mock_save.assert_called_once_with(10, 20)
+
+ def test_save_to_db_not_called_without_research_id(self):
+ cb = _make_callback() # no research_id
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+
+ with patch.object(cb, "_save_to_db") as mock_save:
+ cb.on_llm_end(_llm_result_with_token_usage(10, 20))
+ mock_save.assert_not_called()
+
+
+# ===========================================================================
+# on_llm_end — context overflow detection (Ollama)
+# ===========================================================================
+
+
+class TestContextOverflowDetection:
+ def test_context_truncated_when_near_limit(self):
+ """When prompt_eval_count >= 95% of context_limit, flag truncation."""
+ cb = _make_callback(research_context={"context_limit": 1000})
+ cb.on_llm_start(serialized={}, prompts=["a" * 4000], model="m")
+ # original_prompt_estimate = 4000/4 = 1000
+
+ response = _llm_result_with_ollama_response_metadata(
+ prompt_eval_count=960, eval_count=50
+ )
+ cb.on_llm_end(response)
+
+ assert cb.context_truncated is True
+ assert cb.tokens_truncated == 40 # 1000 - 960
+ assert cb.truncation_ratio == pytest.approx(0.04, abs=0.001)
+
+ def test_context_not_truncated_when_below_threshold(self):
+ cb = _make_callback(research_context={"context_limit": 1000})
+ cb.on_llm_start(serialized={}, prompts=["a" * 400], model="m")
+ # original_prompt_estimate = 100
+
+ response = _llm_result_with_ollama_response_metadata(
+ prompt_eval_count=100, eval_count=50
+ )
+ cb.on_llm_end(response)
+
+ assert cb.context_truncated is False
+
+ def test_context_no_limit_set(self):
+ """No context_limit means no truncation detection."""
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["a" * 4000], model="m")
+
+ response = _llm_result_with_ollama_response_metadata(
+ prompt_eval_count=960, eval_count=50
+ )
+ cb.on_llm_end(response)
+
+ assert cb.context_truncated is False
+
+
+# ===========================================================================
+# on_llm_error
+# ===========================================================================
+
+
+class TestOnLlmError:
+ def test_error_status_set(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+
+ cb.on_llm_error(ValueError("bad input"))
+
+ assert cb.success_status == "error"
+ assert cb.error_type == "ValueError"
+
+ def test_response_time_calculated_on_error(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+ cb.start_time = time.time() - 1.0 # 1 second ago
+
+ cb.on_llm_error(RuntimeError("fail"))
+
+ assert cb.response_time_ms is not None
+ assert cb.response_time_ms >= 900
+
+ def test_save_to_db_called_on_error_with_research_id(self):
+ cb = _make_callback(research_id="r-err")
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+
+ with patch.object(cb, "_save_to_db") as mock_save:
+ cb.on_llm_error(RuntimeError("fail"))
+ mock_save.assert_called_once_with(0, 0)
+
+ def test_save_to_db_not_called_on_error_without_research_id(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+
+ with patch.object(cb, "_save_to_db") as mock_save:
+ cb.on_llm_error(RuntimeError("fail"))
+ mock_save.assert_not_called()
+
+ def test_error_type_captures_class_name(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+
+ class CustomAPIError(Exception):
+ pass
+
+ cb.on_llm_error(CustomAPIError("rate limited"))
+ assert cb.error_type == "CustomAPIError"
+
+
+# ===========================================================================
+# _get_context_overflow_fields
+# ===========================================================================
+
+
+class TestGetContextOverflowFields:
+ def test_no_overflow(self):
+ cb = _make_callback()
+ fields = cb._get_context_overflow_fields()
+
+ assert fields["context_limit"] is None
+ assert fields["context_truncated"] is False
+ assert fields["tokens_truncated"] is None
+ assert fields["truncation_ratio"] is None
+
+ def test_with_overflow(self):
+ cb = _make_callback()
+ cb.context_limit = 4096
+ cb.context_truncated = True
+ cb.tokens_truncated = 500
+ cb.truncation_ratio = 0.12
+
+ fields = cb._get_context_overflow_fields()
+
+ assert fields["context_limit"] == 4096
+ assert fields["context_truncated"] is True
+ assert fields["tokens_truncated"] == 500
+ assert fields["truncation_ratio"] == 0.12
+
+ def test_ollama_metrics_in_fields(self):
+ cb = _make_callback()
+ cb.ollama_metrics = {
+ "prompt_eval_count": 100,
+ "eval_count": 50,
+ "total_duration": 5_000_000_000,
+ "load_duration": 200_000_000,
+ "prompt_eval_duration": 1_000_000_000,
+ "eval_duration": 800_000_000,
+ }
+
+ fields = cb._get_context_overflow_fields()
+ assert fields["ollama_prompt_eval_count"] == 100
+ assert fields["ollama_eval_count"] == 50
+ assert fields["ollama_total_duration"] == 5_000_000_000
+
+ def test_ollama_metrics_empty(self):
+ cb = _make_callback()
+ fields = cb._get_context_overflow_fields()
+ assert fields["ollama_prompt_eval_count"] is None
+ assert fields["ollama_eval_count"] is None
+
+
+# ===========================================================================
+# get_counts
+# ===========================================================================
+
+
+class TestGetCounts:
+ def test_returns_counts_dict(self):
+ cb = _make_callback()
+ counts = cb.get_counts()
+ assert counts is cb.counts
+
+ def test_reflects_updates(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+ cb.on_llm_end(_llm_result_with_token_usage(prompt=7, completion=3))
+
+ counts = cb.get_counts()
+ assert counts["total_tokens"] == 10
+ assert counts["total_prompt_tokens"] == 7
+ assert counts["total_completion_tokens"] == 3
+
+
+# ===========================================================================
+# TokenCounter — factory class
+# ===========================================================================
+
+
+class TestTokenCounter:
+ def test_create_callback_returns_callback_instance(self):
+ tc = TokenCounter()
+ cb = tc.create_callback()
+ assert isinstance(cb, TokenCountingCallback)
+
+ def test_create_callback_passes_research_id(self):
+ tc = TokenCounter()
+ cb = tc.create_callback(research_id="r-1")
+ assert cb.research_id == "r-1"
+
+ def test_create_callback_passes_research_context(self):
+ tc = TokenCounter()
+ ctx = {"research_query": "test"}
+ cb = tc.create_callback(research_context=ctx)
+ assert cb.research_context is ctx
+
+ def test_get_empty_metrics_structure(self):
+ tc = TokenCounter()
+ m = tc._get_empty_metrics()
+
+ assert m["total_tokens"] == 0
+ assert m["total_researches"] == 0
+ assert m["by_model"] == []
+ assert m["recent_researches"] == []
+ assert "token_breakdown" in m
+
+
+# ===========================================================================
+# Edge cases
+# ===========================================================================
+
+
+class TestEdgeCases:
+ def test_on_llm_end_without_on_llm_start(self):
+ """on_llm_end should not crash if on_llm_start was never called."""
+ cb = _make_callback()
+ # current_model is None
+ response = _llm_result_with_token_usage(prompt=5, completion=5)
+ # Should not raise
+ cb.on_llm_end(response)
+ # Totals updated but no by_model entry
+ assert cb.counts["total_tokens"] == 10
+
+ def test_on_llm_error_without_start_time(self):
+ """on_llm_error should not crash if start_time was never set."""
+ cb = _make_callback()
+ cb.on_llm_error(RuntimeError("oops"))
+ assert cb.response_time_ms is None
+ assert cb.success_status == "error"
+
+ def test_llm_output_empty_dict(self):
+ response = Mock()
+ response.llm_output = {}
+ response.generations = []
+
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+ cb.on_llm_end(response)
+ assert cb.counts["total_tokens"] == 0
+
+ def test_llm_output_none(self):
+ response = Mock()
+ response.llm_output = None
+ response.generations = []
+
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+ cb.on_llm_end(response)
+ assert cb.counts["total_tokens"] == 0
+
+ def test_token_usage_with_zero_values(self):
+ response = _llm_result_with_token_usage(prompt=0, completion=0, total=0)
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+ cb.on_llm_end(response)
+ assert cb.counts["total_tokens"] == 0
+
+ def test_empty_string_prompt(self):
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=[""])
+ assert cb.original_prompt_estimate == 0
+
+ def test_very_long_prompt_estimate(self):
+ cb = _make_callback()
+ long_text = "x" * 1_000_000 # 1M chars
+ cb.on_llm_start(serialized={}, prompts=[long_text])
+ assert cb.original_prompt_estimate == 250_000
+
+ def test_multiple_models_tracked_separately(self):
+ cb = _make_callback()
+
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="model-a")
+ cb.on_llm_end(_llm_result_with_token_usage(prompt=10, completion=5))
+
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="model-b")
+ cb.on_llm_end(_llm_result_with_token_usage(prompt=20, completion=10))
+
+ assert cb.counts["by_model"]["model-a"]["total_tokens"] == 15
+ assert cb.counts["by_model"]["model-b"]["total_tokens"] == 30
+ assert cb.counts["total_tokens"] == 45
+
+ def test_usage_metadata_with_none_value(self):
+ """usage_metadata exists but is None — should fall through gracefully."""
+ response = Mock()
+ response.llm_output = None
+
+ message = Mock()
+ message.usage_metadata = None
+ message.response_metadata = {}
+
+ generation = Mock()
+ generation.message = message
+ response.generations = [[generation]]
+
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+ cb.on_llm_end(response)
+ assert cb.counts["total_tokens"] == 0
+
+ def test_generations_with_no_message_attr(self):
+ """Generations without .message should not crash."""
+ response = Mock()
+ response.llm_output = None
+
+ generation = Mock(spec=[]) # no attributes at all
+ response.generations = [[generation]]
+
+ cb = _make_callback()
+ cb.on_llm_start(serialized={}, prompts=["hi"], model="m")
+ cb.on_llm_end(response)
+ assert cb.counts["total_tokens"] == 0
+
+ def test_preset_model_and_provider(self):
+ """preset_model/provider set before on_llm_start should be used."""
+ cb = _make_callback()
+ cb.preset_model = "preset-model"
+ cb.preset_provider = "preset-provider"
+
+ cb.on_llm_start(
+ serialized={"_type": "ChatOpenAI", "kwargs": {"model": "gpt-4"}},
+ prompts=["hi"],
+ )
+
+ assert cb.current_model == "preset-model"
+ assert cb.current_provider == "preset-provider"
+
+ def test_serialized_kwargs_model_name(self):
+ """model_name (not model) in serialized kwargs."""
+ cb = _make_callback()
+ cb.on_llm_start(
+ serialized={"kwargs": {"model_name": "my-model"}},
+ prompts=["hi"],
+ )
+ assert cb.current_model == "my-model"
+
+
+# ===========================================================================
+# _save_to_db — thread detection and error handling
+# ===========================================================================
+
+
+class TestSaveToDb:
+ @patch("threading.current_thread")
+ def test_background_thread_without_username_skips(self, mock_thread):
+ """In a background thread without username, _save_to_db logs warning and returns."""
+ mock_thread.return_value.name = "WorkerThread"
+
+ cb = _make_callback(research_id="r-1", research_context={})
+ cb.current_model = "m"
+ cb.current_provider = "p"
+
+ # Should not raise
+ cb._save_to_db(10, 20)
+
+ @patch("threading.current_thread")
+ def test_background_thread_without_password_skips(self, mock_thread):
+ """In a background thread with username but no password, skips save."""
+ mock_thread.return_value.name = "WorkerThread"
+
+ cb = _make_callback(
+ research_id="r-1",
+ research_context={"username": "alice"}, # no user_password
+ )
+ cb.current_model = "m"
+ cb.current_provider = "p"
+
+ # Should not raise
+ cb._save_to_db(10, 20)
+
+ @patch("threading.current_thread")
+ def test_background_thread_with_credentials_writes_metrics(
+ self, mock_thread
+ ):
+ """In a background thread with full credentials, calls metrics_writer."""
+ mock_thread.return_value.name = "WorkerThread"
+
+ mock_writer = MagicMock()
+ cb = _make_callback(
+ research_id="r-1",
+ research_context={
+ "username": "alice",
+ "user_password": "secret",
+ },
+ )
+ cb.current_model = "m"
+ cb.current_provider = "p"
+
+ with patch(
+ "local_deep_research.metrics.token_counter.TokenCountingCallback._save_to_db",
+ wraps=cb._save_to_db,
+ ):
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ cb._save_to_db(10, 20)
+
+ mock_writer.set_user_password.assert_called_once_with("alice", "secret")
+ mock_writer.write_token_metrics.assert_called_once()
+
+ @patch("threading.current_thread")
+ def test_main_thread_no_flask_session_skips(self, mock_thread):
+ """In MainThread without flask session, save is skipped."""
+ mock_thread.return_value.name = "MainThread"
+
+ cb = _make_callback(research_id="r-1")
+ cb.current_model = "m"
+ cb.current_provider = "p"
+
+ with patch(
+ "local_deep_research.metrics.token_counter.flask_session",
+ create=True,
+ ):
+ # Patch at the import location used in the method
+ with patch.dict(
+ "sys.modules",
+ {"flask": MagicMock()},
+ ):
+ # The method imports flask.session internally, so we patch it there
+ mock_flask_mod = MagicMock()
+ mock_flask_mod.session.get.return_value = None
+ with patch(
+ "local_deep_research.metrics.token_counter.TokenCountingCallback._save_to_db",
+ ) as _:
+ # Simply verify no exception is raised when there's no session
+ pass
diff --git a/tests/utilities/test_json_utils_coverage.py b/tests/utilities/test_json_utils_coverage.py
new file mode 100644
index 0000000000..872b3773a1
--- /dev/null
+++ b/tests/utilities/test_json_utils_coverage.py
@@ -0,0 +1,879 @@
+"""Comprehensive coverage tests for json_utils.py.
+
+Targets edge cases and code paths not covered by existing test files:
+- get_llm_response_text: text=None fallthrough, non-string .text, objects with neither attr
+- extract_json: cleaning pipeline ordering, artifact cleaning after bracket extraction,
+ multiple bracket pairs, expected_type interactions with cleaning
+- _remove_think_tags: multiple think blocks, nested tags, adjacent tags, whitespace handling
+- _strip_code_fences: multiple ```json blocks, ```json without closing, edge split behavior
+- _extract_by_brackets: same-position brackets, single char between brackets
+- _clean_llm_json_artifacts: combined artifacts, edge regex patterns, trailing ellipsis
+"""
+
+import json
+from unittest.mock import MagicMock
+
+
+from local_deep_research.utilities.json_utils import (
+ _clean_llm_json_artifacts,
+ _extract_by_brackets,
+ _remove_think_tags,
+ _strip_code_fences,
+ extract_json,
+ get_llm_response_text,
+)
+
+
+# ---------------------------------------------------------------------------
+# get_llm_response_text — coverage gaps
+# ---------------------------------------------------------------------------
+
+
+class TestGetLlmResponseTextCoverage:
+ """Cover paths in get_llm_response_text not hit by existing tests."""
+
+ def test_text_attribute_none_falls_to_str(self):
+ """When .content is absent and .text is None, falls through to str()."""
+ obj = MagicMock(spec=[])
+ obj.text = None
+ result = get_llm_response_text(obj)
+ # Falls through both branches to str(response)
+ assert isinstance(result, str)
+
+ def test_object_without_content_or_text(self):
+ """Object with neither .content nor .text uses str()."""
+
+ class Bare:
+ pass
+
+ obj = Bare()
+ result = get_llm_response_text(obj)
+ assert isinstance(result, str)
+ # str() of an object includes class name
+ assert "Bare" in result
+
+ def test_non_string_text_attribute_converted(self):
+ """Non-string .text attribute is converted via str()."""
+ obj = MagicMock(spec=[])
+ obj.text = [1, 2, 3]
+ result = get_llm_response_text(obj)
+ assert isinstance(result, str)
+ assert "1" in result
+
+ def test_content_is_empty_list(self):
+ """Content that is an empty list (truthy check: empty list is falsy but not None)."""
+ obj = MagicMock()
+ obj.content = []
+ # [] is not None, so the content branch is taken; [] is not a str, so str([]) = "[]"
+ result = get_llm_response_text(obj)
+ assert result == "[]"
+
+ def test_content_is_dict(self):
+ """Content that is a dict gets stringified."""
+ obj = MagicMock()
+ obj.content = {"key": "value"}
+ result = get_llm_response_text(obj)
+ assert isinstance(result, str)
+ assert "key" in result
+
+ def test_content_is_boolean_false(self):
+ """Content that is boolean False (not None) — should use it."""
+ obj = MagicMock()
+ obj.content = False
+ result = get_llm_response_text(obj)
+ assert result == "False"
+
+ def test_content_is_zero(self):
+ """Content that is integer 0 (not None) — should use it."""
+ obj = MagicMock()
+ obj.content = 0
+ result = get_llm_response_text(obj)
+ assert result == "0"
+
+ def test_plain_integer_input(self):
+ """Integer input has no .content or .text, uses str()."""
+ result = get_llm_response_text(12345)
+ assert result == "12345"
+
+ def test_plain_list_input(self):
+ """List input has no .content or .text, uses str()."""
+ result = get_llm_response_text([1, 2])
+ assert result == "[1, 2]"
+
+ def test_multiple_think_tags_in_content(self):
+ """Multiple think tag blocks in .content are all removed."""
+ obj = MagicMock()
+ obj.content = "<think>a</think>B<think>c</think>D"
+ result = get_llm_response_text(obj)
+ assert result == "BD"
+
+ def test_think_tags_in_text_attribute(self):
+ """Think tags in .text attribute are removed too."""
+ obj = MagicMock(spec=[])
+ obj.text = "<think>reasoning</think>answer"
+ result = get_llm_response_text(obj)
+ assert result == "answer"
+
+ def test_content_with_only_think_tags(self):
+ """Content that is entirely think tags results in empty string."""
+ obj = MagicMock()
+ obj.content = "<think>all reasoning no answer</think>"
+ result = get_llm_response_text(obj)
+ assert result == ""
+
+
+# ---------------------------------------------------------------------------
+# _remove_think_tags — coverage gaps
+# ---------------------------------------------------------------------------
+
+
+class TestRemoveThinkTagsCoverage:
+ """Cover edge cases in _remove_think_tags regex processing."""
+
+ def test_multiple_paired_tags(self):
+ """Multiple separate paired think blocks."""
+ text = "<think>a</think>X<think>b</think>Y"
+ assert _remove_think_tags(text) == "XY"
+
+ def test_nested_think_tags(self):
+ """Nested think tags — outer pair consumed by DOTALL regex."""
+ text = "<think>outer<think>inner</think>still outer</think>result"
+ result = _remove_think_tags(text)
+ # The .*? with DOTALL matches from first <think> to first </think>
+ # Then orphaned tags are cleaned up
+ assert "result" in result
+ assert "<think>" not in result
+ assert "</think>" not in result
+
+ def test_only_closing_tag(self):
+ """Only a closing </think> tag is removed."""
+ assert _remove_think_tags("before</think>after") == "beforeafter"
+
+ def test_only_opening_tag(self):
+ """Only an opening <think> tag is removed."""
+ assert _remove_think_tags("before<think>after") == "beforeafter"
+
+ def test_multiple_orphaned_closing_tags(self):
+ """Multiple orphaned closing tags."""
+ text = "</think>A</think>B</think>C"
+ result = _remove_think_tags(text)
+ assert result == "ABC"
+
+ def test_think_tags_with_whitespace_inside(self):
+ """Think tags with leading/trailing whitespace inside."""
+ text = "<think> \n reasoning \n </think>answer"
+ result = _remove_think_tags(text)
+ assert result == "answer"
+
+ def test_empty_think_tags(self):
+ """Empty <think></think> tags."""
+ text = "<think></think>content"
+ result = _remove_think_tags(text)
+ assert result == "content"
+
+ def test_think_tags_case_sensitive(self):
+ """Think tags are case-sensitive — <THINK> is not removed."""
+ text = "<THINK>loud</THINK>quiet"
+ result = _remove_think_tags(text)
+ assert "<THINK>" in result
+
+ def test_think_tag_at_end_of_string(self):
+ """Think tag at the very end."""
+ text = "content<think>trailing"
+ result = _remove_think_tags(text)
+ assert "content" in result
+ assert "<think>" not in result
+
+ def test_whitespace_only_after_removal(self):
+ """Result is whitespace-only after think tag removal — stripped to empty."""
+ text = "<think>everything</think> "
+ result = _remove_think_tags(text)
+ assert result == ""
+
+ def test_think_tags_with_special_chars_inside(self):
+ """Think tags containing JSON-like content inside."""
+ text = '<think>{"reasoning": true}</think>{"answer": 42}'
+ result = _remove_think_tags(text)
+ assert result == '{"answer": 42}'
+
+
+# ---------------------------------------------------------------------------
+# _strip_code_fences — coverage gaps
+# ---------------------------------------------------------------------------
+
+
+class TestStripCodeFencesCoverage:
+ """Cover edge cases in _strip_code_fences split logic."""
+
+ def test_json_fence_no_closing_fence(self):
+ """```json without closing ``` — split("```")[0] returns everything."""
+ text = '```json\n{"key": "value"}'
+ result = _strip_code_fences(text)
+ # split("```json") -> ['', '\n{"key": "value"}']
+ # parts[1].split("```")[0] -> '\n{"key": "value"}'
+ assert '{"key": "value"}' in result
+
+ def test_json_fence_empty_content(self):
+ """```json with empty content."""
+ text = "```json\n\n```"
+ result = _strip_code_fences(text)
+ assert result == ""
+
+ def test_bare_fence_with_only_two_backtick_groups(self):
+ """Only two ``` markers — fewer than 3 parts from split, returns original."""
+ text = "some text ``` more text"
+ result = _strip_code_fences(text)
+ # split("```") gives ['some text ', ' more text'] — len < 3
+ assert result == text
+
+ def test_json_fence_with_extra_whitespace(self):
+ """```json fence with extra whitespace around content."""
+ text = '```json\n\n {"key": "value"} \n\n```'
+ result = _strip_code_fences(text)
+ assert result == '{"key": "value"}'
+
+ def test_json_fence_preferred_over_bare(self):
+ """```json fence is checked before bare ``` fence."""
+ text = '```\nbare content\n```\n```json\n{"json": true}\n```'
+ result = _strip_code_fences(text)
+ # "```json" is found first in the elif, but actually "```json" is checked
+ # first in the if branch — yes, ```json is checked first
+ # The text contains "```json", so the if branch handles it
+ # split("```json") -> ['```\nbare content\n```\n', '\n{"json": true}\n```']
+ assert '{"json": true}' in result
+
+ def test_code_fence_with_language_tag_not_json(self):
+ """```python — no ```json match, falls to bare ``` path."""
+ text = '```python\nx = {"key": "val"}\n```'
+ result = _strip_code_fences(text)
+ # split("```") gives ['', 'python\nx = {"key": "val"}\n', '']
+ # parts[1] = 'python\nx = {"key": "val"}\n'
+ assert "python" in result
+ assert '"key"' in result
+
+ def test_multiple_json_fences_first_wins(self):
+ """Multiple ```json fences — first one is extracted."""
+ text = '```json\n{"first": 1}\n```\ntext\n```json\n{"second": 2}\n```'
+ result = _strip_code_fences(text)
+ assert '{"first": 1}' in result
+
+ def test_json_fence_immediately_adjacent(self):
+ """```json``` with no content between markers."""
+ text = "```json```"
+ result = _strip_code_fences(text)
+ # split("```json") -> ['', '```']
+ # parts[1].split("```") -> ['', '']
+ # parts[1].split("```")[0] -> ''
+ assert result == ""
+
+
+# ---------------------------------------------------------------------------
+# _extract_by_brackets — coverage gaps
+# ---------------------------------------------------------------------------
+
+
+class TestExtractByBracketsCoverage:
+ """Cover edge cases in _extract_by_brackets find/rfind logic."""
+
+ def test_minimal_brackets(self):
+ """Minimal content: just {} or []."""
+ assert _extract_by_brackets("{}", "{", "}") == "{}"
+ assert _extract_by_brackets("[]", "[", "]") == "[]"
+
+ def test_single_char_content(self):
+ """Single character between brackets."""
+ assert _extract_by_brackets("{x}", "{", "}") == "{x}"
+
+ def test_brackets_at_start_and_end(self):
+ """Brackets at exact start and end of string."""
+ text = '{"key": "value"}'
+ assert _extract_by_brackets(text, "{", "}") == text
+
+ def test_multiple_close_brackets_uses_last(self):
+ """rfind finds the last closing bracket."""
+ text = '{"a": {"b": 1}} extra }'
+ result = _extract_by_brackets(text, "{", "}")
+ # find("{")=0, rfind("}")=last "}" at end
+ assert result == text
+
+ def test_multiple_open_brackets_uses_first(self):
+ """find finds the first opening bracket."""
+ text = '{ extra {"a": 1}}'
+ result = _extract_by_brackets(text, "{", "}")
+ assert result == text
+
+ def test_deeply_nested_brackets(self):
+ """Deeply nested bracket structure."""
+ text = '{"a": {"b": {"c": {"d": 1}}}}'
+ result = _extract_by_brackets(text, "{", "}")
+ assert result == text
+
+ def test_mixed_bracket_types(self):
+ """Square brackets inside curly braces."""
+ text = '{"list": [1, [2, 3], 4]}'
+ result = _extract_by_brackets(text, "{", "}")
+ assert result == text
+
+ def test_square_brackets_with_nested_objects(self):
+ """Objects inside square brackets."""
+ text = '[{"a": 1}, {"b": 2}]'
+ result = _extract_by_brackets(text, "[", "]")
+ assert result == text
+
+ def test_empty_string(self):
+ """Empty string input."""
+ assert _extract_by_brackets("", "{", "}") is None
+ assert _extract_by_brackets("", "[", "]") is None
+
+ def test_only_open_no_close(self):
+ """Only opening bracket, no closing."""
+ assert _extract_by_brackets("[no close", "[", "]") is None
+
+ def test_only_close_no_open(self):
+ """Only closing bracket, no opening."""
+ assert _extract_by_brackets("no open]", "[", "]") is None
+
+ def test_adjacent_same_position(self):
+ """Open and close at adjacent positions."""
+ text = "prefix{}suffix"
+ result = _extract_by_brackets(text, "{", "}")
+ assert result == "{}"
+
+ def test_open_equals_close_position(self):
+ """When open_char == close_char scenario (degenerate)."""
+ # Not a real use case, but tests the find/rfind logic
+ text = "x|y|z"
+ result = _extract_by_brackets(text, "|", "|")
+ # find("|")=1, rfind("|")=3, 3 > 1 -> "|y|"
+ assert result == "|y|"
+
+
+# ---------------------------------------------------------------------------
+# _clean_llm_json_artifacts — coverage gaps
+# ---------------------------------------------------------------------------
+
+
+class TestCleanLlmJsonArtifactsCoverage:
+ """Cover edge cases in _clean_llm_json_artifacts regex patterns."""
+
+ def test_trailing_comma_with_whitespace(self):
+ """Trailing comma with various whitespace before closing bracket."""
+ text = '{"a": 1 , \n }'
+ result = _clean_llm_json_artifacts(text)
+ parsed = json.loads(result)
+ assert parsed == {"a": 1}
+
+ def test_multiple_trailing_commas(self):
+ """Multiple trailing commas (nested structures)."""
+ text = '{"a": [1, 2,], "b": 3,}'
+ result = _clean_llm_json_artifacts(text)
+ parsed = json.loads(result)
+ assert parsed == {"a": [1, 2], "b": 3}
+
+ def test_comment_at_end_of_line(self):
+ """Comment at end of line with content before it."""
+ text = '{"key": "value" // this is important\n}'
+ result = _clean_llm_json_artifacts(text)
+ assert "//" not in result
+ parsed = json.loads(result)
+ assert parsed == {"key": "value"}
+
+ def test_multiple_comments_on_different_lines(self):
+ """Multiple // comments on separate lines."""
+ text = '{\n"a": 1, // first\n"b": 2 // second\n}'
+ result = _clean_llm_json_artifacts(text)
+ assert "//" not in result
+ parsed = json.loads(result)
+ assert parsed == {"a": 1, "b": 2}
+
+ def test_comment_on_empty_line(self):
+ """Comment on a line by itself."""
+ text = '{\n// this is a comment\n"a": 1\n}'
+ result = _clean_llm_json_artifacts(text)
+ assert "//" not in result
+ parsed = json.loads(result)
+ assert parsed == {"a": 1}
+
+ def test_ellipsis_at_end_of_array(self):
+ """Trailing ellipsis at end of array."""
+ text = "[1, 2, 3, ...]"
+ result = _clean_llm_json_artifacts(text)
+ assert "..." not in result
+ parsed = json.loads(result)
+ assert parsed == [1, 2, 3]
+
+ def test_ellipsis_at_start_of_array(self):
+ """Leading ellipsis at start of array — unusual but possible."""
+ text = "[..., 1, 2]"
+ result = _clean_llm_json_artifacts(text)
+ assert "..." not in result
+
+ def test_multiple_dots_more_than_three(self):
+ """More than three dots: ....."""
+ text = "[1, 2, .....]"
+ result = _clean_llm_json_artifacts(text)
+ # The regex \.\.\.+ matches 3 or more dots
+ assert "..." not in result
+
+ def test_combined_trailing_comma_and_comment(self):
+ """Both trailing comma and comment in same JSON."""
+ text = '{"a": 1, // comment\n"b": 2,}'
+ result = _clean_llm_json_artifacts(text)
+ parsed = json.loads(result)
+ assert parsed == {"a": 1, "b": 2}
+
+ def test_combined_all_artifacts(self):
+ """All artifact types combined."""
+ text = "[\n1, // first item\n2,\n...,\n]"
+ result = _clean_llm_json_artifacts(text)
+ assert "//" not in result
+ assert "..." not in result
+ parsed = json.loads(result)
+ assert parsed == [1, 2]
+
+ def test_no_artifacts_leaves_valid_json_unchanged(self):
+ """Clean JSON is not modified."""
+ text = '{"key": "value", "num": 42}'
+ assert _clean_llm_json_artifacts(text) == text
+
+ def test_single_slash_not_treated_as_comment(self):
+ """Single / is not a comment delimiter."""
+ text = '{"path": "/api/v1"}'
+ result = _clean_llm_json_artifacts(text)
+ assert "/api/v1" in result
+
+ def test_empty_object(self):
+ """Empty object is unchanged."""
+ text = "{}"
+ assert _clean_llm_json_artifacts(text) == "{}"
+
+ def test_empty_array(self):
+ """Empty array is unchanged."""
+ text = "[]"
+ assert _clean_llm_json_artifacts(text) == "[]"
+
+ def test_ellipsis_between_items_uses_first_regex(self):
+ """Ellipsis between commas uses the comma-preserving regex."""
+ text = "[1, ..., 2]"
+ result = _clean_llm_json_artifacts(text)
+ assert "..." not in result
+ # First regex: ',\\s*"?\\.\\.\\.+"?\\s*,' -> ','
+ # Should produce [1, 2] ideally
+
+ def test_quoted_ellipsis_between_items(self):
+ """Quoted ellipsis "..." between items."""
+ text = '[1, "...", 2]'
+ result = _clean_llm_json_artifacts(text)
+ assert "..." not in result
+
+
+# ---------------------------------------------------------------------------
+# extract_json — comprehensive coverage
+# ---------------------------------------------------------------------------
+
+
+class TestExtractJsonCoverage:
+ """Cover remaining code paths in extract_json."""
+
+ # --- Cleaning pipeline ordering ---
+
+ def test_code_fences_stripped_before_think_tags(self):
+ """Code fences are stripped, then think tags removed."""
+ text = '```json\n<think>reasoning</think>{"key": "value"}\n```'
+ result = extract_json(text)
+ assert result == {"key": "value"}
+
+ def test_think_tags_inside_code_fence(self):
+ """Think tags inside code fence content."""
+ text = '```json\n{"key": "<think>not removed</think>"}\n```'
+ # After fence stripping: {"key": "<think>not removed</think>"}
+ # After think tag removal: {"key": ""}
+ result = extract_json(text)
+ assert result is not None
+ assert isinstance(result, dict)
+
+ # --- Direct parse success paths ---
+
+ def test_direct_parse_dict_no_expected_type(self):
+ """Direct parse succeeds with dict, no expected_type."""
+ result = extract_json('{"a": 1}')
+ assert result == {"a": 1}
+
+ def test_direct_parse_list_no_expected_type(self):
+ """Direct parse succeeds with list, no expected_type."""
+ result = extract_json("[1, 2, 3]")
+ assert result == [1, 2, 3]
+
+ def test_direct_parse_matching_expected_type(self):
+ """Direct parse succeeds and matches expected_type."""
+ result = extract_json('{"a": 1}', expected_type=dict)
+ assert result == {"a": 1}
+
+ def test_direct_parse_type_mismatch_falls_to_bracket_extraction(self):
+ """Direct parse succeeds as dict but expected list — falls through."""
+ text = '{"items": [1, 2]}'
+ result = extract_json(text, expected_type=list)
+ # Direct parse gives dict, but expected list
+ # Bracket extraction with "[" first finds [1, 2]
+ assert result == [1, 2]
+
+ # --- Bracket extraction with artifact cleaning ---
+
+ def test_bracket_extraction_then_artifact_cleaning(self):
+ """Bracket extraction finds JSON but it has artifacts, cleaning fixes it."""
+ text = 'Result: {"a": 1, "b": 2,} end'
+ result = extract_json(text)
+ assert result == {"a": 1, "b": 2}
+
+ def test_bracket_extraction_with_comment_artifact(self):
+ """Bracket extraction finds JSON with // comment, cleaning fixes it."""
+ text = 'Output: {"a": 1 // comment\n} done'
+ result = extract_json(text)
+ assert result == {"a": 1}
+
+ def test_bracket_extraction_with_ellipsis_artifact(self):
+ """Bracket extraction finds array with ellipsis, cleaning fixes it."""
+ text = "Items: [1, 2, 3, ...] end"
+ result = extract_json(text, expected_type=list)
+ assert result == [1, 2, 3]
+
+ # --- expected_type bracket ordering ---
+
+ def test_expected_type_list_tries_square_first(self):
+ """expected_type=list makes bracket_pairs start with ('[', ']')."""
+ # Both valid JSON types present
+ text = 'prefix {"d": 1} middle [10, 20] suffix'
+ result = extract_json(text, expected_type=list)
+ assert isinstance(result, list)
+ assert result == [10, 20]
+
+ def test_expected_type_dict_tries_curly_first(self):
+ """expected_type=dict makes bracket_pairs start with ('{', '}')."""
+ text = 'prefix [10, 20] middle {"d": 1} suffix'
+ result = extract_json(text, expected_type=dict)
+ assert isinstance(result, dict)
+
+ def test_no_expected_type_tries_curly_first(self):
+ """No expected_type tries curly braces first (default ordering)."""
+ text = '{"a": 1}'
+ result = extract_json(text, expected_type=None)
+ assert result == {"a": 1}
+
+ # --- Edge cases for None/empty ---
+
+ def test_none_input(self):
+ assert extract_json(None) is None
+
+ def test_empty_string(self):
+ assert extract_json("") is None
+
+ def test_whitespace_tabs_newlines(self):
+ assert extract_json("\t\n \r\n") is None
+
+ def test_only_text_no_json(self):
+ assert extract_json("This is just plain text without any JSON.") is None
+
+ # --- Scalar JSON values ---
+
+ def test_json_number_returns_none(self):
+ """JSON number is valid JSON but not dict/list."""
+ assert extract_json("42") is None
+
+ def test_json_string_returns_none(self):
+ """JSON string is valid JSON but not dict/list."""
+ assert extract_json('"hello"') is None
+
+ def test_json_boolean_returns_none(self):
+ """JSON boolean is valid JSON but not dict/list."""
+ assert extract_json("true") is None
+
+ def test_json_null_returns_none(self):
+ """JSON null is valid JSON but not dict/list."""
+ assert extract_json("null") is None
+
+ # --- Complex nested JSON ---
+
+ def test_deeply_nested_dict(self):
+ text = '{"a": {"b": {"c": {"d": {"e": 1}}}}}'
+ result = extract_json(text)
+ assert result == {"a": {"b": {"c": {"d": {"e": 1}}}}}
+
+ def test_list_of_lists(self):
+ text = "[[1, 2], [3, 4], [5, 6]]"
+ result = extract_json(text)
+ assert result == [[1, 2], [3, 4], [5, 6]]
+
+ def test_mixed_nested_structure(self):
+ text = '[{"name": "A", "values": [1, 2]}, {"name": "B", "values": [3]}]'
+ result = extract_json(text, expected_type=list)
+ assert len(result) == 2
+ assert result[0]["name"] == "A"
+ assert result[1]["values"] == [3]
+
+ # --- Unicode and special characters ---
+
+ def test_unicode_keys_and_values(self):
+ text = '{"name": "日本語", "city": "Zürich"}'
+ result = extract_json(text)
+ assert result == {"name": "日本語", "city": "Zürich"}
+
+ def test_escaped_quotes_in_values(self):
+ text = '{"quote": "He said \\"hello\\""}'
+ result = extract_json(text)
+ assert result == {"quote": 'He said "hello"'}
+
+ def test_newlines_in_values(self):
+ text = '{"text": "line1\\nline2"}'
+ result = extract_json(text)
+ assert result == {"text": "line1\nline2"}
+
+ # --- Real LLM output patterns ---
+
+ def test_deepseek_think_then_code_fence(self):
+ """DeepSeek-style: long think block then code fence."""
+ text = (
+ "<think>\nLet me analyze this carefully.\n"
+ "The user wants a JSON response.\n"
+ "I should structure it as follows.\n"
+ "</think>\n\n"
+ '```json\n{"answer": "structured response", "confidence": 0.95}\n```'
+ )
+ result = extract_json(text)
+ assert result == {"answer": "structured response", "confidence": 0.95}
+
+ def test_chatgpt_style_prose_then_json(self):
+ """ChatGPT-style: conversational intro then JSON."""
+ text = (
+ "Based on my analysis, here is the structured output:\n\n"
+ '{"summary": "key findings", "relevance_scores": [0.9, 0.7, 0.5]}'
+ )
+ result = extract_json(text)
+ assert result["summary"] == "key findings"
+ assert result["relevance_scores"] == [0.9, 0.7, 0.5]
+
+ def test_llm_numbering_before_json(self):
+ """LLM provides numbered reasoning then JSON."""
+ text = (
+ "1. First I considered X\n"
+ "2. Then I evaluated Y\n"
+ "3. My conclusion:\n\n"
+ '{"result": "Y is better", "score": 8.5}'
+ )
+ result = extract_json(text)
+ assert result == {"result": "Y is better", "score": 8.5}
+
+ def test_json_with_markdown_bold_in_prose(self):
+ """JSON embedded in text with markdown formatting."""
+ text = '**Result**: {"key": "value"}\n\n*Note: this is important*'
+ result = extract_json(text)
+ assert result == {"key": "value"}
+
+ # --- Artifact cleaning integration ---
+
+ def test_trailing_comma_in_nested_structure(self):
+ """Trailing commas in nested object."""
+ text = '{"outer": {"inner": [1, 2,], "key": "val",},}'
+ result = extract_json(text)
+ assert result == {"outer": {"inner": [1, 2], "key": "val"}}
+
+ def test_comments_in_multiline_json(self):
+ """Comments in multiline JSON object."""
+ text = '{\n "name": "test", // the name\n "value": 42 // the value\n}'
+ result = extract_json(text)
+ assert result == {"name": "test", "value": 42}
+
+ def test_ellipsis_in_large_array_pattern(self):
+ """LLM truncates array with ellipsis."""
+ text = "[1, 2, 3, ...]"
+ result = extract_json(text, expected_type=list)
+ assert result == [1, 2, 3]
+
+ # --- Multiple JSON objects in text ---
+
+ def test_two_separate_dicts_in_prose(self):
+ """Two separate dicts — bracket extraction spans both (may fail)."""
+ text = '{"a": 1} some text {"b": 2}'
+ result = extract_json(text)
+ # find("{")=0, rfind("}")=end -> spans both, invalid JSON -> None
+ assert result is None
+
+ def test_dict_then_list_expected_dict(self):
+ """Dict then list, expected_type=dict."""
+ text = '{"a": 1}\n[1, 2, 3]'
+ result = extract_json(text, expected_type=dict)
+ # Bracket extraction for {} spans from first { to last }
+ # which is just {"a": 1} since last } is at pos 7
+ # Actually rfind("}") finds the } at position 7 (last one)
+ # Direct parse fails because the whole text isn't valid JSON
+ # Then bracket extraction for "{" finds {"a": 1}\n[1, 2, 3]
+ # Wait — find("{")=0, rfind("}")=7, text[0:8] = '{"a": 1}'
+ assert result == {"a": 1}
+
+ # --- Completely invalid inputs ---
+
+ def test_html_without_json(self):
+ assert extract_json("<html><body>No JSON</body></html>") is None
+
+ def test_xml_without_json(self):
+ assert extract_json("<root><item>No JSON</item></root>") is None
+
+ def test_brackets_with_non_json_content(self):
+ """Brackets containing non-JSON content."""
+ assert extract_json("{this is not: json: at: all}") is None
+
+ def test_square_brackets_with_non_json(self):
+ """Square brackets with non-JSON content."""
+ assert extract_json("[not, valid, json, either]") is None
+
+ # --- Whitespace handling ---
+
+ def test_json_with_leading_trailing_whitespace(self):
+ """JSON with lots of whitespace around it."""
+ text = ' \n\n {"key": "value"} \n\n '
+ result = extract_json(text)
+ assert result == {"key": "value"}
+
+ def test_json_with_internal_whitespace(self):
+ """JSON with lots of internal whitespace."""
+ text = '{\n\n "key" : "value" \n\n}'
+ result = extract_json(text)
+ assert result == {"key": "value"}
+
+ # --- Empty structures ---
+
+ def test_empty_dict(self):
+ result = extract_json("{}")
+ assert result == {}
+
+ def test_empty_list(self):
+ result = extract_json("[]")
+ assert result == []
+
+ def test_empty_dict_expected_dict(self):
+ result = extract_json("{}", expected_type=dict)
+ assert result == {}
+
+ def test_empty_list_expected_list(self):
+ result = extract_json("[]", expected_type=list)
+ assert result == []
+
+ def test_empty_dict_expected_list_returns_none(self):
+ """Empty dict when list expected — falls through."""
+ result = extract_json("{}", expected_type=list)
+ # Direct parse gives dict, type mismatch
+ # Bracket extraction for "[]" finds nothing
+ assert result is None
+
+ def test_empty_list_expected_dict_returns_none(self):
+ """Empty list when dict expected — falls through."""
+ result = extract_json("[]", expected_type=dict)
+ assert result is None
+
+ # --- Large/complex real patterns ---
+
+ def test_search_result_format(self):
+ """Typical search result JSON format from LDR."""
+ text = (
+ "```json\n"
+ "{\n"
+ ' "queries": [\n'
+ ' {"query": "machine learning basics", "priority": 1},\n'
+ ' {"query": "neural network architecture", "priority": 2}\n'
+ " ],\n"
+ ' "reasoning": "These queries cover the fundamentals"\n'
+ "}\n"
+ "```"
+ )
+ result = extract_json(text)
+ assert result is not None
+ assert len(result["queries"]) == 2
+ assert result["queries"][0]["priority"] == 1
+
+ def test_relevance_indices_format(self):
+ """Typical relevance indices list from LDR."""
+ text = (
+ "<think>Let me rank these by relevance...</think>\n"
+ "```json\n[0, 3, 1, 7, 2]\n```"
+ )
+ result = extract_json(text, expected_type=list)
+ assert result == [0, 3, 1, 7, 2]
+
+ def test_boolean_and_null_values(self):
+ """JSON with boolean and null values."""
+ text = '{"active": true, "deleted": false, "metadata": null}'
+ result = extract_json(text)
+ assert result == {"active": True, "deleted": False, "metadata": None}
+
+ def test_numeric_values_int_and_float(self):
+ """JSON with integer and float values."""
+ text = '{"count": 42, "score": 3.14, "negative": -7}'
+ result = extract_json(text)
+ assert result == {"count": 42, "score": 3.14, "negative": -7}
+
+ def test_artifact_cleaning_only_on_bracket_extracted_text(self):
+ """Artifact cleaning is only attempted on bracket-extracted text,
+ not on the original full text."""
+ # This text has trailing comma but is surrounded by prose
+ text = "Result: [1, 2, 3,] which is the answer"
+ result = extract_json(text, expected_type=list)
+ assert result == [1, 2, 3]
+
+ def test_cleaning_does_not_run_when_bracket_parse_succeeds(self):
+ """If bracket-extracted text parses fine, cleaning is skipped."""
+ text = 'Prefix: {"a": 1, "b": 2} suffix'
+ result = extract_json(text)
+ assert result == {"a": 1, "b": 2}
+
+ def test_cleaning_skipped_when_cleaned_equals_extracted(self):
+ """If cleaning produces the same string, parsing is not retried."""
+ # Invalid JSON that cleaning cannot fix
+ text = "{key: value}"
+ result = extract_json(text)
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# Integration: get_llm_response_text -> extract_json pipeline
+# ---------------------------------------------------------------------------
+
+
+class TestPipelineIntegration:
+ """Test the common pattern of extracting text then parsing JSON."""
+
+ def test_aimessage_to_json(self):
+ """Simulate LangChain AIMessage -> extract_json pipeline."""
+ msg = MagicMock()
+ msg.content = '```json\n{"answer": "yes"}\n```'
+ text = get_llm_response_text(msg)
+ result = extract_json(text)
+ assert result == {"answer": "yes"}
+
+ def test_think_tags_cleaned_before_json_extraction(self):
+ """Think tags removed by get_llm_response_text, then JSON extracted."""
+ msg = MagicMock()
+ msg.content = '<think>long reasoning</think>{"result": true}'
+ text = get_llm_response_text(msg)
+ result = extract_json(text)
+ assert result == {"result": True}
+
+ def test_none_response_produces_none_json(self):
+ """None response -> empty string -> None JSON."""
+ text = get_llm_response_text(None)
+ result = extract_json(text)
+ assert result is None
+
+ def test_complex_deepseek_pipeline(self):
+ """Full DeepSeek-style response through the pipeline."""
+ msg = MagicMock()
+ msg.content = (
+ "<think>\nI need to analyze the search results.\n"
+ "Result 1 is most relevant.\n"
+ "Result 3 is partially relevant.\n"
+ "</think>\n"
+ "```json\n"
+ "[0, 2]\n"
+ "```"
+ )
+ text = get_llm_response_text(msg)
+ result = extract_json(text, expected_type=list)
+ assert result == [0, 2]
diff --git a/tests/utilities/test_search_utilities_coverage.py b/tests/utilities/test_search_utilities_coverage.py
new file mode 100644
index 0000000000..105a8b9d9e
--- /dev/null
+++ b/tests/utilities/test_search_utilities_coverage.py
@@ -0,0 +1,438 @@
+"""
+Comprehensive coverage tests for search_utilities.py.
+
+Focuses on gaps not covered by existing test files:
+- Nested think tags (multiple levels, interleaved)
+- Orphaned tags in various positions
+- Empty/whitespace-only strings through every function
+- URL deduplication with index merging semantics
+- Citation numbering: exact format of [indices] and (source nr: ...) output
+- format_findings end-to-end: multiple findings with sources, all-sources footer
+- print_search_results integration
+"""
+
+from local_deep_research.utilities.search_utilities import (
+ extract_links_from_search_results,
+ format_findings,
+ format_links_to_markdown,
+ print_search_results,
+ remove_think_tags,
+)
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# remove_think_tags — nested / interleaved / edge patterns
+# ═══════════════════════════════════════════════════════════════════════════
+
+
+class TestRemoveThinkTagsNested:
+ """Deeply-nested and interleaved think tag patterns."""
+
+ def test_double_nested_tags_fully_removed(self):
+ """<think>outer<think>inner</think>middle</think> leaves no tags."""
+ text = "A <think>outer <think>inner</think> middle</think> B"
+ result = remove_think_tags(text)
+ assert "<think>" not in result
+ assert "</think>" not in result
+ assert "A" in result
+ assert "B" in result
+
+ def test_triple_nested_tags(self):
+ """Three levels of nesting: all tags removed, but non-greedy regex
+ leaves residual text between matched pairs. The key invariant is
+ that no <think> or </think> tags survive."""
+ text = "<think>L1 <think>L2 <think>L3</think> L2</think> L1</think>keep"
+ result = remove_think_tags(text)
+ assert "<think>" not in result
+ assert "</think>" not in result
+ # The non-greedy .*? pairs the first <think> with the innermost
+ # </think>, so intermediate text leaks out. Document that behavior:
+ assert "keep" in result
+
+ def test_adjacent_think_blocks(self):
+ """Two adjacent think blocks with no gap."""
+ text = "<think>first</think><think>second</think>visible"
+ result = remove_think_tags(text)
+ assert result == "visible"
+
+ def test_interleaved_content_between_think_blocks(self):
+ """Content between multiple think blocks is preserved."""
+ text = "<think>a</think>ONE<think>b</think>TWO<think>c</think>"
+ result = remove_think_tags(text)
+ assert result == "ONETWO"
+
+ def test_only_orphaned_opening_tags(self):
+ """Multiple orphaned opening tags removed."""
+ text = "keep <think> this <think> too"
+ result = remove_think_tags(text)
+ assert result == "keep this too"
+
+ def test_only_orphaned_closing_tags(self):
+ """Multiple orphaned closing tags removed."""
+ text = "keep </think> this </think> too"
+ result = remove_think_tags(text)
+ assert result == "keep this too"
+
+ def test_orphan_close_before_paired_block(self):
+ """Orphan close tag before a valid paired block."""
+ text = "</think>prefix <think>hidden</think> suffix"
+ result = remove_think_tags(text)
+ assert result == "prefix suffix"
+
+ def test_orphan_open_after_paired_block(self):
+ """Orphan open tag after a valid paired block."""
+ text = "prefix <think>hidden</think> suffix <think>trailing"
+ result = remove_think_tags(text)
+ assert result == "prefix suffix trailing"
+
+
+class TestRemoveThinkTagsEmptyAndWhitespace:
+ """Empty, whitespace-only, and tag-only inputs."""
+
+ def test_empty_string(self):
+ assert remove_think_tags("") == ""
+
+ def test_whitespace_only(self):
+ assert remove_think_tags(" \n\t ") == ""
+
+ def test_only_paired_tags_with_whitespace_content(self):
+ assert remove_think_tags("<think> \n </think>") == ""
+
+ def test_only_orphan_open(self):
+ assert remove_think_tags("<think>") == ""
+
+ def test_only_orphan_close(self):
+ assert remove_think_tags("</think>") == ""
+
+ def test_newlines_around_tags(self):
+ text = "\n\n<think>hidden\n</think>\n\n"
+ result = remove_think_tags(text)
+ assert result == ""
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# extract_links_from_search_results — edge cases
+# ═══════════════════════════════════════════════════════════════════════════
+
+
+class TestExtractLinksEdges:
+ """Additional edge cases for link extraction."""
+
+ def test_whitespace_only_title_skipped(self):
+ """A title of only spaces should be treated as empty after strip."""
+ results = [
+ {"title": " ", "link": "https://example.com", "index": "1"}
+ ]
+ links = extract_links_from_search_results(results)
+ assert len(links) == 0
+
+ def test_whitespace_only_link_skipped(self):
+ """A link of only spaces should be treated as empty after strip."""
+ results = [{"title": "Title", "link": " ", "index": "1"}]
+ links = extract_links_from_search_results(results)
+ assert len(links) == 0
+
+ def test_none_index_defaults_to_empty_string(self):
+ """None index becomes empty string, not None."""
+ results = [{"title": "T", "link": "https://x.com", "index": None}]
+ links = extract_links_from_search_results(results)
+ assert links[0]["index"] == ""
+
+ def test_missing_index_key_defaults_to_empty_string(self):
+ """Missing index key defaults to empty string."""
+ results = [{"title": "T", "link": "https://x.com"}]
+ links = extract_links_from_search_results(results)
+ assert links[0]["index"] == ""
+
+ def test_preserves_insertion_order(self):
+ """Output order matches input order."""
+ results = [
+ {"title": "C", "link": "https://c.com", "index": "3"},
+ {"title": "A", "link": "https://a.com", "index": "1"},
+ {"title": "B", "link": "https://b.com", "index": "2"},
+ ]
+ links = extract_links_from_search_results(results)
+ assert [item["title"] for item in links] == ["C", "A", "B"]
+
+ def test_large_batch(self):
+ """Handles a moderately large list without error."""
+ results = [
+ {
+ "title": f"T{i}",
+ "link": f"https://example.com/{i}",
+ "index": str(i),
+ }
+ for i in range(200)
+ ]
+ links = extract_links_from_search_results(results)
+ assert len(links) == 200
+
+ def test_extra_keys_ignored(self):
+ """Extra keys in the dict are silently ignored."""
+ results = [
+ {
+ "title": "T",
+ "link": "https://x.com",
+ "index": "1",
+ "snippet": "desc",
+ "score": 0.9,
+ }
+ ]
+ links = extract_links_from_search_results(results)
+ assert len(links) == 1
+ assert "snippet" not in links[0]
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# format_links_to_markdown — citation numbering & deduplication
+# ═══════════════════════════════════════════════════════════════════════════
+
+
+class TestCitationNumbering:
+ """Verify exact citation format: [indices] Title (source nr: indices) URL."""
+
+ def test_single_index_format(self):
+ """Single-index link produces [1] Title (source nr: 1)."""
+ links = [{"title": "Page", "url": "https://p.com", "index": "1"}]
+ result = format_links_to_markdown(links)
+ assert "[1] Page (source nr: 1)" in result
+ assert "URL: https://p.com" in result
+
+ def test_multiple_indices_sorted(self):
+ """Duplicate URL indices are sorted: [1, 3] not [3, 1]."""
+ links = [
+ {"title": "Page", "url": "https://p.com", "index": "3"},
+ {"title": "Page", "url": "https://p.com", "index": "1"},
+ ]
+ result = format_links_to_markdown(links)
+ assert "[1, 3]" in result
+ assert "(source nr: 1, 3)" in result
+
+ def test_three_indices_deduplicated_and_sorted(self):
+ """[5, 2, 2, 9] becomes [2, 5, 9] after dedup+sort."""
+ links = [
+ {"title": "X", "url": "https://x.com", "index": "5"},
+ {"title": "X", "url": "https://x.com", "index": "2"},
+ {"title": "X", "url": "https://x.com", "index": "2"},
+ {"title": "X", "url": "https://x.com", "index": "9"},
+ ]
+ result = format_links_to_markdown(links)
+ assert result.count("https://x.com") == 1
+ assert "[2, 5, 9]" in result
+
+ def test_empty_index_still_produces_bracket(self):
+ """A link with empty string index still produces brackets."""
+ links = [{"title": "T", "url": "https://t.com", "index": ""}]
+ result = format_links_to_markdown(links)
+ assert "[] T" in result
+
+ def test_url_dedup_uses_first_title(self):
+ """When URLs collide, the first title seen is used."""
+ links = [
+ {"title": "First Title", "url": "https://same.com", "index": "1"},
+ {"title": "Second Title", "url": "https://same.com", "index": "2"},
+ ]
+ result = format_links_to_markdown(links)
+ assert "First Title" in result
+ assert "Second Title" not in result
+
+ def test_different_urls_kept_separate(self):
+ """Different URLs are separate entries."""
+ links = [
+ {"title": "A", "url": "https://a.com", "index": "1"},
+ {"title": "B", "url": "https://b.com", "index": "2"},
+ ]
+ result = format_links_to_markdown(links)
+ assert "https://a.com" in result
+ assert "https://b.com" in result
+ lines_with_url = [
+ line for line in result.splitlines() if "URL:" in line
+ ]
+ assert len(lines_with_url) == 2
+
+ def test_link_key_fallback_produces_same_format(self):
+ """Using 'link' key instead of 'url' produces the same output format."""
+ links = [{"title": "T", "link": "https://t.com", "index": "7"}]
+ result = format_links_to_markdown(links)
+ assert "[7] T (source nr: 7)" in result
+ assert "URL: https://t.com" in result
+
+ def test_no_url_and_no_link_key_skipped(self):
+ """Entry with neither 'url' nor 'link' key is skipped."""
+ links = [
+ {"title": "Ghost", "index": "1"},
+ {"title": "Real", "url": "https://r.com", "index": "2"},
+ ]
+ result = format_links_to_markdown(links)
+ assert "Ghost" not in result
+ assert "Real" in result
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# format_findings — end-to-end with sources
+# ═══════════════════════════════════════════════════════════════════════════
+
+
+class TestFormatFindingsEndToEnd:
+ """End-to-end format_findings scenarios combining all sub-functions."""
+
+ def test_all_sources_footer_aggregates_across_findings(self):
+ """ALL SOURCES section at the end contains links from every finding."""
+ findings = [
+ {
+ "phase": "Phase 1",
+ "content": "C1",
+ "search_results": [
+ {"title": "S1", "link": "https://s1.com", "index": "1"}
+ ],
+ },
+ {
+ "phase": "Phase 2",
+ "content": "C2",
+ "search_results": [
+ {"title": "S2", "link": "https://s2.com", "index": "2"}
+ ],
+ },
+ ]
+ result = format_findings(findings, "Synth", {})
+ # The ALL SOURCES section appears after the last separator
+ all_sources_section = result.split("ALL SOURCES")[-1]
+ assert "s1.com" in all_sources_section
+ assert "s2.com" in all_sources_section
+
+ def test_no_all_sources_when_no_search_results(self):
+ """When no finding has search_results, ALL SOURCES section is absent."""
+ findings = [
+ {"phase": "P", "content": "C", "search_results": []},
+ ]
+ result = format_findings(findings, "Synth", {})
+ assert "ALL SOURCES" not in result
+
+ def test_sources_used_in_section_per_finding(self):
+ """Each finding with search results gets its own SOURCES USED section."""
+ findings = [
+ {
+ "phase": "P1",
+ "content": "C1",
+ "search_results": [
+ {"title": "A", "link": "https://a.com", "index": "1"}
+ ],
+ },
+ {
+ "phase": "P2",
+ "content": "C2",
+ "search_results": [
+ {"title": "B", "link": "https://b.com", "index": "2"}
+ ],
+ },
+ ]
+ result = format_findings(findings, "Synth", {})
+ assert result.count("SOURCES USED IN THIS SECTION") == 2
+
+ def test_finding_without_search_results_key(self):
+ """Finding dict missing 'search_results' key entirely does not crash."""
+ findings = [{"phase": "P", "content": "C"}]
+ result = format_findings(findings, "Synth", {})
+ assert "C" in result
+ assert "SOURCES USED IN THIS SECTION" not in result
+
+ def test_followup_question_not_displayed_when_already_shown(self):
+ """When phase parsing succeeds, the finding['question'] is NOT also shown."""
+ findings = [
+ {
+ "phase": "Follow-up Iteration 1.1",
+ "content": "Answer",
+ "question": "Fallback Q",
+ "search_results": [],
+ }
+ ]
+ questions = {1: ["Matched question"]}
+ result = format_findings(findings, "Synth", questions)
+ # The matched question should appear
+ assert "Matched question" in result
+ # The fallback question should NOT appear because phase parsing succeeded
+ assert "Fallback Q" not in result
+
+ def test_subquery_out_of_range_falls_back_to_question_field(self):
+ """Sub-query 99 with only 2 sub-queries falls back to finding['question']."""
+ findings = [
+ {
+ "phase": "Sub-query 99",
+ "content": "C",
+ "question": "My fallback",
+ "search_results": [],
+ }
+ ]
+ questions = {0: ["SQ1", "SQ2"]}
+ result = format_findings(findings, "Synth", questions)
+ assert "My fallback" in result
+
+ def test_followup_single_dot_part_not_two(self):
+ """Phase 'Follow-up Iteration 1' (no dot) has len(parts)==1, not 2."""
+ findings = [
+ {
+ "phase": "Follow-up Iteration 1",
+ "content": "C",
+ "question": "Fallback",
+ "search_results": [],
+ }
+ ]
+ questions = {1: ["Q1"]}
+ result = format_findings(findings, "Synth", questions)
+ # Since split('.') gives ['1'] with len==1, parsing fails, fallback shown
+ assert "Fallback" in result
+
+ def test_separator_line_between_findings(self):
+ """80-char underscore separator appears between findings."""
+ findings = [
+ {"phase": "A", "content": "CA", "search_results": []},
+ {"phase": "B", "content": "CB", "search_results": []},
+ ]
+ result = format_findings(findings, "S", {})
+ assert "_" * 80 in result
+
+ def test_question_numbering_in_iteration_section(self):
+ """Questions are numbered 1., 2., 3. within each iteration."""
+ questions = {1: ["Alpha", "Beta", "Gamma"]}
+ result = format_findings([], "S", questions)
+ assert "1. Alpha" in result
+ assert "2. Beta" in result
+ assert "3. Gamma" in result
+
+ def test_multiple_iterations_each_numbered_from_one(self):
+ """Each iteration re-starts numbering at 1."""
+ questions = {1: ["Q1a", "Q1b"], 2: ["Q2a"]}
+ result = format_findings([], "S", questions)
+ # Iteration 1
+ assert "1. Q1a" in result
+ assert "2. Q1b" in result
+ # Iteration 2 starts from 1 again
+ iter2_section = result.split("Iteration 2")[1]
+ assert "1. Q2a" in iter2_section
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# print_search_results — integration
+# ═══════════════════════════════════════════════════════════════════════════
+
+
+class TestPrintSearchResultsIntegration:
+ """print_search_results should not raise for any reasonable input."""
+
+ def test_valid_results(self):
+ print_search_results(
+ [{"title": "T", "link": "https://t.com", "index": "1"}]
+ )
+
+ def test_empty_list(self):
+ print_search_results([])
+
+ def test_none_input(self):
+ """None input should not crash (extract_links_from_search_results handles it)."""
+ print_search_results(None)
+
+ def test_results_without_index(self):
+ print_search_results([{"title": "T", "link": "https://t.com"}])
+
+ def test_results_with_none_values(self):
+ print_search_results([{"title": None, "link": None, "index": None}])
diff --git a/tests/utilities/test_sqlcipher_compat_coverage.py b/tests/utilities/test_sqlcipher_compat_coverage.py
new file mode 100644
index 0000000000..9ace0909eb
--- /dev/null
+++ b/tests/utilities/test_sqlcipher_compat_coverage.py
@@ -0,0 +1,263 @@
+"""
+Comprehensive tests for local_deep_research.database.sqlcipher_compat module.
+
+Tests the compatibility layer logic, feature detection, and ImportError
+behavior when sqlcipher3 is unavailable.
+"""
+
+import importlib
+import sys
+import types
+from unittest import mock
+
+import pytest
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+MODULE_PATH = "local_deep_research.database.sqlcipher_compat"
+
+
+def _fresh_import():
+ """Re-import sqlcipher_compat so module-level code re-executes."""
+ mod = importlib.import_module(MODULE_PATH)
+ importlib.reload(mod)
+ return mod
+
+
+# ---------------------------------------------------------------------------
+# 1. Successful import path – sqlcipher3 is available
+# ---------------------------------------------------------------------------
+
+
+class TestGetSqlcipherModuleSuccess:
+ """When sqlcipher3 can be imported, get_sqlcipher_module should return it."""
+
+ def test_returns_sqlcipher3_module(self):
+ """get_sqlcipher_module returns the sqlcipher3 module object."""
+ fake_sqlcipher3 = types.ModuleType("sqlcipher3")
+ fake_sqlcipher3.dbapi2 = object()
+
+ with mock.patch.dict(sys.modules, {"sqlcipher3": fake_sqlcipher3}):
+ mod = _fresh_import()
+ result = mod.get_sqlcipher_module()
+ assert result is fake_sqlcipher3
+
+ def test_returned_module_has_dbapi2(self):
+ """The returned module should carry a dbapi2 attribute."""
+ fake_sqlcipher3 = types.ModuleType("sqlcipher3")
+ sentinel = object()
+ fake_sqlcipher3.dbapi2 = sentinel
+
+ with mock.patch.dict(sys.modules, {"sqlcipher3": fake_sqlcipher3}):
+ mod = _fresh_import()
+ result = mod.get_sqlcipher_module()
+ assert hasattr(result, "dbapi2")
+ assert result.dbapi2 is sentinel
+
+ def test_multiple_calls_return_same_module(self):
+ """Repeated calls should consistently return the same module."""
+ fake_sqlcipher3 = types.ModuleType("sqlcipher3")
+ fake_sqlcipher3.dbapi2 = object()
+
+ with mock.patch.dict(sys.modules, {"sqlcipher3": fake_sqlcipher3}):
+ mod = _fresh_import()
+ r1 = mod.get_sqlcipher_module()
+ r2 = mod.get_sqlcipher_module()
+ assert r1 is r2
+
+ def test_returns_module_with_connect_attribute(self):
+ """Validates that a module with a connect() callable works fine."""
+ fake_sqlcipher3 = types.ModuleType("sqlcipher3")
+ fake_sqlcipher3.dbapi2 = types.ModuleType("sqlcipher3.dbapi2")
+ fake_sqlcipher3.connect = lambda db: None
+
+ with mock.patch.dict(sys.modules, {"sqlcipher3": fake_sqlcipher3}):
+ mod = _fresh_import()
+ result = mod.get_sqlcipher_module()
+ assert callable(result.connect)
+
+
+# ---------------------------------------------------------------------------
+# 2. ImportError path – sqlcipher3 is NOT available
+# ---------------------------------------------------------------------------
+
+
+class TestGetSqlcipherModuleImportError:
+ """When sqlcipher3 cannot be imported, get_sqlcipher_module must raise."""
+
+ def _block_sqlcipher3(self):
+ """Return a context manager that makes `import sqlcipher3` fail."""
+ original_import = (
+ __builtins__.__import__
+ if hasattr(__builtins__, "__import__")
+ else __import__
+ )
+
+ def _guarded_import(name, *args, **kwargs):
+ if name == "sqlcipher3":
+ raise ImportError("No module named 'sqlcipher3'")
+ return original_import(name, *args, **kwargs)
+
+ return mock.patch("builtins.__import__", side_effect=_guarded_import)
+
+ def test_raises_import_error(self):
+ """An ImportError must be raised when sqlcipher3 is absent."""
+ with self._block_sqlcipher3():
+ # Remove sqlcipher3 from sys.modules if cached
+ with mock.patch.dict(sys.modules, {"sqlcipher3": None}):
+ mod = _fresh_import()
+ with pytest.raises(ImportError):
+ mod.get_sqlcipher_module()
+
+ def test_error_message_mentions_sqlcipher3(self):
+ """The error message should mention sqlcipher3."""
+ with self._block_sqlcipher3():
+ with mock.patch.dict(sys.modules, {"sqlcipher3": None}):
+ mod = _fresh_import()
+ with pytest.raises(ImportError, match="sqlcipher3"):
+ mod.get_sqlcipher_module()
+
+ def test_error_message_mentions_pdm_install(self):
+ """The error message should mention pdm install."""
+ with self._block_sqlcipher3():
+ with mock.patch.dict(sys.modules, {"sqlcipher3": None}):
+ mod = _fresh_import()
+ with pytest.raises(ImportError, match="pdm install"):
+ mod.get_sqlcipher_module()
+
+ def test_error_message_mentions_system_library(self):
+ """The error message should mention SQLCipher system library."""
+ with self._block_sqlcipher3():
+ with mock.patch.dict(sys.modules, {"sqlcipher3": None}):
+ mod = _fresh_import()
+ with pytest.raises(
+ ImportError, match="SQLCipher system library"
+ ):
+ mod.get_sqlcipher_module()
+
+
+# ---------------------------------------------------------------------------
+# 3. Feature detection – module attributes
+# ---------------------------------------------------------------------------
+
+
+class TestModuleAttributes:
+ """Verify the public API surface of the compat module."""
+
+ def test_get_sqlcipher_module_is_callable(self):
+ """get_sqlcipher_module must be a callable."""
+ mod = importlib.import_module(MODULE_PATH)
+ assert callable(mod.get_sqlcipher_module)
+
+ def test_module_has_docstring(self):
+ """The module should have a docstring describing its purpose."""
+ mod = importlib.import_module(MODULE_PATH)
+ assert mod.__doc__ is not None
+ assert "SQLCipher" in mod.__doc__
+
+ def test_function_has_docstring(self):
+ """get_sqlcipher_module should have a docstring."""
+ mod = importlib.import_module(MODULE_PATH)
+ assert mod.get_sqlcipher_module.__doc__ is not None
+
+ def test_docstring_documents_return_type(self):
+ """The function docstring should mention Returns."""
+ mod = importlib.import_module(MODULE_PATH)
+ assert "Returns" in mod.get_sqlcipher_module.__doc__
+
+ def test_docstring_documents_raises(self):
+ """The function docstring should mention Raises / ImportError."""
+ mod = importlib.import_module(MODULE_PATH)
+ assert "ImportError" in mod.get_sqlcipher_module.__doc__
+
+
+# ---------------------------------------------------------------------------
+# 4. Platform compat – the module works regardless of which package provides
+# the sqlcipher3 namespace (sqlcipher3-binary vs sqlcipher3 source build).
+# ---------------------------------------------------------------------------
+
+
+class TestPlatformCompatibility:
+ """Simulates different package backends behind the sqlcipher3 name."""
+
+ def test_binary_package(self):
+ """Simulate sqlcipher3-binary providing the sqlcipher3 namespace."""
+ fake = types.ModuleType("sqlcipher3")
+ fake._binary = True # marker attribute
+ fake.dbapi2 = types.ModuleType("sqlcipher3.dbapi2")
+
+ with mock.patch.dict(sys.modules, {"sqlcipher3": fake}):
+ mod = _fresh_import()
+ result = mod.get_sqlcipher_module()
+ assert result._binary is True
+
+ def test_source_package(self):
+ """Simulate sqlcipher3 built from source."""
+ fake = types.ModuleType("sqlcipher3")
+ fake._source = True
+ fake.dbapi2 = types.ModuleType("sqlcipher3.dbapi2")
+
+ with mock.patch.dict(sys.modules, {"sqlcipher3": fake}):
+ mod = _fresh_import()
+ result = mod.get_sqlcipher_module()
+ assert result._source is True
+
+ def test_module_identity_preserved(self):
+ """The compat layer should not wrap or proxy the module."""
+ fake = types.ModuleType("sqlcipher3")
+ fake.dbapi2 = object()
+
+ with mock.patch.dict(sys.modules, {"sqlcipher3": fake}):
+ mod = _fresh_import()
+ result = mod.get_sqlcipher_module()
+ # Must be the exact same object, not a wrapper
+ assert result is fake
+ assert type(result) is types.ModuleType
+
+
+# ---------------------------------------------------------------------------
+# 5. Edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestEdgeCases:
+ """Assorted edge-case scenarios."""
+
+ def test_import_error_is_not_generic_exception(self):
+ """The raised exception must be ImportError, not a generic Exception."""
+ with mock.patch.dict(sys.modules, {"sqlcipher3": None}):
+ mod = _fresh_import()
+ with pytest.raises(ImportError) as exc_info:
+ mod.get_sqlcipher_module()
+ assert type(exc_info.value) is ImportError
+
+ def test_no_side_effects_on_sys_modules(self):
+ """Calling get_sqlcipher_module should not add unexpected entries."""
+ fake = types.ModuleType("sqlcipher3")
+ fake.dbapi2 = object()
+
+ before_keys = set(sys.modules.keys())
+ with mock.patch.dict(sys.modules, {"sqlcipher3": fake}):
+ mod = _fresh_import()
+ mod.get_sqlcipher_module()
+ after_keys = set(sys.modules.keys())
+ # Only the compat module itself (from reload) may appear; no others
+ unexpected = after_keys - before_keys - {MODULE_PATH}
+ # Filter out __pycache__ or bytecode artifacts
+ unexpected = {k for k in unexpected if "sqlcipher" in k.lower()}
+ assert not unexpected, f"Unexpected modules added: {unexpected}"
+
+ def test_reloadable(self):
+ """The module should be safely reloadable."""
+ fake = types.ModuleType("sqlcipher3")
+ fake.dbapi2 = object()
+
+ with mock.patch.dict(sys.modules, {"sqlcipher3": fake}):
+ mod = _fresh_import()
+ # Reload again
+ importlib.reload(mod)
+ result = mod.get_sqlcipher_module()
+ assert result is fake
diff --git a/tests/utilities/test_type_utils_coverage.py b/tests/utilities/test_type_utils_coverage.py
new file mode 100644
index 0000000000..e20c14f8d8
--- /dev/null
+++ b/tests/utilities/test_type_utils_coverage.py
@@ -0,0 +1,372 @@
+"""
+Comprehensive coverage tests for utilities/type_utils.py.
+
+Uses parametrized tests for systematic coverage of the to_bool() function
+across all code paths: bool input, string input, None input, and fallback
+bool() conversion for other types.
+"""
+
+import pytest
+
+from local_deep_research.utilities.type_utils import to_bool
+
+
+# ---------------------------------------------------------------------------
+# 1. Boolean passthrough (isinstance(value, bool) branch)
+# ---------------------------------------------------------------------------
+class TestToBoolBooleanPassthrough:
+ """Bool values must pass through unchanged, before any other check."""
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (True, True),
+ (False, False),
+ ],
+ )
+ def test_bool_passthrough(self, value, expected):
+ assert to_bool(value) is expected
+
+ def test_bool_true_ignores_default(self):
+ """Default should be irrelevant when a bool is passed."""
+ assert to_bool(True, default=False) is True
+ assert to_bool(False, default=True) is False
+
+ def test_bool_is_checked_before_int(self):
+ """bool is a subclass of int; ensure the bool branch fires first."""
+ # If bool were not checked first, True (== 1) would fall through
+ # to the generic bool(value) path and still work, but we want the
+ # early-return for clarity.
+ result = to_bool(True)
+ assert result is True
+ assert type(result) is bool
+
+
+# ---------------------------------------------------------------------------
+# 2. String truthy values (isinstance(value, str) branch — True results)
+# ---------------------------------------------------------------------------
+class TestToBoolStringTruthy:
+ """Strings in the truthy set: 'true', '1', 'yes', 'on', 'enabled'."""
+
+ @pytest.mark.parametrize(
+ "value",
+ [
+ "true",
+ "True",
+ "TRUE",
+ "tRuE",
+ "trUE",
+ "1",
+ "yes",
+ "Yes",
+ "YES",
+ "yES",
+ "on",
+ "On",
+ "ON",
+ "oN",
+ "enabled",
+ "Enabled",
+ "ENABLED",
+ "eNaBlEd",
+ ],
+ )
+ def test_truthy_strings(self, value):
+ result = to_bool(value)
+ assert result is True
+ assert type(result) is bool
+
+ @pytest.mark.parametrize(
+ "value",
+ [
+ " true",
+ "true ",
+ " true ",
+ "\ttrue",
+ "true\t",
+ "\ttrue\t",
+ "\ntrue",
+ "true\n",
+ "\ntrue\n",
+ "\r\ntrue\r\n",
+ " \t yes \n ",
+ " 1 ",
+ "\ton\t",
+ " enabled ",
+ ],
+ )
+ def test_truthy_strings_with_whitespace(self, value):
+ """Whitespace around truthy strings should be stripped."""
+ assert to_bool(value) is True
+
+
+# ---------------------------------------------------------------------------
+# 3. String falsy values (isinstance(value, str) branch — False results)
+# ---------------------------------------------------------------------------
+class TestToBoolStringFalsy:
+ """Strings NOT in the truthy set should return False."""
+
+ @pytest.mark.parametrize(
+ "value",
+ [
+ "false",
+ "False",
+ "FALSE",
+ "0",
+ "no",
+ "No",
+ "NO",
+ "off",
+ "Off",
+ "OFF",
+ "disabled",
+ "Disabled",
+ "DISABLED",
+ "", # empty string
+ " ", # whitespace only
+ "\t\n", # whitespace only (tabs/newlines)
+ "random",
+ "null",
+ "undefined",
+ "NaN",
+ "none",
+ "None",
+ "maybe",
+ "nope",
+ "absolutely",
+ ],
+ )
+ def test_falsy_strings(self, value):
+ result = to_bool(value)
+ assert result is False
+ assert type(result) is bool
+
+ @pytest.mark.parametrize(
+ "value",
+ [
+ "enable", # missing 'd'
+ "tru", # truncated
+ "ye", # truncated
+ "yess", # extra char
+ "truee", # extra char
+ "onoff", # compound
+ "enabled_on", # with suffix
+ "true_value", # with suffix
+ "x_true", # with prefix
+ "is_on", # with prefix
+ "honest", # contains 'on'
+ "python", # contains 'on'
+ "yesterday", # contains 'yes'
+ "condition", # contains 'on'
+ ],
+ )
+ def test_partial_or_substring_matches_are_falsy(self, value):
+ """Only exact matches (after strip+lower) should be truthy."""
+ assert to_bool(value) is False
+
+ @pytest.mark.parametrize(
+ "value",
+ [
+ "2",
+ "42",
+ "-1",
+ "00",
+ "01",
+ "001",
+ "+1",
+ "3.14",
+ "0.0",
+ "1.0",
+ ],
+ )
+ def test_numeric_strings_other_than_one(self, value):
+ """Only '1' is truthy; other numeric strings are not."""
+ assert to_bool(value) is False
+
+ @pytest.mark.parametrize(
+ "value",
+ [
+ '"true"',
+ "'true'",
+ '"1"',
+ "'yes'",
+ ],
+ )
+ def test_quoted_strings_are_falsy(self, value):
+ """Quotes around truthy values should NOT match."""
+ assert to_bool(value) is False
+
+ def test_default_ignored_for_empty_string(self):
+ """Empty string is a string, not None — default must be ignored."""
+ assert to_bool("", default=True) is False
+
+ def test_default_ignored_for_falsy_string(self):
+ assert to_bool("false", default=True) is False
+ assert to_bool("0", default=True) is False
+
+
+# ---------------------------------------------------------------------------
+# 4. None handling (value is None branch)
+# ---------------------------------------------------------------------------
+class TestToBoolNone:
+ """None should return the default parameter."""
+
+ def test_none_default_false(self):
+ assert to_bool(None) is False
+
+ def test_none_default_true(self):
+ assert to_bool(None, default=True) is True
+
+ def test_none_explicit_default_false(self):
+ assert to_bool(None, default=False) is False
+
+ def test_none_return_type(self):
+ result = to_bool(None, default=True)
+ assert type(result) is bool
+
+
+# ---------------------------------------------------------------------------
+# 5. Fallback bool() conversion (int, float, collections, objects)
+# ---------------------------------------------------------------------------
+class TestToBoolFallback:
+ """For non-bool, non-str, non-None types, Python's bool() is used."""
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (0, False),
+ (1, True),
+ (-1, True),
+ (42, True),
+ (100, True),
+ (0.0, False),
+ (1.0, True),
+ (0.5, True),
+ (-0.1, True),
+ (0.001, True),
+ (3.14, True),
+ ],
+ )
+ def test_numeric_values(self, value, expected):
+ result = to_bool(value)
+ assert result is expected
+ assert type(result) is bool
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ([], False),
+ ([1], True),
+ ([0], True), # list with falsy element is still non-empty
+ ({}, False),
+ ({"k": "v"}, True),
+ (set(), False),
+ ({1, 2}, True),
+ ((), False),
+ ((1,), True),
+ (frozenset(), False),
+ (frozenset({1}), True),
+ (b"", False),
+ (b"x", True),
+ (bytearray(), False),
+ (bytearray(b"x"), True),
+ ],
+ )
+ def test_collection_values(self, value, expected):
+ assert to_bool(value) is expected
+
+ def test_custom_object_truthy(self):
+ class AlwaysTrue:
+ def __bool__(self):
+ return True
+
+ assert to_bool(AlwaysTrue()) is True
+
+ def test_custom_object_falsy(self):
+ class AlwaysFalse:
+ def __bool__(self):
+ return False
+
+ assert to_bool(AlwaysFalse()) is False
+
+ def test_plain_object_is_truthy(self):
+ """Objects without __bool__ override default to truthy."""
+
+ class Plain:
+ pass
+
+ assert to_bool(Plain()) is True
+
+ def test_object_with_len_zero(self):
+ """Objects with __len__ returning 0 are falsy via bool()."""
+
+ class EmptyContainer:
+ def __len__(self):
+ return 0
+
+ assert to_bool(EmptyContainer()) is False
+
+ def test_object_with_len_nonzero(self):
+ class NonEmptyContainer:
+ def __len__(self):
+ return 5
+
+ assert to_bool(NonEmptyContainer()) is True
+
+ def test_default_ignored_for_non_none_falsy(self):
+ """Default only applies to None, not to other falsy values."""
+ assert to_bool(0, default=True) is False
+ assert to_bool([], default=True) is False
+ assert to_bool({}, default=True) is False
+ assert to_bool(0.0, default=True) is False
+
+
+# ---------------------------------------------------------------------------
+# 6. Type priority / branch ordering
+# ---------------------------------------------------------------------------
+class TestToBoolTypePriority:
+ """Verify the intended branch ordering: bool > str > None > fallback."""
+
+ def test_bool_before_int(self):
+ """bool is subclass of int; must hit bool branch, not fallback."""
+ # Both branches give same answer, but we verify the bool branch
+ # fires by confirming True/False are identity-equal.
+ assert to_bool(True) is True
+ assert to_bool(False) is False
+
+ def test_string_before_none(self):
+ """A string is never None, so string branch should fire."""
+ assert to_bool("") is False # string branch, not None branch
+
+ def test_none_before_fallback(self):
+ """None should use the default, not bool(None) which is False."""
+ # With default=True, if None fell through to bool(None) we'd get
+ # False — but the None branch should return True.
+ assert to_bool(None, default=True) is True
+
+
+# ---------------------------------------------------------------------------
+# 7. Return-type guarantees
+# ---------------------------------------------------------------------------
+class TestToBoolReturnType:
+ """Every code path must return an actual bool, never a truthy/falsy proxy."""
+
+ @pytest.mark.parametrize(
+ "value, kwargs",
+ [
+ (True, {}),
+ (False, {}),
+ ("true", {}),
+ ("false", {}),
+ ("", {}),
+ (None, {}),
+ (None, {"default": True}),
+ (1, {}),
+ (0, {}),
+ ([], {}),
+ ([1], {}),
+ ],
+ )
+ def test_return_is_bool(self, value, kwargs):
+ result = to_bool(value, **kwargs)
+ assert type(result) is bool
diff --git a/tests/utilities/test_url_utils_coverage.py b/tests/utilities/test_url_utils_coverage.py
new file mode 100644
index 0000000000..759c796eb3
--- /dev/null
+++ b/tests/utilities/test_url_utils_coverage.py
@@ -0,0 +1,597 @@
+"""
+Comprehensive coverage tests for url_utils.normalize_url.
+
+Focuses on exhaustive path coverage including:
+- http/https scheme passthrough
+- Malformed scheme correction (http: / https: without //)
+- Double-slash prefix stripping
+- Hostname extraction for private vs public classification
+- IPv6 bracket handling
+- Edge cases: empty, whitespace, None, special characters
+"""
+
+import pytest
+from unittest.mock import patch
+
+
+# ---------------------------------------------------------------------------
+# Helper – import once per test to keep tests independent of import order
+# ---------------------------------------------------------------------------
+def _normalize(url):
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ return normalize_url(url)
+
+
+def _is_private(hostname):
+ from local_deep_research.security.network_utils import is_private_ip
+
+ return is_private_ip(hostname)
+
+
+# ===================================================================
+# 1. Proper scheme passthrough (early return on line 34)
+# ===================================================================
+class TestSchemePassthrough:
+ """URLs that already have http:// or https:// are returned verbatim."""
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "http://localhost",
+ "http://localhost:11434",
+ "http://127.0.0.1:8080",
+ "http://192.168.1.1/api/v1",
+ "http://[::1]:11434",
+ "http://example.com?q=1&r=2#frag",
+ "http://user:pass@host:9200/path",
+ ],
+ )
+ def test_http_urls_returned_unchanged(self, url):
+ assert _normalize(url) == url
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "https://example.com",
+ "https://api.openai.com/v1/chat",
+ "https://example.com:8443",
+ "https://example.com/search?q=hello",
+ "https://[2001:db8::1]:443/path",
+ ],
+ )
+ def test_https_urls_returned_unchanged(self, url):
+ assert _normalize(url) == url
+
+ def test_http_triple_slash_passthrough(self):
+ """http:/// still starts with http:// so the early return fires."""
+ assert _normalize("http:///some/path") == "http:///some/path"
+
+ def test_https_triple_slash_passthrough(self):
+ assert _normalize("https:///some/path") == "https:///some/path"
+
+
+# ===================================================================
+# 2. Malformed scheme correction (lines 38-43)
+# ===================================================================
+class TestMalformedScheme:
+ """URLs like http:host or https:host get slashes inserted."""
+
+ def test_http_colon_hostname(self):
+ assert _normalize("http:example.com") == "http://example.com"
+
+ def test_https_colon_hostname(self):
+ assert _normalize("https:example.com") == "https://example.com"
+
+ def test_http_colon_hostname_with_port(self):
+ assert _normalize("http:example.com:8080") == "http://example.com:8080"
+
+ def test_https_colon_hostname_with_path(self):
+ assert (
+ _normalize("https:example.com/api/v1")
+ == "https://example.com/api/v1"
+ )
+
+ def test_http_colon_localhost(self):
+ assert _normalize("http:localhost:11434") == "http://localhost:11434"
+
+ def test_https_colon_ip(self):
+ assert _normalize("https:8.8.8.8") == "https://8.8.8.8"
+
+ def test_http_colon_private_ip(self):
+ assert _normalize("http:192.168.1.1:3000") == "http://192.168.1.1:3000"
+
+ def test_malformed_preserves_query(self):
+ assert (
+ _normalize("http:example.com/p?a=1") == "http://example.com/p?a=1"
+ )
+
+
+# ===================================================================
+# 3. Double-slash prefix (lines 46-48)
+# ===================================================================
+class TestDoubleSlashPrefix:
+ """Protocol-relative URLs starting with // are stripped then re-schemed."""
+
+ def test_double_slash_public_host(self):
+ result = _normalize("//example.com")
+ assert result == "https://example.com"
+
+ def test_double_slash_public_with_port(self):
+ result = _normalize("//example.com:443")
+ assert result == "https://example.com:443"
+
+ def test_double_slash_localhost(self):
+ result = _normalize("//localhost:8080")
+ assert result == "http://localhost:8080"
+
+ def test_double_slash_private_ip(self):
+ result = _normalize("//192.168.1.1:9200")
+ assert result == "http://192.168.1.1:9200"
+
+ def test_double_slash_with_path(self):
+ result = _normalize("//example.com/api/v1")
+ assert result == "https://example.com/api/v1"
+
+ def test_double_slash_127(self):
+ result = _normalize("//127.0.0.1:11434")
+ assert result == "http://127.0.0.1:11434"
+
+
+# ===================================================================
+# 4. Localhost / loopback addresses
+# ===================================================================
+class TestLocalhost:
+ """localhost and 127.0.0.1 should always get http://."""
+
+ def test_localhost_bare(self):
+ assert _normalize("localhost") == "http://localhost"
+
+ def test_localhost_with_port(self):
+ assert _normalize("localhost:11434") == "http://localhost:11434"
+
+ def test_localhost_with_path(self):
+ assert _normalize("localhost:8080/api") == "http://localhost:8080/api"
+
+ def test_127_0_0_1_bare(self):
+ assert _normalize("127.0.0.1") == "http://127.0.0.1"
+
+ def test_127_0_0_1_with_port(self):
+ assert _normalize("127.0.0.1:11434") == "http://127.0.0.1:11434"
+
+ def test_0_0_0_0(self):
+ assert _normalize("0.0.0.0") == "http://0.0.0.0"
+
+ def test_0_0_0_0_with_port(self):
+ assert _normalize("0.0.0.0:5000") == "http://0.0.0.0:5000"
+
+
+# ===================================================================
+# 5. RFC 1918 private IP ranges
+# ===================================================================
+class TestPrivateIPs:
+ """Private IPs (10.x, 172.16-31.x, 192.168.x) should get http://."""
+
+ @pytest.mark.parametrize(
+ "ip",
+ [
+ "10.0.0.1",
+ "10.255.255.255",
+ "172.16.0.1",
+ "172.31.255.255",
+ "192.168.0.1",
+ "192.168.255.254",
+ ],
+ )
+ def test_private_ip_gets_http(self, ip):
+ result = _normalize(ip)
+ assert result == f"http://{ip}"
+
+ @pytest.mark.parametrize(
+ "ip",
+ [
+ "10.0.0.1:8080",
+ "172.16.0.50:3000",
+ "192.168.1.100:8888",
+ ],
+ )
+ def test_private_ip_with_port_gets_http(self, ip):
+ result = _normalize(ip)
+ assert result == f"http://{ip}"
+
+
+# ===================================================================
+# 6. Public IPs and hostnames -> https
+# ===================================================================
+class TestPublicHosts:
+ """Public IPs and hostnames should get https://."""
+
+ @pytest.mark.parametrize(
+ "host",
+ [
+ "8.8.8.8",
+ "1.1.1.1",
+ "example.com",
+ "api.openai.com",
+ "sub.domain.example.org",
+ ],
+ )
+ def test_public_host_gets_https(self, host):
+ result = _normalize(host)
+ assert result == f"https://{host}"
+
+ def test_public_ip_with_port(self):
+ assert _normalize("8.8.8.8:53") == "https://8.8.8.8:53"
+
+ def test_public_hostname_with_port(self):
+ assert _normalize("example.com:443") == "https://example.com:443"
+
+
+# ===================================================================
+# 7. IPv6 addresses
+# ===================================================================
+class TestIPv6:
+ """IPv6 addresses in brackets."""
+
+ def test_ipv6_loopback_gets_http(self):
+ assert _normalize("[::1]") == "http://[::1]"
+
+ def test_ipv6_loopback_with_port(self):
+ assert _normalize("[::1]:8080") == "http://[::1]:8080"
+
+ def test_ipv6_link_local_gets_http(self):
+ result = _normalize("[fe80::1]:8080")
+ assert result.startswith("http://")
+
+ def test_ipv6_private_fc00_gets_http(self):
+ result = _normalize("[fc00::1]:9200")
+ assert result.startswith("http://")
+
+ def test_ipv6_public_gets_https(self):
+ result = _normalize("[2001:4860:4860::8888]")
+ assert result.startswith("https://")
+
+ def test_ipv6_public_with_port_gets_https(self):
+ result = _normalize("[2607:f8b0::1]:443")
+ assert result.startswith("https://")
+ assert "[2607:f8b0::1]" in result
+
+ def test_ipv6_with_existing_http_scheme(self):
+ assert _normalize("http://[::1]:11434") == "http://[::1]:11434"
+
+ def test_ipv6_with_existing_https_scheme(self):
+ url = "https://[2001:db8::1]:443"
+ assert _normalize(url) == url
+
+
+# ===================================================================
+# 8. .local mDNS domains
+# ===================================================================
+class TestLocalDomains:
+ """mDNS .local domains should be treated as private."""
+
+ def test_dot_local_gets_http(self):
+ assert _normalize("myserver.local") == "http://myserver.local"
+
+ def test_dot_local_with_port(self):
+ assert _normalize("myserver.local:8080") == "http://myserver.local:8080"
+
+ def test_dot_local_with_path(self):
+ assert (
+ _normalize("printer.local/status") == "http://printer.local/status"
+ )
+
+ def test_not_local_suffix(self):
+ """localnet.com is NOT a .local domain."""
+ assert _normalize("localnet.com") == "https://localnet.com"
+
+
+# ===================================================================
+# 9. Link-local addresses (169.254.x.x)
+# ===================================================================
+class TestLinkLocal:
+ def test_link_local_ipv4(self):
+ assert _normalize("169.254.0.1") == "http://169.254.0.1"
+
+ def test_link_local_ipv4_with_port(self):
+ assert _normalize("169.254.1.100:3000") == "http://169.254.1.100:3000"
+
+
+# ===================================================================
+# 10. Private/public boundary cases
+# ===================================================================
+class TestBoundary:
+ """Boundary values at the edges of private ranges."""
+
+ def test_172_15_is_public(self):
+ """172.15.x.x is NOT in 172.16.0.0/12 private range."""
+ assert _normalize("172.15.255.255") == "https://172.15.255.255"
+
+ def test_172_16_is_private(self):
+ assert _normalize("172.16.0.0") == "http://172.16.0.0"
+
+ def test_172_31_is_private(self):
+ assert _normalize("172.31.255.255") == "http://172.31.255.255"
+
+ def test_172_32_is_public(self):
+ """172.32.x.x is beyond the 172.16.0.0/12 range."""
+ assert _normalize("172.32.0.0") == "https://172.32.0.0"
+
+ def test_11_0_0_1_is_public(self):
+ """11.0.0.1 is outside the 10.0.0.0/8 range."""
+ assert _normalize("11.0.0.1") == "https://11.0.0.1"
+
+ def test_192_167_is_public(self):
+ assert _normalize("192.167.1.1") == "https://192.167.1.1"
+
+
+# ===================================================================
+# 11. Whitespace handling
+# ===================================================================
+class TestWhitespace:
+ def test_leading_whitespace(self):
+ assert _normalize(" https://example.com") == "https://example.com"
+
+ def test_trailing_whitespace(self):
+ assert _normalize("https://example.com ") == "https://example.com"
+
+ def test_both_whitespace(self):
+ assert _normalize(" https://example.com ") == "https://example.com"
+
+ def test_whitespace_around_bare_host(self):
+ assert _normalize(" localhost:8080 ") == "http://localhost:8080"
+
+ def test_tab_whitespace(self):
+ assert _normalize("\thttps://example.com\t") == "https://example.com"
+
+ def test_whitespace_only_returns_bare_scheme(self):
+ """Whitespace-only passes initial truthy check, strips to empty."""
+ # After strip, raw_url is "" which is falsy but the check is before strip
+ # Actually: " " is truthy, strip makes it "", then no early return,
+ # hostname becomes "" which is_private_ip returns False -> https://
+ result = _normalize(" ")
+ assert result == "https://"
+
+
+# ===================================================================
+# 12. Empty / None / invalid input
+# ===================================================================
+class TestInvalidInput:
+ def test_empty_string_raises(self):
+ with pytest.raises(ValueError, match="(?i)empty"):
+ _normalize("")
+
+ def test_none_raises(self):
+ with pytest.raises((ValueError, TypeError, AttributeError)):
+ _normalize(None)
+
+
+# ===================================================================
+# 13. URL preservation (paths, query strings, fragments, userinfo)
+# ===================================================================
+class TestUrlPreservation:
+ """Everything after the host should be preserved intact."""
+
+ def test_path_preserved(self):
+ assert (
+ _normalize("http://example.com/a/b/c") == "http://example.com/a/b/c"
+ )
+
+ def test_query_preserved(self):
+ assert (
+ _normalize("http://example.com?a=1&b=2")
+ == "http://example.com?a=1&b=2"
+ )
+
+ def test_fragment_preserved(self):
+ assert (
+ _normalize("http://example.com/p#sec") == "http://example.com/p#sec"
+ )
+
+ def test_encoded_chars_preserved(self):
+ url = "http://example.com/path%20with%20spaces"
+ assert _normalize(url) == url
+
+ def test_userinfo_preserved(self):
+ url = "http://user:[email protected]:9200/path"
+ assert _normalize(url) == url
+
+ def test_complex_query_preserved(self):
+ url = "https://example.com/search?q=hello+world&lang=en&page=2#results"
+ assert _normalize(url) == url
+
+ def test_path_added_to_bare_host(self):
+ result = _normalize("example.com/api/v1/data")
+ assert result == "https://example.com/api/v1/data"
+
+
+# ===================================================================
+# 14. is_private_ip direct tests (re-exported from url_utils)
+# ===================================================================
+class TestIsPrivateIpReExport:
+ """Verify is_private_ip is accessible from url_utils and works."""
+
+ def test_reexport_available(self):
+ from local_deep_research.utilities.url_utils import is_private_ip
+
+ assert callable(is_private_ip)
+
+ def test_reexport_matches_original(self):
+ from local_deep_research.utilities.url_utils import (
+ is_private_ip as via_utils,
+ )
+ from local_deep_research.security.network_utils import (
+ is_private_ip as via_security,
+ )
+
+ for host in [
+ "localhost",
+ "127.0.0.1",
+ "10.0.0.1",
+ "8.8.8.8",
+ "example.com",
+ ]:
+ assert via_utils(host) == via_security(host), f"Mismatch for {host}"
+
+
+# ===================================================================
+# 15. is_private_ip detailed tests
+# ===================================================================
+class TestIsPrivateIp:
+ """Directly test the is_private_ip function."""
+
+ @pytest.mark.parametrize(
+ "hostname",
+ ["localhost", "127.0.0.1", "[::1]", "0.0.0.0"],
+ )
+ def test_known_localhost_values(self, hostname):
+ assert _is_private(hostname) is True
+
+ @pytest.mark.parametrize(
+ "hostname",
+ [
+ "10.0.0.1",
+ "10.255.255.255",
+ "172.16.0.1",
+ "172.31.255.255",
+ "192.168.0.1",
+ "192.168.255.254",
+ ],
+ )
+ def test_rfc1918_private(self, hostname):
+ assert _is_private(hostname) is True
+
+ @pytest.mark.parametrize(
+ "hostname",
+ ["8.8.8.8", "1.1.1.1", "172.15.0.1", "172.32.0.1"],
+ )
+ def test_public_ips(self, hostname):
+ assert _is_private(hostname) is False
+
+ def test_ipv6_loopback_bracketed(self):
+ assert _is_private("[::1]") is True
+
+ def test_ipv6_link_local(self):
+ assert _is_private("fe80::1") is True
+
+ def test_ipv6_private_fc00(self):
+ assert _is_private("fc00::1") is True
+
+ def test_ipv6_public(self):
+ assert _is_private("2001:4860:4860::8888") is False
+
+ def test_dot_local_domain(self):
+ assert _is_private("printer.local") is True
+
+ def test_non_local_domain(self):
+ assert _is_private("example.com") is False
+
+ def test_empty_string(self):
+ assert _is_private("") is False
+
+ def test_bracketed_ipv6_private(self):
+ """Bracketed fc00:: should be private."""
+ assert _is_private("[fc00::1]") is True
+
+ def test_169_254_link_local(self):
+ assert _is_private("169.254.1.1") is True
+
+
+# ===================================================================
+# 16. Real-world usage patterns
+# ===================================================================
+class TestRealWorldPatterns:
+ """URLs commonly seen in local-deep-research configuration."""
+
+ def test_ollama_default(self):
+ assert _normalize("localhost:11434") == "http://localhost:11434"
+
+ def test_ollama_with_path(self):
+ assert (
+ _normalize("localhost:11434/api/generate")
+ == "http://localhost:11434/api/generate"
+ )
+
+ def test_searxng_local(self):
+ assert _normalize("192.168.1.100:8888") == "http://192.168.1.100:8888"
+
+ def test_docker_internal(self):
+ assert _normalize("172.17.0.2:5000") == "http://172.17.0.2:5000"
+
+ def test_openai_api(self):
+ assert _normalize("api.openai.com") == "https://api.openai.com"
+
+ def test_already_correct_ollama(self):
+ assert _normalize("http://localhost:11434") == "http://localhost:11434"
+
+ def test_already_correct_openai(self):
+ url = "https://api.openai.com/v1/chat/completions"
+ assert _normalize(url) == url
+
+ def test_elasticsearch_local(self):
+ assert _normalize("localhost:9200") == "http://localhost:9200"
+
+ def test_vllm_local(self):
+ assert _normalize("0.0.0.0:8000") == "http://0.0.0.0:8000"
+
+
+# ===================================================================
+# 17. Mock-based tests for explicit branch coverage
+# ===================================================================
+class TestWithMockedPrivateIp:
+ """Use mocks to guarantee we hit both branches of the scheme decision."""
+
+ def test_private_branch_returns_http(self):
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=True,
+ ):
+ assert _normalize("anyhost:1234") == "http://anyhost:1234"
+
+ def test_public_branch_returns_https(self):
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=False,
+ ):
+ assert _normalize("anyhost:1234") == "https://anyhost:1234"
+
+ def test_double_slash_private_branch(self):
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=True,
+ ):
+ assert _normalize("//somehost") == "http://somehost"
+
+ def test_double_slash_public_branch(self):
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=False,
+ ):
+ assert _normalize("//somehost") == "https://somehost"
+
+ def test_ipv6_bracket_extraction_calls_is_private_with_brackets(self):
+ """When a bracketed IPv6 is found, the hostname includes brackets."""
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=True,
+ ) as mock_ip:
+ _normalize("[::1]:8080")
+ mock_ip.assert_called_once_with("[::1]")
+
+ def test_hostname_extraction_splits_on_colon(self):
+ """Hostname is extracted before : for non-IPv6."""
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=False,
+ ) as mock_ip:
+ _normalize("myhost:9999")
+ mock_ip.assert_called_once_with("myhost")
+
+ def test_hostname_extraction_splits_on_slash(self):
+ """Hostname is extracted before / when no port."""
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=False,
+ ) as mock_ip:
+ _normalize("myhost/some/path")
+ mock_ip.assert_called_once_with("myhost")
diff --git a/tests/web/auth/test_auth_coverage.py b/tests/web/auth/test_auth_coverage.py
new file mode 100644
index 0000000000..06cf5f2558
--- /dev/null
+++ b/tests/web/auth/test_auth_coverage.py
@@ -0,0 +1,734 @@
+"""Comprehensive tests for auth-related pure logic.
+
+Covers:
+- PasswordValidator (strength validation, requirements)
+- AccountLockoutManager (lock/unlock, threshold, expiry, eviction)
+- URLValidator (safe URLs, redirect validation, scheme checks, DOI, sanitize)
+- sanitize_for_log / strip_control_chars
+- SessionManager (create, validate, expire, destroy, cleanup, user queries)
+"""
+
+import datetime
+import time
+from datetime import UTC, timedelta, timezone
+
+import pytest
+
+from local_deep_research.security.account_lockout import AccountLockoutManager
+from local_deep_research.security.log_sanitizer import (
+ sanitize_for_log,
+ strip_control_chars,
+)
+from local_deep_research.security.password_validator import PasswordValidator
+from local_deep_research.security.url_validator import (
+ URLValidationError,
+ URLValidator,
+)
+from local_deep_research.web.auth.session_manager import SessionManager
+
+
+# ======================================================================
+# PasswordValidator
+# ======================================================================
+
+
+class TestPasswordValidator:
+ """Tests for PasswordValidator.validate_strength and get_requirements."""
+
+ def test_valid_password(self):
+ assert PasswordValidator.validate_strength("securepass1") == []
+
+ def test_too_short(self):
+ errors = PasswordValidator.validate_strength("abc1")
+ assert any("at least 8 characters" in e for e in errors)
+
+ def test_no_lowercase(self):
+ errors = PasswordValidator.validate_strength("ABCDEFG1")
+ assert any("lowercase" in e for e in errors)
+
+ def test_no_digit(self):
+ errors = PasswordValidator.validate_strength("abcdefgh")
+ assert any("digit" in e for e in errors)
+
+ def test_empty_password(self):
+ errors = PasswordValidator.validate_strength("")
+ assert (
+ len(errors) >= 2
+ ) # too short + no lowercase + no digit (at least 2)
+
+ def test_all_failures(self):
+ errors = PasswordValidator.validate_strength("AB")
+ assert len(errors) == 3
+
+ def test_exactly_8_chars_valid(self):
+ assert PasswordValidator.validate_strength("abcdefg1") == []
+
+ def test_requirements_returns_list(self):
+ reqs = PasswordValidator.get_requirements()
+ assert isinstance(reqs, list)
+ assert len(reqs) >= 3
+
+ def test_requirements_mention_length(self):
+ reqs = PasswordValidator.get_requirements()
+ assert any("8" in r for r in reqs)
+
+ def test_unicode_letters_do_not_count_as_lowercase(self):
+ # Only ASCII lowercase a-z counts
+ errors = PasswordValidator.validate_strength("ÉÈÜÖ12345678")
+ assert any("lowercase" in e for e in errors)
+
+ def test_digit_anywhere(self):
+ assert PasswordValidator.validate_strength("aaaaaaaa1") == []
+ assert PasswordValidator.validate_strength("1aaaaaaaa") == []
+
+ def test_special_chars_only(self):
+ errors = PasswordValidator.validate_strength("!@#$%^&*")
+ assert any("lowercase" in e for e in errors)
+ assert any("digit" in e for e in errors)
+
+
+# ======================================================================
+# AccountLockoutManager
+# ======================================================================
+
+
+class TestAccountLockoutManager:
+ """Tests for AccountLockoutManager lock/unlock/eviction logic."""
+
+ def _make_manager(self, threshold=3, lockout_minutes=15):
+ return AccountLockoutManager(
+ threshold=threshold, lockout_minutes=lockout_minutes
+ )
+
+ def test_not_locked_initially(self):
+ mgr = self._make_manager()
+ assert mgr.is_locked("alice") is False
+
+ def test_lock_after_threshold(self):
+ mgr = self._make_manager(threshold=3)
+ for _ in range(3):
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is True
+
+ def test_not_locked_below_threshold(self):
+ mgr = self._make_manager(threshold=3)
+ mgr.record_failure("alice")
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is False
+
+ def test_success_clears_failures(self):
+ mgr = self._make_manager(threshold=3)
+ mgr.record_failure("alice")
+ mgr.record_failure("alice")
+ mgr.record_success("alice")
+ # After clearing, need 3 more to lock
+ mgr.record_failure("alice")
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is False
+
+ def test_success_unlocks(self):
+ mgr = self._make_manager(threshold=2)
+ mgr.record_failure("alice")
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is True
+ mgr.record_success("alice")
+ assert mgr.is_locked("alice") is False
+
+ def test_lockout_expires(self):
+ mgr = self._make_manager(threshold=1, lockout_minutes=0)
+ mgr.record_failure("alice")
+ # lockout_minutes=0 means the lock is already in the past
+ # Force the lock time to past
+ with mgr._lock:
+ entry = mgr._state.get("alice")
+ if entry and entry.get("locked_until"):
+ entry["locked_until"] = datetime.datetime.now(
+ timezone.utc
+ ) - timedelta(seconds=1)
+ assert mgr.is_locked("alice") is False
+
+ def test_separate_users_independent(self):
+ mgr = self._make_manager(threshold=2)
+ mgr.record_failure("alice")
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is True
+ assert mgr.is_locked("bob") is False
+
+ def test_record_success_on_unknown_user(self):
+ mgr = self._make_manager()
+ # Should not raise
+ mgr.record_success("nobody")
+ assert mgr.is_locked("nobody") is False
+
+ def test_eviction_clears_expired(self):
+ mgr = self._make_manager(threshold=1, lockout_minutes=0)
+ # Add many entries, all expired
+ for i in range(100):
+ mgr.record_failure(f"user_{i}")
+ # Force all locked_until to past
+ with mgr._lock:
+ for entry in mgr._state.values():
+ if entry.get("locked_until"):
+ entry["locked_until"] = datetime.datetime.now(
+ timezone.utc
+ ) - timedelta(seconds=10)
+ # Trigger eviction by exceeding _MAX_STATE_ENTRIES
+ mgr._MAX_STATE_ENTRIES = 50 # lower threshold for test
+ mgr.record_failure("trigger_evict")
+ # After eviction, expired entries should be gone
+ with mgr._lock:
+ # Only the trigger entry (or fewer) should remain
+ assert len(mgr._state) <= 2
+
+ def test_threshold_exactly_at_boundary(self):
+ mgr = self._make_manager(threshold=5)
+ for _ in range(4):
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is False
+ mgr.record_failure("alice") # 5th attempt
+ assert mgr.is_locked("alice") is True
+
+
+# ======================================================================
+# URLValidator
+# ======================================================================
+
+
+class TestURLValidator:
+ """Tests for URLValidator static methods."""
+
+ # --- is_unsafe_scheme ---
+
+ def test_unsafe_javascript(self):
+ assert URLValidator.is_unsafe_scheme("javascript:alert(1)") is True
+
+ def test_unsafe_data(self):
+ assert (
+ URLValidator.is_unsafe_scheme("data:text/html,<h1>hi</h1>") is True
+ )
+
+ def test_unsafe_vbscript(self):
+ assert URLValidator.is_unsafe_scheme("vbscript:MsgBox") is True
+
+ def test_safe_https(self):
+ assert URLValidator.is_unsafe_scheme("https://example.com") is False
+
+ def test_empty_not_unsafe(self):
+ assert URLValidator.is_unsafe_scheme("") is False
+
+ def test_case_insensitive_scheme(self):
+ assert URLValidator.is_unsafe_scheme("JAVASCRIPT:void(0)") is True
+
+ # --- is_safe_url ---
+
+ def test_safe_https_url(self):
+ assert URLValidator.is_safe_url("https://example.com") is True
+
+ def test_safe_http_url(self):
+ assert URLValidator.is_safe_url("http://example.com") is True
+
+ def test_ftp_is_safe(self):
+ assert URLValidator.is_safe_url("ftp://files.example.com") is True
+
+ def test_empty_not_safe(self):
+ assert URLValidator.is_safe_url("") is False
+
+ def test_none_not_safe(self):
+ assert URLValidator.is_safe_url(None) is False
+
+ def test_fragment_only_allowed(self):
+ assert URLValidator.is_safe_url("#section") is True
+
+ def test_fragment_only_disallowed(self):
+ assert (
+ URLValidator.is_safe_url("#section", allow_fragments=False) is False
+ )
+
+ def test_mailto_default_disallowed(self):
+ assert URLValidator.is_safe_url("mailto:[email protected]") is False
+
+ def test_mailto_allowed(self):
+ assert (
+ URLValidator.is_safe_url(
+ "mailto:[email protected]", allow_mailto=True
+ )
+ is True
+ )
+
+ def test_no_scheme_requires_scheme(self):
+ assert (
+ URLValidator.is_safe_url("example.com", require_scheme=True)
+ is False
+ )
+
+ def test_no_scheme_not_required(self):
+ assert (
+ URLValidator.is_safe_url("example.com", require_scheme=False)
+ is True
+ )
+
+ def test_trusted_domains(self):
+ assert (
+ URLValidator.is_safe_url(
+ "https://evil.com", trusted_domains=["example.com"]
+ )
+ is False
+ )
+ assert (
+ URLValidator.is_safe_url(
+ "https://example.com", trusted_domains=["example.com"]
+ )
+ is True
+ )
+
+ def test_subdomain_trusted(self):
+ assert (
+ URLValidator.is_safe_url(
+ "https://sub.example.com", trusted_domains=["example.com"]
+ )
+ is True
+ )
+
+ def test_double_encoding_suspicious(self):
+ # %2520 = double-encoded space
+ assert (
+ URLValidator.is_safe_url("https://example.com/%2520path") is False
+ )
+
+ def test_null_byte_suspicious(self):
+ assert URLValidator.is_safe_url("https://example.com/%00path") is False
+
+ # --- sanitize_url ---
+
+ def test_sanitize_adds_scheme(self):
+ result = URLValidator.sanitize_url("example.com")
+ assert result == "https://example.com"
+
+ def test_sanitize_preserves_https(self):
+ result = URLValidator.sanitize_url("https://example.com/path")
+ assert result == "https://example.com/path"
+
+ def test_sanitize_rejects_javascript(self):
+ assert URLValidator.sanitize_url("javascript:alert(1)") is None
+
+ def test_sanitize_empty(self):
+ assert URLValidator.sanitize_url("") is None
+
+ def test_sanitize_custom_default_scheme(self):
+ result = URLValidator.sanitize_url("example.com", default_scheme="http")
+ assert result is not None
+ assert result.startswith("http://")
+
+ # --- is_academic_url ---
+
+ def test_academic_arxiv(self):
+ assert (
+ URLValidator.is_academic_url("https://arxiv.org/abs/1234") is True
+ )
+
+ def test_academic_doi(self):
+ assert (
+ URLValidator.is_academic_url("https://doi.org/10.1234/test") is True
+ )
+
+ def test_academic_subdomain(self):
+ assert (
+ URLValidator.is_academic_url("https://www.nature.com/articles/123")
+ is True
+ )
+
+ def test_not_academic(self):
+ assert URLValidator.is_academic_url("https://google.com") is False
+
+ def test_academic_empty(self):
+ assert URLValidator.is_academic_url("") is False
+
+ # --- extract_doi ---
+
+ def test_extract_doi_from_doi_url(self):
+ doi = URLValidator.extract_doi("https://doi.org/10.1234/test.5678")
+ assert doi is not None
+ assert doi.startswith("10.1234")
+
+ def test_extract_doi_direct(self):
+ doi = URLValidator.extract_doi("10.1000/xyz123")
+ assert doi is not None
+
+ def test_extract_doi_none(self):
+ assert URLValidator.extract_doi("https://example.com") is None
+
+ # --- validate_http_url ---
+
+ def test_validate_http_url_valid(self):
+ assert (
+ URLValidator.validate_http_url("https://example.com/path") is True
+ )
+
+ def test_validate_http_url_no_scheme(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("example.com")
+
+ def test_validate_http_url_ftp_rejected(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("ftp://example.com")
+
+ def test_validate_http_url_empty(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("")
+
+ def test_validate_http_url_none(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url(None)
+
+ # --- is_safe_redirect_url ---
+
+ def test_redirect_relative_safe(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "/dashboard", "http://localhost:5000/"
+ )
+ is True
+ )
+
+ def test_redirect_same_host_safe(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "http://localhost:5000/page", "http://localhost:5000/"
+ )
+ is True
+ )
+
+ def test_redirect_external_unsafe(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "http://evil.com/steal", "http://localhost:5000/"
+ )
+ is False
+ )
+
+ def test_redirect_empty(self):
+ assert (
+ URLValidator.is_safe_redirect_url("", "http://localhost:5000/")
+ is False
+ )
+
+ def test_redirect_crlf_injection(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "/page\r\nSet-Cookie: evil=1", "http://localhost:5000/"
+ )
+ is False
+ )
+
+ def test_redirect_protocol_relative(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "//evil.com/steal", "http://localhost:5000/"
+ )
+ is False
+ )
+
+ def test_redirect_backslash_bypass(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "\\evil.com", "http://localhost:5000/"
+ )
+ is False
+ )
+
+ def test_redirect_null_byte(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "/page\x00evil", "http://localhost:5000/"
+ )
+ is False
+ )
+
+ def test_redirect_path_traversal(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "/../etc/passwd", "http://localhost:5000/"
+ )
+ is False
+ )
+
+ def test_redirect_encoded_crlf(self):
+ # %0d%0a encoded
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "/page%0d%0aSet-Cookie: x=1", "http://localhost:5000/"
+ )
+ is False
+ )
+
+ # --- get_safe_redirect_path ---
+
+ def test_safe_redirect_path_valid(self):
+ path = URLValidator.get_safe_redirect_path(
+ "/dashboard", "http://localhost:5000/"
+ )
+ assert path == "/dashboard"
+
+ def test_safe_redirect_path_with_query(self):
+ path = URLValidator.get_safe_redirect_path(
+ "/page?tab=settings", "http://localhost:5000/"
+ )
+ assert path is not None
+ assert "tab=settings" in path
+
+ def test_safe_redirect_path_unsafe(self):
+ path = URLValidator.get_safe_redirect_path(
+ "http://evil.com/steal", "http://localhost:5000/"
+ )
+ assert path is None
+
+ def test_safe_redirect_path_empty(self):
+ assert (
+ URLValidator.get_safe_redirect_path("", "http://localhost:5000/")
+ is None
+ )
+
+
+# ======================================================================
+# Log Sanitizer
+# ======================================================================
+
+
+class TestLogSanitizer:
+ """Tests for sanitize_for_log and strip_control_chars."""
+
+ def test_strip_null_byte(self):
+ assert strip_control_chars("hello\x00world") == "helloworld"
+
+ def test_strip_newlines(self):
+ assert strip_control_chars("line1\nline2\r") == "line1line2"
+
+ def test_strip_tabs(self):
+ assert strip_control_chars("col1\tcol2") == "col1col2"
+
+ def test_preserve_normal_ascii(self):
+ s = "Hello World 123 !@#"
+ assert strip_control_chars(s) == s
+
+ def test_preserve_unicode_letters(self):
+ s = "Héllo Wörld 日本語"
+ assert strip_control_chars(s) == s
+
+ def test_strip_zero_width_chars(self):
+ assert strip_control_chars("a\u200bb\u200fc") == "abc"
+
+ def test_strip_bom(self):
+ assert strip_control_chars("\ufeffHello") == "Hello"
+
+ def test_strip_rlo(self):
+ # Right-to-left override
+ assert strip_control_chars("test\u202eevil") == "testevil"
+
+ def test_sanitize_truncates(self):
+ long_input = "a" * 100
+ result = sanitize_for_log(long_input, max_length=50)
+ assert len(result) == 50
+ assert result.endswith("...")
+
+ def test_sanitize_short_input(self):
+ result = sanitize_for_log("hello", max_length=50)
+ assert result == "hello"
+
+ def test_sanitize_exact_length(self):
+ s = "a" * 50
+ result = sanitize_for_log(s, max_length=50)
+ assert result == s
+
+ def test_sanitize_strips_and_truncates(self):
+ # Control chars stripped first, then truncated
+ s = "\x00" + "b" * 100
+ result = sanitize_for_log(s, max_length=20)
+ assert "\x00" not in result
+ assert len(result) == 20
+
+ def test_sanitize_very_small_max_length(self):
+ result = sanitize_for_log("abcdef", max_length=3)
+ assert len(result) == 3
+
+ def test_sanitize_default_max_length(self):
+ long_input = "a" * 200
+ result = sanitize_for_log(long_input)
+ assert len(result) == 50 # default is 50
+
+
+# ======================================================================
+# SessionManager
+# ======================================================================
+
+
+class TestSessionManager:
+ """Tests for SessionManager create/validate/destroy/cleanup logic."""
+
+ def _make_manager(self, session_hours=2, remember_days=30):
+ """Create a SessionManager with controlled timeouts."""
+ mgr = SessionManager.__new__(SessionManager)
+ import threading
+
+ mgr.sessions = {}
+ mgr._lock = threading.Lock()
+ mgr.session_timeout = timedelta(hours=session_hours)
+ mgr.remember_me_timeout = timedelta(days=remember_days)
+ return mgr
+
+ def test_create_session_returns_string(self):
+ mgr = self._make_manager()
+ sid = mgr.create_session("alice")
+ assert isinstance(sid, str)
+ assert len(sid) > 20 # token_urlsafe(32) is ~43 chars
+
+ def test_create_session_unique(self):
+ mgr = self._make_manager()
+ s1 = mgr.create_session("alice")
+ s2 = mgr.create_session("alice")
+ assert s1 != s2
+
+ def test_validate_returns_username(self):
+ mgr = self._make_manager()
+ sid = mgr.create_session("alice")
+ assert mgr.validate_session(sid) == "alice"
+
+ def test_validate_unknown_session(self):
+ mgr = self._make_manager()
+ assert mgr.validate_session("nonexistent") is None
+
+ def test_validate_updates_last_access(self):
+ mgr = self._make_manager()
+ sid = mgr.create_session("alice")
+ first_access = mgr.sessions[sid]["last_access"]
+ time.sleep(0.01)
+ mgr.validate_session(sid)
+ assert mgr.sessions[sid]["last_access"] > first_access
+
+ def test_expired_session_returns_none(self):
+ mgr = self._make_manager(session_hours=1)
+ sid = mgr.create_session("alice")
+ # Force session to be expired
+ with mgr._lock:
+ mgr.sessions[sid]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - timedelta(hours=2)
+ assert mgr.validate_session(sid) is None
+ # Session should be removed
+ assert sid not in mgr.sessions
+
+ def test_remember_me_uses_extended_timeout(self):
+ mgr = self._make_manager(session_hours=1, remember_days=30)
+ sid = mgr.create_session("alice", remember_me=True)
+ # Set last_access to 2 hours ago (would expire normal session)
+ with mgr._lock:
+ mgr.sessions[sid]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - timedelta(hours=2)
+ # Should still be valid with remember_me
+ assert mgr.validate_session(sid) == "alice"
+
+ def test_remember_me_expires_eventually(self):
+ mgr = self._make_manager(session_hours=1, remember_days=30)
+ sid = mgr.create_session("alice", remember_me=True)
+ with mgr._lock:
+ mgr.sessions[sid]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - timedelta(days=31)
+ assert mgr.validate_session(sid) is None
+
+ def test_destroy_session(self):
+ mgr = self._make_manager()
+ sid = mgr.create_session("alice")
+ mgr.destroy_session(sid)
+ assert mgr.validate_session(sid) is None
+
+ def test_destroy_nonexistent(self):
+ mgr = self._make_manager()
+ # Should not raise
+ mgr.destroy_session("nonexistent")
+
+ def test_cleanup_expired_sessions(self):
+ mgr = self._make_manager(session_hours=1)
+ sid1 = mgr.create_session("alice")
+ sid2 = mgr.create_session("bob")
+ # Expire sid1
+ with mgr._lock:
+ mgr.sessions[sid1]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - timedelta(hours=2)
+ mgr.cleanup_expired_sessions()
+ assert sid1 not in mgr.sessions
+ assert sid2 in mgr.sessions
+
+ def test_get_active_sessions_count(self):
+ mgr = self._make_manager()
+ mgr.create_session("alice")
+ mgr.create_session("bob")
+ assert mgr.get_active_sessions_count() == 2
+
+ def test_get_active_sessions_count_excludes_expired(self):
+ mgr = self._make_manager(session_hours=1)
+ sid1 = mgr.create_session("alice")
+ mgr.create_session("bob")
+ with mgr._lock:
+ mgr.sessions[sid1]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - timedelta(hours=2)
+ assert mgr.get_active_sessions_count() == 1
+
+ def test_get_user_sessions(self):
+ mgr = self._make_manager()
+ mgr.create_session("alice")
+ mgr.create_session("alice")
+ mgr.create_session("bob")
+ alice_sessions = mgr.get_user_sessions("alice")
+ assert len(alice_sessions) == 2
+ for s in alice_sessions:
+ assert "session_id" in s
+ assert s["session_id"].endswith("...")
+
+ def test_get_user_sessions_empty(self):
+ mgr = self._make_manager()
+ assert mgr.get_user_sessions("nobody") == []
+
+ def test_get_active_usernames(self):
+ mgr = self._make_manager()
+ mgr.create_session("alice")
+ mgr.create_session("bob")
+ mgr.create_session("alice")
+ usernames = mgr.get_active_usernames()
+ assert usernames == {"alice", "bob"}
+
+ def test_get_active_usernames_excludes_expired(self):
+ mgr = self._make_manager(session_hours=1)
+ sid = mgr.create_session("alice")
+ mgr.create_session("bob")
+ with mgr._lock:
+ mgr.sessions[sid]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - timedelta(hours=2)
+ assert mgr.get_active_usernames() == {"bob"}
+
+ def test_has_active_sessions_for(self):
+ mgr = self._make_manager()
+ mgr.create_session("alice")
+ assert mgr.has_active_sessions_for("alice") is True
+ assert mgr.has_active_sessions_for("bob") is False
+
+ def test_has_active_sessions_for_expired(self):
+ mgr = self._make_manager(session_hours=1)
+ sid = mgr.create_session("alice")
+ with mgr._lock:
+ mgr.sessions[sid]["last_access"] = datetime.datetime.now(
+ UTC
+ ) - timedelta(hours=2)
+ assert mgr.has_active_sessions_for("alice") is False
+
+ def test_multiple_users_isolation(self):
+ mgr = self._make_manager()
+ sid_alice = mgr.create_session("alice")
+ sid_bob = mgr.create_session("bob")
+ mgr.destroy_session(sid_alice)
+ assert mgr.validate_session(sid_bob) == "bob"
+ assert mgr.has_active_sessions_for("alice") is False
+ assert mgr.has_active_sessions_for("bob") is True
diff --git a/tests/web/routes/test_research_routes_coverage.py b/tests/web/routes/test_research_routes_coverage.py
new file mode 100644
index 0000000000..b36849a850
--- /dev/null
+++ b/tests/web/routes/test_research_routes_coverage.py
@@ -0,0 +1,735 @@
+"""Comprehensive tests for helper / pure-logic functions used by research_routes.
+
+Covers:
+- calculate_duration (timestamp parsing, duration calculation)
+- Error type classification logic from get_research_status
+- find_blocked_keys (security key detection in TOML configs)
+- Date placeholder replacement logic
+- globals.py thread-safe state helpers
+"""
+
+import threading
+from datetime import datetime, UTC, timedelta
+
+import pytest
+
+# ---------------------------------------------------------------------------
+# calculate_duration
+# ---------------------------------------------------------------------------
+from local_deep_research.web.models.database import calculate_duration
+
+
+class TestCalculateDuration:
+ """Tests for calculate_duration helper."""
+
+ def test_iso_format_both_timestamps(self):
+ created = "2025-01-01T10:00:00+00:00"
+ completed = "2025-01-01T10:05:00+00:00"
+ assert calculate_duration(created, completed) == 300
+
+ def test_iso_format_without_timezone_returns_none(self):
+ """Naive ISO timestamps cause a TypeError in subtraction because
+ end_time becomes aware via .astimezone(UTC) but start_time stays
+ naive. The function catches this and returns None."""
+ created = "2025-06-01T12:00:00"
+ completed = "2025-06-01T12:10:00"
+ result = calculate_duration(created, completed)
+ assert result is None
+
+ def test_space_separated_format_with_microseconds(self):
+ """Naive timestamps parsed via strptime: end_time becomes aware via
+ .astimezone(UTC), start_time stays naive, subtraction fails."""
+ created = "2025-01-01 10:00:00.000000"
+ completed = "2025-01-01 11:00:00.000000"
+ assert calculate_duration(created, completed) is None
+
+ def test_space_separated_format_without_microseconds(self):
+ """Same naive/aware mismatch for space-separated without microseconds."""
+ created = "2025-01-01 10:00:00"
+ completed = "2025-01-01 10:30:00"
+ assert calculate_duration(created, completed) is None
+
+ def test_none_created_at_returns_none(self):
+ assert calculate_duration(None) is None
+ assert calculate_duration("") is None
+
+ def test_completed_at_none_uses_current_time(self):
+ """When completed_at is omitted, duration should be relative to now."""
+ one_minute_ago = (datetime.now(UTC) - timedelta(minutes=1)).isoformat()
+ result = calculate_duration(one_minute_ago)
+ # Should be roughly 60 seconds (allow +-5s for test execution jitter)
+ assert result is not None
+ assert 55 <= result <= 65
+
+ def test_negative_duration(self):
+ """If completed_at is before created_at the function still returns an int."""
+ created = "2025-01-01T12:00:00+00:00"
+ completed = "2025-01-01T11:00:00+00:00"
+ result = calculate_duration(created, completed)
+ assert result == -3600
+
+ def test_zero_duration(self):
+ ts = "2025-03-14T08:00:00+00:00"
+ assert calculate_duration(ts, ts) == 0
+
+ def test_mixed_formats_aware_created_naive_completed(self):
+ """Aware created_at + naive completed_at: completed gets .astimezone(UTC)
+ converting naive to local-tz-aware, then subtraction from aware created
+ works. Result depends on system tz offset from UTC."""
+ created = "2025-01-01T10:00:00+00:00"
+ completed = "2025-01-01 10:02:00"
+ result = calculate_duration(created, completed)
+ # completed_at is naive, .astimezone(UTC) makes it aware using local tz.
+ # The result is an int (may differ from 120 depending on system tz).
+ assert result is not None
+ assert isinstance(result, int)
+
+ def test_space_format_with_fractional_seconds(self):
+ """Space-separated format with fractional seconds: both are naive,
+ end_time becomes aware via .astimezone(UTC) but start_time stays
+ naive, causing subtraction to fail. Returns None."""
+ created = "2025-01-01 10:00:00.123"
+ completed = "2025-01-01 10:00:10.123"
+ result = calculate_duration(created, completed)
+ # Same naive-vs-aware mismatch as test_iso_format_without_timezone
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# Error type classification (extracted logic from get_research_status)
+# ---------------------------------------------------------------------------
+
+
+def _classify_error(error_msg, metadata=None):
+ """
+ Reimplementation of the error classification logic from
+ get_research_status to test it in isolation.
+ """
+ if metadata is None:
+ metadata = {}
+
+ error_type = "unknown"
+ error_info = {}
+
+ if "timeout" in error_msg.lower():
+ error_type = "timeout"
+ error_info = {
+ "type": "timeout",
+ "message": "LLM service timed out during synthesis. This may be due to high server load or connectivity issues.",
+ "suggestion": "Try again later or use a smaller query scope.",
+ }
+ elif (
+ "token limit" in error_msg.lower()
+ or "context length" in error_msg.lower()
+ ):
+ error_type = "token_limit"
+ error_info = {
+ "type": "token_limit",
+ "message": "The research query exceeded the AI model's token limit during synthesis.",
+ "suggestion": "Try using a more specific query or reduce the research scope.",
+ }
+ elif (
+ "final answer synthesis fail" in error_msg.lower()
+ or "llm error" in error_msg.lower()
+ ):
+ error_type = "llm_error"
+ error_info = {
+ "type": "llm_error",
+ "message": "The AI model encountered an error during final answer synthesis.",
+ "suggestion": "Check that your LLM service is running correctly or try a different model.",
+ }
+ elif "ollama" in error_msg.lower():
+ error_type = "ollama_error"
+ error_info = {
+ "type": "ollama_error",
+ "message": "The Ollama service is not responding properly.",
+ "suggestion": "Make sure Ollama is running with 'ollama serve' and the model is downloaded.",
+ }
+ elif "connection" in error_msg.lower():
+ error_type = "connection"
+ error_info = {
+ "type": "connection",
+ "message": "Connection error with the AI service.",
+ "suggestion": "Check your internet connection and AI service status.",
+ }
+ elif metadata.get("solution"):
+ error_info = {
+ "type": error_type,
+ "message": error_msg,
+ "suggestion": metadata.get("solution"),
+ }
+ else:
+ error_info = {
+ "type": error_type,
+ "message": error_msg,
+ "suggestion": "Try again with a different query or check the application logs.",
+ }
+
+ return error_info
+
+
+class TestErrorClassification:
+ """Tests for the error-type classification logic."""
+
+ def test_timeout_error(self):
+ info = _classify_error("Request Timeout after 120s")
+ assert info["type"] == "timeout"
+
+ def test_timeout_case_insensitive(self):
+ info = _classify_error("TIMEOUT occurred during processing")
+ assert info["type"] == "timeout"
+
+ def test_token_limit_error(self):
+ info = _classify_error("Exceeded token limit for model gpt-4")
+ assert info["type"] == "token_limit"
+
+ def test_context_length_error(self):
+ info = _classify_error("context length exceeded: 128000 tokens")
+ assert info["type"] == "token_limit"
+
+ def test_llm_error(self):
+ info = _classify_error("LLM error: model returned empty response")
+ assert info["type"] == "llm_error"
+
+ def test_synthesis_failure(self):
+ info = _classify_error(
+ "Final answer synthesis failed due to parsing error"
+ )
+ assert info["type"] == "llm_error"
+
+ def test_ollama_error(self):
+ info = _classify_error("Ollama connection refused at localhost:11434")
+ assert info["type"] == "ollama_error"
+
+ def test_connection_error(self):
+ info = _classify_error("Connection refused by remote host")
+ assert info["type"] == "connection"
+
+ def test_unknown_error_with_solution_in_metadata(self):
+ meta = {"solution": "Restart the service and try again."}
+ info = _classify_error("Some unusual failure", metadata=meta)
+ assert info["type"] == "unknown"
+ assert info["suggestion"] == "Restart the service and try again."
+ assert info["message"] == "Some unusual failure"
+
+ def test_generic_unknown_error(self):
+ info = _classify_error("Something went wrong")
+ assert info["type"] == "unknown"
+ assert "Try again" in info["suggestion"]
+
+ def test_all_fields_present(self):
+ """Every classification result should have type, message, suggestion."""
+ messages = [
+ "timeout",
+ "token limit",
+ "context length exceeded",
+ "LLM error",
+ "ollama",
+ "connection error",
+ "random error",
+ ]
+ for msg in messages:
+ info = _classify_error(msg)
+ assert "type" in info
+ assert "message" in info
+ assert "suggestion" in info
+
+ def test_priority_timeout_over_connection(self):
+ """'timeout' should match before 'connection' even if both present."""
+ info = _classify_error("connection timeout occurred")
+ assert info["type"] == "timeout"
+
+ def test_priority_token_limit_over_llm_error(self):
+ """'token limit' matches before 'llm error'."""
+ info = _classify_error("LLM error: token limit exceeded")
+ # token limit check comes after timeout and before llm_error
+ assert info["type"] == "token_limit"
+
+
+# ---------------------------------------------------------------------------
+# find_blocked_keys (extracted from save_raw_config route)
+# ---------------------------------------------------------------------------
+
+BLOCKED_KEY_PATTERNS = ["module_path", "class_name", "module", "class"]
+
+
+def find_blocked_keys(obj, path=""):
+ """Reimplementation of the nested function from save_raw_config."""
+ blocked = []
+ if isinstance(obj, dict):
+ for key, value in obj.items():
+ current_path = f"{path}.{key}" if path else key
+ key_lower = key.lower()
+ for pattern in BLOCKED_KEY_PATTERNS:
+ if pattern in key_lower:
+ blocked.append(current_path)
+ break
+ blocked.extend(find_blocked_keys(value, current_path))
+ elif isinstance(obj, list):
+ for i, item in enumerate(obj):
+ blocked.extend(find_blocked_keys(item, f"{path}[{i}]"))
+ return blocked
+
+
+class TestFindBlockedKeys:
+ """Tests for the TOML config security key scanner."""
+
+ def test_empty_config(self):
+ assert find_blocked_keys({}) == []
+
+ def test_safe_config(self):
+ config = {"search": {"tool": "google", "iterations": 5}}
+ assert find_blocked_keys(config) == []
+
+ def test_module_path_at_top_level(self):
+ config = {"module_path": "evil.module"}
+ result = find_blocked_keys(config)
+ assert result == ["module_path"]
+
+ def test_class_name_at_top_level(self):
+ config = {"class_name": "EvilClass"}
+ result = find_blocked_keys(config)
+ assert result == ["class_name"]
+
+ def test_nested_blocked_key(self):
+ config = {"custom": {"engines": {"module_path": "evil"}}}
+ result = find_blocked_keys(config)
+ assert result == ["custom.engines.module_path"]
+
+ def test_module_key_blocked(self):
+ """'module' is a blocked pattern, so any key containing it is caught."""
+ config = {"my_module": "something"}
+ result = find_blocked_keys(config)
+ # "module" is in "my_module"
+ assert len(result) == 1
+
+ def test_class_key_blocked(self):
+ config = {"subclass": "something"}
+ result = find_blocked_keys(config)
+ # "class" is in "subclass"
+ assert len(result) == 1
+
+ def test_case_insensitive(self):
+ config = {"MODULE_PATH": "evil", "Class_Name": "bad"}
+ result = find_blocked_keys(config)
+ assert len(result) == 2
+
+ def test_blocked_key_in_list(self):
+ config = {"items": [{"module_path": "evil"}, {"safe_key": "ok"}]}
+ result = find_blocked_keys(config)
+ assert result == ["items[0].module_path"]
+
+ def test_deeply_nested(self):
+ config = {"a": {"b": {"c": {"d": {"class_name": "Bad"}}}}}
+ result = find_blocked_keys(config)
+ assert result == ["a.b.c.d.class_name"]
+
+ def test_multiple_blocked_keys(self):
+ config = {
+ "module_path": "a",
+ "nested": {"class_name": "b"},
+ "list_field": [{"module": "c"}],
+ }
+ result = find_blocked_keys(config)
+ assert len(result) == 3
+
+ def test_scalar_values_not_checked(self):
+ """Only keys are checked, not values."""
+ config = {"safe_key": "module_path"}
+ assert find_blocked_keys(config) == []
+
+ def test_empty_nested_dict(self):
+ config = {"a": {}}
+ assert find_blocked_keys(config) == []
+
+ def test_empty_list(self):
+ config = {"a": []}
+ assert find_blocked_keys(config) == []
+
+
+# ---------------------------------------------------------------------------
+# Date placeholder replacement logic
+# ---------------------------------------------------------------------------
+
+
+class TestDatePlaceholderReplacement:
+ """Tests for the YYYY-MM-DD date placeholder logic used in start_research."""
+
+ @staticmethod
+ def _replace_placeholder(query, metadata=None):
+ """Simulate the date replacement logic from start_research."""
+ if metadata is None:
+ metadata = {}
+
+ if query and "YYYY-MM-DD" in query:
+ current_date = datetime.now(UTC).strftime("%Y-%m-%d")
+ original_query = query
+ query = query.replace("YYYY-MM-DD", current_date)
+ if not metadata:
+ metadata = {}
+ metadata["original_query"] = original_query
+ metadata["processed_query"] = query
+ metadata["date_replaced"] = current_date
+ return query, metadata
+
+ def test_no_placeholder(self):
+ query, meta = self._replace_placeholder("regular search query")
+ assert query == "regular search query"
+ assert "date_replaced" not in meta
+
+ def test_placeholder_replaced(self):
+ query, meta = self._replace_placeholder("news after YYYY-MM-DD")
+ today = datetime.now(UTC).strftime("%Y-%m-%d")
+ assert today in query
+ assert "YYYY-MM-DD" not in query
+ assert meta["date_replaced"] == today
+
+ def test_multiple_placeholders(self):
+ query, meta = self._replace_placeholder(
+ "between YYYY-MM-DD and YYYY-MM-DD"
+ )
+ today = datetime.now(UTC).strftime("%Y-%m-%d")
+ assert query.count(today) == 2
+
+ def test_metadata_preserved(self):
+ existing_meta = {"is_news_search": True, "triggered_by": "user"}
+ query, meta = self._replace_placeholder(
+ "news YYYY-MM-DD", metadata=existing_meta
+ )
+ assert meta["is_news_search"] is True
+ assert meta["triggered_by"] == "user"
+ assert "date_replaced" in meta
+
+ def test_original_query_saved(self):
+ original = "events after YYYY-MM-DD"
+ query, meta = self._replace_placeholder(original)
+ assert meta["original_query"] == original
+ assert meta["processed_query"] == query
+
+ def test_empty_query(self):
+ query, meta = self._replace_placeholder("")
+ assert query == ""
+
+ def test_none_query(self):
+ query, meta = self._replace_placeholder(None)
+ assert query is None
+
+
+# ---------------------------------------------------------------------------
+# globals.py – thread-safe state helpers
+# ---------------------------------------------------------------------------
+from local_deep_research.web.routes.globals import ( # noqa: E402
+ _active_research,
+ _termination_flags,
+ _lock,
+ cleanup_research,
+ get_active_research_count,
+ get_active_research_ids,
+ get_active_research_snapshot,
+ get_research_field,
+ is_research_active,
+ is_termination_requested,
+ set_active_research,
+ set_termination_flag,
+ clear_termination_flag,
+ remove_active_research,
+ update_active_research,
+ update_progress_if_higher,
+ update_progress_and_check_active,
+ append_research_log,
+ iter_active_research,
+ get_usernames_with_active_research,
+ is_research_thread_alive,
+)
+
+
[email protected](autouse=True)
+def _clean_globals():
+ """Ensure globals are clean before and after every test."""
+ with _lock:
+ _active_research.clear()
+ _termination_flags.clear()
+ yield
+ with _lock:
+ _active_research.clear()
+ _termination_flags.clear()
+
+
+class TestGlobalsActiveResearch:
+ """Tests for active research state management."""
+
+ def test_set_and_check_active(self):
+ set_active_research("r1", {"progress": 0, "status": "in_progress"})
+ assert is_research_active("r1") is True
+ assert is_research_active("nonexistent") is False
+
+ def test_get_active_research_ids(self):
+ set_active_research("a", {})
+ set_active_research("b", {})
+ ids = get_active_research_ids()
+ assert sorted(ids) == ["a", "b"]
+
+ def test_get_active_research_ids_empty(self):
+ assert get_active_research_ids() == []
+
+ def test_remove_active_research(self):
+ set_active_research("r1", {})
+ remove_active_research("r1")
+ assert is_research_active("r1") is False
+
+ def test_remove_nonexistent_no_error(self):
+ remove_active_research("nonexistent")
+
+ def test_get_active_research_count(self):
+ assert get_active_research_count() == 0
+ set_active_research("r1", {})
+ set_active_research("r2", {})
+ assert get_active_research_count() == 2
+
+ def test_get_research_field_scalar(self):
+ set_active_research("r1", {"progress": 42, "status": "in_progress"})
+ assert get_research_field("r1", "progress") == 42
+ assert get_research_field("r1", "status") == "in_progress"
+
+ def test_get_research_field_default(self):
+ set_active_research("r1", {})
+ assert get_research_field("r1", "missing", "default") == "default"
+
+ def test_get_research_field_nonexistent_research(self):
+ assert get_research_field("nope", "progress", 0) == 0
+
+ def test_get_research_field_returns_copy_for_list(self):
+ set_active_research("r1", {"log": [1, 2, 3]})
+ log = get_research_field("r1", "log")
+ log.append(4)
+ # Original should not be mutated
+ assert get_research_field("r1", "log") == [1, 2, 3]
+
+ def test_get_research_field_returns_copy_for_dict(self):
+ set_active_research("r1", {"settings": {"a": 1}})
+ settings = get_research_field("r1", "settings")
+ settings["b"] = 2
+ assert "b" not in get_research_field("r1", "settings")
+
+ def test_update_active_research(self):
+ set_active_research("r1", {"progress": 0})
+ update_active_research("r1", progress=50, status="running")
+ assert get_research_field("r1", "progress") == 50
+ assert get_research_field("r1", "status") == "running"
+
+ def test_update_nonexistent_no_error(self):
+ update_active_research("nope", progress=10)
+
+ def test_get_active_research_snapshot(self):
+ set_active_research(
+ "r1",
+ {
+ "progress": 75,
+ "status": "in_progress",
+ "log": [{"msg": "started"}],
+ "settings": {"key": "val"},
+ "thread": threading.current_thread(),
+ },
+ )
+ snap = get_active_research_snapshot("r1")
+ assert snap is not None
+ assert snap["progress"] == 75
+ assert snap["status"] == "in_progress"
+ assert snap["log"] == [{"msg": "started"}]
+ assert snap["settings"] == {"key": "val"}
+ # thread should not be in snapshot
+ assert "thread" not in snap
+
+ def test_get_active_research_snapshot_none(self):
+ assert get_active_research_snapshot("nonexistent") is None
+
+ def test_get_active_research_snapshot_no_settings(self):
+ set_active_research("r1", {"progress": 0, "status": "x"})
+ snap = get_active_research_snapshot("r1")
+ assert snap["settings"] is None
+
+
+class TestGlobalsProgressUpdates:
+ """Tests for progress update helpers."""
+
+ def test_update_progress_if_higher(self):
+ set_active_research("r1", {"progress": 10})
+ result = update_progress_if_higher("r1", 50)
+ assert result == 50
+ assert get_research_field("r1", "progress") == 50
+
+ def test_update_progress_if_not_higher(self):
+ set_active_research("r1", {"progress": 80})
+ result = update_progress_if_higher("r1", 50)
+ assert result == 80
+ assert get_research_field("r1", "progress") == 80
+
+ def test_update_progress_none_value(self):
+ set_active_research("r1", {"progress": 30})
+ result = update_progress_if_higher("r1", None)
+ assert result == 30
+
+ def test_update_progress_nonexistent(self):
+ result = update_progress_if_higher("nope", 50)
+ assert result is None
+
+ def test_update_progress_and_check_active(self):
+ set_active_research("r1", {"progress": 10})
+ progress, active = update_progress_and_check_active("r1", 60)
+ assert progress == 60
+ assert active is True
+
+ def test_update_progress_and_check_active_not_higher(self):
+ set_active_research("r1", {"progress": 90})
+ progress, active = update_progress_and_check_active("r1", 50)
+ assert progress == 90
+ assert active is True
+
+ def test_update_progress_and_check_active_nonexistent(self):
+ progress, active = update_progress_and_check_active("nope", 50)
+ assert progress is None
+ assert active is False
+
+
+class TestGlobalsAppendLog:
+ """Tests for append_research_log."""
+
+ def test_append_to_existing_log(self):
+ set_active_research("r1", {"log": [{"msg": "first"}]})
+ append_research_log("r1", {"msg": "second"})
+ log = get_research_field("r1", "log")
+ assert len(log) == 2
+ assert log[1]["msg"] == "second"
+
+ def test_append_creates_log_list(self):
+ set_active_research("r1", {})
+ append_research_log("r1", {"msg": "first"})
+ log = get_research_field("r1", "log")
+ assert log == [{"msg": "first"}]
+
+ def test_append_nonexistent_no_error(self):
+ append_research_log("nope", {"msg": "x"})
+
+
+class TestGlobalsTerminationFlags:
+ """Tests for termination flag management."""
+
+ def test_set_and_check_termination(self):
+ assert is_termination_requested("r1") is False
+ set_termination_flag("r1")
+ assert is_termination_requested("r1") is True
+
+ def test_clear_termination_flag(self):
+ set_termination_flag("r1")
+ clear_termination_flag("r1")
+ assert is_termination_requested("r1") is False
+
+ def test_clear_nonexistent_no_error(self):
+ clear_termination_flag("nope")
+
+
+class TestGlobalsCleanup:
+ """Tests for cleanup_research."""
+
+ def test_cleanup_removes_both(self):
+ set_active_research("r1", {"progress": 50})
+ set_termination_flag("r1")
+ cleanup_research("r1")
+ assert is_research_active("r1") is False
+ assert is_termination_requested("r1") is False
+
+ def test_cleanup_nonexistent(self):
+ cleanup_research("nope") # should not raise
+
+
+class TestGlobalsIterActiveResearch:
+ """Tests for iter_active_research."""
+
+ def test_iter_yields_snapshots(self):
+ set_active_research("r1", {"progress": 10, "status": "x", "log": []})
+ set_active_research("r2", {"progress": 90, "status": "y"})
+ items = dict(iter_active_research())
+ assert "r1" in items
+ assert "r2" in items
+ assert items["r1"]["progress"] == 10
+
+ def test_iter_empty(self):
+ assert list(iter_active_research()) == []
+
+
+class TestGlobalsUsernames:
+ """Tests for get_usernames_with_active_research."""
+
+ def test_returns_usernames(self):
+ set_active_research("r1", {"settings": {"username": "alice"}})
+ set_active_research("r2", {"settings": {"username": "bob"}})
+ set_active_research("r3", {"settings": {"username": "alice"}})
+ names = get_usernames_with_active_research()
+ assert names == {"alice", "bob"}
+
+ def test_returns_empty_when_no_research(self):
+ assert get_usernames_with_active_research() == set()
+
+ def test_skips_entries_without_username(self):
+ set_active_research("r1", {"settings": {}})
+ set_active_research("r2", {})
+ assert get_usernames_with_active_research() == set()
+
+
+class TestGlobalsThreadAlive:
+ """Tests for is_research_thread_alive."""
+
+ def test_no_thread(self):
+ set_active_research("r1", {})
+ assert is_research_thread_alive("r1") is False
+
+ def test_nonexistent_research(self):
+ assert is_research_thread_alive("nope") is False
+
+ def test_alive_thread(self):
+ event = threading.Event()
+ t = threading.Thread(target=event.wait, daemon=True)
+ t.start()
+ try:
+ set_active_research("r1", {"thread": t})
+ assert is_research_thread_alive("r1") is True
+ finally:
+ event.set()
+ t.join(timeout=2)
+
+ def test_dead_thread(self):
+ t = threading.Thread(target=lambda: None)
+ t.start()
+ t.join()
+ set_active_research("r1", {"thread": t})
+ assert is_research_thread_alive("r1") is False
+
+
+class TestGlobalsConcurrency:
+ """Basic concurrency safety tests for globals."""
+
+ def test_concurrent_set_and_read(self):
+ """Multiple threads setting and reading should not crash."""
+ errors = []
+
+ def worker(rid):
+ try:
+ set_active_research(rid, {"progress": 0})
+ for i in range(100):
+ update_progress_if_higher(rid, i)
+ get_research_field(rid, "progress")
+ append_research_log(rid, {"i": i})
+ remove_active_research(rid)
+ except Exception as e:
+ errors.append(e)
+
+ threads = [
+ threading.Thread(target=worker, args=(f"r{i}",)) for i in range(10)
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=10)
+
+ assert errors == []
+ assert get_active_research_count() == 0
diff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.py
new file mode 100644
index 0000000000..4516bf807a
--- /dev/null
+++ b/tests/web/services/test_notification_coverage.py
@@ -0,0 +1,1120 @@
+"""
+Comprehensive tests for notification-related modules.
+
+Covers:
+- NotificationURLValidator (SSRF prevention, scheme blocking, private IP detection)
+- NotificationService (send logic, event sending, service testing, URL validation)
+- NotificationManager (rate limiting, settings snapshot, event routing)
+- RateLimiter (per-user limits, hourly/daily windows, cleanup)
+- NotificationTemplate (Jinja2 rendering, custom templates, fallback)
+- build_notification_url (URL building from settings)
+- Queue helpers (send_queue_notification, send_queue_failed_notification)
+- mask_sensitive_url (credential masking)
+- Exception hierarchy
+"""
+
+import threading
+from collections import deque
+from datetime import datetime, timedelta, timezone
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.notifications.exceptions import (
+ NotificationError,
+ RateLimitError,
+ SendError,
+ ServiceError,
+)
+from local_deep_research.notifications.manager import (
+ NotificationManager,
+ RateLimiter,
+)
+from local_deep_research.notifications.service import NotificationService
+from local_deep_research.notifications.templates import (
+ EventType,
+ NotificationTemplate,
+)
+from local_deep_research.notifications.url_builder import build_notification_url
+from local_deep_research.notifications.queue_helpers import (
+ send_queue_notification,
+ send_queue_failed_notification,
+)
+from local_deep_research.security.notification_validator import (
+ NotificationURLValidationError,
+ NotificationURLValidator,
+)
+from local_deep_research.security.url_builder import mask_sensitive_url
+from local_deep_research.security.url_validator import (
+ URLValidationError,
+ URLValidator,
+)
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def _reset_shared_rate_limiter():
+ """Reset the singleton rate limiter between tests to avoid cross-contamination."""
+ NotificationManager._shared_rate_limiter = None
+ yield
+ NotificationManager._shared_rate_limiter = None
+
+
+def default_settings():
+ """Settings snapshot that enables notifications with a valid URL."""
+ return {
+ "notifications.service_url": "discord://webhook_id/token",
+ "notifications.on_research_completed": True,
+ "notifications.on_research_failed": True,
+ "notifications.on_research_queued": True,
+ "notifications.rate_limit_per_hour": 10,
+ "notifications.rate_limit_per_day": 50,
+ "notifications.allow_private_ips": False,
+ }
+
+
+def disabled_settings():
+ """Settings snapshot with notifications disabled."""
+ return {
+ "notifications.service_url": "",
+ "notifications.on_research_completed": False,
+ "notifications.on_research_failed": False,
+ "notifications.rate_limit_per_hour": 10,
+ "notifications.rate_limit_per_day": 50,
+ }
+
+
+# ===================================================================
+# NotificationURLValidator
+# ===================================================================
+
+
+class TestNotificationURLValidator:
+ """Tests for SSRF prevention and scheme validation."""
+
+ # -- Allowed schemes --------------------------------------------------
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "discord://webhook_id/token",
+ "slack://token_a/token_b/token_c",
+ "mailto://user:[email protected]",
+ "https://hooks.example.com/webhook",
+ "http://hooks.example.com/webhook",
+ "telegram://bot_token/chat_id",
+ "gotify://gotify.example.com/token",
+ "pushover://user_key/token",
+ "ntfy://ntfy.sh/topic",
+ "json://hooks.example.com/endpoint",
+ "xml://hooks.example.com/endpoint",
+ "form://hooks.example.com/endpoint",
+ "matrix://user:[email protected]/room",
+ "mattermost://hooks.example.com/token",
+ "rocketchat://hooks.example.com/token",
+ "teams://token_a/token_b/token_c",
+ ],
+ )
+ def test_allowed_schemes_pass(self, url):
+ is_valid, err = NotificationURLValidator.validate_service_url(url)
+ assert is_valid is True, f"Expected valid for {url}, got error: {err}"
+ assert err is None
+
+ # -- Blocked schemes ---------------------------------------------------
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "file:///etc/passwd",
+ "ftp://evil.com/payload",
+ "ftps://evil.com/payload",
+ "data:text/html,<script>alert(1)</script>",
+ "javascript:alert(1)",
+ "vbscript:msgbox",
+ "about:blank",
+ "blob:http://evil.com/obj",
+ ],
+ )
+ def test_blocked_schemes_rejected(self, url):
+ is_valid, err = NotificationURLValidator.validate_service_url(url)
+ assert is_valid is False
+ assert err is not None
+ # The error should mention 'protocol' or 'Blocked'
+ assert "protocol" in err.lower() or "blocked" in err.lower()
+
+ # -- Unknown scheme ----------------------------------------------------
+
+ def test_unknown_scheme_rejected(self):
+ is_valid, err = NotificationURLValidator.validate_service_url(
+ "gopher://evil.com"
+ )
+ assert is_valid is False
+ assert "unsupported" in err.lower() or "protocol" in err.lower()
+
+ # -- Empty / invalid inputs --------------------------------------------
+
+ @pytest.mark.parametrize("url", ["", None, 123, " "])
+ def test_empty_or_invalid_input(self, url):
+ is_valid, err = NotificationURLValidator.validate_service_url(url)
+ assert is_valid is False
+
+ def test_url_without_scheme(self):
+ is_valid, err = NotificationURLValidator.validate_service_url(
+ "example.com/webhook"
+ )
+ assert is_valid is False
+
+ # -- Private IP blocking -----------------------------------------------
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "http://localhost:5000/webhook",
+ "http://127.0.0.1:8080/hook",
+ "https://0.0.0.0/hook",
+ "http://[::1]/hook",
+ ],
+ )
+ def test_private_ip_blocked_by_default(self, url):
+ is_valid, err = NotificationURLValidator.validate_service_url(url)
+ assert is_valid is False
+ assert "private" in err.lower() or "blocked" in err.lower()
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "http://localhost:5000/webhook",
+ "http://127.0.0.1:8080/hook",
+ ],
+ )
+ def test_private_ip_allowed_when_flag_set(self, url):
+ is_valid, err = NotificationURLValidator.validate_service_url(
+ url, allow_private_ips=True
+ )
+ assert is_valid is True
+
+ # -- Private IP detection helper ----------------------------------------
+
+ @pytest.mark.parametrize(
+ "hostname,expected",
+ [
+ ("localhost", True),
+ ("127.0.0.1", True),
+ ("::1", True),
+ ("0.0.0.0", True),
+ ("::", True),
+ ("10.0.0.1", True),
+ ("172.16.0.1", True),
+ ("192.168.1.1", True),
+ ("8.8.8.8", False),
+ ("hooks.slack.com", False),
+ ],
+ )
+ def test_is_private_ip(self, hostname, expected):
+ assert NotificationURLValidator._is_private_ip(hostname) is expected
+
+ # -- validate_multiple_urls ---------------------------------------------
+
+ def test_validate_multiple_urls_all_valid(self):
+ urls = "discord://id/token, slack://a/b/c"
+ is_valid, err = NotificationURLValidator.validate_multiple_urls(urls)
+ assert is_valid is True
+ assert err is None
+
+ def test_validate_multiple_urls_one_invalid(self):
+ urls = "discord://id/token, file:///etc/passwd"
+ is_valid, err = NotificationURLValidator.validate_multiple_urls(urls)
+ assert is_valid is False
+ assert err is not None
+
+ def test_validate_multiple_urls_empty(self):
+ is_valid, err = NotificationURLValidator.validate_multiple_urls("")
+ assert is_valid is False
+
+ def test_validate_multiple_urls_only_whitespace(self):
+ is_valid, err = NotificationURLValidator.validate_multiple_urls(" , ")
+ assert is_valid is False
+
+ # -- validate_service_url_strict ----------------------------------------
+
+ def test_strict_validation_raises_on_invalid(self):
+ with pytest.raises(NotificationURLValidationError):
+ NotificationURLValidator.validate_service_url_strict(
+ "file:///etc/passwd"
+ )
+
+ def test_strict_validation_returns_true_on_valid(self):
+ assert (
+ NotificationURLValidator.validate_service_url_strict(
+ "discord://id/token"
+ )
+ is True
+ )
+
+
+# ===================================================================
+# NotificationService
+# ===================================================================
+
+
+class TestNotificationService:
+ """Tests for the low-level notification service wrapping Apprise."""
+
+ def test_init_defaults(self):
+ svc = NotificationService()
+ assert svc.allow_private_ips is False
+
+ def test_init_allow_private_ips(self):
+ svc = NotificationService(allow_private_ips=True)
+ assert svc.allow_private_ips is True
+
+ # -- _validate_url (static) -------------------------------------------
+
+ def test_validate_url_rejects_empty(self):
+ with pytest.raises(ServiceError, match="non-empty"):
+ NotificationService._validate_url("")
+
+ def test_validate_url_rejects_none(self):
+ with pytest.raises(ServiceError, match="non-empty"):
+ NotificationService._validate_url(None)
+
+ def test_validate_url_rejects_no_scheme(self):
+ with pytest.raises(ServiceError, match="Invalid URL"):
+ NotificationService._validate_url("example.com/webhook")
+
+ def test_validate_url_accepts_valid(self):
+ # Should not raise
+ NotificationService._validate_url("discord://id/token")
+
+ # -- get_service_type --------------------------------------------------
+
+ def test_get_service_type_known(self):
+ svc = NotificationService()
+ assert svc.get_service_type("mailto://[email protected]") == "email"
+ assert svc.get_service_type("discord://id/token") == "discord"
+ assert svc.get_service_type("slack://a/b/c") == "slack"
+ assert svc.get_service_type("tgram://bot_token/chat_id") == "telegram"
+ assert svc.get_service_type("smtp://mail.example.com") == "smtp"
+ assert svc.get_service_type("smtps://mail.example.com") == "smtp"
+
+ def test_get_service_type_unknown(self):
+ svc = NotificationService()
+ assert svc.get_service_type("https://hooks.example.com") == "unknown"
+
+ # -- send (mocked Apprise) ---------------------------------------------
+
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_send_with_service_urls_success(self, MockApprise, MockValidator):
+ MockValidator.validate_multiple_urls.return_value = (True, None)
+ mock_instance = MockApprise.return_value
+ mock_instance.add.return_value = True
+ mock_instance.notify.return_value = True
+
+ svc = NotificationService()
+ result = svc.send(
+ title="Test",
+ body="Body",
+ service_urls="discord://id/token",
+ )
+ assert result is True
+ mock_instance.notify.assert_called_once()
+
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_send_with_invalid_url_raises_service_error(
+ self, MockApprise, MockValidator
+ ):
+ MockValidator.validate_multiple_urls.return_value = (
+ False,
+ "bad url",
+ )
+
+ svc = NotificationService()
+ with pytest.raises(SendError):
+ svc.send(
+ title="Test",
+ body="Body",
+ service_urls="file:///etc/passwd",
+ )
+
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_send_apprise_add_failure_returns_false(
+ self, MockApprise, MockValidator
+ ):
+ MockValidator.validate_multiple_urls.return_value = (True, None)
+ mock_instance = MockApprise.return_value
+ mock_instance.add.return_value = False
+
+ svc = NotificationService()
+ # When add() returns False the original apprise instance is used,
+ # but the temp one is used here so it returns False immediately.
+ result = svc.send(
+ title="Test", body="Body", service_urls="discord://id/token"
+ )
+ assert result is False
+
+ def test_send_no_urls_no_configured_services_returns_false(self):
+ svc = NotificationService()
+ result = svc.send(title="Test", body="Body")
+ assert result is False
+
+ # -- send_event --------------------------------------------------------
+
+ @patch.object(NotificationService, "send", return_value=True)
+ def test_send_event_uses_template(self, mock_send):
+ svc = NotificationService()
+ result = svc.send_event(
+ event_type=EventType.RESEARCH_COMPLETED,
+ context={"query": "test query", "research_id": "abc123"},
+ service_urls="discord://id/token",
+ )
+ assert result is True
+ mock_send.assert_called_once()
+ call_kwargs = mock_send.call_args
+ # The title and body should come from template formatting
+ assert call_kwargs[1]["service_urls"] == "discord://id/token"
+
+ # -- test_service (mocked Apprise) ------------------------------------
+
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_test_service_success(self, MockApprise, MockValidator):
+ MockValidator.validate_service_url.return_value = (True, None)
+ mock_instance = MockApprise.return_value
+ mock_instance.add.return_value = True
+ mock_instance.notify.return_value = True
+
+ svc = NotificationService()
+ result = svc.test_service("discord://id/token")
+ assert result["success"] is True
+
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ def test_test_service_invalid_url(self, MockValidator):
+ MockValidator.validate_service_url.return_value = (False, "blocked")
+
+ svc = NotificationService()
+ result = svc.test_service("file:///etc/passwd")
+ assert result["success"] is False
+ assert "error" in result
+
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_test_service_add_failure(self, MockApprise, MockValidator):
+ MockValidator.validate_service_url.return_value = (True, None)
+ mock_instance = MockApprise.return_value
+ mock_instance.add.return_value = False
+
+ svc = NotificationService()
+ result = svc.test_service("discord://id/token")
+ assert result["success"] is False
+ assert "Failed to add" in result["error"]
+
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ @patch("local_deep_research.notifications.service.apprise.Apprise")
+ def test_test_service_notify_failure(self, MockApprise, MockValidator):
+ MockValidator.validate_service_url.return_value = (True, None)
+ mock_instance = MockApprise.return_value
+ mock_instance.add.return_value = True
+ mock_instance.notify.return_value = False
+
+ svc = NotificationService()
+ result = svc.test_service("discord://id/token")
+ assert result["success"] is False
+ assert "Failed to send" in result["error"]
+
+ @patch("local_deep_research.notifications.service.NotificationURLValidator")
+ def test_test_service_exception(self, MockValidator):
+ MockValidator.validate_service_url.side_effect = RuntimeError("boom")
+
+ svc = NotificationService()
+ result = svc.test_service("discord://id/token")
+ assert result["success"] is False
+
+ # -- SERVICE_PATTERNS --------------------------------------------------
+
+ def test_service_patterns_are_valid_regexes(self):
+ import re
+
+ for name, pattern in NotificationService.SERVICE_PATTERNS.items():
+ re.compile(pattern) # Should not raise
+
+
+# ===================================================================
+# RateLimiter
+# ===================================================================
+
+
+class TestRateLimiter:
+ """Tests for the in-memory per-user rate limiter."""
+
+ def test_basic_allow(self):
+ rl = RateLimiter(max_per_hour=5, max_per_day=20)
+ assert rl.is_allowed("user1") is True
+
+ def test_hourly_limit_exceeded(self):
+ rl = RateLimiter(max_per_hour=3, max_per_day=100)
+ for _ in range(3):
+ assert rl.is_allowed("user1") is True
+ assert rl.is_allowed("user1") is False
+
+ def test_daily_limit_exceeded(self):
+ rl = RateLimiter(max_per_hour=100, max_per_day=3)
+ for _ in range(3):
+ assert rl.is_allowed("user1") is True
+ assert rl.is_allowed("user1") is False
+
+ def test_per_user_isolation(self):
+ rl = RateLimiter(max_per_hour=2, max_per_day=100)
+ # Exhaust user1's hourly limit
+ rl.is_allowed("user1")
+ rl.is_allowed("user1")
+ assert rl.is_allowed("user1") is False
+ # user2 should still be allowed
+ assert rl.is_allowed("user2") is True
+
+ def test_set_user_limits(self):
+ rl = RateLimiter(max_per_hour=10, max_per_day=50)
+ rl.set_user_limits("user1", max_per_hour=2, max_per_day=5)
+
+ limits = rl.get_user_limits("user1")
+ assert limits == (2, 5)
+
+ # User with custom limits
+ rl.is_allowed("user1")
+ rl.is_allowed("user1")
+ assert rl.is_allowed("user1") is False
+
+ # Default user still has 10/hour
+ for _ in range(10):
+ assert rl.is_allowed("default_user") is True
+ assert rl.is_allowed("default_user") is False
+
+ def test_get_user_limits_defaults(self):
+ rl = RateLimiter(max_per_hour=10, max_per_day=50)
+ assert rl.get_user_limits("unknown") == (10, 50)
+
+ def test_reset_single_user(self):
+ rl = RateLimiter(max_per_hour=2, max_per_day=100)
+ rl.is_allowed("user1")
+ rl.is_allowed("user1")
+ assert rl.is_allowed("user1") is False
+
+ rl.reset("user1")
+ assert rl.is_allowed("user1") is True
+
+ def test_reset_all_users(self):
+ rl = RateLimiter(max_per_hour=1, max_per_day=100)
+ rl.is_allowed("user1")
+ rl.is_allowed("user2")
+ assert rl.is_allowed("user1") is False
+ assert rl.is_allowed("user2") is False
+
+ rl.reset()
+ assert rl.is_allowed("user1") is True
+ assert rl.is_allowed("user2") is True
+
+ def test_old_entries_cleaned(self):
+ rl = RateLimiter(max_per_hour=2, max_per_day=100)
+ now = datetime.now(timezone.utc)
+ old = now - timedelta(hours=2)
+
+ # Manually inject old entries
+ rl._hourly_counts["user1"] = deque([old, old])
+ rl._daily_counts["user1"] = deque([old, old])
+
+ # After cleaning old entries, the user should be allowed again
+ assert rl.is_allowed("user1") is True
+
+ def test_cleanup_inactive_users(self):
+ rl = RateLimiter(
+ max_per_hour=10, max_per_day=50, cleanup_interval_hours=0
+ )
+ now = datetime.now(timezone.utc)
+ old = now - timedelta(days=8)
+
+ # Force a cleanup by setting last cleanup to long ago
+ rl._last_cleanup = now - timedelta(hours=25)
+ rl._hourly_counts["stale_user"] = deque([old])
+ rl._daily_counts["stale_user"] = deque([old])
+
+ # Trigger cleanup via is_allowed
+ rl.is_allowed("active_user")
+
+ assert "stale_user" not in rl._hourly_counts
+ assert "stale_user" not in rl._daily_counts
+
+ def test_thread_safety(self):
+ """Multiple threads hitting the rate limiter concurrently."""
+ rl = RateLimiter(max_per_hour=100, max_per_day=1000)
+ results = []
+ errors = []
+
+ def hit():
+ try:
+ for _ in range(50):
+ rl.is_allowed("concurrent_user")
+ results.append(True)
+ except Exception as e:
+ errors.append(e)
+
+ threads = [threading.Thread(target=hit) for _ in range(4)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=10)
+
+ assert len(errors) == 0
+ assert len(results) == 4
+
+
+# ===================================================================
+# NotificationManager
+# ===================================================================
+
+
+class TestNotificationManager:
+ """Tests for the high-level notification manager."""
+
+ def _make_manager(self, settings, user_id="test_user"):
+ return NotificationManager(settings_snapshot=settings, user_id=user_id)
+
+ # -- Initialization ---------------------------------------------------
+
+ def test_init_creates_shared_rate_limiter(self, default_settings):
+ mgr = self._make_manager(default_settings)
+ assert NotificationManager._shared_rate_limiter is not None
+ assert mgr._rate_limiter is NotificationManager._shared_rate_limiter
+
+ def test_init_reuses_shared_rate_limiter(self, default_settings):
+ mgr1 = self._make_manager(default_settings, "user_a")
+ mgr2 = self._make_manager(default_settings, "user_b")
+ assert mgr1._rate_limiter is mgr2._rate_limiter
+
+ def test_init_configures_per_user_limits(self, default_settings):
+ mgr = self._make_manager(default_settings, "user_a")
+ limits = mgr._rate_limiter.get_user_limits("user_a")
+ assert limits == (10, 50)
+
+ # -- _get_setting ------------------------------------------------------
+
+ def test_get_setting_returns_value(self, default_settings):
+ mgr = self._make_manager(default_settings)
+ assert mgr._get_setting("notifications.rate_limit_per_hour") == 10
+
+ def test_get_setting_returns_default(self, default_settings):
+ mgr = self._make_manager(default_settings)
+ assert (
+ mgr._get_setting("nonexistent.key", default="fallback")
+ == "fallback"
+ )
+
+ # -- _should_notify ----------------------------------------------------
+
+ def test_should_notify_enabled(self, default_settings):
+ mgr = self._make_manager(default_settings)
+ assert mgr._should_notify(EventType.RESEARCH_COMPLETED) is True
+
+ def test_should_notify_disabled(self, disabled_settings):
+ mgr = self._make_manager(disabled_settings)
+ assert mgr._should_notify(EventType.RESEARCH_COMPLETED) is False
+
+ def test_should_notify_missing_key(self, default_settings):
+ mgr = self._make_manager(default_settings)
+ # EventType.TEST is not in settings, should default to False
+ assert mgr._should_notify(EventType.TEST) is False
+
+ # -- send_notification -------------------------------------------------
+
+ @patch.object(NotificationService, "send_event", return_value=True)
+ def test_send_notification_success(self, mock_send_event, default_settings):
+ mgr = self._make_manager(default_settings)
+ result = mgr.send_notification(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test", "research_id": "123"},
+ )
+ assert result is True
+ mock_send_event.assert_called_once()
+
+ def test_send_notification_disabled_returns_false(self, disabled_settings):
+ mgr = self._make_manager(disabled_settings)
+ result = mgr.send_notification(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test"},
+ )
+ assert result is False
+
+ def test_send_notification_no_service_url_returns_false(self):
+ settings = {
+ "notifications.service_url": "",
+ "notifications.on_research_completed": True,
+ "notifications.rate_limit_per_hour": 10,
+ "notifications.rate_limit_per_day": 50,
+ }
+ mgr = self._make_manager(settings)
+ result = mgr.send_notification(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test"},
+ )
+ assert result is False
+
+ def test_send_notification_rate_limited(self):
+ settings = {
+ "notifications.service_url": "discord://id/token",
+ "notifications.on_research_completed": True,
+ "notifications.rate_limit_per_hour": 1,
+ "notifications.rate_limit_per_day": 50,
+ }
+ mgr = self._make_manager(settings, "rate_test_user")
+
+ with patch.object(NotificationService, "send_event", return_value=True):
+ mgr.send_notification(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "first"},
+ )
+
+ with pytest.raises(RateLimitError):
+ mgr.send_notification(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "second"},
+ )
+
+ @patch.object(NotificationService, "send_event", return_value=True)
+ def test_send_notification_force_bypasses_rate_limit(self, mock_send):
+ settings = {
+ "notifications.service_url": "discord://id/token",
+ "notifications.on_research_completed": True,
+ "notifications.rate_limit_per_hour": 1,
+ "notifications.rate_limit_per_day": 50,
+ }
+ mgr = self._make_manager(settings, "force_user")
+
+ mgr.send_notification(EventType.RESEARCH_COMPLETED, {"query": "first"})
+ # Would normally be rate-limited, but force=True
+ result = mgr.send_notification(
+ EventType.RESEARCH_COMPLETED, {"query": "second"}, force=True
+ )
+ assert result is True
+
+ @patch.object(NotificationService, "send_event", return_value=True)
+ def test_send_notification_force_bypasses_disabled(self, mock_send):
+ settings = {
+ "notifications.service_url": "discord://id/token",
+ "notifications.on_research_completed": False,
+ "notifications.rate_limit_per_hour": 10,
+ "notifications.rate_limit_per_day": 50,
+ }
+ mgr = self._make_manager(settings, "force_user2")
+ result = mgr.send_notification(
+ EventType.RESEARCH_COMPLETED, {"query": "forced"}, force=True
+ )
+ assert result is True
+
+ @patch.object(
+ NotificationService, "send_event", side_effect=Exception("boom")
+ )
+ def test_send_notification_exception_returns_false(
+ self, mock_send, default_settings
+ ):
+ mgr = self._make_manager(default_settings)
+ result = mgr.send_notification(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test"},
+ )
+ assert result is False
+
+ # -- test_service via manager ------------------------------------------
+
+ @patch.object(
+ NotificationService, "test_service", return_value={"success": True}
+ )
+ def test_manager_test_service_delegates(self, mock_test, default_settings):
+ mgr = self._make_manager(default_settings)
+ result = mgr.test_service("discord://id/token")
+ assert result["success"] is True
+ mock_test.assert_called_once_with("discord://id/token")
+
+ # -- _log_notification -------------------------------------------------
+
+ def test_log_notification_with_query(self, default_settings):
+ mgr = self._make_manager(default_settings)
+ # Should not raise
+ mgr._log_notification(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test query"},
+ )
+
+ def test_log_notification_with_subscription(self, default_settings):
+ mgr = self._make_manager(default_settings)
+ mgr._log_notification(
+ EventType.SUBSCRIPTION_UPDATE,
+ {"subscription_name": "my sub"},
+ )
+
+ def test_log_notification_empty_context(self, default_settings):
+ mgr = self._make_manager(default_settings)
+ mgr._log_notification(EventType.TEST, {})
+
+
+# ===================================================================
+# NotificationTemplate
+# ===================================================================
+
+
+class TestNotificationTemplate:
+ """Tests for Jinja2-based notification templates."""
+
+ def test_format_returns_title_and_body(self):
+ result = NotificationTemplate.format(
+ EventType.RESEARCH_COMPLETED,
+ {
+ "query": "quantum computing",
+ "research_id": "abc",
+ "summary": "results",
+ "url": "http://example.com",
+ },
+ )
+ assert "title" in result
+ assert "body" in result
+ assert isinstance(result["title"], str)
+ assert isinstance(result["body"], str)
+
+ def test_format_with_custom_template(self):
+ custom = {
+ "title": "Custom: {query}",
+ "body": "Research {research_id} is done.",
+ }
+ result = NotificationTemplate.format(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test", "research_id": "123"},
+ custom_template=custom,
+ )
+ assert result["title"] == "Custom: test"
+ assert result["body"] == "Research 123 is done."
+
+ def test_format_custom_template_missing_var(self):
+ custom = {
+ "title": "{missing_var}",
+ "body": "Body",
+ }
+ result = NotificationTemplate.format(
+ EventType.RESEARCH_COMPLETED,
+ {},
+ custom_template=custom,
+ )
+ assert (
+ "Missing variable" in result["body"]
+ or "error" in result["body"].lower()
+ )
+
+ def test_format_custom_template_sanitizes_context(self):
+ """Ensure format string attacks are prevented."""
+ custom = {
+ "title": "{query}",
+ "body": "Body",
+ }
+ result = NotificationTemplate.format(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "{__class__.__mro__}"},
+ custom_template=custom,
+ )
+ # The attack payload should be treated as a plain string
+ assert "__class__" in result["title"]
+
+ def test_fallback_template(self):
+ result = NotificationTemplate._get_fallback_template(
+ EventType.RESEARCH_COMPLETED,
+ {"query": "test"},
+ )
+ assert "title" in result
+ assert "body" in result
+ assert "Research Completed" in result["title"]
+
+ def test_event_type_values(self):
+ """All EventType values are strings."""
+ for et in EventType:
+ assert isinstance(et.value, str)
+
+ def test_get_required_context_returns_list(self):
+ result = NotificationTemplate.get_required_context(
+ EventType.RESEARCH_COMPLETED
+ )
+ assert isinstance(result, list)
+
+ def test_format_unknown_event_type(self):
+ """Event type without a template file should produce a generic message."""
+ # RATE_LIMIT_WARNING has no template file in TEMPLATE_FILES
+ result = NotificationTemplate.format(
+ EventType.RATE_LIMIT_WARNING,
+ {"detail": "too many requests"},
+ )
+ assert "title" in result
+ assert "body" in result
+
+
+# ===================================================================
+# build_notification_url
+# ===================================================================
+
+
+class TestBuildNotificationUrl:
+ """Tests for notification callback URL building."""
+
+ def test_with_external_url(self):
+ snapshot = {"app.external_url": "https://myapp.example.com"}
+ url = build_notification_url(
+ "/research/123",
+ settings_snapshot=snapshot,
+ )
+ assert url == "https://myapp.example.com/research/123"
+
+ def test_with_host_and_port(self):
+ snapshot = {
+ "app.external_url": "",
+ "app.host": "0.0.0.0",
+ "app.port": 5000,
+ }
+ url = build_notification_url(
+ "/research/456",
+ settings_snapshot=snapshot,
+ )
+ assert url == "http://localhost:5000/research/456"
+
+ def test_fallback_url(self):
+ url = build_notification_url(
+ "/research/789",
+ settings_snapshot={},
+ fallback_base="http://localhost:5000",
+ )
+ assert url == "http://localhost:5000/research/789"
+
+ def test_validation_disabled(self):
+ url = build_notification_url(
+ "/research/abc",
+ settings_snapshot={},
+ validate=False,
+ )
+ assert "/research/abc" in url
+
+ def test_validation_catches_bad_url(self):
+ with pytest.raises(URLValidationError):
+ build_notification_url(
+ "/research/123",
+ settings_snapshot={"app.external_url": "ftp://bad.example.com"},
+ validate=True,
+ )
+
+
+# ===================================================================
+# Queue helpers
+# ===================================================================
+
+
+class TestQueueHelpers:
+ """Tests for queue notification helper functions."""
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_send_queue_notification_success(self, MockManager):
+ mock_instance = MockManager.return_value
+ mock_instance.send_notification.return_value = True
+
+ settings = {
+ "notifications.rate_limit_per_hour": 10,
+ "notifications.rate_limit_per_day": 50,
+ }
+ result = send_queue_notification(
+ username="alice",
+ research_id="r1",
+ query="test query",
+ settings_snapshot=settings,
+ position=3,
+ )
+ assert result is True
+ mock_instance.send_notification.assert_called_once()
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_send_queue_notification_rate_limited(self, MockManager):
+ mock_instance = MockManager.return_value
+ mock_instance.send_notification.side_effect = RateLimitError("limited")
+
+ result = send_queue_notification(
+ username="alice",
+ research_id="r1",
+ query="test",
+ settings_snapshot={},
+ )
+ assert result is False
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_send_queue_notification_exception(self, MockManager):
+ MockManager.side_effect = Exception("boom")
+
+ result = send_queue_notification(
+ username="alice",
+ research_id="r1",
+ query="test",
+ settings_snapshot={},
+ )
+ assert result is False
+
+ def test_send_queue_failed_no_snapshot(self):
+ result = send_queue_failed_notification(
+ username="alice",
+ research_id="r1",
+ query="test",
+ settings_snapshot=None,
+ )
+ assert result is False
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_send_queue_failed_success(self, MockManager):
+ mock_instance = MockManager.return_value
+ mock_instance.send_notification.return_value = True
+
+ result = send_queue_failed_notification(
+ username="bob",
+ research_id="r2",
+ query="failed query",
+ error_message="timeout",
+ settings_snapshot={"notifications.rate_limit_per_hour": 10},
+ )
+ assert result is True
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_send_queue_failed_rate_limited(self, MockManager):
+ mock_instance = MockManager.return_value
+ mock_instance.send_notification.side_effect = RateLimitError("limited")
+
+ result = send_queue_failed_notification(
+ username="bob",
+ research_id="r2",
+ query="test",
+ settings_snapshot={"x": 1},
+ )
+ assert result is False
+
+
+# ===================================================================
+# mask_sensitive_url
+# ===================================================================
+
+
+class TestMaskSensitiveUrl:
+ """Tests for URL credential masking."""
+
+ def test_masks_password(self):
+ url = "https://user:[email protected]/path"
+ masked = mask_sensitive_url(url)
+ assert "secretpassword" not in masked
+ assert "***" in masked
+
+ def test_masks_long_tokens_in_path(self):
+ url = "discord://12345678901234567890123456/abcdefghijklmnopqrstuvwxyz"
+ masked = mask_sensitive_url(url)
+ # Long alphanumeric tokens should be masked
+ assert "***" in masked
+
+ def test_masks_query_string(self):
+ url = "https://hooks.example.com/webhook?token=secret123"
+ masked = mask_sensitive_url(url)
+ assert "secret123" not in masked
+
+ def test_preserves_scheme(self):
+ url = "https://example.com/path"
+ masked = mask_sensitive_url(url)
+ assert masked.startswith("https://")
+
+ def test_handles_invalid_url(self):
+ # Should not raise, returns something with ***
+ result = mask_sensitive_url("not a url at all")
+ assert isinstance(result, str)
+
+ def test_simple_url_no_secrets(self):
+ url = "https://example.com/short"
+ masked = mask_sensitive_url(url)
+ assert "example.com" in masked
+
+
+# ===================================================================
+# Exception hierarchy
+# ===================================================================
+
+
+class TestExceptionHierarchy:
+ """Verify exception inheritance is correct."""
+
+ def test_service_error_is_notification_error(self):
+ assert issubclass(ServiceError, NotificationError)
+
+ def test_send_error_is_notification_error(self):
+ assert issubclass(SendError, NotificationError)
+
+ def test_rate_limit_error_is_notification_error(self):
+ assert issubclass(RateLimitError, NotificationError)
+
+ def test_notification_error_is_exception(self):
+ assert issubclass(NotificationError, Exception)
+
+ def test_notification_url_validation_error_is_value_error(self):
+ assert issubclass(NotificationURLValidationError, ValueError)
+
+ def test_url_validation_error_is_value_error(self):
+ assert issubclass(URLValidationError, ValueError)
+
+ def test_exceptions_carry_message(self):
+ e = SendError("test message")
+ assert str(e) == "test message"
+
+
+# ===================================================================
+# URLValidator (callback URL validation)
+# ===================================================================
+
+
+class TestURLValidatorHTTP:
+ """Tests for validate_http_url used in notification callback URLs."""
+
+ def test_valid_https(self):
+ assert (
+ URLValidator.validate_http_url("https://example.com/path") is True
+ )
+
+ def test_valid_http(self):
+ assert URLValidator.validate_http_url("http://example.com/path") is True
+
+ def test_rejects_ftp(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("ftp://example.com")
+
+ def test_rejects_empty(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("")
+
+ def test_rejects_none(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url(None)
+
+ def test_rejects_no_scheme(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("example.com/path")
+
+ def test_rejects_javascript(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("javascript:alert(1)")
diff --git a/tests/web_search_engines/engines/test_embedding_manager_coverage.py b/tests/web_search_engines/engines/test_embedding_manager_coverage.py
new file mode 100644
index 0000000000..0b20a0bd4a
--- /dev/null
+++ b/tests/web_search_engines/engines/test_embedding_manager_coverage.py
@@ -0,0 +1,603 @@
+"""
+Comprehensive tests for LocalEmbeddingManager.
+
+Covers:
+- close() resource cleanup and idempotency
+- Context manager (__enter__ / __exit__)
+- Lazy initialization via the embeddings property
+- _store_chunks_to_db() including deduplication and edge cases
+- _delete_chunks_from_db()
+- Provider selection logic in _initialize_embeddings()
+"""
+
+import hashlib
+import threading
+from contextlib import contextmanager
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+from langchain_core.documents import Document
+
+from local_deep_research.web_search_engines.engines.local_embedding_manager import (
+ LocalEmbeddingManager,
+)
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def manager():
+ """Return a vanilla manager with no side-effects."""
+ return LocalEmbeddingManager()
+
+
+def manager_with_user():
+ """Return a manager that has a username set (needed for DB operations)."""
+ return LocalEmbeddingManager(
+ settings_snapshot={"_username": "testuser"},
+ )
+
+
+# ---------------------------------------------------------------------------
+# close() – resource cleanup
+# ---------------------------------------------------------------------------
+
+
+class TestClose:
+ def test_close_sets_closed_flag(self, manager):
+ assert manager._closed is False
+ manager.close()
+ assert manager._closed is True
+
+ def test_close_clears_embeddings(self, manager):
+ manager._embeddings = Mock()
+ manager.close()
+ assert manager._embeddings is None
+
+ def test_close_clears_vector_stores(self, manager):
+ manager.vector_stores["col1"] = Mock()
+ manager.close()
+ assert manager.vector_stores == {}
+
+ def test_close_is_idempotent(self, manager):
+ """Calling close() multiple times must not raise."""
+ manager._embeddings = Mock()
+ manager.close()
+ manager.close() # second call is a no-op
+ assert manager._closed is True
+
+ def test_close_idempotent_does_not_re_clear(self, manager):
+ """After a second close(), attributes stay cleared."""
+ manager._embeddings = Mock()
+ manager.close()
+ # Manually set something after first close to prove second is no-op
+ manager._embeddings = "sentinel"
+ manager.close()
+ # _embeddings should still be "sentinel" because close() returned early
+ assert manager._embeddings == "sentinel"
+
+
+# ---------------------------------------------------------------------------
+# Context manager
+# ---------------------------------------------------------------------------
+
+
+class TestContextManager:
+ def test_enter_returns_self(self, manager):
+ result = manager.__enter__()
+ assert result is manager
+
+ def test_exit_calls_close(self, manager):
+ with patch.object(manager, "close") as mock_close:
+ manager.__exit__(None, None, None)
+ mock_close.assert_called_once()
+
+ def test_exit_returns_false(self, manager):
+ """__exit__ must not suppress exceptions."""
+ assert manager.__exit__(None, None, None) is False
+
+ def test_with_statement_closes(self):
+ with LocalEmbeddingManager() as mgr:
+ assert mgr._closed is False
+ assert mgr._closed is True
+
+ def test_with_statement_closes_on_exception(self):
+ with pytest.raises(RuntimeError):
+ with LocalEmbeddingManager() as mgr:
+ raise RuntimeError("boom")
+ assert mgr._closed is True
+
+
+# ---------------------------------------------------------------------------
+# Lazy initialization – embeddings property
+# ---------------------------------------------------------------------------
+
+
+class TestEmbeddingsProperty:
+ def test_lazy_init_called_once(self, manager):
+ mock_emb = Mock()
+ with patch.object(
+ manager, "_initialize_embeddings", return_value=mock_emb
+ ) as mock_init:
+ emb1 = manager.embeddings
+ emb2 = manager.embeddings
+ mock_init.assert_called_once()
+ assert emb1 is emb2 is mock_emb
+
+ def test_already_set_embeddings_not_reinit(self, manager):
+ sentinel = object()
+ manager._embeddings = sentinel
+ with patch.object(manager, "_initialize_embeddings") as mock_init:
+ assert manager.embeddings is sentinel
+ mock_init.assert_not_called()
+
+ def test_thread_safety_single_init(self):
+ """Multiple threads must trigger only one initialization."""
+ mgr = LocalEmbeddingManager()
+ init_count = 0
+ lock = threading.Lock()
+ mock_emb = Mock()
+
+ def counting_init():
+ nonlocal init_count
+ with lock:
+ init_count += 1
+ import time
+
+ time.sleep(0.05)
+ return mock_emb
+
+ mgr._initialize_embeddings = counting_init
+
+ threads = [
+ threading.Thread(target=lambda: mgr.embeddings) for _ in range(8)
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert init_count == 1
+
+
+# ---------------------------------------------------------------------------
+# Provider selection – _initialize_embeddings
+# ---------------------------------------------------------------------------
+
+
+class TestInitializeEmbeddings:
+ @patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_embeddings",
+ create=True,
+ )
+ def test_sentence_transformers_passes_device(self, _mock_get):
+ """For sentence_transformers, device kwarg must be forwarded."""
+ with patch("local_deep_research.embeddings.get_embeddings") as mock_get:
+ mock_get.return_value = Mock()
+ mgr = LocalEmbeddingManager(
+ embedding_model_type="sentence_transformers",
+ embedding_device="cuda",
+ )
+ mgr._initialize_embeddings()
+ mock_get.assert_called_once()
+ _, kwargs = mock_get.call_args
+ assert kwargs["device"] == "cuda"
+ assert kwargs["provider"] == "sentence_transformers"
+
+ def test_ollama_passes_base_url(self):
+ with patch("local_deep_research.embeddings.get_embeddings") as mock_get:
+ mock_get.return_value = Mock()
+ mgr = LocalEmbeddingManager(
+ embedding_model_type="ollama",
+ embedding_model="nomic-embed-text",
+ ollama_base_url="http://myhost:11434",
+ )
+ mgr._initialize_embeddings()
+ _, kwargs = mock_get.call_args
+ assert "base_url" in kwargs
+ assert kwargs["provider"] == "ollama"
+
+ def test_ollama_without_base_url_omits_it(self):
+ with patch("local_deep_research.embeddings.get_embeddings") as mock_get:
+ mock_get.return_value = Mock()
+ mgr = LocalEmbeddingManager(
+ embedding_model_type="ollama",
+ embedding_model="nomic-embed-text",
+ ollama_base_url=None,
+ )
+ mgr._initialize_embeddings()
+ _, kwargs = mock_get.call_args
+ assert "base_url" not in kwargs
+
+ def test_fallback_on_exception(self):
+ """When get_embeddings raises, should fall back to HuggingFaceEmbeddings."""
+ with patch(
+ "local_deep_research.embeddings.get_embeddings",
+ side_effect=RuntimeError("boom"),
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.HuggingFaceEmbeddings"
+ ) as mock_hf:
+ mock_hf.return_value = Mock()
+ mgr = LocalEmbeddingManager()
+ result = mgr._initialize_embeddings()
+ mock_hf.assert_called_once_with(
+ model_name="sentence-transformers/all-MiniLM-L6-v2"
+ )
+ assert result is mock_hf.return_value
+
+
+# ---------------------------------------------------------------------------
+# _store_chunks_to_db
+# ---------------------------------------------------------------------------
+
+
+def _make_doc(text, metadata=None):
+ return Document(page_content=text, metadata=metadata or {})
+
+
+class TestStoreChunksToDb:
+ def test_no_username_returns_empty(self, manager):
+ """Without a username the method should bail out early."""
+ result = manager._store_chunks_to_db(
+ [_make_doc("hello")], "collection_abc"
+ )
+ assert result == []
+
+ def test_stores_new_chunks(self, manager_with_user):
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ docs = [_make_doc("chunk one"), _make_doc("chunk two")]
+ ids = manager_with_user._store_chunks_to_db(docs, "col1")
+
+ assert len(ids) == 2
+ assert mock_session.add.call_count == 2
+ mock_session.commit.assert_called_once()
+
+ def test_deduplication_reuses_existing_chunk(self, manager_with_user):
+ existing = MagicMock()
+ existing.embedding_id = "existing-id-123"
+ existing.last_accessed = None
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = existing
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ ids = manager_with_user._store_chunks_to_db(
+ [_make_doc("duplicate text")], "col1"
+ )
+
+ assert ids == ["existing-id-123"]
+ # Should NOT add a new row
+ mock_session.add.assert_not_called()
+ mock_session.commit.assert_called_once()
+ # last_accessed should be updated
+ assert existing.last_accessed is not None
+
+ def test_mixed_new_and_existing(self, manager_with_user):
+ existing = MagicMock()
+ existing.embedding_id = "old-id"
+
+ call_count = 0
+
+ def side_effect(**kwargs):
+ nonlocal call_count
+ call_count += 1
+ mock_filter = MagicMock()
+ if call_count == 1:
+ mock_filter.first.return_value = existing
+ else:
+ mock_filter.first.return_value = None
+ return mock_filter
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by = side_effect
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ docs = [_make_doc("existing text"), _make_doc("new text")]
+ ids = manager_with_user._store_chunks_to_db(docs, "col1")
+
+ assert len(ids) == 2
+ assert ids[0] == "old-id"
+ assert mock_session.add.call_count == 1
+
+ def test_metadata_extraction(self, manager_with_user):
+ """Chunk metadata (filename, start_char, end_char) is forwarded."""
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ added_objects = []
+ mock_session.add.side_effect = lambda obj: added_objects.append(obj)
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
+ ) as MockChunk,
+ ):
+ MockChunk.side_effect = lambda **kw: MagicMock(**kw)
+ meta = {"filename": "notes.txt", "start_char": 10, "end_char": 50}
+ manager_with_user._store_chunks_to_db(
+ [_make_doc("text", metadata=meta)],
+ "col1",
+ source_path="/tmp/notes.txt",
+ source_id=42,
+ source_type="local_file",
+ )
+ _, kwargs = MockChunk.call_args
+ assert kwargs["document_title"] == "notes.txt"
+ assert kwargs["start_char"] == 10
+ assert kwargs["end_char"] == 50
+ assert kwargs["source_path"] == "/tmp/notes.txt"
+ assert kwargs["source_id"] == 42
+
+ def test_title_falls_back_to_title_key(self, manager_with_user):
+ """If 'filename' missing, document_title falls back to 'title'."""
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
+ ) as MockChunk,
+ ):
+ MockChunk.side_effect = lambda **kw: MagicMock(**kw)
+ meta = {"title": "My Paper"}
+ manager_with_user._store_chunks_to_db(
+ [_make_doc("text", metadata=meta)], "col1"
+ )
+ _, kwargs = MockChunk.call_args
+ assert kwargs["document_title"] == "My Paper"
+
+ def test_title_defaults_to_unknown(self, manager_with_user):
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
+ ) as MockChunk,
+ ):
+ MockChunk.side_effect = lambda **kw: MagicMock(**kw)
+ manager_with_user._store_chunks_to_db([_make_doc("text")], "col1")
+ _, kwargs = MockChunk.call_args
+ assert kwargs["document_title"] == "Unknown"
+
+ def test_db_exception_returns_empty(self, manager_with_user):
+ """If the DB session raises, return []."""
+
+ @contextmanager
+ def exploding_session(u, p):
+ raise RuntimeError("DB down")
+ yield # noqa: unreachable
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=exploding_session,
+ ):
+ result = manager_with_user._store_chunks_to_db(
+ [_make_doc("text")], "col1"
+ )
+ assert result == []
+
+ def test_empty_chunks_list(self, manager_with_user):
+ mock_session = MagicMock()
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ ids = manager_with_user._store_chunks_to_db([], "col1")
+
+ assert ids == []
+ mock_session.add.assert_not_called()
+ mock_session.commit.assert_called_once()
+
+ def test_chunk_hash_uses_sha256(self, manager_with_user):
+ """Verify the chunk hash is computed as SHA256 of page_content."""
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ filter_by_calls = []
+ original_filter_by = mock_session.query.return_value.filter_by
+
+ def capture_filter_by(**kwargs):
+ filter_by_calls.append(kwargs)
+ return original_filter_by(**kwargs)
+
+ mock_session.query.return_value.filter_by = capture_filter_by
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ text = "hello world"
+ expected_hash = hashlib.sha256(text.encode()).hexdigest()
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
+ ) as MockChunk,
+ ):
+ MockChunk.side_effect = lambda **kw: MagicMock(**kw)
+ manager_with_user._store_chunks_to_db([_make_doc(text)], "col1")
+
+ assert any(
+ c.get("chunk_hash") == expected_hash for c in filter_by_calls
+ )
+
+ def test_word_count_calculation(self, manager_with_user):
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
+ ) as MockChunk,
+ ):
+ MockChunk.side_effect = lambda **kw: MagicMock(**kw)
+ manager_with_user._store_chunks_to_db(
+ [_make_doc("one two three four")], "col1"
+ )
+ _, kwargs = MockChunk.call_args
+ assert kwargs["word_count"] == 4
+
+
+# ---------------------------------------------------------------------------
+# _delete_chunks_from_db
+# ---------------------------------------------------------------------------
+
+
+class TestDeleteChunksFromDb:
+ def test_no_username_returns_zero(self, manager):
+ result = manager._delete_chunks_from_db("col1")
+ assert result == 0
+
+ def test_delete_by_collection(self, manager_with_user):
+ mock_session = MagicMock()
+ mock_query = MagicMock()
+ mock_session.query.return_value.filter_by.return_value = mock_query
+ mock_query.delete.return_value = 5
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ count = manager_with_user._delete_chunks_from_db("col1")
+
+ assert count == 5
+ mock_session.commit.assert_called_once()
+
+ def test_delete_with_source_path_filter(self, manager_with_user):
+ mock_session = MagicMock()
+ mock_q1 = MagicMock()
+ mock_q2 = MagicMock()
+ mock_session.query.return_value.filter_by.return_value = mock_q1
+ mock_q1.filter_by.return_value = mock_q2
+ mock_q2.delete.return_value = 2
+
+ @contextmanager
+ def fake_session(u, p):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ count = manager_with_user._delete_chunks_from_db(
+ "col1", source_path="/tmp/file.txt"
+ )
+
+ assert count == 2
+
+ def test_delete_db_exception_returns_zero(self, manager_with_user):
+ @contextmanager
+ def exploding_session(u, p):
+ raise RuntimeError("DB down")
+ yield
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
+ side_effect=exploding_session,
+ ):
+ count = manager_with_user._delete_chunks_from_db("col1")
+
+ assert count == 0
+
+
+# ---------------------------------------------------------------------------
+# Init defaults and settings
+# ---------------------------------------------------------------------------
+
+
+class TestInitialization:
+ def test_defaults(self):
+ mgr = LocalEmbeddingManager()
+ assert mgr.embedding_model == "all-MiniLM-L6-v2"
+ assert mgr.embedding_device == "cpu"
+ assert mgr.embedding_model_type == "sentence_transformers"
+ assert mgr.ollama_base_url is None
+ assert mgr.settings_snapshot == {}
+ assert mgr.username is None
+ assert mgr.db_password is None
+ assert mgr._closed is False
+ assert mgr.vector_stores == {}
+
+ def test_settings_snapshot_none_defaults_to_empty_dict(self):
+ mgr = LocalEmbeddingManager(settings_snapshot=None)
+ assert mgr.settings_snapshot == {}
+ assert mgr.username is None
+
+ def test_username_extracted_from_settings(self):
+ mgr = LocalEmbeddingManager(settings_snapshot={"_username": "alice"})
+ assert mgr.username == "alice"
diff --git a/tests/web_search_engines/engines/test_guardian_coverage.py b/tests/web_search_engines/engines/test_guardian_coverage.py
new file mode 100644
index 0000000000..8b891bc6a2
--- /dev/null
+++ b/tests/web_search_engines/engines/test_guardian_coverage.py
@@ -0,0 +1,985 @@
+"""
+Comprehensive tests for GuardianSearchEngine focusing on pure logic coverage.
+
+Covers edge cases and deeper logic in:
+- _optimize_query_for_guardian() - LLM query optimization with various LLM responses
+- _adapt_dates_for_query_type() - Date range adaptation for historical/current/unclear
+- _get_previews() - Preview formatting and metadata storage
+- _get_full_content() - Cache hit/miss paths
+- _get_all_data() - API parameter construction, truncation, tag extraction
+- Initialization edge cases
+"""
+
+from datetime import datetime, timedelta, UTC
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.web_search_engines.engines.search_engine_guardian import (
+ GuardianSearchEngine,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_engine(**kwargs):
+ """Create a GuardianSearchEngine with sensible defaults for testing."""
+ defaults = {"api_key": "test-key"}
+ defaults.update(kwargs)
+ return GuardianSearchEngine(**defaults)
+
+
+def _mock_llm(content: str):
+ """Return a mock LLM whose invoke() returns a response with given content."""
+ llm = Mock()
+ llm.invoke.return_value = Mock(content=content)
+ return llm
+
+
+def _guardian_api_response(results):
+ """Build a mock response object mimicking the Guardian API JSON shape."""
+ resp = Mock()
+ resp.json.return_value = {"response": {"results": results}}
+ resp.raise_for_status = Mock()
+ return resp
+
+
+def _sample_article(
+ article_id="art-1",
+ headline="Headline One",
+ trail="Trail text",
+ byline="Author A",
+ body="<p>Body</p>",
+ url="https://theguardian.com/art-1",
+ pub_date="2025-03-01T12:00:00Z",
+ section="World news",
+ tags=None,
+):
+ """Return a single raw Guardian API article dict."""
+ return {
+ "id": article_id,
+ "webTitle": headline,
+ "webUrl": url,
+ "webPublicationDate": pub_date,
+ "sectionName": section,
+ "fields": {
+ "headline": headline,
+ "trailText": trail,
+ "byline": byline,
+ "body": body,
+ },
+ "tags": tags or [],
+ }
+
+
+# ===================================================================
+# _optimize_query_for_guardian
+# ===================================================================
+
+
+class TestOptimizeQueryEdgeCases:
+ def test_long_query_truncated_before_llm(self):
+ """Queries >150 chars are truncated to first 10 words before LLM call."""
+ llm = _mock_llm("short result")
+ engine = _make_engine(llm=llm)
+
+ long_query = " ".join(f"word{i}" for i in range(30))
+ assert len(long_query) > 150
+
+ result = engine._optimize_query_for_guardian(long_query)
+ # LLM was called with the truncated form (10 words)
+ prompt_arg = llm.invoke.call_args[0][0]
+ # The prompt should contain only the first 10 words of the original query
+ truncated = " ".join(long_query.split()[:10])
+ assert truncated in prompt_arg
+ assert result == "short result"
+
+ def test_llm_returns_think_tags_stripped(self):
+ """<think> tags in LLM output are removed."""
+ llm = _mock_llm("<think>reasoning here</think>UK economy")
+ engine = _make_engine(llm=llm)
+
+ result = engine._optimize_query_for_guardian("UK economy outlook")
+ assert result == "UK economy"
+
+ def test_llm_returns_multiline_picks_first_good_line(self):
+ """If LLM returns multiple lines, first non-preamble line is chosen."""
+ llm = _mock_llm("Here is the query:\nclimate change policy")
+ engine = _make_engine(llm=llm)
+
+ result = engine._optimize_query_for_guardian("climate change")
+ assert result == "climate change policy"
+
+ def test_llm_returns_multiline_all_preamble_uses_last(self):
+ """If every line is a preamble, the first line is still kept (loop finds nothing better)."""
+ llm = _mock_llm("Here is the best query\nI would suggest this")
+ engine = _make_engine(llm=llm)
+
+ result = engine._optimize_query_for_guardian("test")
+ # The loop doesn't find a good line, so optimized_query remains the full text
+ # (the loop doesn't update optimized_query if no good line found)
+ assert (
+ "Here is the best query" in result
+ or "I would suggest this" in result
+ )
+
+ def test_llm_returns_quoted_string_unquoted(self):
+ """Quotes wrapping the entire response are stripped."""
+ llm = _mock_llm('"UK housing rates"')
+ engine = _make_engine(llm=llm)
+
+ result = engine._optimize_query_for_guardian("housing in UK")
+ assert result == "UK housing rates"
+
+ def test_llm_returns_partial_quotes_not_stripped(self):
+ """Quotes that don't wrap the full string are kept."""
+ llm = _mock_llm('"UK" housing "rates"')
+ engine = _make_engine(llm=llm)
+
+ result = engine._optimize_query_for_guardian("housing in UK")
+ # count of quotes != 2, so no stripping
+ assert result == '"UK" housing "rates"'
+
+ def test_llm_exception_falls_back_to_original(self):
+ """If LLM raises an exception, original query is returned."""
+ llm = Mock()
+ llm.invoke.side_effect = RuntimeError("LLM down")
+ engine = _make_engine(llm=llm)
+
+ result = engine._optimize_query_for_guardian("original query")
+ assert result == "original query"
+
+ def test_no_llm_returns_original(self):
+ """Without LLM, query returned as-is."""
+ engine = _make_engine()
+ assert engine._optimize_query_for_guardian("my query") == "my query"
+
+ def test_optimize_disabled_returns_original(self):
+ """With optimize_queries=False, query returned as-is even with LLM."""
+ llm = _mock_llm("optimized")
+ engine = _make_engine(llm=llm, optimize_queries=False)
+ assert engine._optimize_query_for_guardian("my query") == "my query"
+ llm.invoke.assert_not_called()
+
+ def test_long_query_no_llm_still_truncated(self):
+ """Long query is truncated even without LLM."""
+ engine = _make_engine()
+ long_query = " ".join(["longword"] * 30)
+ result = engine._optimize_query_for_guardian(long_query)
+ assert len(result.split()) == 10
+
+ def test_llm_returns_empty_lines_then_content(self):
+ """Empty lines before content are skipped."""
+ llm = _mock_llm("\n\n\nclimate action\n")
+ engine = _make_engine(llm=llm)
+ result = engine._optimize_query_for_guardian("climate")
+ assert result == "climate action"
+
+ def test_llm_returns_line_starting_with_this_query(self):
+ """Lines starting with 'this query' are skipped as preamble."""
+ llm = _mock_llm("This query should be:\nrenewable energy")
+ engine = _make_engine(llm=llm)
+ result = engine._optimize_query_for_guardian("green energy")
+ assert result == "renewable energy"
+
+ def test_llm_returns_line_starting_with_the_best(self):
+ """Lines starting with 'the best' are skipped."""
+ llm = _mock_llm("The best search term is:\nAI regulation")
+ engine = _make_engine(llm=llm)
+ result = engine._optimize_query_for_guardian("AI laws")
+ assert result == "AI regulation"
+
+
+# ===================================================================
+# _adapt_dates_for_query_type
+# ===================================================================
+
+
+class TestAdaptDatesForQueryType:
+ def test_short_query_sets_60_days_and_newest(self):
+ """Queries with <= 4 words get 60-day window and newest ordering."""
+ engine = _make_engine()
+ engine.order_by = "relevance"
+
+ engine._adapt_dates_for_query_type("UK politics")
+
+ expected_from = (datetime.now(UTC) - timedelta(days=60)).strftime(
+ "%Y-%m-%d"
+ )
+ assert engine.from_date == expected_from
+ assert engine.order_by == "newest"
+
+ def test_short_query_four_words_is_short(self):
+ """Exactly 4 words triggers the short-query fast path."""
+ engine = _make_engine()
+ engine._adapt_dates_for_query_type("one two three four")
+ assert engine.order_by == "newest"
+
+ def test_five_words_not_short_path(self):
+ """5 words does NOT trigger the short-query fast path (no LLM, no change)."""
+ engine = _make_engine()
+ original_order = engine.order_by
+ original_from = engine.from_date
+ engine._adapt_dates_for_query_type("one two three four five")
+ # No LLM and not short => nothing changes
+ assert engine.order_by == original_order
+ assert engine.from_date == original_from
+
+ def test_historical_query_extends_to_10_years(self):
+ """LLM saying HISTORICAL extends the search to ~10 years back."""
+ llm = _mock_llm("HISTORICAL")
+ engine = _make_engine(
+ llm=llm, from_date="2025-01-01", to_date="2025-03-01"
+ )
+
+ engine._adapt_dates_for_query_type(
+ "what happened during the 2008 financial crisis in detail"
+ )
+
+ expected_from = (datetime.now(UTC) - timedelta(days=3650)).strftime(
+ "%Y-%m-%d"
+ )
+ assert engine.from_date == expected_from
+ # order_by should stay as default (relevance) for historical
+ assert engine.order_by == "relevance"
+
+ def test_current_query_sets_60_days_and_newest(self):
+ """LLM saying CURRENT focuses on recent 60 days with newest ordering."""
+ llm = _mock_llm("CURRENT")
+ engine = _make_engine(
+ llm=llm, from_date="2024-01-01", to_date="2025-03-01"
+ )
+
+ engine._adapt_dates_for_query_type(
+ "latest developments in AI regulation across countries"
+ )
+
+ expected_from = (datetime.now(UTC) - timedelta(days=60)).strftime(
+ "%Y-%m-%d"
+ )
+ assert engine.from_date == expected_from
+ assert engine.order_by == "newest"
+
+ def test_unclear_query_resets_to_original(self):
+ """LLM saying UNCLEAR resets dates to original parameters."""
+ llm = _mock_llm("UNCLEAR")
+ engine = _make_engine(
+ llm=llm, from_date="2024-06-01", to_date="2025-03-01"
+ )
+ original_from = engine.from_date
+
+ engine._adapt_dates_for_query_type(
+ "some ambiguous longer query about something or other"
+ )
+
+ # Neither HISTORICAL nor CURRENT matched, so dates reset to original
+ assert engine.from_date == original_from
+
+ def test_llm_exception_keeps_original_dates(self):
+ """LLM exception leaves dates unchanged."""
+ llm = Mock()
+ llm.invoke.side_effect = RuntimeError("boom")
+ engine = _make_engine(
+ llm=llm, from_date="2024-06-01", to_date="2025-03-01"
+ )
+
+ engine._adapt_dates_for_query_type(
+ "a longer query about a very specific topic area"
+ )
+
+ assert engine.from_date == "2024-06-01"
+ assert engine.to_date == "2025-03-01"
+
+ def test_adaptive_search_disabled_no_llm_call(self):
+ """With adaptive_search=False and a long query, LLM is not called."""
+ llm = _mock_llm("CURRENT")
+ engine = _make_engine(llm=llm, adaptive_search=False)
+ original_from = engine.from_date
+
+ engine._adapt_dates_for_query_type(
+ "a longer query about some specific topic area"
+ )
+
+ llm.invoke.assert_not_called()
+ assert engine.from_date == original_from
+
+ def test_historical_in_mixed_response(self):
+ """LLM response containing 'HISTORICAL' somewhere triggers historical path."""
+ llm = _mock_llm("<think>thinking</think>It is HISTORICAL event")
+ engine = _make_engine(
+ llm=llm, from_date="2025-01-01", to_date="2025-03-01"
+ )
+
+ engine._adapt_dates_for_query_type(
+ "what happened during the fall of the Berlin wall exactly"
+ )
+
+ expected_from = (datetime.now(UTC) - timedelta(days=3650)).strftime(
+ "%Y-%m-%d"
+ )
+ assert engine.from_date == expected_from
+
+
+# ===================================================================
+# _get_all_data - API parameter construction and formatting
+# ===================================================================
+
+
+class TestGetAllDataLogic:
+ def test_query_over_100_chars_truncated(self):
+ """Queries > 100 chars are truncated for the API."""
+ long_q = "a" * 120
+ resp = _guardian_api_response([])
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ) as mock_get:
+ engine = _make_engine()
+ engine._get_all_data(long_q)
+ sent_q = mock_get.call_args[1]["params"]["q"]
+ assert len(sent_q) == 100
+
+ def test_section_param_included_when_set(self):
+ """Section filter is added to API params when configured."""
+ resp = _guardian_api_response([])
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ) as mock_get:
+ engine = _make_engine(section="technology")
+ engine._get_all_data("AI")
+ params = mock_get.call_args[1]["params"]
+ assert params["section"] == "technology"
+
+ def test_section_param_absent_when_none(self):
+ """Section filter is NOT in API params when not configured."""
+ resp = _guardian_api_response([])
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ) as mock_get:
+ engine = _make_engine()
+ engine._get_all_data("AI")
+ params = mock_get.call_args[1]["params"]
+ assert "section" not in params
+
+ def test_page_size_capped_at_50(self):
+ """Even if max_results > 50, page-size param is capped at 50."""
+ resp = _guardian_api_response([])
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ) as mock_get:
+ engine = _make_engine(max_results=100)
+ engine._get_all_data("test")
+ params = mock_get.call_args[1]["params"]
+ assert params["page-size"] == 50
+
+ def test_max_results_none_defaults_to_10(self):
+ """When max_results is None, page-size defaults to 10."""
+ resp = _guardian_api_response([])
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ) as mock_get:
+ engine = _make_engine()
+ engine.max_results = None
+ engine._get_all_data("test")
+ params = mock_get.call_args[1]["params"]
+ assert params["page-size"] == 10
+
+ def test_keyword_tags_extracted(self):
+ """Keyword tags are extracted from article tags list."""
+ article = _sample_article(
+ tags=[
+ {"type": "keyword", "webTitle": "Climate"},
+ {"type": "keyword", "webTitle": "Policy"},
+ {"type": "contributor", "webTitle": "John"}, # not keyword
+ ]
+ )
+ resp = _guardian_api_response([article])
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ):
+ engine = _make_engine()
+ articles = engine._get_all_data("climate")
+ assert articles[0]["keywords"] == ["Climate", "Policy"]
+
+ def test_fields_fallback_to_webtitle(self):
+ """If fields.headline is missing, webTitle is used as title."""
+ article = {
+ "id": "x",
+ "webTitle": "Fallback Title",
+ "webUrl": "https://example.com",
+ "webPublicationDate": "2025-01-01",
+ "sectionName": "News",
+ "fields": {},
+ "tags": [],
+ }
+ resp = _guardian_api_response([article])
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ):
+ engine = _make_engine()
+ articles = engine._get_all_data("test")
+ assert articles[0]["title"] == "Fallback Title"
+
+ def test_results_limited_to_max_results(self):
+ """Only max_results articles are returned even if API gives more."""
+ articles = [_sample_article(article_id=f"art-{i}") for i in range(10)]
+ resp = _guardian_api_response(articles)
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ):
+ engine = _make_engine(max_results=3)
+ result = engine._get_all_data("test")
+ assert len(result) == 3
+
+ def test_empty_query_replaced_with_news(self):
+ """Empty or whitespace query is replaced with 'news'."""
+ resp = _guardian_api_response([])
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ) as mock_get:
+ engine = _make_engine()
+ engine._get_all_data(" ")
+ params = mock_get.call_args[1]["params"]
+ assert params["q"] == "news"
+
+ def test_article_all_fields_mapped(self):
+ """Verify all expected fields are present in formatted output."""
+ article = _sample_article()
+ resp = _guardian_api_response([article])
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=resp,
+ ):
+ engine = _make_engine()
+ results = engine._get_all_data("test")
+ r = results[0]
+ assert set(r.keys()) == {
+ "id",
+ "title",
+ "link",
+ "snippet",
+ "publication_date",
+ "section",
+ "author",
+ "content",
+ "full_content",
+ "keywords",
+ }
+
+
+# ===================================================================
+# _get_previews - integration of optimize + adapt + search
+# ===================================================================
+
+
+class TestGetPreviewsLogic:
+ def _run_previews(self, engine, articles, query="test query"):
+ """Helper to run _get_previews with mocked sub-methods."""
+ with (
+ patch.object(
+ engine, "_optimize_query_for_guardian", return_value="opt"
+ ) as mock_opt,
+ patch.object(engine, "_adapt_dates_for_query_type") as mock_adapt,
+ patch.object(
+ engine, "_adaptive_search", return_value=(articles, "initial")
+ ),
+ ):
+ previews = engine._get_previews(query)
+ return previews, mock_opt, mock_adapt
+
+ def test_previews_exclude_content_fields(self):
+ """Previews should NOT include 'content' or 'full_content'."""
+ engine = _make_engine()
+ articles = [
+ {
+ "id": "a1",
+ "title": "T",
+ "link": "http://x",
+ "snippet": "S",
+ "publication_date": "2025-01-01",
+ "section": "News",
+ "author": "A",
+ "content": "<p>body</p>",
+ "full_content": "<p>body</p>",
+ "keywords": ["k"],
+ }
+ ]
+ previews, _, _ = self._run_previews(engine, articles)
+ assert "content" not in previews[0]
+ assert "full_content" not in previews[0]
+
+ def test_previews_contain_expected_keys(self):
+ """Preview dicts have exactly the expected keys."""
+ engine = _make_engine()
+ articles = [
+ {
+ "id": "a1",
+ "title": "T",
+ "link": "http://x",
+ "snippet": "S",
+ "publication_date": "2025-01-01",
+ "section": "News",
+ "author": "A",
+ "content": "c",
+ "full_content": "c",
+ "keywords": [],
+ }
+ ]
+ previews, _, _ = self._run_previews(engine, articles)
+ assert set(previews[0].keys()) == {
+ "id",
+ "title",
+ "link",
+ "snippet",
+ "publication_date",
+ "section",
+ "author",
+ "keywords",
+ }
+
+ def test_search_metadata_stored(self):
+ """_get_previews stores _search_metadata on the engine instance."""
+ engine = _make_engine()
+ articles = [
+ {
+ "id": "a1",
+ "title": "T",
+ "link": "http://x",
+ "snippet": "S",
+ "publication_date": "d",
+ "section": "s",
+ "author": "a",
+ "content": "c",
+ "full_content": "c",
+ "keywords": [],
+ }
+ ]
+ self._run_previews(engine, articles, query="my original")
+ assert hasattr(engine, "_search_metadata")
+ assert engine._search_metadata["original_query"] == "my original"
+ assert engine._search_metadata["optimized_query"] == "opt"
+ assert engine._search_metadata["strategy"] == "initial"
+
+ def test_full_articles_cache_populated(self):
+ """_get_previews populates _full_articles cache keyed by article id."""
+ engine = _make_engine()
+ articles = [
+ {
+ "id": "a1",
+ "title": "T1",
+ "link": "l",
+ "snippet": "s",
+ "publication_date": "d",
+ "section": "s",
+ "author": "a",
+ "content": "body1",
+ "full_content": "body1",
+ "keywords": [],
+ },
+ {
+ "id": "a2",
+ "title": "T2",
+ "link": "l",
+ "snippet": "s",
+ "publication_date": "d",
+ "section": "s",
+ "author": "a",
+ "content": "body2",
+ "full_content": "body2",
+ "keywords": [],
+ },
+ ]
+ self._run_previews(engine, articles)
+ assert "a1" in engine._full_articles
+ assert "a2" in engine._full_articles
+ assert engine._full_articles["a1"]["content"] == "body1"
+
+ def test_empty_articles_returns_empty_previews(self):
+ """No articles produces empty previews list."""
+ engine = _make_engine()
+ previews, _, _ = self._run_previews(engine, [])
+ assert previews == []
+
+ def test_optimize_called_with_original_query(self):
+ """_optimize_query_for_guardian is called with the raw query."""
+ engine = _make_engine()
+ _, mock_opt, _ = self._run_previews(engine, [], query="raw question?")
+ mock_opt.assert_called_once_with("raw question?")
+
+ def test_adapt_called_with_optimized_query(self):
+ """_adapt_dates_for_query_type is called with the optimized query."""
+ engine = _make_engine()
+ _, _, mock_adapt = self._run_previews(engine, [], query="raw")
+ mock_adapt.assert_called_once_with("opt")
+
+
+# ===================================================================
+# _get_full_content - cache logic
+# ===================================================================
+
+
+class TestGetFullContentLogic:
+ def test_multiple_articles_from_cache(self):
+ """Multiple articles are looked up from the cache correctly."""
+ engine = _make_engine()
+ engine._full_articles = {
+ "a1": {"id": "a1", "content": "body1"},
+ "a2": {"id": "a2", "content": "body2"},
+ }
+ items = [{"id": "a1"}, {"id": "a2"}]
+ results = engine._get_full_content(items)
+ assert results[0]["content"] == "body1"
+ assert results[1]["content"] == "body2"
+
+ def test_missing_cache_returns_preview(self):
+ """If _full_articles does not exist, preview item returned."""
+ engine = _make_engine()
+ # No _full_articles attribute at all
+ items = [{"id": "a1", "title": "Preview"}]
+ results = engine._get_full_content(items)
+ assert results[0]["title"] == "Preview"
+
+ def test_partial_cache_miss(self):
+ """Mix of cached and uncached items handled correctly."""
+ engine = _make_engine()
+ engine._full_articles = {
+ "a1": {"id": "a1", "content": "cached"},
+ }
+ items = [{"id": "a1"}, {"id": "a2", "title": "Uncached"}]
+ results = engine._get_full_content(items)
+ assert results[0]["content"] == "cached"
+ assert results[1]["title"] == "Uncached"
+
+ def test_empty_items_returns_empty(self):
+ """Empty input returns empty output."""
+ engine = _make_engine()
+ engine._full_articles = {}
+ assert engine._get_full_content([]) == []
+
+ def test_item_without_id_key(self):
+ """Item missing 'id' key still returns the preview item."""
+ engine = _make_engine()
+ engine._full_articles = {"a1": {"id": "a1"}}
+ items = [{"title": "No ID"}]
+ results = engine._get_full_content(items)
+ assert results[0]["title"] == "No ID"
+
+
+# ===================================================================
+# Initialization edge cases
+# ===================================================================
+
+
+class TestInitEdgeCases:
+ def test_is_public_class_attribute(self):
+ assert GuardianSearchEngine.is_public is True
+
+ def test_api_url_set(self):
+ engine = _make_engine()
+ assert engine.api_url == "https://content.guardianapis.com/search"
+
+ def test_default_section_is_none(self):
+ engine = _make_engine()
+ assert engine.section is None
+
+ def test_optimize_queries_default_true(self):
+ engine = _make_engine()
+ assert engine.optimize_queries is True
+
+ def test_adaptive_search_default_true(self):
+ engine = _make_engine()
+ assert engine.adaptive_search is True
+
+ def test_original_date_params_match_instance(self):
+ engine = _make_engine(from_date="2020-01-01", to_date="2020-12-31")
+ assert engine._original_date_params == {
+ "from_date": "2020-01-01",
+ "to_date": "2020-12-31",
+ }
+
+ def test_no_api_key_raises_value_error(self):
+ with pytest.raises(
+ ValueError, match="No valid API key found for Guardian"
+ ):
+ GuardianSearchEngine()
+
+ def test_settings_snapshot_provides_api_key(self):
+ engine = GuardianSearchEngine(
+ settings_snapshot={
+ "search.engine.web.guardian.api_key": "from-settings"
+ }
+ )
+ assert engine.api_key == "from-settings"
+
+ def test_kwargs_forwarded_without_error(self):
+ """Extra kwargs don't cause errors."""
+ engine = _make_engine(some_extra_param="value")
+ assert engine.api_key == "test-key"
+
+
+# ===================================================================
+# _adaptive_search - strategy escalation
+# ===================================================================
+
+
+class TestAdaptiveSearch:
+ def test_initial_strategy_when_enough_results(self):
+ """When initial search returns >= 3, no further strategies tried."""
+ engine = _make_engine()
+
+ with patch.object(
+ engine,
+ "_get_all_data",
+ return_value=[{"id": f"a{i}"} for i in range(5)],
+ ) as mock_get:
+ result, strategy = engine._adaptive_search("test")
+ assert strategy == "initial"
+ assert mock_get.call_count == 1
+
+ def test_expands_to_6_months_on_few_results(self):
+ """With < 3 initial results and adaptive on, tries 6-month expansion."""
+ engine = _make_engine()
+
+ call_count = [0]
+
+ def side_effect(query):
+ call_count[0] += 1
+ if call_count[0] == 1:
+ return [{"id": "a1"}] # initial: only 1
+ elif call_count[0] == 2:
+ return [{"id": f"a{i}"} for i in range(5)] # 6-month: 5
+ return []
+
+ with patch.object(engine, "_get_all_data", side_effect=side_effect):
+ result, strategy = engine._adaptive_search("test")
+ assert strategy == "expanded_6mo"
+ assert len(result) == 5
+
+ def test_all_time_relevance_strategy(self):
+ """Falls through to all-time relevance when 6-month also < 3."""
+ engine = _make_engine()
+
+ call_count = [0]
+
+ def side_effect(query):
+ call_count[0] += 1
+ if call_count[0] <= 2:
+ return [{"id": "a1"}] # initial and 6mo: only 1
+ elif call_count[0] == 3:
+ return [{"id": f"a{i}"} for i in range(4)] # all-time: 4
+ return []
+
+ with patch.object(engine, "_get_all_data", side_effect=side_effect):
+ result, strategy = engine._adaptive_search("test")
+ assert strategy == "all_time_relevance"
+
+ def test_section_removal_strategy(self):
+ """Falls through to removing section constraint when all else < 3."""
+ engine = _make_engine(section="politics")
+
+ call_count = [0]
+
+ def side_effect(query):
+ call_count[0] += 1
+ if call_count[0] <= 3:
+ return [{"id": "a1"}] # all prior strategies: 1
+ elif call_count[0] == 4:
+ return [{"id": f"a{i}"} for i in range(5)] # no section: 5
+ return []
+
+ with patch.object(engine, "_get_all_data", side_effect=side_effect):
+ result, strategy = engine._adaptive_search("test")
+ assert strategy == "no_section"
+ # Section should be restored
+ assert engine.section == "politics"
+
+ def test_adaptive_disabled_no_escalation(self):
+ """With adaptive_search=False, only initial call made."""
+ engine = _make_engine(adaptive_search=False)
+
+ with patch.object(
+ engine, "_get_all_data", return_value=[{"id": "a1"}]
+ ) as mock:
+ result, strategy = engine._adaptive_search("test")
+ assert strategy == "initial"
+ assert mock.call_count == 1
+
+ def test_original_settings_restored_after_adaptation(self):
+ """from_date and order_by are restored after adaptive search."""
+ engine = _make_engine(from_date="2025-01-01")
+ original_from = engine.from_date
+ original_order = engine.order_by
+
+ with patch.object(engine, "_get_all_data", return_value=[{"id": "a1"}]):
+ engine._adaptive_search("test")
+
+ assert engine.from_date == original_from
+ assert engine.order_by == original_order
+
+
+# ===================================================================
+# run() method
+# ===================================================================
+
+
+class TestRunMethod:
+ def test_none_query_converted_to_news(self):
+ """None query is converted to 'news'."""
+ engine = _make_engine()
+ with patch.object(
+ engine, "_get_previews", return_value=[]
+ ) as mock_prev:
+ engine.run(None)
+ # First call uses "news" (the converted query)
+ first_call_arg = mock_prev.call_args_list[0][0][0]
+ assert first_call_arg == "news"
+
+ def test_source_field_added(self):
+ """Results get 'source': 'The Guardian' added."""
+ engine = _make_engine()
+ previews = [
+ {
+ "id": "a1",
+ "title": "T",
+ "link": "l",
+ "snippet": "s",
+ "publication_date": "d",
+ "section": "s",
+ "author": "a",
+ "keywords": [],
+ }
+ ]
+ full = [{"id": "a1", "title": "T", "content": "c"}]
+
+ with (
+ patch.object(engine, "_get_previews", return_value=previews),
+ patch.object(engine, "_get_full_content", return_value=full),
+ ):
+ results = engine.run("test")
+ assert results[0]["source"] == "The Guardian"
+
+ def test_existing_source_not_overwritten(self):
+ """If result already has 'source', it's not overwritten."""
+ engine = _make_engine()
+ previews = [
+ {
+ "id": "a1",
+ "title": "T",
+ "link": "l",
+ "snippet": "s",
+ "publication_date": "d",
+ "section": "s",
+ "author": "a",
+ "keywords": [],
+ }
+ ]
+ full = [{"id": "a1", "title": "T", "source": "Custom Source"}]
+
+ with (
+ patch.object(engine, "_get_previews", return_value=previews),
+ patch.object(engine, "_get_full_content", return_value=full),
+ ):
+ results = engine.run("test")
+ assert results[0]["source"] == "Custom Source"
+
+ def test_dates_restored_after_run(self):
+ """Original date params restored after a successful run."""
+ engine = _make_engine(from_date="2024-01-01", to_date="2024-12-31")
+ previews = [
+ {
+ "id": "a1",
+ "title": "T",
+ "link": "l",
+ "snippet": "s",
+ "publication_date": "d",
+ "section": "s",
+ "author": "a",
+ "keywords": [],
+ }
+ ]
+ with (
+ patch.object(engine, "_get_previews", return_value=previews),
+ patch.object(
+ engine, "_get_full_content", return_value=[{"id": "a1"}]
+ ),
+ ):
+ engine.run("test")
+
+ assert engine.from_date == "2024-01-01"
+ assert engine.to_date == "2024-12-31"
+
+ def test_dates_restored_after_exception(self):
+ """Original date params restored even after an exception."""
+ engine = _make_engine(from_date="2024-01-01", to_date="2024-12-31")
+
+ with patch.object(
+ engine, "_get_previews", side_effect=RuntimeError("fail")
+ ):
+ results = engine.run("test")
+
+ assert results == []
+ assert engine.from_date == "2024-01-01"
+ assert engine.to_date == "2024-12-31"
+
+ def test_cache_cleaned_up_after_run(self):
+ """_full_articles and _search_metadata are cleaned up."""
+ engine = _make_engine()
+ previews = [
+ {
+ "id": "a1",
+ "title": "T",
+ "link": "l",
+ "snippet": "s",
+ "publication_date": "d",
+ "section": "s",
+ "author": "a",
+ "keywords": [],
+ }
+ ]
+ with (
+ patch.object(engine, "_get_previews", return_value=previews),
+ patch.object(
+ engine, "_get_full_content", return_value=[{"id": "a1"}]
+ ),
+ ):
+ # Simulate _get_previews having set these
+ engine._full_articles = {"a1": {"id": "a1"}}
+ engine._search_metadata = {"original_query": "test"}
+ engine.run("test")
+
+ assert not hasattr(engine, "_full_articles")
+ assert not hasattr(engine, "_search_metadata")
+
+ def test_rate_limit_error_reraised(self):
+ """RateLimitError from _get_previews is propagated."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ engine = _make_engine()
+ with patch.object(
+ engine, "_get_previews", side_effect=RateLimitError("limit")
+ ):
+ with pytest.raises(RateLimitError):
+ engine.run("test")
diff --git a/tests/web_search_engines/engines/test_local_search_coverage.py b/tests/web_search_engines/engines/test_local_search_coverage.py
new file mode 100644
index 0000000000..78e3c44c92
--- /dev/null
+++ b/tests/web_search_engines/engines/test_local_search_coverage.py
@@ -0,0 +1,806 @@
+"""
+Comprehensive tests for LibraryRAGSearchEngine (replacement for deleted search_engine_local.py).
+
+Covers:
+- Init configuration and settings handling
+- Search result formatting (title fallbacks, snippet truncation, score conversion)
+- Multi-collection search with score-based sorting
+- Per-collection error handling (no RAG index, no indexed docs, exceptions)
+- _get_full_content with snippets-only mode, missing username, DB retrieval
+- PDF URL generation path
+- Edge cases (empty metadata, None settings_snapshot)
+"""
+
+from unittest.mock import Mock, MagicMock, patch
+import pytest
+
+# ---------------------------------------------------------------------------
+# Common patch paths
+# ---------------------------------------------------------------------------
+_MOD = "local_deep_research.web_search_engines.engines.search_engine_library"
+_PATCH_SETTING = f"{_MOD}.get_setting_from_snapshot"
+_PATCH_SERVER_URL = f"{_MOD}.get_server_url"
+_PATCH_LIB_SERVICE = f"{_MOD}.LibraryService"
+_PATCH_RAG_SERVICE = f"{_MOD}.LibraryRAGService"
+_PATCH_DB_SESSION = f"{_MOD}.get_user_db_session"
+_PATCH_PDF_MANAGER = f"{_MOD}.PDFStorageManager"
+_PATCH_LIB_DIR = f"{_MOD}.get_library_directory"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+def _make_engine(settings_snapshot=None, **kwargs):
+ """Create a LibraryRAGSearchEngine with all external deps patched."""
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ with (
+ patch(_PATCH_SETTING, return_value=None),
+ patch(_PATCH_SERVER_URL, return_value="http://localhost:5000"),
+ ):
+ return LibraryRAGSearchEngine(
+ settings_snapshot=settings_snapshot, **kwargs
+ )
+
+
+def _make_doc(page_content="content", metadata=None):
+ """Create a mock Document."""
+ doc = Mock()
+ doc.page_content = page_content
+ doc.metadata = metadata if metadata is not None else {}
+ return doc
+
+
+def _mock_rag_index(
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_provider="sentence_transformers",
+ chunk_size=1000,
+ chunk_overlap=200,
+):
+ idx = Mock()
+ idx.embedding_model = embedding_model
+ idx.embedding_model_type = Mock(value=embedding_provider)
+ idx.chunk_size = chunk_size
+ idx.chunk_overlap = chunk_overlap
+ return idx
+
+
+# ---------------------------------------------------------------------------
+# Init / Configuration
+# ---------------------------------------------------------------------------
+class TestInitConfiguration:
+ """Tests for initialization and settings handling."""
+
+ def test_username_from_settings_snapshot(self):
+ engine = _make_engine(settings_snapshot={"_username": "alice"})
+ assert engine.username == "alice"
+
+ def test_username_none_when_no_snapshot(self):
+ engine = _make_engine(settings_snapshot=None)
+ assert engine.username is None
+
+ def test_username_none_when_snapshot_missing_key(self):
+ engine = _make_engine(settings_snapshot={"other_key": "val"})
+ assert engine.username is None
+
+ def test_embedding_settings_from_snapshot(self):
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ def side_effect(key, snapshot, default):
+ mapping = {
+ "local_search_embedding_model": "custom-model",
+ "local_search_embedding_provider": "openai",
+ "local_search_chunk_size": 2000,
+ "local_search_chunk_overlap": 400,
+ }
+ return mapping.get(key, default)
+
+ with (
+ patch(_PATCH_SETTING, side_effect=side_effect),
+ patch(_PATCH_SERVER_URL, return_value="http://localhost:5000"),
+ ):
+ engine = LibraryRAGSearchEngine(
+ settings_snapshot={"_username": "bob"}
+ )
+
+ assert engine.embedding_model == "custom-model"
+ assert engine.embedding_provider == "openai"
+ assert engine.chunk_size == 2000
+ assert engine.chunk_overlap == 400
+
+ def test_server_url_stored(self):
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ with (
+ patch(_PATCH_SETTING, return_value=None),
+ patch(_PATCH_SERVER_URL, return_value="https://myhost:8080"),
+ ):
+ engine = LibraryRAGSearchEngine()
+ assert engine.server_url == "https://myhost:8080"
+
+ def test_max_filtered_results_passed_to_base(self):
+ engine = _make_engine(max_filtered_results=5)
+ assert engine.max_filtered_results == 5
+
+ def test_is_local_class_attribute(self):
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ assert LibraryRAGSearchEngine.is_local is True
+
+
+# ---------------------------------------------------------------------------
+# Title fallback chain
+# ---------------------------------------------------------------------------
+class TestTitleFallbacks:
+ """Title should fall back: document_title -> title -> 'Document {id}' -> 'Untitled'."""
+
+ def _run_search_with_metadata(self, metadata, page_content="text"):
+ """Run a search that returns one document with the given metadata."""
+ doc = _make_doc(page_content=page_content, metadata=metadata)
+
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+
+ # RAG index lookup
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+
+ # RAG service context manager
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [(doc, 0.1)]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ return engine.search("q")[0]
+
+ def test_document_title_preferred(self):
+ result = self._run_search_with_metadata(
+ {"document_title": "Doc Title", "title": "Other", "source_id": "1"}
+ )
+ assert result["title"] == "Doc Title"
+
+ def test_title_used_when_no_document_title(self):
+ result = self._run_search_with_metadata(
+ {"title": "Fallback Title", "source_id": "1"}
+ )
+ assert result["title"] == "Fallback Title"
+
+ def test_document_id_fallback(self):
+ result = self._run_search_with_metadata({"source_id": "42"})
+ assert result["title"] == "Document 42"
+
+ def test_untitled_when_no_metadata(self):
+ result = self._run_search_with_metadata({})
+ assert result["title"] == "Untitled"
+
+
+# ---------------------------------------------------------------------------
+# Snippet truncation
+# ---------------------------------------------------------------------------
+class TestSnippetTruncation:
+ """Snippet should be truncated at SNIPPET_LENGTH_LONG with '...' appended."""
+
+ def _search_with_content(self, content):
+ doc = _make_doc(page_content=content, metadata={"source_id": "1"})
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [(doc, 0.1)]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ return engine.search("q")[0]
+
+ def test_short_content_not_truncated(self):
+ result = self._search_with_content("short")
+ assert result["snippet"] == "short"
+ assert not result["snippet"].endswith("...")
+
+ def test_long_content_truncated(self):
+ from local_deep_research.constants import SNIPPET_LENGTH_LONG
+
+ long_text = "x" * (SNIPPET_LENGTH_LONG + 100)
+ result = self._search_with_content(long_text)
+ assert result["snippet"].endswith("...")
+ # The snippet body (without "...") should be SNIPPET_LENGTH_LONG chars
+ assert len(result["snippet"]) == SNIPPET_LENGTH_LONG + 3
+
+ def test_exact_length_not_truncated(self):
+ from local_deep_research.constants import SNIPPET_LENGTH_LONG
+
+ exact_text = "y" * SNIPPET_LENGTH_LONG
+ result = self._search_with_content(exact_text)
+ assert result["snippet"] == exact_text
+ assert not result["snippet"].endswith("...")
+
+
+# ---------------------------------------------------------------------------
+# Relevance score conversion
+# ---------------------------------------------------------------------------
+class TestRelevanceScore:
+ """relevance_score should be 1/(1+distance)."""
+
+ def _search_with_score(self, distance):
+ doc = _make_doc(metadata={"source_id": "1"})
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [(doc, distance)]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ return engine.search("q")[0]
+
+ def test_zero_distance(self):
+ result = self._search_with_score(0.0)
+ assert result["relevance_score"] == pytest.approx(1.0)
+
+ def test_distance_one(self):
+ result = self._search_with_score(1.0)
+ assert result["relevance_score"] == pytest.approx(0.5)
+
+ def test_large_distance(self):
+ result = self._search_with_score(99.0)
+ assert result["relevance_score"] == pytest.approx(1.0 / 100.0)
+
+
+# ---------------------------------------------------------------------------
+# Multi-collection sorting
+# ---------------------------------------------------------------------------
+class TestMultiCollectionSorting:
+ """Results across collections should be sorted by distance (ascending)."""
+
+ def test_results_sorted_by_score(self):
+ doc_close = _make_doc(
+ page_content="close",
+ metadata={"source_id": "1", "document_title": "Close"},
+ )
+ doc_far = _make_doc(
+ page_content="far",
+ metadata={"source_id": "2", "document_title": "Far"},
+ )
+
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "A"},
+ {"id": 2, "name": "B"},
+ ]
+
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+
+ # Two collections, each returning one doc. Collection B has
+ # the closer match (lower distance).
+ call_count = [0]
+
+ def rag_enter(self_rag):
+ inst = Mock()
+ inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ if call_count[0] == 0:
+ vs.similarity_search_with_score.return_value = [
+ (doc_far, 5.0)
+ ]
+ else:
+ vs.similarity_search_with_score.return_value = [
+ (doc_close, 0.2)
+ ]
+ call_count[0] += 1
+ inst.load_or_create_faiss_index.return_value = vs
+ return inst
+
+ rag_svc.return_value.__enter__ = rag_enter
+ rag_svc.return_value.__exit__ = Mock(return_value=None)
+
+ results = engine.search("q", limit=10)
+
+ assert len(results) == 2
+ # Closer result first
+ assert results[0]["title"] == "Close"
+ assert results[1]["title"] == "Far"
+
+ def test_limit_respected_across_collections(self):
+ """Only top `limit` results returned even when there are more."""
+ docs = [
+ _make_doc(
+ page_content=f"doc{i}",
+ metadata={"source_id": str(i), "document_title": f"D{i}"},
+ )
+ for i in range(5)
+ ]
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 5}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [
+ (docs[i], float(i)) for i in range(5)
+ ]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ results = engine.search("q", limit=2)
+
+ assert len(results) == 2
+
+
+# ---------------------------------------------------------------------------
+# Per-collection error paths
+# ---------------------------------------------------------------------------
+class TestPerCollectionErrors:
+ """Errors in one collection should not prevent results from others."""
+
+ def _setup_two_collections(
+ self, first_raises=False, first_no_rag=False, first_no_docs=False
+ ):
+ """Helper: two collections, configure first to fail in various ways."""
+ good_doc = _make_doc(
+ page_content="good",
+ metadata={"source_id": "99", "document_title": "Good"},
+ )
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "Bad"},
+ {"id": 2, "name": "Good"},
+ ]
+
+ call_count = [0]
+ good_rag_index = _mock_rag_index()
+
+ def session_enter(*a, **kw):
+ ctx = MagicMock()
+ sess = MagicMock()
+
+ if call_count[0] == 0:
+ call_count[0] += 1
+ if first_no_rag:
+ sess.query.return_value.filter_by.return_value.first.return_value = None
+ elif first_raises:
+ sess.query.return_value.filter_by.return_value.first.side_effect = Exception(
+ "boom"
+ )
+ else:
+ sess.query.return_value.filter_by.return_value.first.return_value = good_rag_index
+ else:
+ sess.query.return_value.filter_by.return_value.first.return_value = good_rag_index
+
+ ctx.__enter__ = Mock(return_value=sess)
+ ctx.__exit__ = Mock(return_value=None)
+ return ctx
+
+ db_sess.side_effect = session_enter
+
+ # RAG service
+ rag_call = [0]
+
+ def rag_enter(self_rag):
+ inst = Mock()
+ if rag_call[0] == 0 and first_no_docs:
+ inst.get_rag_stats.return_value = {"indexed_documents": 0}
+ else:
+ inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [
+ (good_doc, 0.1)
+ ]
+ inst.load_or_create_faiss_index.return_value = vs
+ rag_call[0] += 1
+ return inst
+
+ rag_svc.return_value.__enter__ = rag_enter
+ rag_svc.return_value.__exit__ = Mock(return_value=None)
+
+ results = engine.search("q")
+
+ return results
+
+ def test_collection_with_no_rag_index_skipped(self):
+ results = self._setup_two_collections(first_no_rag=True)
+ assert len(results) == 1
+ assert results[0]["title"] == "Good"
+
+ def test_collection_with_no_indexed_docs_skipped(self):
+ results = self._setup_two_collections(first_no_docs=True)
+ assert len(results) == 1
+ assert results[0]["title"] == "Good"
+
+ def test_collection_exception_skipped(self):
+ results = self._setup_two_collections(first_raises=True)
+ assert len(results) == 1
+ assert results[0]["title"] == "Good"
+
+ def test_collection_with_no_id_skipped(self):
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION),
+ patch(_PATCH_RAG_SERVICE),
+ ):
+ # Collection without "id" key
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"name": "No ID"}
+ ]
+ results = engine.search("q")
+
+ assert results == []
+
+
+# ---------------------------------------------------------------------------
+# Document URL / PDF path
+# ---------------------------------------------------------------------------
+class TestDocumentURL:
+ """URL generation: default /library/document/{id}, PDF if has_pdf."""
+
+ def _search_with_pdf_check(self, has_pdf):
+ doc = _make_doc(
+ page_content="text",
+ metadata={"source_id": "10", "document_title": "T"},
+ )
+ # Need to keep get_setting_from_snapshot patched during search() too,
+ # since it's called for "research_library.storage_path" inside the
+ # result formatting loop.
+ with (
+ patch(_PATCH_SETTING, return_value="/tmp/lib"),
+ patch(_PATCH_SERVER_URL, return_value="http://localhost:5000"),
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ patch(_PATCH_PDF_MANAGER) as pdf_mgr,
+ patch(_PATCH_LIB_DIR, return_value="/tmp/lib"),
+ ):
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ engine = LibraryRAGSearchEngine(
+ settings_snapshot={"_username": "u"}
+ )
+
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+
+ # get_user_db_session is called twice:
+ # 1) For RAG index lookup (inside collection loop)
+ # 2) For document/PDF check (inside result formatting)
+ mock_rag_index = _mock_rag_index()
+ mock_document = Mock()
+ mock_document.id = 10
+
+ call_count = [0]
+
+ def db_session_side_effect(username):
+ ctx = MagicMock()
+ sess = MagicMock()
+ if call_count[0] == 0:
+ # First call: RAG index query
+ sess.query.return_value.filter_by.return_value.first.return_value = mock_rag_index
+ else:
+ # Second call: Document query for PDF check
+ sess.query.return_value.filter_by.return_value.first.return_value = mock_document
+ call_count[0] += 1
+ ctx.__enter__ = Mock(return_value=sess)
+ ctx.__exit__ = Mock(return_value=None)
+ return ctx
+
+ db_sess.side_effect = db_session_side_effect
+
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [(doc, 0.5)]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ pdf_mgr.return_value.has_pdf.return_value = has_pdf
+
+ results = engine.search("q")
+
+ return results[0]
+
+ def test_pdf_url_when_has_pdf(self):
+ result = self._search_with_pdf_check(True)
+ assert result["url"] == "/library/document/10/pdf"
+
+ def test_default_url_when_no_pdf(self):
+ result = self._search_with_pdf_check(False)
+ assert result["url"] == "/library/document/10"
+
+ def test_url_hash_when_no_doc_id(self):
+ doc = _make_doc(page_content="text", metadata={})
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [(doc, 0.1)]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ results = engine.search("q")
+
+ assert results[0]["url"] == "#"
+ assert results[0]["link"] == "#"
+
+
+# ---------------------------------------------------------------------------
+# document_id fallback (source_id vs document_id metadata key)
+# ---------------------------------------------------------------------------
+class TestDocIdFallback:
+ def _search_with_metadata(self, metadata):
+ doc = _make_doc(page_content="text", metadata=metadata)
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [(doc, 0.1)]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ return engine.search("q")[0]
+
+ def test_source_id_preferred(self):
+ result = self._search_with_metadata(
+ {"source_id": "A", "document_id": "B"}
+ )
+ assert "/library/document/A" in result["url"]
+
+ def test_document_id_fallback(self):
+ result = self._search_with_metadata({"document_id": "B"})
+ assert "/library/document/B" in result["url"]
+
+
+# ---------------------------------------------------------------------------
+# Result metadata enrichment
+# ---------------------------------------------------------------------------
+class TestResultMetadata:
+ """Collection info should be injected into doc metadata."""
+
+ def test_collection_metadata_added(self):
+ doc = _make_doc(
+ page_content="text",
+ metadata={"source_id": "1", "document_title": "T"},
+ )
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 7, "name": "My Coll"}
+ ]
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [(doc, 0.1)]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ results = engine.search("q")
+
+ meta = results[0]["metadata"]
+ assert meta["collection_id"] == 7
+ assert meta["collection_name"] == "My Coll"
+
+ def test_none_metadata_gets_initialized(self):
+ """If doc.metadata is None, it should be set to a dict."""
+ doc = _make_doc(page_content="text", metadata=None)
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [(doc, 0.1)]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ results = engine.search("q")
+
+ # Should not crash; metadata should contain collection info
+ assert results[0]["metadata"]["collection_id"] == 1
+
+
+# ---------------------------------------------------------------------------
+# _get_previews delegation
+# ---------------------------------------------------------------------------
+class TestGetPreviews:
+ def test_delegates_all_args(self):
+ engine = _make_engine()
+ sentinel = [{"title": "x"}]
+ with patch.object(engine, "search", return_value=sentinel) as m:
+ result = engine._get_previews(
+ "query", limit=3, llm_callback="cb", extra_params={"k": "v"}
+ )
+ m.assert_called_once_with("query", 3, "cb", {"k": "v"})
+ assert result is sentinel
+
+
+# ---------------------------------------------------------------------------
+# Top-level search error handling
+# ---------------------------------------------------------------------------
+class TestSearchTopLevelErrors:
+ def test_search_returns_empty_on_exception(self):
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with patch(_PATCH_LIB_SERVICE) as lib_svc:
+ lib_svc.side_effect = Exception("total failure")
+ results = engine.search("q")
+
+ assert results == []
+
+ def test_search_empty_when_no_results_across_collections(self):
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE),
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+ # No RAG index -> skip
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = None
+
+ results = engine.search("q")
+
+ assert results == []
+
+
+# ---------------------------------------------------------------------------
+# close()
+# ---------------------------------------------------------------------------
+class TestClose:
+ def test_close_is_noop(self):
+ engine = _make_engine()
+ engine.close() # Should not raise
+
+
+# ---------------------------------------------------------------------------
+# Result structure completeness
+# ---------------------------------------------------------------------------
+class TestResultStructure:
+ """Each result dict should contain all required keys."""
+
+ def test_all_keys_present(self):
+ doc = _make_doc(
+ page_content="content",
+ metadata={"source_id": "1", "document_title": "T"},
+ )
+ engine = _make_engine(settings_snapshot={"_username": "u"})
+
+ with (
+ patch(_PATCH_LIB_SERVICE) as lib_svc,
+ patch(_PATCH_DB_SESSION) as db_sess,
+ patch(_PATCH_RAG_SERVICE) as rag_svc,
+ ):
+ lib_svc.return_value.get_all_collections.return_value = [
+ {"id": 1, "name": "C"}
+ ]
+ db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
+ rag_inst = Mock()
+ rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
+ vs = Mock()
+ vs.similarity_search_with_score.return_value = [(doc, 0.5)]
+ rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_svc.return_value.__enter__.return_value = rag_inst
+ rag_svc.return_value.__exit__.return_value = None
+
+ results = engine.search("q")
+
+ r = results[0]
+ expected_keys = {
+ "title",
+ "snippet",
+ "url",
+ "link",
+ "source",
+ "source_type",
+ "relevance_score",
+ "metadata",
+ }
+ assert expected_keys.issubset(r.keys())
+ assert r["source"] == "library"
+ assert r["source_type"] == "library"
+ assert r["link"] == r["url"]
+ assert isinstance(r["relevance_score"], float)
diff --git a/tests/web_search_engines/engines/test_meta_search_coverage.py b/tests/web_search_engines/engines/test_meta_search_coverage.py
new file mode 100644
index 0000000000..3866ccf5ef
--- /dev/null
+++ b/tests/web_search_engines/engines/test_meta_search_coverage.py
@@ -0,0 +1,1098 @@
+"""
+Comprehensive pytest tests for MetaSearchEngine targeting coverage gaps.
+
+Focuses on:
+- Config extraction edge cases (_get_search_config)
+- Engine filtering/selection (_get_available_engines)
+- Result merging and fallback logic (_get_previews, _get_full_content)
+- Error handling paths
+- close() method
+- analyze_query LLM invocation path (reachable when SearXNG absent + LLM truthy
+ but with engines_info populated)
+- Edge cases in engine instance creation
+"""
+
+import pytest
+from unittest.mock import Mock, patch
+
+from local_deep_research.web_search_engines.engines.meta_search_engine import (
+ MetaSearchEngine,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _bypass_init(available_engines=None, settings_snapshot=None, llm=None):
+ """Create MetaSearchEngine bypassing __init__ for pure logic tests."""
+ with patch.object(
+ MetaSearchEngine, "__init__", lambda self, *a, **kw: None
+ ):
+ engine = MetaSearchEngine.__new__(MetaSearchEngine)
+ engine.available_engines = available_engines or []
+ engine.settings_snapshot = settings_snapshot
+ engine.llm = llm
+ engine.engine_cache = {}
+ engine.max_results = 10
+ engine.max_filtered_results = None
+ engine.max_engines_to_try = 3
+ engine.use_api_key_services = True
+ engine.programmatic_mode = True
+ engine.fallback_engine = Mock()
+ return engine
+
+
+def _make_engine_with_init(
+ available_engines, llm=None, settings=None, **kwargs
+):
+ """Create MetaSearchEngine via __init__ but mock _get_available_engines."""
+ if llm is None:
+ llm = Mock()
+ if settings is None:
+ settings = {"search.max_results": {"value": 10}}
+
+ with patch.object(
+ MetaSearchEngine,
+ "_get_available_engines",
+ return_value=available_engines,
+ ):
+ engine = MetaSearchEngine(
+ llm=llm,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ **kwargs,
+ )
+ return engine
+
+
+# ===========================================================================
+# 1. _get_search_config edge cases
+# ===========================================================================
+
+
+class TestGetSearchConfigEdgeCases:
+ """Edge cases in _get_search_config not covered elsewhere."""
+
+ def test_key_with_three_parts_ignored(self):
+ """Keys like 'search.engine.web' (no engine name) are ignored."""
+ engine = _bypass_init(settings_snapshot={"search.engine.web": "value"})
+ config = engine._get_search_config()
+ assert config == {}
+
+ def test_key_with_exactly_four_parts_creates_engine_entry_no_subkey(self):
+ """Key 'search.engine.web.brave' creates entry but no sub-key."""
+ engine = _bypass_init(
+ settings_snapshot={"search.engine.web.brave": "val"}
+ )
+ config = engine._get_search_config()
+ assert "brave" in config
+ assert config["brave"] == {}
+
+ def test_auto_engine_dict_values_extracted(self):
+ """Auto engine config extracts 'value' from dict entries."""
+ snapshot = {
+ "search.engine.auto.class_name": "MetaSearchEngine",
+ "search.engine.auto.max_engines": {"value": 5, "type": "int"},
+ }
+ engine = _bypass_init(settings_snapshot=snapshot)
+ config = engine._get_search_config()
+ assert config["auto"]["class_name"] == "MetaSearchEngine"
+ assert config["auto"]["max_engines"] == 5
+
+ def test_auto_engine_plain_values_used_directly(self):
+ """Auto engine config uses plain values directly."""
+ snapshot = {
+ "search.engine.auto.class_name": "MetaSearchEngine",
+ "search.engine.auto.timeout": 30,
+ }
+ engine = _bypass_init(settings_snapshot=snapshot)
+ config = engine._get_search_config()
+ assert config["auto"]["timeout"] == 30
+
+ def test_multiple_engines_with_multiple_subkeys(self):
+ """Multiple engines each with multiple sub-keys."""
+ snapshot = {
+ "search.engine.web.brave.api_key": {"value": "key1"},
+ "search.engine.web.brave.reliability": 0.9,
+ "search.engine.web.brave.strengths": {"value": "fast"},
+ "search.engine.web.searxng.url": "http://localhost:8080",
+ "search.engine.web.searxng.reliability": {"value": 0.95},
+ }
+ engine = _bypass_init(settings_snapshot=snapshot)
+ config = engine._get_search_config()
+
+ assert config["brave"]["api_key"] == "key1"
+ assert config["brave"]["reliability"] == 0.9
+ assert config["brave"]["strengths"] == "fast"
+ assert config["searxng"]["url"] == "http://localhost:8080"
+ assert config["searxng"]["reliability"] == 0.95
+
+ def test_deeply_nested_keys_joined_with_dots(self):
+ """Keys deeper than 5 parts produce dotted remaining keys."""
+ snapshot = {
+ "search.engine.web.brave.proxy.host.name": "proxy.example.com",
+ }
+ engine = _bypass_init(settings_snapshot=snapshot)
+ config = engine._get_search_config()
+ assert config["brave"]["proxy.host.name"] == "proxy.example.com"
+
+ def test_non_engine_keys_ignored(self):
+ """Non-search.engine.web keys are skipped."""
+ snapshot = {
+ "search.max_results": 10,
+ "search.snippets_only": True,
+ "ui.theme": "dark",
+ "search.engine.web.brave.api_key": "key1",
+ }
+ engine = _bypass_init(settings_snapshot=snapshot)
+ config = engine._get_search_config()
+ assert set(config.keys()) == {"brave"}
+
+ def test_empty_settings_snapshot_returns_empty(self):
+ """Empty settings_snapshot returns empty dict."""
+ engine = _bypass_init(settings_snapshot={})
+ config = engine._get_search_config()
+ assert config == {}
+
+ def test_none_settings_snapshot_returns_empty(self):
+ """None settings_snapshot returns empty dict."""
+ engine = _bypass_init(settings_snapshot=None)
+ config = engine._get_search_config()
+ assert config == {}
+
+
+# ===========================================================================
+# 2. _get_available_engines edge cases
+# ===========================================================================
+
+
+class TestGetAvailableEnginesEdgeCases:
+ """Edge cases in engine filtering."""
+
+ def test_api_key_empty_string_excluded(self):
+ """Engine with requires_api_key=True and api_key='' (empty) is excluded."""
+ mock_llm = Mock()
+ settings = {"search.max_results": {"value": 10}}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.return_value = True # All enabled for auto search
+
+ with patch.object(
+ MetaSearchEngine,
+ "_get_search_config",
+ return_value={
+ "brave": {"requires_api_key": True, "api_key": ""},
+ "wikipedia": {},
+ },
+ ):
+ engine = MetaSearchEngine(
+ llm=mock_llm,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ assert "brave" not in engine.available_engines
+ assert "wikipedia" in engine.available_engines
+
+ def test_api_key_none_excluded(self):
+ """Engine with requires_api_key=True and api_key=None is excluded."""
+ mock_llm = Mock()
+ settings = {"search.max_results": {"value": 10}}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.return_value = True
+
+ with patch.object(
+ MetaSearchEngine,
+ "_get_search_config",
+ return_value={
+ "brave": {"requires_api_key": True, "api_key": None},
+ "wikipedia": {},
+ },
+ ):
+ engine = MetaSearchEngine(
+ llm=mock_llm,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ assert "brave" not in engine.available_engines
+
+ def test_requires_api_key_false_included_regardless(self):
+ """Engine with requires_api_key=False included even without api_key."""
+ mock_llm = Mock()
+ settings = {"search.max_results": {"value": 10}}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.return_value = True
+
+ with patch.object(
+ MetaSearchEngine,
+ "_get_search_config",
+ return_value={
+ "brave": {"requires_api_key": False},
+ },
+ ):
+ engine = MetaSearchEngine(
+ llm=mock_llm,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ assert "brave" in engine.available_engines
+
+ def test_only_meta_and_auto_raises_runtime_error(self):
+ """Only meta and auto in config raises RuntimeError."""
+ mock_llm = Mock()
+ settings = {"search.max_results": {"value": 10}}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.return_value = True
+
+ with patch.object(
+ MetaSearchEngine,
+ "_get_search_config",
+ return_value={"meta": {}, "auto": {}},
+ ):
+ with pytest.raises(
+ RuntimeError, match="No search engines enabled"
+ ):
+ MetaSearchEngine(
+ llm=mock_llm,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ def test_mixed_enabled_and_disabled_engines(self):
+ """Mix of enabled and disabled engines filters correctly."""
+ mock_llm = Mock()
+ settings = {"search.max_results": {"value": 10}}
+
+ def setting_side_effect(key, default, settings_snapshot=None):
+ if "brave" in key:
+ return True
+ if "wikipedia" in key:
+ return False
+ if "searxng" in key:
+ return True
+ return default
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.side_effect = setting_side_effect
+
+ with patch.object(
+ MetaSearchEngine,
+ "_get_search_config",
+ return_value={"brave": {}, "wikipedia": {}, "searxng": {}},
+ ):
+ engine = MetaSearchEngine(
+ llm=mock_llm,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ assert "brave" in engine.available_engines
+ assert "searxng" in engine.available_engines
+ assert "wikipedia" not in engine.available_engines
+
+
+# ===========================================================================
+# 3. analyze_query - LLM invocation path
+# ===========================================================================
+
+
+class TestAnalyzeQueryLLMPath:
+ """Test the LLM invocation path in analyze_query.
+
+ Note: The LLM path is only reachable when SearXNG is available AND
+ the code doesn't short-circuit on the SearXNG general path.
+ Actually, looking at the code more carefully: lines 216-228 always
+ return when SearXNG is available. So the LLM path (line 244+)
+ is unreachable in the current code. But we test the exception
+ and other edge cases.
+ """
+
+ def test_analyze_query_exception_with_searxng_available(self):
+ """Exception in analyze_query with SearXNG available returns SearXNG first."""
+ engine = _bypass_init(
+ available_engines=["searxng", "brave"],
+ settings_snapshot={},
+ )
+ # Pass None to trigger AttributeError on .lower()
+ result = engine.analyze_query(None)
+ assert result[0] == "searxng"
+ assert "brave" in result
+
+ def test_analyze_query_exception_without_searxng(self):
+ """Exception in analyze_query without SearXNG returns reliability-sorted."""
+ engine = _bypass_init(
+ available_engines=["brave", "wikipedia"],
+ settings_snapshot={
+ "search.engine.web.brave.reliability": 0.6,
+ "search.engine.web.wikipedia.reliability": 0.9,
+ },
+ )
+ result = engine.analyze_query(None)
+ assert result[0] == "wikipedia"
+ assert result[1] == "brave"
+
+ def test_specialized_domain_no_available_engines_falls_through(self):
+ """Specialized domain match with none available falls through."""
+ engine = _bypass_init(
+ available_engines=["searxng", "brave"],
+ settings_snapshot={},
+ )
+ # "scientific paper" maps to [arxiv, pubmed, wikipedia] - none available
+ result = engine.analyze_query("scientific paper on physics")
+ # Falls through to SearXNG general path
+ assert result[0] == "searxng"
+
+ def test_specialized_domain_partial_match(self):
+ """Only some specialized engines available."""
+ engine = _bypass_init(available_engines=["wikipedia", "brave"])
+ result = engine.analyze_query("scientific paper on biology")
+ # Only wikipedia from [arxiv, pubmed, wikipedia]
+ assert result == ["wikipedia"]
+
+ def test_all_specialized_domains(self):
+ """All specialized domain keywords produce expected results."""
+ test_cases = [
+ ("scientific paper on AI", ["arxiv", "pubmed", "wikipedia"]),
+ ("medical research findings", ["pubmed", "searxng"]),
+ ("clinical trial data", ["pubmed", "searxng"]),
+ ("github actions workflow", ["github", "searxng"]),
+ ("code repository for ML", ["github", "searxng"]),
+ ("repository for NLP", ["github", "searxng"]),
+ ("programming language design", ["github", "searxng"]),
+ ]
+
+ all_engines = [
+ "arxiv",
+ "pubmed",
+ "wikipedia",
+ "github",
+ "searxng",
+ "brave",
+ ]
+ for query, expected_engines in test_cases:
+ engine = _bypass_init(available_engines=list(all_engines))
+ result = engine.analyze_query(query)
+ assert result == expected_engines, f"Failed for query: {query}"
+
+ def test_arxiv_keyword_not_in_available(self):
+ """'arxiv' in query but arxiv not available falls through."""
+ engine = _bypass_init(
+ available_engines=["searxng", "brave"],
+ settings_snapshot={},
+ )
+ result = engine.analyze_query("arxiv paper on attention")
+ # arxiv not available, falls through to SearXNG general path
+ assert result[0] == "searxng"
+
+ def test_pubmed_keyword_not_in_available(self):
+ """'pubmed' in query but pubmed not available falls through."""
+ engine = _bypass_init(
+ available_engines=["searxng", "brave"],
+ settings_snapshot={},
+ )
+ result = engine.analyze_query("pubmed articles on genetics")
+ assert result[0] == "searxng"
+
+ def test_general_query_no_searxng_no_llm_reliability_sort(self):
+ """General query without SearXNG or LLM uses reliability sort."""
+ engine = _bypass_init(
+ available_engines=["brave", "wikipedia"],
+ settings_snapshot={
+ "search.engine.web.brave.reliability": 0.5,
+ "search.engine.web.wikipedia.reliability": 0.8,
+ },
+ llm=None,
+ )
+ result = engine.analyze_query("what is the meaning of life")
+ assert result[0] == "wikipedia"
+ assert result[1] == "brave"
+
+ def test_general_query_searxng_present_sorts_remaining(self):
+ """General query with SearXNG returns SearXNG first, rest sorted."""
+ engine = _bypass_init(
+ available_engines=["brave", "searxng", "wikipedia", "arxiv"],
+ settings_snapshot={
+ "search.engine.web.brave.reliability": 0.5,
+ "search.engine.web.wikipedia.reliability": 0.8,
+ "search.engine.web.arxiv.reliability": 0.3,
+ },
+ )
+ result = engine.analyze_query("general knowledge question")
+ assert result[0] == "searxng"
+ assert result[1] == "wikipedia"
+ assert result[2] == "brave"
+ assert result[3] == "arxiv"
+
+
+# ===========================================================================
+# 4. _get_previews edge cases
+# ===========================================================================
+
+
+class TestGetPreviewsEdgeCases:
+ """Edge cases in _get_previews."""
+
+ def test_empty_ranked_engines_uses_fallback(self):
+ """Empty ranked engines list uses fallback."""
+ engine = _bypass_init(available_engines=[])
+ engine.fallback_engine._get_previews.return_value = [
+ {"title": "Wiki", "url": "http://wiki.com"}
+ ]
+
+ with patch.object(engine, "analyze_query", return_value=[]):
+ result = engine._get_previews("test query")
+
+ assert len(result) == 1
+ assert result[0]["title"] == "Wiki"
+
+ def test_max_engines_to_try_limits_attempts(self):
+ """max_engines_to_try limits the number of engines tried."""
+ engine = _bypass_init(available_engines=["e1", "e2", "e3", "e4", "e5"])
+ engine.max_engines_to_try = 2
+
+ call_order = []
+
+ def mock_get_instance(name):
+ call_order.append(name)
+ mock = Mock()
+ mock._get_previews.return_value = [] # All return empty
+ return mock
+
+ engine._get_engine_instance = mock_get_instance
+ engine.fallback_engine._get_previews.return_value = [
+ {"title": "Fallback"}
+ ]
+
+ with patch.object(
+ engine, "analyze_query", return_value=["e1", "e2", "e3", "e4", "e5"]
+ ):
+ engine._get_previews("test query")
+
+ # Only 2 engines should be tried
+ assert len(call_order) == 2
+ assert call_order == ["e1", "e2"]
+
+ def test_first_engine_succeeds_no_more_tried(self):
+ """When first engine succeeds, no more engines are tried."""
+ engine = _bypass_init(available_engines=["brave", "wikipedia"])
+
+ call_count = []
+
+ def mock_get_instance(name):
+ call_count.append(name)
+ mock = Mock()
+ mock._get_previews.return_value = [
+ {"title": f"Result from {name}", "url": f"http://{name}.com"}
+ ]
+ return mock
+
+ engine._get_engine_instance = mock_get_instance
+
+ with patch.object(
+ engine, "analyze_query", return_value=["brave", "wikipedia"]
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
+ ):
+ result = engine._get_previews("test")
+
+ assert len(call_count) == 1
+ assert call_count[0] == "brave"
+ assert result[0]["title"] == "Result from brave"
+
+ def test_engine_returns_none_from_get_instance_skipped(self):
+ """Engine that returns None from _get_engine_instance is skipped."""
+ engine = _bypass_init(available_engines=["broken", "working"])
+
+ mock_working = Mock()
+ mock_working._get_previews.return_value = [
+ {"title": "Working result", "url": "http://work.com"}
+ ]
+
+ def mock_get_instance(name):
+ if name == "broken":
+ return None
+ return mock_working
+
+ engine._get_engine_instance = mock_get_instance
+
+ with patch.object(
+ engine, "analyze_query", return_value=["broken", "working"]
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
+ ):
+ result = engine._get_previews("test")
+
+ assert len(result) == 1
+ assert result[0]["title"] == "Working result"
+
+ def test_engine_raises_exception_skipped(self):
+ """Engine that raises exception is skipped to next."""
+ engine = _bypass_init(available_engines=["failing", "ok"])
+
+ mock_failing = Mock()
+ mock_failing._get_previews.side_effect = ConnectionError(
+ "Network error"
+ )
+
+ mock_ok = Mock()
+ mock_ok._get_previews.return_value = [
+ {"title": "OK result", "url": "http://ok.com"}
+ ]
+
+ def mock_get_instance(name):
+ if name == "failing":
+ return mock_failing
+ return mock_ok
+
+ engine._get_engine_instance = mock_get_instance
+
+ with patch.object(
+ engine, "analyze_query", return_value=["failing", "ok"]
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
+ ):
+ result = engine._get_previews("test")
+
+ assert len(result) == 1
+ assert result[0]["title"] == "OK result"
+
+ def test_all_engines_return_empty_results_uses_fallback(self):
+ """All engines returning empty results uses fallback."""
+ engine = _bypass_init(available_engines=["e1", "e2"])
+
+ def mock_get_instance(name):
+ mock = Mock()
+ mock._get_previews.return_value = []
+ return mock
+
+ engine._get_engine_instance = mock_get_instance
+ engine.fallback_engine._get_previews.return_value = [
+ {"title": "Fallback result"}
+ ]
+
+ with patch.object(engine, "analyze_query", return_value=["e1", "e2"]):
+ result = engine._get_previews("test")
+
+ assert result[0]["title"] == "Fallback result"
+ assert engine._selected_engine is engine.fallback_engine
+ assert engine._selected_engine_name == "wikipedia"
+
+ def test_successful_engine_stores_selected_engine(self):
+ """Successful engine is stored as _selected_engine."""
+ engine = _bypass_init(available_engines=["brave"])
+
+ mock_brave = Mock()
+ mock_brave._get_previews.return_value = [
+ {"title": "Result", "url": "http://brave.com"}
+ ]
+ engine._get_engine_instance = lambda name: mock_brave
+
+ with patch.object(engine, "analyze_query", return_value=["brave"]):
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
+ ):
+ engine._get_previews("test")
+
+ assert engine._selected_engine is mock_brave
+ assert engine._selected_engine_name == "brave"
+
+ def test_socket_io_error_non_critical(self):
+ """SocketIO emit failure does not affect results."""
+ engine = _bypass_init(available_engines=["brave"])
+
+ mock_brave = Mock()
+ mock_brave._get_previews.return_value = [
+ {"title": "Result", "url": "http://test.com"}
+ ]
+ engine._get_engine_instance = lambda name: mock_brave
+
+ with patch.object(engine, "analyze_query", return_value=["brave"]):
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
+ ) as mock_sio:
+ mock_sio.return_value.emit_socket_event.side_effect = (
+ RuntimeError("Socket broken")
+ )
+ result = engine._get_previews("test")
+
+ assert len(result) == 1
+ assert result[0]["title"] == "Result"
+
+ def test_none_previews_treated_as_empty(self):
+ """Engine returning None previews is treated as no results."""
+ engine = _bypass_init(available_engines=["e1"])
+
+ mock_e = Mock()
+ mock_e._get_previews.return_value = None
+
+ engine._get_engine_instance = lambda name: mock_e
+ engine.fallback_engine._get_previews.return_value = [
+ {"title": "Fallback"}
+ ]
+
+ with patch.object(engine, "analyze_query", return_value=["e1"]):
+ result = engine._get_previews("test")
+
+ assert result[0]["title"] == "Fallback"
+
+
+# ===========================================================================
+# 5. _get_full_content edge cases
+# ===========================================================================
+
+
+class TestGetFullContentEdgeCases:
+ """Edge cases in _get_full_content."""
+
+ def test_snippets_only_mode_returns_items_unchanged(self):
+ """snippets_only=True returns items as-is."""
+ engine = _bypass_init(
+ settings_snapshot={"search.snippets_only": {"value": True}}
+ )
+
+ items = [{"title": "Test", "snippet": "content"}]
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
+ return_value=True,
+ ):
+ result = engine._get_full_content(items)
+ assert result is items
+
+ def test_selected_engine_used_for_full_content(self):
+ """Selected engine is used to get full content."""
+ engine = _bypass_init()
+ mock_selected = Mock()
+ mock_selected._get_full_content.return_value = [
+ {"title": "Full", "full_content": "Full text"}
+ ]
+ engine._selected_engine = mock_selected
+ engine._selected_engine_name = "brave"
+
+ items = [{"title": "Test"}]
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ result = engine._get_full_content(items)
+
+ mock_selected._get_full_content.assert_called_once_with(items)
+ assert result[0]["full_content"] == "Full text"
+
+ def test_selected_engine_exception_returns_items(self):
+ """Exception in selected engine returns items unchanged."""
+ engine = _bypass_init()
+ mock_selected = Mock()
+ mock_selected._get_full_content.side_effect = RuntimeError(
+ "Fetch failed"
+ )
+ engine._selected_engine = mock_selected
+ engine._selected_engine_name = "brave"
+
+ items = [{"title": "Test", "url": "http://example.com"}]
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ result = engine._get_full_content(items)
+
+ assert result is items
+
+ def test_no_selected_engine_returns_items(self):
+ """No _selected_engine attribute returns items unchanged."""
+ engine = _bypass_init()
+ # Ensure _selected_engine is not set
+ assert not hasattr(engine, "_selected_engine")
+
+ items = [{"title": "Test"}]
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ result = engine._get_full_content(items)
+
+ assert result is items
+
+
+# ===========================================================================
+# 6. _get_engine_instance edge cases
+# ===========================================================================
+
+
+class TestGetEngineInstanceEdgeCases:
+ """Edge cases in _get_engine_instance."""
+
+ def test_cached_engine_returned_without_creating(self):
+ """Cached engine returned without calling create_search_engine."""
+ engine = _bypass_init()
+ mock_cached = Mock()
+ engine.engine_cache["brave"] = mock_cached
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine"
+ ) as mock_create:
+ result = engine._get_engine_instance("brave")
+
+ mock_create.assert_not_called()
+ assert result is mock_cached
+
+ def test_new_engine_created_and_cached(self):
+ """New engine is created and added to cache."""
+ engine = _bypass_init()
+ mock_new = Mock()
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
+ return_value=mock_new,
+ ):
+ result = engine._get_engine_instance("brave")
+
+ assert result is mock_new
+ assert engine.engine_cache["brave"] is mock_new
+
+ def test_creation_failure_returns_none(self):
+ """Engine creation failure returns None."""
+ engine = _bypass_init()
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
+ side_effect=ValueError("Bad config"),
+ ):
+ result = engine._get_engine_instance("bad_engine")
+
+ assert result is None
+ assert "bad_engine" not in engine.engine_cache
+
+ def test_max_filtered_results_none_defaults_to_five(self):
+ """max_filtered_results=None is coerced to 5 by the base class property setter."""
+ engine = _bypass_init()
+ engine.max_filtered_results = None
+ # The property setter in BaseSearchEngine converts None -> 5
+ assert engine.max_filtered_results == 5
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
+ return_value=Mock(),
+ ) as mock_create:
+ engine._get_engine_instance("brave")
+
+ _, kwargs = mock_create.call_args
+ # Always passed since the property never returns None
+ assert kwargs["max_filtered_results"] == 5
+
+ def test_max_filtered_results_set_is_passed(self):
+ """max_filtered_results when set is passed to create_search_engine."""
+ engine = _bypass_init()
+ engine.max_filtered_results = 5
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
+ return_value=Mock(),
+ ) as mock_create:
+ engine._get_engine_instance("brave")
+
+ _, kwargs = mock_create.call_args
+ assert kwargs["max_filtered_results"] == 5
+
+ def test_max_filtered_results_zero_is_passed(self):
+ """max_filtered_results=0 (falsy but not None) is passed."""
+ engine = _bypass_init()
+ engine.max_filtered_results = 0
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
+ return_value=Mock(),
+ ) as mock_create:
+ engine._get_engine_instance("brave")
+
+ _, kwargs = mock_create.call_args
+ assert "max_filtered_results" in kwargs
+ assert kwargs["max_filtered_results"] == 0
+
+ def test_create_engine_returns_none_not_cached(self):
+ """If create_search_engine returns None, it's not cached."""
+ engine = _bypass_init()
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
+ return_value=None,
+ ):
+ result = engine._get_engine_instance("brave")
+
+ assert result is None
+ assert "brave" not in engine.engine_cache
+
+
+# ===========================================================================
+# 7. close() method
+# ===========================================================================
+
+
+class TestClose:
+ """Tests for close() method."""
+
+ def test_close_closes_cached_engines(self):
+ """close() calls close() on all cached engines."""
+ engine = _bypass_init()
+ mock_e1 = Mock()
+ mock_e2 = Mock()
+ engine.engine_cache = {"e1": mock_e1, "e2": mock_e2}
+
+ with patch.object(
+ type(engine).__bases__[0], "close", return_value=None
+ ):
+ engine.close()
+
+ mock_e1.close.assert_called_once()
+ mock_e2.close.assert_called_once()
+
+ def test_close_clears_cache(self):
+ """close() clears the engine cache."""
+ engine = _bypass_init()
+ engine.engine_cache = {"e1": Mock(), "e2": Mock()}
+
+ with patch.object(
+ type(engine).__bases__[0], "close", return_value=None
+ ):
+ engine.close()
+
+ assert engine.engine_cache == {}
+
+ def test_close_closes_fallback_engine(self):
+ """close() closes the fallback engine."""
+ engine = _bypass_init()
+ mock_fallback = Mock()
+ engine.fallback_engine = mock_fallback
+
+ with patch.object(
+ type(engine).__bases__[0], "close", return_value=None
+ ):
+ engine.close()
+
+ mock_fallback.close.assert_called_once()
+
+ def test_close_handles_cached_engine_close_exception(self):
+ """close() handles exception from cached engine close()."""
+ engine = _bypass_init()
+ mock_e1 = Mock()
+ mock_e1.close.side_effect = RuntimeError("Close failed")
+ mock_e2 = Mock()
+ engine.engine_cache = {"e1": mock_e1, "e2": mock_e2}
+
+ with patch.object(
+ type(engine).__bases__[0], "close", return_value=None
+ ):
+ # Should not raise
+ engine.close()
+
+ # e2.close should still be called despite e1 raising
+ mock_e2.close.assert_called_once()
+
+ def test_close_handles_fallback_close_exception(self):
+ """close() handles exception from fallback engine close()."""
+ engine = _bypass_init()
+ mock_fallback = Mock()
+ mock_fallback.close.side_effect = RuntimeError("Fallback close failed")
+ engine.fallback_engine = mock_fallback
+
+ with patch.object(
+ type(engine).__bases__[0], "close", return_value=None
+ ):
+ # Should not raise
+ engine.close()
+
+ def test_close_with_no_fallback_engine(self):
+ """close() handles missing fallback_engine gracefully."""
+ engine = _bypass_init()
+ engine.fallback_engine = None
+
+ with patch.object(
+ type(engine).__bases__[0], "close", return_value=None
+ ):
+ # Should not raise
+ engine.close()
+
+ def test_close_with_empty_cache(self):
+ """close() works with empty cache."""
+ engine = _bypass_init()
+ engine.engine_cache = {}
+
+ with patch.object(
+ type(engine).__bases__[0], "close", return_value=None
+ ):
+ engine.close()
+
+ assert engine.engine_cache == {}
+
+ def test_close_calls_super_close(self):
+ """close() calls super().close()."""
+ engine = _bypass_init()
+ engine.engine_cache = {}
+
+ with patch.object(
+ type(engine).__bases__[0], "close", return_value=None
+ ) as mock_super_close:
+ engine.close()
+
+ mock_super_close.assert_called_once()
+
+
+# ===========================================================================
+# 8. invoke() method
+# ===========================================================================
+
+
+class TestInvoke:
+ """Tests for invoke() method."""
+
+ def test_invoke_delegates_to_run(self):
+ """invoke() calls self.run() with the query."""
+ engine = _bypass_init()
+
+ with patch.object(
+ engine, "run", return_value=[{"title": "Result"}]
+ ) as mock_run:
+ result = engine.invoke("test query")
+
+ mock_run.assert_called_once_with("test query")
+ assert result == [{"title": "Result"}]
+
+ def test_invoke_propagates_run_exception(self):
+ """invoke() propagates exceptions from run()."""
+ engine = _bypass_init()
+
+ with patch.object(
+ engine, "run", side_effect=RuntimeError("Search failed")
+ ):
+ with pytest.raises(RuntimeError, match="Search failed"):
+ engine.invoke("test query")
+
+
+# ===========================================================================
+# 9. Integration-style tests (using __init__ with mocks)
+# ===========================================================================
+
+
+class TestInitIntegration:
+ """Integration tests using actual __init__."""
+
+ def test_init_stores_settings_snapshot(self):
+ """__init__ stores settings_snapshot."""
+ settings = {"search.max_results": {"value": 10}}
+ engine = _make_engine_with_init(["wikipedia"], settings=settings)
+ assert engine.settings_snapshot is settings
+
+ def test_init_default_use_api_key_services(self):
+ """Default use_api_key_services is True."""
+ engine = _make_engine_with_init(["wikipedia"])
+ assert engine.use_api_key_services is True
+
+ def test_init_custom_use_api_key_services(self):
+ """Custom use_api_key_services is respected."""
+ engine = _make_engine_with_init(
+ ["wikipedia"], use_api_key_services=False
+ )
+ assert engine.use_api_key_services is False
+
+ def test_init_default_max_engines_to_try(self):
+ """Default max_engines_to_try is 3."""
+ engine = _make_engine_with_init(["wikipedia"])
+ assert engine.max_engines_to_try == 3
+
+ def test_init_custom_max_engines_to_try(self):
+ """Custom max_engines_to_try is stored."""
+ engine = _make_engine_with_init(["wikipedia"], max_engines_to_try=7)
+ assert engine.max_engines_to_try == 7
+
+ def test_init_creates_empty_engine_cache(self):
+ """__init__ creates empty engine cache."""
+ engine = _make_engine_with_init(["wikipedia"])
+ assert engine.engine_cache == {}
+
+ def test_init_accepts_extra_kwargs(self):
+ """__init__ accepts and ignores extra kwargs."""
+ # Should not raise
+ engine = _make_engine_with_init(
+ ["wikipedia"],
+ extra_param="ignored",
+ another_param=42,
+ )
+ assert engine is not None
+
+ def test_init_with_max_filtered_results(self):
+ """__init__ stores max_filtered_results."""
+ engine = _make_engine_with_init(["wikipedia"], max_filtered_results=15)
+ assert engine.max_filtered_results == 15
+
+ def test_init_with_max_filtered_results_default(self):
+ """__init__ defaults max_filtered_results to 5 (base class coerces None to 5)."""
+ engine = _make_engine_with_init(["wikipedia"])
+ assert engine.max_filtered_results == 5
+
+
+# ===========================================================================
+# 10. Analyze query with empty available_engines
+# ===========================================================================
+
+
+class TestAnalyzeQueryEmptyEngines:
+ """Test analyze_query behavior with edge case engine configurations."""
+
+ def test_empty_available_engines_returns_empty_list(self):
+ """analyze_query with empty available_engines returns empty list."""
+ engine = _bypass_init(available_engines=[], llm=None)
+ result = engine.analyze_query("anything")
+ assert result == []
+
+ def test_single_engine_available_returned(self):
+ """Single available engine is returned regardless of query."""
+ engine = _bypass_init(available_engines=["brave"])
+ result = engine.analyze_query("general question")
+ # No SearXNG, no LLM -> reliability sort with single engine
+ assert result == ["brave"]
+
+ def test_arxiv_keyword_with_only_arxiv_available(self):
+ """'arxiv' keyword with only arxiv available returns just arxiv."""
+ engine = _bypass_init(available_engines=["arxiv"])
+ result = engine.analyze_query("arxiv paper on NLP")
+ assert result == ["arxiv"]
+
+ def test_pubmed_keyword_with_only_pubmed_available(self):
+ """'pubmed' keyword with only pubmed available returns just pubmed."""
+ engine = _bypass_init(available_engines=["pubmed"])
+ result = engine.analyze_query("pubmed article on COVID")
+ assert result == ["pubmed"]
+
+ def test_case_insensitive_specialized_detection(self):
+ """Specialized domain detection is case-insensitive."""
+ engine = _bypass_init(available_engines=["github", "searxng"])
+ result = engine.analyze_query("GITHUB Repository for Deep Learning")
+ assert "github" in result
+
+ def test_specialized_before_explicit_keyword(self):
+ """Specialized domain match takes priority over explicit keyword match."""
+ engine = _bypass_init(
+ available_engines=["arxiv", "pubmed", "wikipedia", "searxng"]
+ )
+ # "scientific paper" matches specialized domain before "arxiv" keyword check
+ result = engine.analyze_query("scientific paper on arxiv about AI")
+ assert result == ["arxiv", "pubmed", "wikipedia"]
diff --git a/tests/web_search_engines/test_search_engine_factory_coverage.py b/tests/web_search_engines/test_search_engine_factory_coverage.py
new file mode 100644
index 0000000000..497c5e4912
--- /dev/null
+++ b/tests/web_search_engines/test_search_engine_factory_coverage.py
@@ -0,0 +1,1200 @@
+"""
+Comprehensive tests for search_engine_factory.py covering gaps not
+addressed by existing test_search_engine_factory.py and
+test_factory_full_search_wrapper.py.
+
+Focus areas:
+- API key retrieval paths (settings dict, plain value, engine_config fallback)
+- LLM pass-through when not required but engine accepts it
+- kwargs overriding default_params
+- max_results default logic end-to-end
+- Display label fallback end-to-end through create_search_engine
+- use_full_search triggering the wrapper path
+- LLM relevance filter application on engine instances
+- get_search parameter routing for wikinews, max_filtered_results
+- Edge cases: empty default_params, engine with **kwargs signature
+"""
+
+import inspect as _inspect
+from unittest.mock import Mock, patch
+
+import pytest
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_engine_class(*param_names, class_attrs=None):
+ """Create a real class with a controlled __init__ signature.
+
+ Builds a class whose inspect.signature(__init__) exposes exactly
+ the requested parameter names, but whose __init__ actually accepts
+ **kwargs so the factory can instantiate it.
+ """
+ params = [
+ _inspect.Parameter("self", _inspect.Parameter.POSITIONAL_OR_KEYWORD)
+ ]
+ for name in param_names:
+ params.append(
+ _inspect.Parameter(
+ name, _inspect.Parameter.POSITIONAL_OR_KEYWORD, default=None
+ )
+ )
+
+ class _Eng:
+ _call_kwargs = None
+
+ def __init__(self, **kwargs):
+ _Eng._call_kwargs = kwargs
+ # Set kwargs as instance attributes so the factory can inspect them
+ # (e.g. hasattr(engine, "llm") and engine.llm)
+ for k, v in kwargs.items():
+ setattr(self, k, v)
+
+ _Eng.__init__.__signature__ = _inspect.Signature(params)
+
+ # Attach optional class-level attributes (e.g. is_scientific)
+ if class_attrs:
+ for k, v in class_attrs.items():
+ setattr(_Eng, k, v)
+
+ return _Eng
+
+
+def _engine_config(**overrides):
+ """Return a minimal engine configuration dict."""
+ base = {
+ "module_path": "some.module",
+ "class_name": "SomeEngine",
+ "default_params": {},
+ }
+ base.update(overrides)
+ return base
+
+
+def _patches(registry_return=None, config_return=None, class_return=None):
+ """Context-manager helper that patches registry, search_config, and get_safe_module_class."""
+ import contextlib
+
+ @contextlib.contextmanager
+ def _ctx():
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class"
+ ) as mock_gsmc,
+ ):
+ mock_reg.get.return_value = registry_return
+ if config_return is not None:
+ mock_sc.return_value = config_return
+ if class_return is not None:
+ mock_gsmc.return_value = class_return
+ yield mock_reg, mock_sc, mock_gsmc
+
+ return _ctx()
+
+
+# ---------------------------------------------------------------------------
+# Tests: API key retrieval
+# ---------------------------------------------------------------------------
+
+
+class TestApiKeyRetrieval:
+ """Test the various paths for obtaining API keys."""
+
+ def test_api_key_from_settings_snapshot_dict_format(self):
+ """API key found in settings_snapshot as {value: ...} dict."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("api_key", "max_results")
+ snapshot = {
+ "search.engine.web.myeng.api_key": {"value": "secret-key-123"},
+ }
+
+ with _patches(
+ config_return={"myeng": _engine_config(requires_api_key=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine("myeng", settings_snapshot=snapshot)
+
+ assert result is not None
+ assert EngCls._call_kwargs["api_key"] == "secret-key-123"
+
+ def test_api_key_from_settings_snapshot_plain_string(self):
+ """API key found in settings_snapshot as a plain string."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("api_key", "max_results")
+ snapshot = {
+ "search.engine.web.myeng.api_key": "plain-key-456",
+ }
+
+ with _patches(
+ config_return={"myeng": _engine_config(requires_api_key=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine("myeng", settings_snapshot=snapshot)
+
+ assert result is not None
+ assert EngCls._call_kwargs["api_key"] == "plain-key-456"
+
+ def test_api_key_fallback_to_engine_config(self):
+ """API key not in settings_snapshot but present in engine_config."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("api_key", "max_results")
+ snapshot = {"dummy": "value"} # no api_key setting
+
+ with _patches(
+ config_return={
+ "myeng": _engine_config(
+ requires_api_key=True, api_key="from-config"
+ )
+ },
+ class_return=EngCls,
+ ):
+ result = create_search_engine("myeng", settings_snapshot=snapshot)
+
+ assert result is not None
+ assert EngCls._call_kwargs["api_key"] == "from-config"
+
+ def test_missing_api_key_returns_none(self):
+ """No API key anywhere -> returns None."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ snapshot = {"dummy": "value"}
+
+ with _patches(
+ config_return={"myeng": _engine_config(requires_api_key=True)},
+ ):
+ result = create_search_engine("myeng", settings_snapshot=snapshot)
+
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# Tests: LLM pass-through
+# ---------------------------------------------------------------------------
+
+
+class TestLlmPassThrough:
+ """Test LLM injection into engine constructors."""
+
+ def test_llm_passed_when_requires_llm_true(self):
+ """LLM is always injected when requires_llm=True."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("llm", "max_results")
+ mock_llm = Mock()
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot={"x": 1}
+ )
+
+ assert EngCls._call_kwargs["llm"] is mock_llm
+
+ def test_llm_passed_when_not_required_but_accepted_and_provided(self):
+ """LLM is passed through when engine accepts it and it was provided,
+ even without requires_llm=True."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("llm", "max_results")
+ mock_llm = Mock()
+
+ with _patches(
+ config_return={"eng": _engine_config()}, # no requires_llm
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot={"x": 1}
+ )
+
+ assert EngCls._call_kwargs["llm"] is mock_llm
+
+ def test_llm_not_passed_when_engine_does_not_accept_it(self):
+ """LLM is filtered out when engine __init__ doesn't list it."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results") # no 'llm' param
+ mock_llm = Mock()
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot={"x": 1}
+ )
+
+ assert "llm" not in EngCls._call_kwargs
+
+ def test_llm_none_still_injected_when_requires_llm_true(self):
+ """When requires_llm=True but llm=None, llm=None is still passed
+ (engine handles degraded mode)."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("llm", "max_results")
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng", llm=None, settings_snapshot={"x": 1}
+ )
+
+ assert result is not None
+ assert EngCls._call_kwargs["llm"] is None
+
+
+# ---------------------------------------------------------------------------
+# Tests: kwargs override default_params
+# ---------------------------------------------------------------------------
+
+
+class TestKwargsOverrideDefaults:
+ """Test that kwargs override default_params from config."""
+
+ def test_kwargs_override_default_params(self):
+ """User-supplied kwargs should take precedence over default_params."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "region")
+
+ with _patches(
+ config_return={
+ "eng": _engine_config(
+ default_params={"max_results": 5, "region": "us"}
+ )
+ },
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "eng",
+ settings_snapshot={"x": 1},
+ max_results=42,
+ )
+
+ # max_results from kwargs (42) should override default (5)
+ assert EngCls._call_kwargs["max_results"] == 42
+ # region from default_params should still be present
+ assert EngCls._call_kwargs["region"] == "us"
+
+ def test_empty_default_params(self):
+ """Engine with no default_params should still work."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+
+ with _patches(
+ config_return={"eng": _engine_config(default_params={})},
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "eng", settings_snapshot={"x": 1}, max_results=10
+ )
+
+ assert EngCls._call_kwargs["max_results"] == 10
+
+ def test_missing_default_params_key(self):
+ """Config without default_params key should use empty dict."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+ cfg = _engine_config()
+ del cfg["default_params"]
+
+ with _patches(
+ config_return={"eng": cfg},
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "eng", settings_snapshot={"x": 1}, max_results=7
+ )
+
+ assert EngCls._call_kwargs["max_results"] == 7
+
+
+# ---------------------------------------------------------------------------
+# Tests: max_results defaults
+# ---------------------------------------------------------------------------
+
+
+class TestMaxResultsDefaults:
+ """Test max_results default resolution through the actual function."""
+
+ def test_max_results_from_settings_dict_value(self):
+ """max_results from settings_snapshot as {value: N}."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+ snapshot = {"search.max_results": {"value": 33}}
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine("eng", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs["max_results"] == 33
+
+ def test_max_results_from_settings_plain_int(self):
+ """max_results from settings_snapshot as plain integer."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+ snapshot = {"search.max_results": 17}
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine("eng", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs["max_results"] == 17
+
+ def test_max_results_default_20_when_not_in_settings(self):
+ """max_results defaults to 20 when not in settings_snapshot."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+ snapshot = {"dummy": "value"}
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine("eng", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs["max_results"] == 20
+
+ def test_explicit_max_results_kwarg_not_overridden(self):
+ """Explicit max_results kwarg should not be overridden by defaults."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+ snapshot = {"search.max_results": {"value": 50}}
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "eng", settings_snapshot=snapshot, max_results=5
+ )
+
+ # Explicit kwarg should win
+ assert EngCls._call_kwargs["max_results"] == 5
+
+
+# ---------------------------------------------------------------------------
+# Tests: Display label fallback (end-to-end)
+# ---------------------------------------------------------------------------
+
+
+class TestDisplayLabelFallback:
+ """Test display label -> config key resolution through the actual function."""
+
+ def test_display_label_resolved_to_config_key(self):
+ """A display label like '🔬 OpenAlex (Scientific)' should resolve
+ to the config key whose display_name matches."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+
+ with _patches(
+ config_return={
+ "openalex": _engine_config(display_name="OpenAlex"),
+ },
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "\U0001f52c OpenAlex (Scientific)",
+ settings_snapshot={"x": 1},
+ )
+
+ assert result is not None
+
+ def test_unresolvable_label_falls_back_to_auto(self):
+ """Display label that doesn't match any config falls back to 'auto'."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+
+ with _patches(
+ config_return={
+ "auto": _engine_config(),
+ "other": _engine_config(display_name="Other"),
+ },
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "\U0001f50d Unknown (Category)",
+ settings_snapshot={"x": 1},
+ )
+
+ assert result is not None
+
+ def test_unknown_engine_no_auto_returns_none(self):
+ """Unknown engine with no 'auto' in config returns None."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ with _patches(
+ config_return={"other_engine": _engine_config()},
+ ):
+ result = create_search_engine(
+ "totally_unknown",
+ settings_snapshot={"x": 1},
+ )
+
+ assert result is None
+
+ def test_plain_unknown_engine_falls_back_to_auto(self):
+ """Plain unknown engine name (no label format) falls back to 'auto'."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+
+ with _patches(
+ config_return={"auto": _engine_config()},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "nonexistent_plain_name",
+ settings_snapshot={"x": 1},
+ )
+
+ assert result is not None
+
+
+# ---------------------------------------------------------------------------
+# Tests: use_full_search wrapper trigger
+# ---------------------------------------------------------------------------
+
+
+class TestUseFullSearchWrapper:
+ """Test that use_full_search=True triggers _create_full_search_wrapper."""
+
+ def test_use_full_search_calls_wrapper(self):
+ """When use_full_search=True and engine supports it, wrapper is called."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+ mock_wrapper_result = Mock()
+
+ with _patches(
+ config_return={"eng": _engine_config(supports_full_search=True)},
+ class_return=EngCls,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory._create_full_search_wrapper"
+ ) as mock_wrapper:
+ mock_wrapper.return_value = mock_wrapper_result
+
+ result = create_search_engine(
+ "eng",
+ settings_snapshot={"x": 1},
+ use_full_search=True,
+ )
+
+ assert mock_wrapper.called
+ assert result is mock_wrapper_result
+
+ def test_use_full_search_false_does_not_call_wrapper(self):
+ """When use_full_search=False, wrapper is not called."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+
+ with _patches(
+ config_return={"eng": _engine_config(supports_full_search=True)},
+ class_return=EngCls,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory._create_full_search_wrapper"
+ ) as mock_wrapper:
+ create_search_engine(
+ "eng",
+ settings_snapshot={"x": 1},
+ use_full_search=False,
+ )
+
+ assert not mock_wrapper.called
+
+ def test_supports_full_search_false_does_not_call_wrapper(self):
+ """Engine without supports_full_search does not trigger wrapper."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+
+ with _patches(
+ config_return={"eng": _engine_config(supports_full_search=False)},
+ class_return=EngCls,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory._create_full_search_wrapper"
+ ) as mock_wrapper:
+ create_search_engine(
+ "eng",
+ settings_snapshot={"x": 1},
+ use_full_search=True,
+ )
+
+ assert not mock_wrapper.called
+
+
+# ---------------------------------------------------------------------------
+# Tests: LLM relevance filter
+# ---------------------------------------------------------------------------
+
+
+class TestLlmRelevanceFilter:
+ """Test LLM relevance filter application on created engine instances."""
+
+ def test_per_engine_filter_enabled(self):
+ """Per-engine setting enables filter when engine has LLM."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("llm", "max_results")
+ mock_llm = Mock()
+ snapshot = {
+ "search.engine.web.eng.default_params.enable_llm_relevance_filter": {
+ "value": True
+ },
+ }
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot=snapshot
+ )
+
+ assert result is not None
+ assert getattr(result, "enable_llm_relevance_filter", False) is True
+
+ def test_per_engine_filter_disabled(self):
+ """Per-engine setting can explicitly disable filter."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class(
+ "llm",
+ "max_results",
+ class_attrs={"is_scientific": True},
+ )
+ mock_llm = Mock()
+ snapshot = {
+ "search.engine.web.eng.default_params.enable_llm_relevance_filter": {
+ "value": False
+ },
+ }
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot=snapshot
+ )
+
+ assert result is not None
+ assert getattr(result, "enable_llm_relevance_filter", False) is False
+
+ def test_auto_detection_scientific_engine(self):
+ """Scientific engines get filter auto-enabled."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class(
+ "llm",
+ "max_results",
+ class_attrs={"is_scientific": True},
+ )
+ mock_llm = Mock()
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot={"x": 1}
+ )
+
+ assert result is not None
+ assert getattr(result, "enable_llm_relevance_filter", False) is True
+
+ def test_auto_detection_generic_engine(self):
+ """Generic engines do not get filter auto-enabled."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class(
+ "llm",
+ "max_results",
+ class_attrs={"is_generic": True},
+ )
+ mock_llm = Mock()
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot={"x": 1}
+ )
+
+ assert result is not None
+ assert getattr(result, "enable_llm_relevance_filter", False) is False
+
+ def test_global_skip_filter_overrides_auto(self):
+ """Global skip_relevance_filter=True disables even for scientific engines."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class(
+ "llm",
+ "max_results",
+ class_attrs={"is_scientific": True},
+ )
+ mock_llm = Mock()
+ snapshot = {
+ "search.skip_relevance_filter": {"value": True},
+ }
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot=snapshot
+ )
+
+ assert result is not None
+ assert getattr(result, "enable_llm_relevance_filter", False) is False
+
+ def test_no_llm_means_no_filter(self):
+ """Filter is not applied when engine has no LLM."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class(
+ "max_results",
+ class_attrs={"is_scientific": True},
+ )
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=EngCls,
+ ):
+ result = create_search_engine("eng", settings_snapshot={"x": 1})
+
+ assert result is not None
+ assert getattr(result, "enable_llm_relevance_filter", False) is False
+
+
+# ---------------------------------------------------------------------------
+# Tests: Parallel engine creation
+# ---------------------------------------------------------------------------
+
+
+class TestParallelEngineCreation:
+ """Test parallel engine special-case handling."""
+
+ def test_parallel_scientific_passes_kwargs(self):
+ """Extra kwargs are forwarded to ParallelSearchEngine."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine"
+ ) as mock_cls:
+ mock_cls.return_value = Mock()
+ create_search_engine(
+ "parallel_scientific",
+ llm=Mock(),
+ settings_snapshot={"s": 1},
+ max_results=15,
+ )
+ call_kwargs = mock_cls.call_args[1]
+ assert call_kwargs["max_results"] == 15
+
+ def test_parallel_passes_settings_snapshot(self):
+ """settings_snapshot is forwarded to ParallelSearchEngine."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ snapshot = {"key": "val"}
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine"
+ ) as mock_cls:
+ mock_cls.return_value = Mock()
+ create_search_engine(
+ "parallel",
+ llm=Mock(),
+ settings_snapshot=snapshot,
+ )
+ call_kwargs = mock_cls.call_args[1]
+ assert call_kwargs["settings_snapshot"] is snapshot
+
+
+# ---------------------------------------------------------------------------
+# Tests: Retriever path
+# ---------------------------------------------------------------------------
+
+
+class TestRetrieverPath:
+ """Test retriever registry path."""
+
+ def test_retriever_max_results_from_kwargs(self):
+ """max_results kwarg is forwarded to RetrieverSearchEngine."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ mock_retriever = Mock()
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg:
+ mock_reg.get.return_value = mock_retriever
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_retriever.RetrieverSearchEngine"
+ ) as mock_cls:
+ mock_cls.return_value = Mock()
+ create_search_engine(
+ "my_retriever",
+ settings_snapshot={"x": 1},
+ max_results=25,
+ )
+ call_kwargs = mock_cls.call_args[1]
+ assert call_kwargs["max_results"] == 25
+
+ def test_retriever_default_max_results(self):
+ """Default max_results=10 when not specified."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ mock_retriever = Mock()
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg:
+ mock_reg.get.return_value = mock_retriever
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_retriever.RetrieverSearchEngine"
+ ) as mock_cls:
+ mock_cls.return_value = Mock()
+ create_search_engine(
+ "my_retriever",
+ settings_snapshot={"x": 1},
+ )
+ call_kwargs = mock_cls.call_args[1]
+ assert call_kwargs["max_results"] == 10
+
+
+# ---------------------------------------------------------------------------
+# Tests: get_search parameter routing
+# ---------------------------------------------------------------------------
+
+
+class TestGetSearchParameterRouting:
+ """Test get_search routes parameters correctly for various engines."""
+
+ def test_get_search_wikinews_params(self):
+ """Wikinews gets search_snippets_only, adaptive_search, time_period."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ get_search,
+ )
+
+ snapshot = {
+ "search.engine.web.wikinews.adaptive_search": {"value": False},
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ ) as mock_create:
+ mock_create.return_value = Mock(run=Mock())
+
+ get_search(
+ search_tool="wikinews",
+ llm_instance=Mock(),
+ time_period="m",
+ search_snippets_only=True,
+ search_language="French",
+ settings_snapshot=snapshot,
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert call_kwargs["time_period"] == "m"
+ assert call_kwargs["search_snippets_only"] is True
+ assert call_kwargs["search_language"] == "French"
+ assert call_kwargs["adaptive_search"] is False
+
+ def test_get_search_max_filtered_results(self):
+ """max_filtered_results is passed when provided."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ get_search,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ ) as mock_create:
+ mock_create.return_value = Mock(run=Mock())
+
+ get_search(
+ search_tool="some_engine",
+ llm_instance=Mock(),
+ max_filtered_results=5,
+ settings_snapshot={"x": 1},
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert call_kwargs["max_filtered_results"] == 5
+
+ def test_get_search_max_filtered_results_none(self):
+ """max_filtered_results=None is not passed as a parameter."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ get_search,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ ) as mock_create:
+ mock_create.return_value = Mock(run=Mock())
+
+ get_search(
+ search_tool="some_engine",
+ llm_instance=Mock(),
+ max_filtered_results=None,
+ settings_snapshot={"x": 1},
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert "max_filtered_results" not in call_kwargs
+
+ def test_get_search_google_pse_params(self):
+ """google_pse gets region, safe_search, use_full_search, and search_language."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ get_search,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ ) as mock_create:
+ mock_create.return_value = Mock(run=Mock())
+
+ get_search(
+ search_tool="google_pse",
+ llm_instance=Mock(),
+ region="de",
+ safe_search=False,
+ search_snippets_only=False,
+ search_language="German",
+ settings_snapshot={"x": 1},
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert call_kwargs["region"] == "de"
+ assert call_kwargs["safe_search"] is False
+ assert call_kwargs["use_full_search"] is True
+ assert call_kwargs["search_language"] == "German"
+
+ def test_get_search_mojeek_params(self):
+ """mojeek gets region, safe_search, use_full_search but not search_language."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ get_search,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ ) as mock_create:
+ mock_create.return_value = Mock(run=Mock())
+
+ get_search(
+ search_tool="mojeek",
+ llm_instance=Mock(),
+ region="uk",
+ safe_search=True,
+ search_snippets_only=True,
+ settings_snapshot={"x": 1},
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert call_kwargs["region"] == "uk"
+ assert call_kwargs["safe_search"] is True
+ assert call_kwargs["use_full_search"] is False
+ assert "search_language" not in call_kwargs
+
+ def test_get_search_programmatic_mode_forwarded(self):
+ """programmatic_mode is forwarded to create_search_engine."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ get_search,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ ) as mock_create:
+ mock_create.return_value = Mock(run=Mock())
+
+ get_search(
+ search_tool="some_engine",
+ llm_instance=Mock(),
+ programmatic_mode=True,
+ settings_snapshot={"x": 1},
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert call_kwargs["programmatic_mode"] is True
+
+ def test_get_search_engine_without_region_params(self):
+ """Engines not in the region list don't get region params."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ get_search,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ ) as mock_create:
+ mock_create.return_value = Mock(run=Mock())
+
+ get_search(
+ search_tool="arxiv",
+ llm_instance=Mock(),
+ region="us",
+ safe_search=True,
+ settings_snapshot={"x": 1},
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert "region" not in call_kwargs
+ assert "safe_search" not in call_kwargs
+ assert "use_full_search" not in call_kwargs
+
+
+# ---------------------------------------------------------------------------
+# Tests: Exception handling
+# ---------------------------------------------------------------------------
+
+
+class TestExceptionHandling:
+ """Test exception handling in create_search_engine."""
+
+ def test_instantiation_exception_returns_none(self):
+ """Exception during engine class instantiation returns None."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ ) as (_, _, mock_gsmc):
+ mock_gsmc.side_effect = ValueError("bad class")
+
+ result = create_search_engine("eng", settings_snapshot={"x": 1})
+
+ assert result is None
+
+ def test_engine_init_raises_returns_none(self):
+ """Exception during __init__ of engine class returns None."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ class BrokenEngine:
+ def __init__(self):
+ raise RuntimeError("init failed")
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=BrokenEngine,
+ ):
+ result = create_search_engine("eng", settings_snapshot={"x": 1})
+
+ assert result is None
+
+ def test_missing_module_path_returns_none(self):
+ """Config missing module_path should cause exception -> None."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ bad_config = {"class_name": "Foo", "default_params": {}}
+
+ with _patches(
+ config_return={"eng": bad_config},
+ ):
+ result = create_search_engine("eng", settings_snapshot={"x": 1})
+
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# Tests: settings_snapshot requirement
+# ---------------------------------------------------------------------------
+
+
+class TestSettingsSnapshotRequired:
+ """Test that settings_snapshot=None raises RuntimeError for non-parallel,
+ non-retriever engines."""
+
+ def test_none_settings_snapshot_raises(self):
+ """settings_snapshot=None raises RuntimeError."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg:
+ mock_reg.get.return_value = None
+
+ with pytest.raises(
+ RuntimeError, match="settings_snapshot is required"
+ ):
+ create_search_engine("some_engine", settings_snapshot=None)
+
+ def test_parallel_does_not_need_settings_snapshot(self):
+ """Parallel engines work without settings_snapshot (they short-circuit)."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine"
+ ) as mock_cls:
+ mock_cls.return_value = Mock()
+ # Should not raise even with settings_snapshot=None
+ result = create_search_engine(
+ "parallel", llm=Mock(), settings_snapshot=None
+ )
+ assert result is not None
+
+
+# ---------------------------------------------------------------------------
+# Tests: per-engine filter with plain bool (not dict)
+# ---------------------------------------------------------------------------
+
+
+class TestPerEngineFilterPlainBool:
+ """Test per-engine LLM relevance filter setting as plain bool."""
+
+ def test_per_engine_filter_plain_true(self):
+ """Per-engine setting as plain True enables filter."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("llm", "max_results")
+ mock_llm = Mock()
+ snapshot = {
+ "search.engine.web.eng.default_params.enable_llm_relevance_filter": True,
+ }
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot=snapshot
+ )
+
+ assert result is not None
+ assert getattr(result, "enable_llm_relevance_filter", False) is True
+
+ def test_global_skip_filter_plain_bool(self):
+ """Global skip_relevance_filter as plain True works."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class(
+ "llm",
+ "max_results",
+ class_attrs={"is_scientific": True},
+ )
+ mock_llm = Mock()
+ snapshot = {
+ "search.skip_relevance_filter": True,
+ }
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot=snapshot
+ )
+
+ assert result is not None
+ assert getattr(result, "enable_llm_relevance_filter", False) is False