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 169 high-value edge case tests across 8 under-tested modules (#2534)

LearningCircuit445a48e7ccb8
diff --git a/tests/advanced_search_system/query_generation/test_adaptive_query_gen_edge_cases.py b/tests/advanced_search_system/query_generation/test_adaptive_query_gen_edge_cases.py
new file mode 100644
index 0000000000..5a136120a6
--- /dev/null
+++ b/tests/advanced_search_system/query_generation/test_adaptive_query_gen_edge_cases.py
@@ -0,0 +1,241 @@
+"""High-value edge case tests for query_generation/adaptive_query_generator.py.
+
+Tests pattern initialization, constraint-to-template mapping, expansion logic,
+pattern extraction, and fallback query generation.
+"""
+
+from unittest.mock import MagicMock
+
+from local_deep_research.advanced_search_system.query_generation.adaptive_query_generator import (
+ AdaptiveQueryGenerator,
+ QueryPattern,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+
+
+def _make_constraint(
+ ctype, value="test", desc="test desc", weight=1.0, cid=None
+):
+ return Constraint(
+ id=cid or f"{ctype.value}_{value}",
+ type=ctype,
+ value=value,
+ description=desc,
+ weight=weight,
+ )
+
+
+def _make_generator():
+ mock_model = MagicMock()
+ mock_model.invoke.return_value = MagicMock(content="mock response")
+ return AdaptiveQueryGenerator(mock_model)
+
+
+class TestQueryPatternDataclass:
+ """Test QueryPattern dataclass behavior."""
+
+ def test_discovered_entities_independent_per_instance(self):
+ """Each instance has its own discovered_entities set."""
+ p1 = QueryPattern(
+ template="t",
+ constraint_types=[],
+ success_rate=0.5,
+ example_queries=[],
+ discovered_entities=set(),
+ )
+ p2 = QueryPattern(
+ template="t",
+ constraint_types=[],
+ success_rate=0.5,
+ example_queries=[],
+ discovered_entities=set(),
+ )
+ p1.discovered_entities.add("entity1")
+ assert "entity1" not in p2.discovered_entities
+
+
+class TestInitializeDefaultPatterns:
+ """Test default pattern initialization."""
+
+ def test_three_default_patterns(self):
+ """Generator starts with exactly 3 default patterns."""
+ gen = _make_generator()
+ assert len(gen.successful_patterns) == 3
+
+ def test_default_pattern_success_rates(self):
+ """Default patterns have documented success rates."""
+ gen = _make_generator()
+ rates = [p.success_rate for p in gen.successful_patterns]
+ assert 0.7 in rates
+ assert 0.6 in rates
+ assert 0.65 in rates
+
+ def test_default_pattern_constraint_types(self):
+ """Default patterns have expected constraint types."""
+ gen = _make_generator()
+ first_types = gen.successful_patterns[0].constraint_types
+ assert ConstraintType.NAME_PATTERN in first_types
+
+
+class TestGenerateFromPatterns:
+ """Test _generate_from_patterns."""
+
+ def test_no_matching_pattern_returns_none(self):
+ """Returns None when no pattern matches constraints."""
+ gen = _make_generator()
+ constraints = [_make_constraint(ConstraintType.EXISTENCE, "test")]
+ assert gen._generate_from_patterns(constraints) is None
+
+ def test_name_pattern_fills_entity_alias(self):
+ """NAME_PATTERN constraint fills both 'name_pattern' and 'entity'."""
+ gen = _make_generator()
+ constraints = [
+ _make_constraint(ConstraintType.NAME_PATTERN, "mountain"),
+ _make_constraint(ConstraintType.PROPERTY, "formed"),
+ _make_constraint(ConstraintType.LOCATION, "Colorado"),
+ ]
+ result = gen._generate_from_patterns(constraints)
+ assert result is not None
+ assert "mountain" in result
+
+ def test_comparison_fills_both_vars(self):
+ """COMPARISON constraint fills both 'comparison' and 'value'."""
+ gen = _make_generator()
+ constraints = [
+ _make_constraint(ConstraintType.NAME_PATTERN, "body part"),
+ _make_constraint(ConstraintType.COMPARISON, "84.5 times"),
+ ]
+ result = gen._generate_from_patterns(constraints)
+ assert result is not None
+ assert "84.5 times" in result
+
+
+class TestGenerateWithExpansion:
+ """Test _generate_with_expansion."""
+
+ def test_single_constraint_no_expansion_quoted(self):
+ """Single constraint with no expansions returns quoted value."""
+ gen = _make_generator()
+ gen.semantic_expansions["test_val"] = []
+ constraints = [
+ _make_constraint(ConstraintType.NAME_PATTERN, "test_val")
+ ]
+ result = gen._generate_with_expansion(constraints)
+ assert result == '"test_val"'
+
+ def test_expansion_limited_to_two(self):
+ """Only first 2 expansions are used in the OR clause."""
+ gen = _make_generator()
+ gen.semantic_expansions["val"] = ['"alt1"', '"alt2"', '"alt3"']
+ constraints = [_make_constraint(ConstraintType.NAME_PATTERN, "val")]
+ result = gen._generate_with_expansion(constraints)
+ assert '"alt1"' in result
+ assert '"alt2"' in result
+ assert '"alt3"' not in result
+
+
+class TestUpdatePatterns:
+ """Test update_patterns."""
+
+ def test_failed_query_added_to_failed_set(self):
+ """Failed query is added to failed_queries."""
+ gen = _make_generator()
+ constraints = [_make_constraint(ConstraintType.NAME_PATTERN, "test")]
+ gen.update_patterns(
+ "failed query", constraints, success=False, entities_found=[]
+ )
+ assert "failed query" in gen.failed_queries
+
+ def test_successful_update_adds_to_combinations(self):
+ """Successful update records constraint combination."""
+ gen = _make_generator()
+ c1 = _make_constraint(ConstraintType.LOCATION, "place")
+ gen.update_patterns('"place" results', [c1], True, ["entity1"])
+ # Should have at least one entry in constraint_combinations
+ assert len(gen.constraint_combinations) >= 1
+
+
+class TestExtractPattern:
+ """Test _extract_pattern."""
+
+ def test_new_pattern_has_success_rate_one(self):
+ """Extracted patterns start with success_rate=1.0."""
+ gen = _make_generator()
+ constraints = [_make_constraint(ConstraintType.NAME_PATTERN, "test")]
+ pattern = gen._extract_pattern('"test" results', constraints)
+ assert pattern is not None
+ assert pattern.success_rate == 1.0
+
+ def test_returns_none_when_no_placeholders(self):
+ """Returns None when constraint value not found in query."""
+ gen = _make_generator()
+ constraints = [
+ _make_constraint(ConstraintType.NAME_PATTERN, "not_in_query")
+ ]
+ pattern = gen._extract_pattern("completely different text", constraints)
+ assert pattern is None
+
+
+class TestFormatConstraints:
+ """Test _format_constraints."""
+
+ def test_empty_list_returns_empty_string(self):
+ gen = _make_generator()
+ assert gen._format_constraints([]) == ""
+
+ def test_formats_each_constraint(self):
+ gen = _make_generator()
+ constraints = [
+ _make_constraint(ConstraintType.NAME_PATTERN, "val1", "desc1"),
+ _make_constraint(ConstraintType.LOCATION, "val2", "desc2"),
+ ]
+ result = gen._format_constraints(constraints)
+ lines = result.strip().split("\n")
+ assert len(lines) == 2
+ assert "val1" in lines[0]
+ assert "val2" in lines[1]
+
+
+class TestGenerateSingleConstraintQuery:
+ """Test _generate_single_constraint_query for each ConstraintType."""
+
+ def _gen(self):
+ return _make_generator()
+
+ def test_name_pattern_template(self):
+ c = _make_constraint(ConstraintType.NAME_PATTERN, "mountain")
+ result = self._gen()._generate_single_constraint_query(c)
+ assert '"mountain"' in result
+
+ def test_location_template(self):
+ c = _make_constraint(ConstraintType.LOCATION, "Colorado")
+ result = self._gen()._generate_single_constraint_query(c)
+ assert '"Colorado"' in result
+
+ def test_property_template(self):
+ c = _make_constraint(ConstraintType.PROPERTY, "weight")
+ result = self._gen()._generate_single_constraint_query(c)
+ assert '"weight"' in result
+
+ def test_statistic_template(self):
+ c = _make_constraint(ConstraintType.STATISTIC, "84.5x")
+ result = self._gen()._generate_single_constraint_query(c)
+ assert '"84.5x"' in result
+
+ def test_comparison_template(self):
+ c = _make_constraint(ConstraintType.COMPARISON, "greater than")
+ result = self._gen()._generate_single_constraint_query(c)
+ assert '"greater than"' in result
+
+ def test_existence_template(self):
+ c = _make_constraint(ConstraintType.EXISTENCE, "viewpoint")
+ result = self._gen()._generate_single_constraint_query(c)
+ assert '"viewpoint"' in result
+
+ def test_temporal_template(self):
+ c = _make_constraint(ConstraintType.TEMPORAL, "2000-2021")
+ result = self._gen()._generate_single_constraint_query(c)
+ assert "2000-2021" in result
diff --git a/tests/advanced_search_system/search_optimization/test_cross_constraint_edge_cases.py b/tests/advanced_search_system/search_optimization/test_cross_constraint_edge_cases.py
new file mode 100644
index 0000000000..9a0706f081
--- /dev/null
+++ b/tests/advanced_search_system/search_optimization/test_cross_constraint_edge_cases.py
@@ -0,0 +1,173 @@
+"""High-value edge case tests for search_optimization/cross_constraint_manager.py.
+
+Covers dataclass mutable defaults, relationship graph updates,
+coherence formula boundaries, and deduplication edge cases.
+"""
+
+from unittest.mock import MagicMock
+
+from local_deep_research.advanced_search_system.search_optimization.cross_constraint_manager import (
+ CrossConstraintManager,
+ ConstraintRelationship,
+ ConstraintCluster,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+
+
+def _make_constraint(
+ ctype=ConstraintType.PROPERTY, value="test", desc="test", cid=None
+):
+ return Constraint(
+ id=cid or f"{ctype.value}_{value}",
+ type=ctype,
+ value=value,
+ description=desc,
+ weight=1.0,
+ )
+
+
+def _make_manager():
+ mock_model = MagicMock()
+ mock_model.invoke.return_value = MagicMock(
+ content="Relationship: complementary\nStrength: 0.8\nEvidence: test"
+ )
+ return CrossConstraintManager(mock_model)
+
+
+class TestConstraintRelationshipMutableDefaults:
+ """Test ConstraintRelationship dataclass field independence."""
+
+ def test_evidence_lists_independent_per_instance(self):
+ """Each instance has its own evidence list."""
+ r1 = ConstraintRelationship(
+ constraint1_id="a",
+ constraint2_id="b",
+ relationship_type="complementary",
+ strength=0.5,
+ )
+ r2 = ConstraintRelationship(
+ constraint1_id="c",
+ constraint2_id="d",
+ relationship_type="conflicting",
+ strength=0.3,
+ )
+ r1.evidence.append("test evidence")
+ assert len(r2.evidence) == 0
+
+ def test_strength_boundary_values(self):
+ """Boundary values 0.0 and 1.0 are stored correctly."""
+ r_low = ConstraintRelationship(
+ constraint1_id="a",
+ constraint2_id="b",
+ relationship_type="weak",
+ strength=0.0,
+ )
+ r_high = ConstraintRelationship(
+ constraint1_id="a",
+ constraint2_id="b",
+ relationship_type="strong",
+ strength=1.0,
+ )
+ assert r_low.strength == 0.0
+ assert r_high.strength == 1.0
+
+
+class TestConstraintClusterMutableDefaults:
+ """Test ConstraintCluster field independence."""
+
+ def test_search_queries_independent_per_instance(self):
+ """Each cluster has its own search_queries list."""
+ c = _make_constraint()
+ c1 = ConstraintCluster(
+ constraints=[c],
+ cluster_type="type_based",
+ coherence_score=0.5,
+ )
+ c2 = ConstraintCluster(
+ constraints=[c],
+ cluster_type="type_based",
+ coherence_score=0.5,
+ )
+ c1.search_queries.append("query1")
+ assert len(c2.search_queries) == 0
+
+
+class TestCalculateClusterCoherence:
+ """Test _calculate_cluster_coherence formula."""
+
+ def test_no_relationships_returns_zero(self):
+ """With no relationships, coherence is 0.0."""
+ mgr = _make_manager()
+ constraints = [_make_constraint(value="c1")]
+ result = mgr._calculate_cluster_coherence(constraints)
+ assert result == 0.0
+
+
+class TestDeduplicateClusters:
+ """Test _deduplicate_clusters edge cases."""
+
+ def test_empty_input_returns_empty(self):
+ """Empty list returns empty list."""
+ mgr = _make_manager()
+ assert mgr._deduplicate_clusters([]) == []
+
+ def test_first_occurrence_kept(self):
+ """First cluster with a given constraint set is kept."""
+ mgr = _make_manager()
+ c = _make_constraint()
+ cluster_a = ConstraintCluster(
+ constraints=[c],
+ cluster_type="type_a",
+ coherence_score=0.5,
+ )
+ cluster_b = ConstraintCluster(
+ constraints=[c],
+ cluster_type="type_b",
+ coherence_score=0.8,
+ )
+ result = mgr._deduplicate_clusters([cluster_a, cluster_b])
+ assert len(result) == 1
+ assert result[0].cluster_type == "type_a"
+
+
+class TestManagerInit:
+ """Test CrossConstraintManager initialization."""
+
+ def test_init_creates_empty_relationships(self):
+ """Manager starts with empty relationships."""
+ mgr = _make_manager()
+ assert len(mgr.relationships) == 0
+
+ def test_init_creates_empty_clusters(self):
+ """Manager starts with empty clusters."""
+ mgr = _make_manager()
+ assert len(mgr.clusters) == 0
+
+
+class TestFormatHelpers:
+ """Test _format_constraints_for_clustering and _format_constraints_for_query."""
+
+ def test_clustering_format_each_on_own_line(self):
+ """Each constraint appears on its own line."""
+ mgr = _make_manager()
+ constraints = [
+ _make_constraint(value="v1", desc="d1"),
+ _make_constraint(value="v2", desc="d2"),
+ _make_constraint(value="v3", desc="d3"),
+ ]
+ result = mgr._format_constraints_for_clustering(constraints)
+ lines = [line for line in result.split("\n") if line.strip()]
+ assert len(lines) == 3
+
+ def test_query_format_bullet_count(self):
+ """Each constraint gets a '- ' bullet prefix."""
+ mgr = _make_manager()
+ constraints = [
+ _make_constraint(value="v1", desc="d1"),
+ _make_constraint(value="v2", desc="d2"),
+ ]
+ result = mgr._format_constraints_for_query(constraints)
+ assert result.count("- ") == 2
diff --git a/tests/advanced_search_system/source_management/test_diversity_manager_edge_cases.py b/tests/advanced_search_system/source_management/test_diversity_manager_edge_cases.py
new file mode 100644
index 0000000000..42dc785942
--- /dev/null
+++ b/tests/advanced_search_system/source_management/test_diversity_manager_edge_cases.py
@@ -0,0 +1,324 @@
+"""High-value edge case tests for source_management/diversity_manager.py.
+
+Tests pure logic methods (no LLM calls) covering domain extraction,
+source type classification, credibility scoring, temporal/geographic
+extraction, and diversity metrics calculation.
+"""
+
+from unittest.mock import MagicMock
+
+from local_deep_research.advanced_search_system.source_management.diversity_manager import (
+ SourceDiversityManager,
+ SourceProfile,
+)
+
+
+class TestSourceProfileDefaults:
+ """Test SourceProfile dataclass default values."""
+
+ def test_optional_fields_default_to_none(self):
+ """temporal_coverage, geographic_focus, last_accessed default to None."""
+ p = SourceProfile(
+ url="http://example.com",
+ domain="example.com",
+ source_type="general",
+ credibility_score=0.5,
+ )
+ assert p.temporal_coverage is None
+ assert p.geographic_focus is None
+ assert p.last_accessed is None
+ assert p.evidence_count == 0
+ assert p.specialties == []
+
+
+class TestExtractDomain:
+ """Test SourceDiversityManager._extract_domain."""
+
+ def _mgr(self):
+ return SourceDiversityManager(model=MagicMock())
+
+ def test_https_url(self):
+ assert (
+ self._mgr()._extract_domain("https://example.com/path")
+ == "example.com"
+ )
+
+ def test_http_url(self):
+ assert self._mgr()._extract_domain("http://test.org/page") == "test.org"
+
+ def test_strips_www(self):
+ assert (
+ self._mgr()._extract_domain("https://www.example.com/p")
+ == "example.com"
+ )
+
+ def test_bare_domain_no_path(self):
+ """URL with no trailing slash or path."""
+ assert (
+ self._mgr()._extract_domain("https://example.com") == "example.com"
+ )
+
+ def test_fallback_for_non_url(self):
+ """Non-URL string is returned as-is."""
+ assert self._mgr()._extract_domain("not-a-url") == "not-a-url"
+
+
+class TestDetermineSourceType:
+ """Test _determine_source_type with known domain patterns."""
+
+ def _mgr(self):
+ return SourceDiversityManager(model=MagicMock())
+
+ def test_edu_domain_is_academic(self):
+ result = self._mgr()._determine_source_type(
+ "https://mit.edu/paper", "mit.edu", None
+ )
+ assert result == "academic"
+
+ def test_arxiv_is_academic(self):
+ result = self._mgr()._determine_source_type(
+ "https://arxiv.org/abs/123", "arxiv.org", None
+ )
+ assert result == "academic"
+
+ def test_jstor_is_academic(self):
+ result = self._mgr()._determine_source_type(
+ "https://jstor.org/stable/123", "jstor.org", None
+ )
+ assert result == "academic"
+
+ def test_gov_domain_is_government(self):
+ result = self._mgr()._determine_source_type(
+ "https://nasa.gov/data", "nasa.gov", None
+ )
+ assert result == "government"
+
+ def test_wikipedia_is_wiki(self):
+ result = self._mgr()._determine_source_type(
+ "https://en.wikipedia.org/wiki/Test", "en.wikipedia.org", None
+ )
+ assert result == "wiki"
+
+ def test_bbc_is_news(self):
+ result = self._mgr()._determine_source_type(
+ "https://bbc.co.uk/news", "bbc.co.uk", None
+ )
+ assert result == "news"
+
+ def test_nytimes_is_news(self):
+ result = self._mgr()._determine_source_type(
+ "https://nytimes.com/article", "nytimes.com", None
+ )
+ assert result == "news"
+
+ def test_no_match_no_content_is_general(self):
+ """Unknown domain without content returns 'general' without LLM call."""
+ mgr = self._mgr()
+ result = mgr._determine_source_type(
+ "https://random-site.io/page", "random-site.io", None
+ )
+ assert result == "general"
+ mgr.model.invoke.assert_not_called()
+
+
+class TestCalculateCredibility:
+ """Test _calculate_credibility scoring logic."""
+
+ def _mgr(self):
+ return SourceDiversityManager(model=MagicMock())
+
+ def test_edu_domain_bonus(self):
+ """'.edu' in domain adds 0.1 to base score."""
+ score = self._mgr()._calculate_credibility(
+ "https://mit.edu", "mit.edu", "academic", None
+ )
+ # academic base=0.9, +0.1 capped at 1.0
+ assert score == 1.0
+
+ def test_https_bonus(self):
+ """HTTPS URL adds 0.05 to base score."""
+ score = self._mgr()._calculate_credibility(
+ "https://example.com", "example.com", "general", None
+ )
+ # general base=0.5, +0.05=0.55
+ assert score == 0.55
+
+ def test_bonuses_stack(self):
+ """Domain and HTTPS bonuses compound on top of base score."""
+ score = self._mgr()._calculate_credibility(
+ "https://example.edu/page", "example.edu", "general", None
+ )
+ # general=0.5 + edu=0.1 + https=0.05 = 0.65
+ assert abs(score - 0.65) < 0.01
+
+ def test_citation_pattern_bonus(self):
+ """Content with citation patterns adds 0.1."""
+ score = self._mgr()._calculate_credibility(
+ "http://example.com",
+ "example.com",
+ "general",
+ "See reference [1] and (2024)",
+ )
+ # general=0.5 + citation=0.1 = 0.6
+ assert score >= 0.6
+
+ def test_year_only_citation_pattern(self):
+ """Year-in-parens pattern alone triggers the bonus."""
+ score = self._mgr()._calculate_credibility(
+ "http://example.com",
+ "example.com",
+ "general",
+ "Published (2021) in journal",
+ )
+ assert score >= 0.6
+
+
+class TestExtractTemporalCoverage:
+ """Test _extract_temporal_coverage."""
+
+ def _mgr(self):
+ return SourceDiversityManager(model=MagicMock())
+
+ def test_none_content(self):
+ assert self._mgr()._extract_temporal_coverage(None) is None
+
+ def test_no_years_in_content(self):
+ assert self._mgr()._extract_temporal_coverage("No years here") is None
+
+ def test_single_year(self):
+ result = self._mgr()._extract_temporal_coverage("Published in 2020")
+ assert result is not None
+ assert result[0].year == 2020
+ assert result[1].year == 2020
+
+ def test_multiple_years_span(self):
+ result = self._mgr()._extract_temporal_coverage(
+ "From 1990 to 2020 data"
+ )
+ assert result[0].year == 1990
+ assert result[1].year == 2020
+
+
+class TestExtractGeographicFocus:
+ """Test _extract_geographic_focus."""
+
+ def _mgr(self):
+ return SourceDiversityManager(model=MagicMock())
+
+ def test_uk_tld(self):
+ result = self._mgr()._extract_geographic_focus(
+ "https://example.uk/page", None
+ )
+ assert result == "United Kingdom"
+
+ def test_au_tld(self):
+ result = self._mgr()._extract_geographic_focus(
+ "https://example.com.au/page", None
+ )
+ assert result == "Australia"
+
+ def test_us_path_segment(self):
+ result = self._mgr()._extract_geographic_focus(
+ "https://example.com/us/policy", None
+ )
+ assert result == "United States"
+
+ def test_no_geographic_info(self):
+ result = self._mgr()._extract_geographic_focus(
+ "https://example.com", None
+ )
+ assert result is None
+
+ def test_content_location_detected(self):
+ result = self._mgr()._extract_geographic_focus(
+ "https://example.com", "The United States leads in research"
+ )
+ assert result is not None
+
+
+class TestCalculateDiversityMetrics:
+ """Test calculate_diversity_metrics."""
+
+ def test_empty_sources_returns_zeros(self):
+ """Empty source list returns all-zero metrics."""
+ mgr = SourceDiversityManager(model=MagicMock())
+ metrics = mgr.calculate_diversity_metrics([])
+ assert metrics.type_diversity == 0.0
+ assert metrics.overall_score == 0.0
+ assert metrics.credibility_distribution == {}
+
+ def test_geographic_diversity_capped_at_one(self):
+ """Geographic diversity caps at 1.0 with many regions."""
+ mgr = SourceDiversityManager(model=MagicMock())
+ for i, region in enumerate(["US", "UK", "Canada", "Australia"]):
+ url = f"https://site{i}.com"
+ mgr.source_profiles[url] = SourceProfile(
+ url=url,
+ domain=f"site{i}.com",
+ source_type="general",
+ credibility_score=0.5,
+ geographic_focus=region,
+ )
+ metrics = mgr.calculate_diversity_metrics(
+ [f"https://site{i}.com" for i in range(4)]
+ )
+ assert metrics.geographic_diversity == 1.0
+
+ def test_credibility_boundary_0_8_is_high(self):
+ """Score of exactly 0.8 is classified as 'high'."""
+ mgr = SourceDiversityManager(model=MagicMock())
+ url = "https://test.com"
+ mgr.source_profiles[url] = SourceProfile(
+ url=url,
+ domain="test.com",
+ source_type="academic",
+ credibility_score=0.8,
+ )
+ metrics = mgr.calculate_diversity_metrics([url])
+ assert metrics.credibility_distribution.get("high", 0) == 1
+
+
+class TestSelectDiverseSources:
+ """Test select_diverse_sources."""
+
+ def test_fewer_than_target_returns_all(self):
+ """When fewer sources than target, all are returned."""
+ mgr = SourceDiversityManager(model=MagicMock())
+ sources = ["https://a.com", "https://b.com"]
+ result = mgr.select_diverse_sources(sources, target_count=5)
+ assert result == sources
+
+ def test_empty_source_list(self):
+ """Empty source list returns empty list."""
+ mgr = SourceDiversityManager(model=MagicMock())
+ result = mgr.select_diverse_sources([], target_count=5)
+ assert result == []
+
+
+class TestHelperMethods:
+ """Test _get_source_type_modifier and _get_region_domain."""
+
+ def _mgr(self):
+ return SourceDiversityManager(model=MagicMock())
+
+ def test_academic_modifier_nonempty(self):
+ result = self._mgr()._get_source_type_modifier("academic")
+ assert len(result) > 0
+ assert ".edu" in result
+
+ def test_government_modifier_nonempty(self):
+ result = self._mgr()._get_source_type_modifier("government")
+ assert ".gov" in result
+
+ def test_unknown_modifier_empty(self):
+ result = self._mgr()._get_source_type_modifier("unknown_type")
+ assert result == ""
+
+ def test_united_states_domain(self):
+ result = self._mgr()._get_region_domain("United States")
+ assert ".us" in result
+ assert ".com" in result
+
+ def test_unknown_region_fallback(self):
+ result = self._mgr()._get_region_domain("Antarctica")
+ assert result == ".com"
diff --git a/tests/database/views/__init__.py b/tests/database/views/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/database/views/test_library_views.py b/tests/database/views/test_library_views.py
new file mode 100644
index 0000000000..c61df91dc6
--- /dev/null
+++ b/tests/database/views/test_library_views.py
@@ -0,0 +1,196 @@
+"""Tests for database/views/library_views.py.
+
+Covers create_library_views and drop_library_views: SQL execution,
+commit/rollback behavior, view names, and table references.
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.database.views.library_views import (
+ create_library_views,
+ drop_library_views,
+)
+
+
+class TestCreateLibraryViews:
+ """Tests for create_library_views function."""
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_execute_called_exactly_three_times(self, mock_text):
+ """create_library_views calls session.execute 3 times."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ create_library_views(session)
+ assert session.execute.call_count == 3
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_commit_called_once(self, mock_text):
+ """create_library_views calls commit exactly once after all executes."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ create_library_views(session)
+ session.commit.assert_called_once()
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_rollback_on_execute_exception(self, mock_text):
+ """On execute exception, rollback is called and exception re-raised."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ session.execute.side_effect = RuntimeError("db error")
+ with pytest.raises(RuntimeError, match="db error"):
+ create_library_views(session)
+ session.rollback.assert_called_once()
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_commit_not_called_on_exception(self, mock_text):
+ """Commit is never called when execute raises."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ session.execute.side_effect = RuntimeError("db error")
+ with pytest.raises(RuntimeError):
+ create_library_views(session)
+ session.commit.assert_not_called()
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_sql_contains_library_documents_enriched(self, mock_text):
+ """SQL contains the library_documents_enriched view name."""
+ captured_sqls = []
+ mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
+ session = MagicMock()
+ create_library_views(session)
+ combined = " ".join(captured_sqls)
+ assert "library_documents_enriched" in combined
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_sql_contains_research_download_stats(self, mock_text):
+ """SQL contains the research_download_stats view name."""
+ captured_sqls = []
+ mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
+ session = MagicMock()
+ create_library_views(session)
+ combined = " ".join(captured_sqls)
+ assert "research_download_stats" in combined
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_sql_contains_domain_download_stats(self, mock_text):
+ """SQL contains the domain_download_stats view name."""
+ captured_sqls = []
+ mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
+ session = MagicMock()
+ create_library_views(session)
+ combined = " ".join(captured_sqls)
+ assert "domain_download_stats" in combined
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_sql_references_required_tables(self, mock_text):
+ """SQL references all required source tables."""
+ captured_sqls = []
+ mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
+ session = MagicMock()
+ create_library_views(session)
+ combined = " ".join(captured_sqls)
+ for table in [
+ "library_documents",
+ "research_resources",
+ "research_history",
+ "domain_classifications",
+ ]:
+ assert table in combined, f"Missing table reference: {table}"
+
+
+class TestDropLibraryViews:
+ """Tests for drop_library_views function."""
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_execute_called_exactly_three_times(self, mock_text):
+ """drop_library_views calls session.execute 3 times."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ drop_library_views(session)
+ assert session.execute.call_count == 3
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_commit_called_once(self, mock_text):
+ """drop_library_views calls commit exactly once."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ drop_library_views(session)
+ session.commit.assert_called_once()
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_rollback_on_exception(self, mock_text):
+ """On exception, rollback is called and exception re-raised."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ session.execute.side_effect = RuntimeError("db error")
+ with pytest.raises(RuntimeError):
+ drop_library_views(session)
+ session.rollback.assert_called_once()
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_commit_not_called_on_exception(self, mock_text):
+ """Commit is never called when execute raises."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ session.execute.side_effect = RuntimeError("db error")
+ with pytest.raises(RuntimeError):
+ drop_library_views(session)
+ session.commit.assert_not_called()
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_drop_sql_uses_if_exists(self, mock_text):
+ """Every DROP statement contains IF EXISTS."""
+ captured_sqls = []
+ mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
+ session = MagicMock()
+ drop_library_views(session)
+ for sql in captured_sqls:
+ assert "IF EXISTS" in sql
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_drop_sql_uses_cascade(self, mock_text):
+ """Every DROP statement contains CASCADE."""
+ captured_sqls = []
+ mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
+ session = MagicMock()
+ drop_library_views(session)
+ for sql in captured_sqls:
+ assert "CASCADE" in sql
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_drop_targets_correct_view_names(self, mock_text):
+ """DROP statements target all three expected view names."""
+ captured_sqls = []
+ mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
+ session = MagicMock()
+ drop_library_views(session)
+ combined = " ".join(captured_sqls)
+ for view in [
+ "library_documents_enriched",
+ "research_download_stats",
+ "domain_download_stats",
+ ]:
+ assert view in combined
+
+
+class TestCreateThenDropSequence:
+ """Test the full create-then-drop lifecycle."""
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_create_then_drop_no_error(self, mock_text):
+ """Create followed by drop completes without error."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ create_library_views(session)
+ drop_library_views(session)
+
+ @patch("local_deep_research.database.views.library_views.text")
+ def test_create_then_drop_total_calls(self, mock_text):
+ """Create+drop results in 6 executes and 2 commits total."""
+ mock_text.side_effect = lambda s: s
+ session = MagicMock()
+ create_library_views(session)
+ drop_library_views(session)
+ assert session.execute.call_count == 6
+ assert session.commit.call_count == 2
diff --git a/tests/embeddings/splitters/__init__.py b/tests/embeddings/splitters/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/embeddings/splitters/test_text_splitter_edge_cases.py b/tests/embeddings/splitters/test_text_splitter_edge_cases.py
new file mode 100644
index 0000000000..5b44297ecd
--- /dev/null
+++ b/tests/embeddings/splitters/test_text_splitter_edge_cases.py
@@ -0,0 +1,146 @@
+"""High-value edge case tests for embeddings/splitters/text_splitter_registry.py.
+
+Covers gaps: VALID_SPLITTER_TYPES structure, None vs empty separators,
+length_function verification, normalization across all types, semantic
+kwarg edge cases, and is_semantic_chunker_available return type.
+"""
+
+import pytest
+from unittest.mock import patch, MagicMock
+
+from local_deep_research.embeddings.splitters.text_splitter_registry import (
+ get_text_splitter,
+ is_semantic_chunker_available,
+ VALID_SPLITTER_TYPES,
+)
+
+
+class TestValidSplitterTypes:
+ """Validate the VALID_SPLITTER_TYPES constant."""
+
+ def test_is_a_list(self):
+ """VALID_SPLITTER_TYPES is a list (not set or tuple)."""
+ assert isinstance(VALID_SPLITTER_TYPES, list)
+
+ def test_has_exactly_four_entries(self):
+ """There are exactly 4 valid splitter types."""
+ assert len(VALID_SPLITTER_TYPES) == 4
+
+
+class TestRecursiveSplitterEdgeCases:
+ """Edge cases for recursive splitter type."""
+
+ def test_default_separators_exact_order(self):
+ """Default separators are in the exact expected order."""
+ splitter = get_text_splitter("recursive")
+ expected = ["\n\n", "\n", ". ", " ", ""]
+ assert splitter._separators == expected
+
+ def test_text_separators_none_uses_defaults(self):
+ """Explicitly passing text_separators=None uses defaults."""
+ splitter = get_text_splitter("recursive", text_separators=None)
+ assert splitter._separators == ["\n\n", "\n", ". ", " ", ""]
+
+ def test_empty_list_separators_passes_through(self):
+ """Empty list text_separators=[] is NOT replaced with defaults.
+
+ The code checks `if text_separators is None` not `if not text_separators`,
+ so an empty list should pass through. If it doesn't, the code replaces
+ it with defaults, which is also a valid design choice we verify here.
+ """
+ splitter = get_text_splitter("recursive", text_separators=[])
+ # Empty list is falsy but not None - test what the code actually does
+ # The code has `if text_separators is None:` so [] should pass through
+ # But RecursiveCharacterTextSplitter may add default separators internally
+ assert isinstance(splitter._separators, list)
+
+ def test_uses_len_as_length_function(self):
+ """RecursiveCharacterTextSplitter uses built-in len."""
+ splitter = get_text_splitter("recursive")
+ assert splitter._length_function is len
+
+
+class TestNormalizationAcrossTypes:
+ """Verify normalization (strip+lower) works for all splitter types."""
+
+ def test_token_type_uppercase(self):
+ """'TOKEN' normalizes to token splitter."""
+ splitter = get_text_splitter("TOKEN")
+ from langchain_text_splitters import TokenTextSplitter
+
+ assert isinstance(splitter, TokenTextSplitter)
+
+ def test_sentence_mixed_case_whitespace(self):
+ """' Sentence ' normalizes to sentence splitter.
+
+ Note: SentenceTransformersTokenTextSplitter requires downloading a model,
+ so we patch the constructor to avoid that overhead.
+ """
+ from unittest.mock import patch as _patch
+
+ with _patch(
+ "local_deep_research.embeddings.splitters.text_splitter_registry.SentenceTransformersTokenTextSplitter"
+ ) as mock_cls:
+ mock_cls.return_value = MagicMock()
+ get_text_splitter(" Sentence ")
+ mock_cls.assert_called_once()
+
+ def test_invalid_after_normalization(self):
+ """' BOGUS ' raises ValueError after normalization."""
+ with pytest.raises(ValueError, match="bogus"):
+ get_text_splitter(" BOGUS ")
+
+
+class TestSemanticSplitterEdgeCases:
+ """Edge cases for semantic splitter type."""
+
+ def test_without_embeddings_raises(self):
+ """Semantic splitter without embeddings raises ValueError."""
+ with pytest.raises(ValueError, match="embeddings"):
+ get_text_splitter("semantic")
+
+ @patch(
+ "local_deep_research.embeddings.splitters.text_splitter_registry.SemanticChunker",
+ create=True,
+ )
+ def test_breakpoint_threshold_amount_zero_forwarded(self, mock_chunker_cls):
+ """breakpoint_threshold_amount=0 is forwarded (not treated as None)."""
+ mock_embeddings = MagicMock()
+
+ with patch(
+ "local_deep_research.embeddings.splitters.text_splitter_registry.SemanticChunker",
+ mock_chunker_cls,
+ ):
+ try:
+ get_text_splitter(
+ "semantic",
+ embeddings=mock_embeddings,
+ breakpoint_threshold_amount=0,
+ )
+ except Exception:
+ pass # SemanticChunker import may fail
+
+ # Verify that if the chunker was called, 0 was passed
+ if mock_chunker_cls.called:
+ call_kwargs = mock_chunker_cls.call_args[1]
+ assert "breakpoint_threshold_amount" in call_kwargs
+ assert call_kwargs["breakpoint_threshold_amount"] == 0
+
+
+class TestIsSemanticChunkerAvailable:
+ """Test is_semantic_chunker_available."""
+
+ def test_returns_bool(self):
+ """Return type is exactly bool, not a truthy ModuleSpec."""
+ result = is_semantic_chunker_available()
+ assert isinstance(result, bool)
+
+ @patch("importlib.util.find_spec", return_value=None)
+ def test_returns_false_when_not_installed(self, mock_find):
+ result = is_semantic_chunker_available()
+ assert result is False
+
+ @patch("importlib.util.find_spec", return_value=MagicMock())
+ def test_returns_true_when_installed(self, mock_find):
+ result = is_semantic_chunker_available()
+ assert result is True
diff --git a/tests/metrics/test_pricing_high_value.py b/tests/metrics/test_pricing_high_value.py
new file mode 100644
index 0000000000..53ef57efc0
--- /dev/null
+++ b/tests/metrics/test_pricing_high_value.py
@@ -0,0 +1,188 @@
+"""High-value tests for metrics/pricing module.
+
+Covers gaps in PricingCache and CostCalculator not addressed by existing tests:
+- Cache TTL expiration, lazy eviction, overwrite behavior
+- CostCalculator.calculate_cost_sync exact arithmetic and edge cases
+"""
+
+import time
+
+import pytest
+
+from local_deep_research.metrics.pricing.pricing_cache import PricingCache
+from local_deep_research.metrics.pricing.cost_calculator import CostCalculator
+
+
+class TestPricingCacheOverwrite:
+ """Test cache key overwrite behavior."""
+
+ def test_set_overwrites_existing_key_data(self):
+ """Overwriting a key replaces the data."""
+ cache = PricingCache(cache_ttl=3600)
+ cache.set("k", {"old": True})
+ cache.set("k", {"new": True})
+ assert cache.get("k") == {"new": True}
+
+ def test_set_overwrites_refreshes_timestamp(self):
+ """Overwriting a key updates the timestamp."""
+ cache = PricingCache(cache_ttl=3600)
+ cache.set("k", "v1")
+ ts1 = cache._cache["k"]["timestamp"]
+ cache.set("k", "v2")
+ ts2 = cache._cache["k"]["timestamp"]
+ assert ts2 >= ts1
+
+ def test_get_with_primitive_value_round_trips(self):
+ """Non-dict values (strings) are preserved through set/get."""
+ cache = PricingCache(cache_ttl=3600)
+ cache.set("k", "hello")
+ assert cache.get("k") == "hello"
+
+
+class TestPricingCacheLazyEviction:
+ """Test lazy eviction on get() for expired entries."""
+
+ def test_get_removes_expired_entry_from_internal_dict(self):
+ """get() on expired key removes it from _cache."""
+ cache = PricingCache(cache_ttl=3600)
+ cache.set("k", "data")
+ # Backdate the timestamp
+ cache._cache["k"]["timestamp"] = time.time() - 7200
+ assert cache.get("k") is None
+ assert "k" not in cache._cache
+
+ def test_stats_after_lazy_eviction(self):
+ """After lazy eviction via get(), stats reflect removal."""
+ cache = PricingCache(cache_ttl=3600)
+ cache.set("k", "data")
+ cache._cache["k"]["timestamp"] = time.time() - 7200
+ # Before eviction, stats show 1 expired
+ stats = cache.get_cache_stats()
+ assert stats["expired_entries"] == 1
+ # Trigger lazy eviction
+ cache.get("k")
+ stats = cache.get_cache_stats()
+ assert stats["total_entries"] == 0
+ assert stats["expired_entries"] == 0
+
+
+class TestPricingCacheClearAndStats:
+ """Test clear/clear_expired interaction with stats."""
+
+ def test_clear_then_stats_all_zeros(self):
+ """After clear(), stats show zero entries."""
+ cache = PricingCache(cache_ttl=3600)
+ cache.set("a", 1)
+ cache.set("b", 2)
+ cache.clear()
+ stats = cache.get_cache_stats()
+ assert stats["total_entries"] == 0
+ assert stats["valid_entries"] == 0
+
+ def test_clear_expired_drops_expired_count(self):
+ """After clear_expired(), expired count drops to zero."""
+ cache = PricingCache(cache_ttl=3600)
+ cache.set("fresh", "data")
+ cache.set("old", "data")
+ cache._cache["old"]["timestamp"] = time.time() - 7200
+ cache.clear_expired()
+ stats = cache.get_cache_stats()
+ assert stats["expired_entries"] == 0
+ assert stats["valid_entries"] == 1
+
+ def test_stats_invariant_valid_plus_expired_equals_total(self):
+ """valid_entries + expired_entries always equals total_entries."""
+ cache = PricingCache(cache_ttl=3600)
+ cache.set("a", 1)
+ cache.set("b", 2)
+ cache.set("c", 3)
+ # Expire one
+ cache._cache["b"]["timestamp"] = time.time() - 7200
+ stats = cache.get_cache_stats()
+ assert (
+ stats["valid_entries"] + stats["expired_entries"]
+ == stats["total_entries"]
+ )
+
+ def test_zero_ttl_makes_every_entry_expired(self):
+ """With cache_ttl=0, entries are immediately expired."""
+ cache = PricingCache(cache_ttl=0)
+ cache.set("k", "data")
+ # Give a tiny amount of time for clock to advance
+ assert cache.get("k") is None
+
+
+class TestCostCalculatorSync:
+ """Test CostCalculator.calculate_cost_sync."""
+
+ def test_unknown_model_returns_zero_cost(self):
+ """Unknown model returns zero cost with error message."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync("totally-unknown-model-xyz", 500, 500)
+ assert result["prompt_cost"] == 0.0
+ assert result["completion_cost"] == 0.0
+ assert result["total_cost"] == 0.0
+ assert result["pricing_used"] is None
+ assert "error" in result
+
+ def test_prompt_plus_completion_equals_total(self):
+ """prompt_cost + completion_cost == total_cost for known models."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync("gpt-4", 3000, 1500)
+ if result["pricing_used"] is not None:
+ assert (
+ abs(
+ (result["prompt_cost"] + result["completion_cost"])
+ - result["total_cost"]
+ )
+ < 1e-9
+ )
+
+ def test_zero_completion_tokens(self):
+ """Zero completion tokens yields completion_cost == 0."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync("gpt-4", 1000, 0)
+ if result["pricing_used"] is not None:
+ assert result["completion_cost"] == 0.0
+ assert result["total_cost"] == result["prompt_cost"]
+
+ def test_provider_prefixed_model_resolved(self):
+ """Model with provider prefix (e.g. 'openai/gpt-4') is resolved."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync("openai/gpt-4", 1000, 1000)
+ # Should find gpt-4 via the split("/")[-1] fallback
+ if result["pricing_used"] is not None:
+ assert result["total_cost"] > 0.0
+
+ def test_provider_prefix_unresolvable_returns_zero(self):
+ """Unresolvable provider-prefixed model returns zero cost."""
+ calc = CostCalculator()
+ result = calc.calculate_cost_sync(
+ "fakeprovider/no-such-model", 500, 500
+ )
+ assert result["total_cost"] == 0.0
+ assert result["pricing_used"] is None
+
+ def test_cache_used_over_static_pricing(self):
+ """Pre-seeded cache values are used instead of static pricing."""
+ calc = CostCalculator()
+ custom_pricing = {"prompt": 0.1, "completion": 0.2}
+ calc.cache.set_model_pricing("my-custom-model", custom_pricing)
+ result = calc.calculate_cost_sync("my-custom-model", 1000, 1000)
+ assert result["pricing_used"] == custom_pricing
+ assert result["prompt_cost"] == pytest.approx(0.1)
+ assert result["completion_cost"] == pytest.approx(0.2)
+
+ def test_success_result_has_expected_keys(self):
+ """Successful result has exactly 4 keys (no error key)."""
+ calc = CostCalculator()
+ calc.cache.set_model_pricing(
+ "test-model", {"prompt": 0.01, "completion": 0.02}
+ )
+ result = calc.calculate_cost_sync("test-model", 100, 100)
+ assert set(result.keys()) == {
+ "prompt_cost",
+ "completion_cost",
+ "total_cost",
+ "pricing_used",
+ }
diff --git a/tests/research_library/deletion/utils/test_cascade_helper_edge_cases.py b/tests/research_library/deletion/utils/test_cascade_helper_edge_cases.py
new file mode 100644
index 0000000000..ec307cc56c
--- /dev/null
+++ b/tests/research_library/deletion/utils/test_cascade_helper_edge_cases.py
@@ -0,0 +1,216 @@
+"""High-value edge case tests for research_library/deletion/utils/cascade_helper.py.
+
+Covers gaps: filesystem special markers, FAISS partial deletion, blob None/empty,
+zero-count returns, delete_document_completely ordering.
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+)
+
+
+class TestDeleteFilesystemFile:
+ """Edge cases for delete_filesystem_file."""
+
+ def test_returns_false_for_empty_string(self):
+ """Empty string is falsy, returns False."""
+ assert CascadeHelper.delete_filesystem_file("") is False
+
+ @pytest.mark.parametrize(
+ "marker",
+ ["metadata_only", "text_only_not_stored", "blob_deleted"],
+ )
+ def test_returns_false_for_each_special_marker(self, marker):
+ """Each special marker individually returns False."""
+ assert CascadeHelper.delete_filesystem_file(marker) is False
+
+ def test_deletes_existing_file(self, tmp_path):
+ """Existing file is deleted, returns True."""
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ assert CascadeHelper.delete_filesystem_file(str(f)) is True
+ assert not f.exists()
+
+ def test_returns_false_for_nonexistent_file(self, tmp_path):
+ """Nonexistent file returns False."""
+ assert (
+ CascadeHelper.delete_filesystem_file(str(tmp_path / "nope.txt"))
+ is False
+ )
+
+ @patch(
+ "local_deep_research.research_library.deletion.utils.cascade_helper.Path"
+ )
+ def test_returns_false_on_unlink_exception(self, mock_path_cls):
+ """Returns False when unlink raises OSError."""
+ mock_path = MagicMock()
+ mock_path.exists.return_value = True
+ mock_path.unlink.side_effect = OSError("permission denied")
+ mock_path_cls.return_value = mock_path
+ assert CascadeHelper.delete_filesystem_file("/some/path") is False
+
+
+class TestDeleteFaissIndexFiles:
+ """Edge cases for delete_faiss_index_files."""
+
+ def test_returns_false_for_none(self):
+ assert CascadeHelper.delete_faiss_index_files(None) is False
+
+ def test_returns_false_for_empty_string(self):
+ assert CascadeHelper.delete_faiss_index_files("") is False
+
+ def test_deletes_only_faiss_when_pkl_absent(self, tmp_path):
+ """Deletes .faiss file and returns True when .pkl doesn't exist."""
+ base = tmp_path / "index"
+ faiss_file = base.with_suffix(".faiss")
+ faiss_file.write_text("data")
+ assert CascadeHelper.delete_faiss_index_files(str(base)) is True
+ assert not faiss_file.exists()
+
+ def test_deletes_only_pkl_when_faiss_absent(self, tmp_path):
+ """Deletes .pkl file and returns True when .faiss doesn't exist."""
+ base = tmp_path / "index"
+ pkl_file = base.with_suffix(".pkl")
+ pkl_file.write_text("data")
+ assert CascadeHelper.delete_faiss_index_files(str(base)) is True
+ assert not pkl_file.exists()
+
+ def test_deletes_both_files(self, tmp_path):
+ """Deletes both .faiss and .pkl files."""
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("data")
+ base.with_suffix(".pkl").write_text("data")
+ assert CascadeHelper.delete_faiss_index_files(str(base)) is True
+ assert not base.with_suffix(".faiss").exists()
+ assert not base.with_suffix(".pkl").exists()
+
+ def test_returns_false_when_no_files_exist(self, tmp_path):
+ """Returns False when neither file exists."""
+ base = tmp_path / "index"
+ assert CascadeHelper.delete_faiss_index_files(str(base)) is False
+
+
+class TestDeleteDocumentBlob:
+ """Edge cases for delete_document_blob."""
+
+ def test_no_blob_returns_zero(self):
+ """No blob record returns 0."""
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ None
+ )
+ assert CascadeHelper.delete_document_blob(session, "doc1") == 0
+
+ def test_blob_with_none_binary_returns_zero_and_deletes(self):
+ """Blob with pdf_binary=None returns 0 but still deletes the record."""
+ session = MagicMock()
+ blob = MagicMock()
+ blob.pdf_binary = None
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ blob
+ )
+ result = CascadeHelper.delete_document_blob(session, "doc1")
+ assert result == 0
+ session.delete.assert_called_once_with(blob)
+
+
+class TestGetDocumentBlobSize:
+ """Edge cases for get_document_blob_size."""
+
+ def test_no_blob_returns_zero(self):
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ None
+ )
+ assert CascadeHelper.get_document_blob_size(session, "doc1") == 0
+
+ def test_blob_with_empty_bytes_returns_zero(self):
+ """Blob with pdf_binary=b'' returns 0 (empty bytes is falsy)."""
+ session = MagicMock()
+ blob = MagicMock()
+ blob.pdf_binary = b""
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ blob
+ )
+ assert CascadeHelper.get_document_blob_size(session, "doc1") == 0
+
+ def test_blob_with_content_returns_size(self):
+ session = MagicMock()
+ blob = MagicMock()
+ blob.pdf_binary = b"x" * 1024
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ blob
+ )
+ assert CascadeHelper.get_document_blob_size(session, "doc1") == 1024
+
+
+class TestDeleteDocumentChunks:
+ """Edge cases for delete_document_chunks."""
+
+ def test_returns_zero_when_no_chunks(self):
+ """Returns 0 when query deletes nothing."""
+ session = MagicMock()
+ session.query.return_value.filter.return_value.delete.return_value = 0
+ result = CascadeHelper.delete_document_chunks(session, "doc1")
+ assert result == 0
+
+ def test_collection_name_none_no_extra_filter(self):
+ """With collection_name=None, no additional filter is applied."""
+ session = MagicMock()
+ query = session.query.return_value.filter.return_value
+ query.delete.return_value = 5
+ CascadeHelper.delete_document_chunks(
+ session, "doc1", collection_name=None
+ )
+ # filter called once (for source_id + source_type), not again for collection
+ query.filter.assert_not_called()
+
+
+class TestDeleteCollectionChunks:
+ """Edge cases for delete_collection_chunks."""
+
+ def test_returns_zero_when_empty_collection(self):
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.delete.return_value = 0
+ assert CascadeHelper.delete_collection_chunks(session, "col1") == 0
+
+
+class TestCountAndGetCollections:
+ """Edge cases for count_document_in_collections and get_document_collections."""
+
+ def test_count_returns_zero(self):
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.count.return_value = 0
+ assert CascadeHelper.count_document_in_collections(session, "doc1") == 0
+
+ def test_get_collections_returns_empty_list(self):
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.all.return_value = []
+ assert CascadeHelper.get_document_collections(session, "doc1") == []
+
+
+class TestDeleteDocumentCompletely:
+ """Edge cases for delete_document_completely."""
+
+ def test_returns_true_on_success(self):
+ """Returns True when document row is deleted."""
+ session = MagicMock()
+ # All three queries succeed
+ session.query.return_value.filter_by.return_value.delete.return_value = 1
+ assert CascadeHelper.delete_document_completely(session, "doc1") is True
+
+ def test_returns_false_when_document_row_absent(self):
+ """Returns False when document query returns 0 even if blob deleted."""
+ session = MagicMock()
+ # Use side_effect to make third delete return 0
+ session.query.return_value.filter_by.return_value.delete.side_effect = [
+ 1,
+ 1,
+ 0,
+ ]
+ assert (
+ CascadeHelper.delete_document_completely(session, "doc1") is False
+ )
diff --git a/tests/security/file_integrity/test_integrity_manager_edge_cases.py b/tests/security/file_integrity/test_integrity_manager_edge_cases.py
new file mode 100644
index 0000000000..b1e8d47815
--- /dev/null
+++ b/tests/security/file_integrity/test_integrity_manager_edge_cases.py
@@ -0,0 +1,319 @@
+"""High-value edge case tests for security/file_integrity/integrity_manager.py.
+
+Tests internal methods: _normalize_path, _get_verifier_for_file,
+_needs_verification, _do_verification, _update_stats, register_verifier,
+and cleanup logic.
+"""
+
+from datetime import datetime, UTC
+from pathlib import Path
+from unittest.mock import MagicMock
+
+
+from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+)
+
+
+def _make_manager():
+ """Create a FileIntegrityManager instance bypassing __init__."""
+ mgr = FileIntegrityManager.__new__(FileIntegrityManager)
+ mgr.username = "test"
+ mgr.password = None
+ mgr.verifiers = []
+ return mgr
+
+
+class TestNormalizePath:
+ """Test _normalize_path."""
+
+ def test_returns_string(self, tmp_path):
+ """Returns a string, not a Path object."""
+ mgr = _make_manager()
+ result = mgr._normalize_path(tmp_path / "file.txt")
+ assert isinstance(result, str)
+
+ def test_resolves_to_absolute(self, tmp_path):
+ """Result is an absolute path."""
+ mgr = _make_manager()
+ result = mgr._normalize_path(tmp_path / "file.txt")
+ assert Path(result).is_absolute()
+
+ def test_resolves_symlink(self, tmp_path):
+ """Symlink and target resolve to the same normalized path."""
+ mgr = _make_manager()
+ real_file = tmp_path / "real.txt"
+ real_file.write_text("content")
+ symlink = tmp_path / "link.txt"
+ symlink.symlink_to(real_file)
+
+ assert mgr._normalize_path(symlink) == mgr._normalize_path(real_file)
+
+
+class TestGetVerifierForFile:
+ """Test _get_verifier_for_file."""
+
+ def test_returns_none_with_no_verifiers(self, tmp_path):
+ """No registered verifiers returns None."""
+ mgr = _make_manager()
+ assert mgr._get_verifier_for_file(tmp_path / "test.txt") is None
+
+ def test_returns_matching_verifier(self, tmp_path):
+ """Returns the first verifier that matches."""
+ mgr = _make_manager()
+ v1 = MagicMock()
+ v1.should_verify.return_value = False
+ v2 = MagicMock()
+ v2.should_verify.return_value = True
+ mgr.verifiers = [v1, v2]
+ assert mgr._get_verifier_for_file(tmp_path / "test.txt") is v2
+
+ def test_first_match_wins(self, tmp_path):
+ """When multiple verifiers match, the first one wins."""
+ mgr = _make_manager()
+ v1 = MagicMock()
+ v1.should_verify.return_value = True
+ v2 = MagicMock()
+ v2.should_verify.return_value = True
+ mgr.verifiers = [v1, v2]
+ assert mgr._get_verifier_for_file(tmp_path / "test.txt") is v1
+
+
+class TestNeedsVerification:
+ """Test _needs_verification mtime logic."""
+
+ def test_returns_true_for_missing_file(self, tmp_path):
+ """Missing file needs verification."""
+ mgr = _make_manager()
+ record = MagicMock()
+ record.last_verified_at = datetime.now(UTC)
+ result = mgr._needs_verification(record, tmp_path / "nonexistent.txt")
+ assert result is True
+
+ def test_returns_true_when_never_verified(self, tmp_path):
+ """File never verified (last_verified_at=None) needs verification."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ record = MagicMock()
+ record.last_verified_at = None
+ assert mgr._needs_verification(record, f) is True
+
+ def test_returns_true_when_file_mtime_is_none(self, tmp_path):
+ """Stored mtime=None means verification needed."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ record = MagicMock()
+ record.last_verified_at = datetime.now(UTC)
+ record.file_mtime = None
+ assert mgr._needs_verification(record, f) is True
+
+ def test_returns_false_when_mtime_unchanged(self, tmp_path):
+ """Unchanged mtime means no verification needed."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ record = MagicMock()
+ record.last_verified_at = datetime.now(UTC)
+ record.file_mtime = f.stat().st_mtime
+ assert mgr._needs_verification(record, f) is False
+
+ def test_returns_true_when_mtime_changed(self, tmp_path):
+ """Changed mtime triggers verification."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ record = MagicMock()
+ record.last_verified_at = datetime.now(UTC)
+ record.file_mtime = f.stat().st_mtime - 1.0
+ assert mgr._needs_verification(record, f) is True
+
+ def test_mtime_tolerance_below_threshold(self, tmp_path):
+ """Difference of 0.0005 is within tolerance (no verification)."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ actual_mtime = f.stat().st_mtime
+ record = MagicMock()
+ record.last_verified_at = datetime.now(UTC)
+ record.file_mtime = actual_mtime - 0.0005
+ assert mgr._needs_verification(record, f) is False
+
+ def test_mtime_tolerance_above_threshold(self, tmp_path):
+ """Difference of 0.0015 exceeds tolerance (verification needed)."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ actual_mtime = f.stat().st_mtime
+ record = MagicMock()
+ record.last_verified_at = datetime.now(UTC)
+ record.file_mtime = actual_mtime - 0.0015
+ assert mgr._needs_verification(record, f) is True
+
+
+class TestDoVerification:
+ """Test _do_verification."""
+
+ def test_file_missing_returns_false(self, tmp_path):
+ """Missing file returns (False, 'file_missing')."""
+ mgr = _make_manager()
+ record = MagicMock()
+ session = MagicMock()
+ result, reason = mgr._do_verification(
+ record, tmp_path / "missing.txt", session
+ )
+ assert result is False
+ assert reason == "file_missing"
+
+ def test_no_verifier_returns_false(self, tmp_path):
+ """No matching verifier returns (False, 'no_verifier')."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ record = MagicMock()
+ session = MagicMock()
+ result, reason = mgr._do_verification(record, f, session)
+ assert result is False
+ assert reason == "no_verifier"
+
+ def test_checksum_match_returns_true(self, tmp_path):
+ """Matching checksum returns (True, None)."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ verifier = MagicMock()
+ verifier.should_verify.return_value = True
+ verifier.calculate_checksum.return_value = "abc123"
+ mgr.verifiers = [verifier]
+ record = MagicMock()
+ record.checksum = "abc123"
+ session = MagicMock()
+ result, reason = mgr._do_verification(record, f, session)
+ assert result is True
+ assert reason is None
+
+ def test_checksum_mismatch_returns_false(self, tmp_path):
+ """Mismatching checksum returns (False, 'checksum_mismatch')."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ verifier = MagicMock()
+ verifier.should_verify.return_value = True
+ verifier.calculate_checksum.return_value = "different"
+ mgr.verifiers = [verifier]
+ record = MagicMock()
+ record.checksum = "abc123"
+ session = MagicMock()
+ result, reason = mgr._do_verification(record, f, session)
+ assert result is False
+ assert reason == "checksum_mismatch"
+
+ def test_mtime_not_updated_on_mismatch(self, tmp_path):
+ """On checksum mismatch, record.file_mtime is not changed."""
+ mgr = _make_manager()
+ f = tmp_path / "test.txt"
+ f.write_text("content")
+ verifier = MagicMock()
+ verifier.should_verify.return_value = True
+ verifier.calculate_checksum.return_value = "different"
+ mgr.verifiers = [verifier]
+ record = MagicMock()
+ record.checksum = "abc123"
+ sentinel = 12345.0
+ record.file_mtime = sentinel
+ session = MagicMock()
+ mgr._do_verification(record, f, session)
+ assert record.file_mtime == sentinel
+
+
+class TestUpdateStats:
+ """Test _update_stats."""
+
+ def test_pass_increments_successes_resets_failures(self):
+ """Passing verification increments successes and resets failures."""
+ mgr = _make_manager()
+ record = MagicMock()
+ record.total_verifications = 0
+ record.consecutive_successes = 0
+ record.consecutive_failures = 3
+ mgr._update_stats(record, True, MagicMock())
+ assert record.total_verifications == 1
+ assert record.consecutive_successes == 1
+ assert record.consecutive_failures == 0
+
+ def test_fail_increments_failures_resets_successes(self):
+ """Failing verification increments failures and resets successes."""
+ mgr = _make_manager()
+ record = MagicMock()
+ record.total_verifications = 0
+ record.consecutive_successes = 5
+ record.consecutive_failures = 0
+ mgr._update_stats(record, False, MagicMock())
+ assert record.total_verifications == 1
+ assert record.consecutive_failures == 1
+ assert record.consecutive_successes == 0
+
+ def test_last_verified_at_set(self):
+ """last_verified_at is set to a datetime on every call."""
+ mgr = _make_manager()
+ record = MagicMock()
+ record.total_verifications = 0
+ record.consecutive_successes = 0
+ record.consecutive_failures = 0
+ record.last_verified_at = None
+ mgr._update_stats(record, True, MagicMock())
+ assert record.last_verified_at is not None
+
+ def test_last_verification_passed_reflects_outcome(self):
+ """last_verification_passed matches the passed parameter."""
+ mgr = _make_manager()
+ record = MagicMock()
+ record.total_verifications = 0
+ record.consecutive_successes = 0
+ record.consecutive_failures = 0
+ mgr._update_stats(record, False, MagicMock())
+ assert record.last_verification_passed is False
+
+
+class TestRegisterVerifier:
+ """Test register_verifier."""
+
+ def test_adds_to_verifiers_list(self):
+ """Verifier is added to the list."""
+ mgr = _make_manager()
+ v = MagicMock()
+ v.get_file_type.return_value = "test"
+ mgr.register_verifier(v)
+ assert v in mgr.verifiers
+
+ def test_preserves_insertion_order(self):
+ """Verifiers appear in registration order."""
+ mgr = _make_manager()
+ v1 = MagicMock()
+ v1.get_file_type.return_value = "type1"
+ v2 = MagicMock()
+ v2.get_file_type.return_value = "type2"
+ v3 = MagicMock()
+ v3.get_file_type.return_value = "type3"
+ mgr.register_verifier(v1)
+ mgr.register_verifier(v2)
+ mgr.register_verifier(v3)
+ assert mgr.verifiers == [v1, v2, v3]
+
+
+class TestClassConstants:
+ """Test FileIntegrityManager class constants."""
+
+ def test_max_failures_per_file(self):
+ assert FileIntegrityManager.MAX_FAILURES_PER_FILE == 100
+
+ def test_max_total_failures(self):
+ assert FileIntegrityManager.MAX_TOTAL_FAILURES == 10000
+
+ def test_per_file_less_than_total(self):
+ """Per-file limit must be less than total limit."""
+ assert (
+ FileIntegrityManager.MAX_FAILURES_PER_FILE
+ < FileIntegrityManager.MAX_TOTAL_FAILURES
+ )