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 valuable tests to increase coverage

LearningCircuit3d74cc1a58f6
diff --git a/tests/advanced_search_system/search_optimization/test_cross_constraint_manager.py b/tests/advanced_search_system/search_optimization/test_cross_constraint_manager.py
index a2603a8f92..ec82b0b7e1 100644
--- a/tests/advanced_search_system/search_optimization/test_cross_constraint_manager.py
+++ b/tests/advanced_search_system/search_optimization/test_cross_constraint_manager.py
@@ -1,109 +1,780 @@
"""
Tests for Cross Constraint Manager
-Phase 24: Search Optimization - Constraint Manager Tests
-Tests constraint management and coordination.
+Covers the CrossConstraintManager class and related dataclasses including
+constraint relationship analysis, clustering, query generation, and validation.
"""
+from collections import defaultdict
+from dataclasses import fields
+from unittest.mock import MagicMock
-class TestConstraintManagement:
- """Tests for constraint management"""
-
- def test_constraint_registration(self):
- """Test registering constraints"""
- # Test adding new constraints
- pass
-
- def test_constraint_validation(self):
- """Test constraint validation"""
- # Test validating constraint values
- pass
-
- def test_constraint_conflict_detection(self):
- """Test detecting conflicting constraints"""
- # Test finding conflicts
- pass
-
- def test_constraint_priority_ordering(self):
- """Test constraint priority ordering"""
- # Test ordering by priority
- pass
-
- def test_constraint_relaxation(self):
- """Test constraint relaxation"""
- # Test loosening constraints
- pass
-
- def test_constraint_propagation(self):
- """Test constraint propagation"""
- # Test propagating changes
- pass
-
- def test_constraint_satisfaction(self):
- """Test constraint satisfaction checking"""
- # Test if constraints are met
- pass
-
- def test_constraint_optimization(self):
- """Test constraint optimization"""
- # Test optimizing constraint values
- pass
-
- def test_multi_constraint_handling(self):
- """Test handling multiple constraints"""
- # Test combining constraints
- pass
-
- def test_constraint_dependency_graph(self):
- """Test constraint dependency tracking"""
- # Test dependency relationships
- pass
-
- def test_constraint_serialization(self):
- """Test constraint serialization"""
- # Test saving/loading constraints
- pass
-
- def test_dynamic_constraint_update(self):
- """Test dynamic constraint updates"""
- # Test modifying constraints at runtime
- pass
-
-
-class TestCrossConstraintCoordination:
- """Tests for cross-constraint coordination"""
-
- def test_cross_domain_constraint(self):
- """Test cross-domain constraints"""
- # Test constraints spanning domains
- pass
-
- def test_temporal_constraint(self):
- """Test temporal constraints"""
- # Test time-based constraints
- pass
-
- def test_source_constraint(self):
- """Test source constraints"""
- # Test source-based constraints
- pass
-
- def test_quality_constraint(self):
- """Test quality constraints"""
- # Test quality thresholds
- pass
-
- def test_cost_constraint(self):
- """Test cost constraints"""
- # Test cost limits
- pass
-
- def test_latency_constraint(self):
- """Test latency constraints"""
- # Test timing limits
- pass
-
- def test_constraint_trade_off_analysis(self):
- """Test trade-off analysis"""
- # Test analyzing constraint trade-offs
- pass
+import pytest
+
+from tests.test_utils import add_src_to_path
+
+add_src_to_path()
+
+from local_deep_research.advanced_search_system.constraints.base_constraint import ( # noqa: E402
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.search_optimization.cross_constraint_manager import ( # noqa: E402
+ ConstraintCluster,
+ ConstraintRelationship,
+ CrossConstraintManager,
+)
+
+
+# ============================================================================
+# Test Fixtures
+# ============================================================================
+
+
+def mock_model():
+ """Create a mock LLM model."""
+ model = MagicMock()
+ return model
+
+
+def sample_constraints():
+ """Create sample constraints for testing."""
+ return [
+ Constraint(
+ id="c1",
+ type=ConstraintType.TEMPORAL,
+ description="Happened in 2020",
+ value="2020",
+ weight=0.9,
+ ),
+ Constraint(
+ id="c2",
+ type=ConstraintType.LOCATION,
+ description="Located in Colorado",
+ value="Colorado",
+ weight=0.8,
+ ),
+ Constraint(
+ id="c3",
+ type=ConstraintType.PROPERTY,
+ description="Has mountain peak",
+ value="mountain peak",
+ weight=0.7,
+ ),
+ Constraint(
+ id="c4",
+ type=ConstraintType.TEMPORAL,
+ description="After 2015",
+ value="after 2015",
+ weight=0.6,
+ ),
+ ]
+
+
+def manager(mock_model):
+ """Create a CrossConstraintManager instance."""
+ return CrossConstraintManager(mock_model)
+
+
+# ============================================================================
+# Tests for ConstraintRelationship Dataclass
+# ============================================================================
+
+
+class TestConstraintRelationship:
+ """Tests for ConstraintRelationship dataclass."""
+
+ def test_creation_with_required_fields(self):
+ """Should create with required fields."""
+ rel = ConstraintRelationship(
+ constraint1_id="c1",
+ constraint2_id="c2",
+ relationship_type="complementary",
+ strength=0.8,
+ )
+
+ assert rel.constraint1_id == "c1"
+ assert rel.constraint2_id == "c2"
+ assert rel.relationship_type == "complementary"
+ assert rel.strength == 0.8
+
+ def test_default_evidence_list(self):
+ """Should have empty list as default evidence."""
+ rel = ConstraintRelationship(
+ constraint1_id="c1",
+ constraint2_id="c2",
+ relationship_type="dependent",
+ strength=0.5,
+ )
+
+ assert rel.evidence == []
+ assert isinstance(rel.evidence, list)
+
+ def test_creation_with_evidence(self):
+ """Should create with provided evidence."""
+ evidence = ["They share temporal context", "Both relate to events"]
+ rel = ConstraintRelationship(
+ constraint1_id="c1",
+ constraint2_id="c2",
+ relationship_type="complementary",
+ strength=0.9,
+ evidence=evidence,
+ )
+
+ assert rel.evidence == evidence
+ assert len(rel.evidence) == 2
+
+ def test_field_types(self):
+ """Should have correct field types."""
+ rel_fields = {f.name: f.type for f in fields(ConstraintRelationship)}
+
+ assert rel_fields["constraint1_id"] is str
+ assert rel_fields["constraint2_id"] is str
+ assert rel_fields["relationship_type"] is str
+ assert rel_fields["strength"] is float
+
+
+# ============================================================================
+# Tests for ConstraintCluster Dataclass
+# ============================================================================
+
+
+class TestConstraintCluster:
+ """Tests for ConstraintCluster dataclass."""
+
+ def test_creation_with_required_fields(self, sample_constraints):
+ """Should create with required fields."""
+ cluster = ConstraintCluster(
+ constraints=sample_constraints[:2],
+ cluster_type="temporal",
+ coherence_score=0.75,
+ )
+
+ assert len(cluster.constraints) == 2
+ assert cluster.cluster_type == "temporal"
+ assert cluster.coherence_score == 0.75
+
+ def test_default_search_queries(self, sample_constraints):
+ """Should have empty list as default search_queries."""
+ cluster = ConstraintCluster(
+ constraints=sample_constraints,
+ cluster_type="spatial",
+ coherence_score=0.6,
+ )
+
+ assert cluster.search_queries == []
+ assert isinstance(cluster.search_queries, list)
+
+ def test_creation_with_queries(self, sample_constraints):
+ """Should create with provided search queries."""
+ queries = ["query 1", "query 2"]
+ cluster = ConstraintCluster(
+ constraints=sample_constraints[:2],
+ cluster_type="causal",
+ coherence_score=0.8,
+ search_queries=queries,
+ )
+
+ assert cluster.search_queries == queries
+ assert len(cluster.search_queries) == 2
+
+
+# ============================================================================
+# Tests for CrossConstraintManager Initialization
+# ============================================================================
+
+
+class TestCrossConstraintManagerInit:
+ """Tests for CrossConstraintManager initialization."""
+
+ def test_initialization_with_model(self, mock_model):
+ """Should initialize with provided model."""
+ manager = CrossConstraintManager(mock_model)
+
+ assert manager.model is mock_model
+
+ def test_initial_relationships_empty(self, mock_model):
+ """Should have empty relationships dict on init."""
+ manager = CrossConstraintManager(mock_model)
+
+ assert manager.relationships == {}
+ assert isinstance(manager.relationships, dict)
+
+ def test_initial_clusters_empty(self, mock_model):
+ """Should have empty clusters list on init."""
+ manager = CrossConstraintManager(mock_model)
+
+ assert manager.clusters == []
+ assert isinstance(manager.clusters, list)
+
+ def test_initial_cross_validation_patterns(self, mock_model):
+ """Should have defaultdict for cross_validation_patterns."""
+ manager = CrossConstraintManager(mock_model)
+
+ assert isinstance(manager.cross_validation_patterns, defaultdict)
+ # Accessing non-existent key should return empty list
+ assert manager.cross_validation_patterns["nonexistent"] == []
+
+ def test_initial_constraint_graph(self, mock_model):
+ """Should have defaultdict for constraint_graph."""
+ manager = CrossConstraintManager(mock_model)
+
+ assert isinstance(manager.constraint_graph, defaultdict)
+ # Accessing non-existent key should return empty set
+ assert manager.constraint_graph["nonexistent"] == set()
+
+
+# ============================================================================
+# Tests for analyze_constraint_relationships
+# ============================================================================
+
+
+class TestAnalyzeConstraintRelationships:
+ """Tests for analyze_constraint_relationships method."""
+
+ def test_empty_list_returns_empty(self, manager):
+ """Should return empty dict for empty constraint list."""
+ result = manager.analyze_constraint_relationships([])
+
+ assert result == {}
+
+ def test_single_constraint_returns_empty(self, manager, sample_constraints):
+ """Should return empty dict for single constraint."""
+ result = manager.analyze_constraint_relationships(
+ [sample_constraints[0]]
+ )
+
+ assert result == {}
+
+ def test_calls_model_for_pairs(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should call model.invoke for each constraint pair."""
+ mock_response = MagicMock()
+ mock_response.content = (
+ "Type: complementary\nStrength: 0.8\nEvidence: Related"
+ )
+ mock_model.invoke.return_value = mock_response
+
+ # Two constraints = 1 pair
+ manager.analyze_constraint_relationships(sample_constraints[:2])
+
+ assert mock_model.invoke.call_count == 1
+
+ def test_filters_by_strength_threshold(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should only keep relationships with strength > 0.3."""
+ # First pair: weak relationship
+ mock_response_weak = MagicMock()
+ mock_response_weak.content = (
+ "Type: none\nStrength: 0.1\nEvidence: Unrelated"
+ )
+
+ # Second pair: strong relationship
+ mock_response_strong = MagicMock()
+ mock_response_strong.content = (
+ "Type: complementary\nStrength: 0.8\nEvidence: Related"
+ )
+
+ mock_model.invoke.side_effect = [
+ mock_response_weak,
+ mock_response_strong,
+ ]
+
+ # Three constraints = 3 pairs, but mock only 2 for simplicity
+ result = manager.analyze_constraint_relationships(
+ sample_constraints[:2]
+ )
+
+ # Weak relationship should not be included
+ if result:
+ for rel in result.values():
+ assert rel.strength > 0.3
+
+ def test_updates_constraint_graph(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should update constraint_graph for strong relationships."""
+ mock_response = MagicMock()
+ mock_response.content = (
+ "Type: complementary\nStrength: 0.8\nEvidence: Related"
+ )
+ mock_model.invoke.return_value = mock_response
+
+ manager.analyze_constraint_relationships(sample_constraints[:2])
+
+ # Both constraints should have each other in their graph
+ c1_neighbors = manager.constraint_graph["c1"]
+ c2_neighbors = manager.constraint_graph["c2"]
+
+ assert "c2" in c1_neighbors or len(manager.relationships) == 0
+ assert "c1" in c2_neighbors or len(manager.relationships) == 0
+
+
+# ============================================================================
+# Tests for _analyze_pair
+# ============================================================================
+
+
+class TestAnalyzePair:
+ """Tests for _analyze_pair method."""
+
+ def test_parses_response_correctly(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should parse model response correctly."""
+ mock_response = MagicMock()
+ mock_response.content = """Type: dependent
+Strength: 0.75
+Evidence: Temporal ordering required"""
+ mock_model.invoke.return_value = mock_response
+
+ result = manager._analyze_pair(
+ sample_constraints[0], sample_constraints[1]
+ )
+
+ assert result.relationship_type == "dependent"
+ assert result.strength == 0.75
+ assert "Temporal ordering required" in result.evidence
+
+ def test_handles_malformed_response(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should handle malformed responses gracefully."""
+ mock_response = MagicMock()
+ mock_response.content = "This is not formatted correctly at all"
+ mock_model.invoke.return_value = mock_response
+
+ result = manager._analyze_pair(
+ sample_constraints[0], sample_constraints[1]
+ )
+
+ # Should return default values
+ assert result.relationship_type == "none"
+ assert result.strength == 0.0
+ assert result.constraint1_id == "c1"
+ assert result.constraint2_id == "c2"
+
+ def test_handles_invalid_strength(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should handle invalid strength values."""
+ mock_response = MagicMock()
+ mock_response.content = (
+ "Type: complementary\nStrength: not_a_number\nEvidence: Test"
+ )
+ mock_model.invoke.return_value = mock_response
+
+ result = manager._analyze_pair(
+ sample_constraints[0], sample_constraints[1]
+ )
+
+ assert result.strength == 0.0
+
+ def test_returns_constraint_ids(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should return correct constraint IDs."""
+ mock_response = MagicMock()
+ mock_response.content = (
+ "Type: none\nStrength: 0.0\nEvidence: No relation"
+ )
+ mock_model.invoke.return_value = mock_response
+
+ result = manager._analyze_pair(
+ sample_constraints[0], sample_constraints[2]
+ )
+
+ assert result.constraint1_id == "c1"
+ assert result.constraint2_id == "c3"
+
+
+# ============================================================================
+# Tests for create_constraint_clusters
+# ============================================================================
+
+
+class TestCreateConstraintClusters:
+ """Tests for create_constraint_clusters method."""
+
+ def test_creates_type_based_clusters(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should create clusters based on constraint types."""
+ # Set up minimal mock responses
+ mock_response = MagicMock()
+ mock_response.content = "Type: none\nStrength: 0.1\nEvidence: None"
+ mock_model.invoke.return_value = mock_response
+
+ result = manager.create_constraint_clusters(sample_constraints)
+
+ # Should have at least type-based clusters for TEMPORAL (c1, c4)
+ type_based = [c for c in result if c.cluster_type == "type_based"]
+ assert len(type_based) >= 1
+
+ def test_deduplicates_clusters(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should remove duplicate clusters."""
+ mock_response = MagicMock()
+ mock_response.content = "Type: none\nStrength: 0.1\nEvidence: None"
+ mock_model.invoke.return_value = mock_response
+
+ result = manager.create_constraint_clusters(sample_constraints)
+
+ # Check for uniqueness
+ seen_sets = []
+ for cluster in result:
+ constraint_set = frozenset(c.id for c in cluster.constraints)
+ assert constraint_set not in seen_sets
+ seen_sets.append(constraint_set)
+
+ def test_stores_clusters_in_manager(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should store clusters in manager.clusters."""
+ mock_response = MagicMock()
+ mock_response.content = "Type: none\nStrength: 0.1\nEvidence: None"
+ mock_model.invoke.return_value = mock_response
+
+ result = manager.create_constraint_clusters(sample_constraints)
+
+ assert manager.clusters == result
+
+
+# ============================================================================
+# Tests for _create_relationship_clusters
+# ============================================================================
+
+
+class TestCreateRelationshipClusters:
+ """Tests for _create_relationship_clusters method."""
+
+ def test_bfs_clustering(self, manager, sample_constraints):
+ """Should use BFS to find connected components."""
+ # Create relationships that form a connected component
+ relationships = [
+ ConstraintRelationship(
+ constraint1_id="c1",
+ constraint2_id="c2",
+ relationship_type="complementary",
+ strength=0.8,
+ ),
+ ConstraintRelationship(
+ constraint1_id="c2",
+ constraint2_id="c3",
+ relationship_type="complementary",
+ strength=0.7,
+ ),
+ ]
+
+ result = manager._create_relationship_clusters(
+ sample_constraints[:3], relationships
+ )
+
+ # c1, c2, c3 should be in same cluster
+ if result:
+ cluster_ids = {c.id for c in result[0].constraints}
+ assert "c1" in cluster_ids
+ assert "c2" in cluster_ids
+ assert "c3" in cluster_ids
+
+ def test_isolated_constraints_not_clustered(
+ self, manager, sample_constraints
+ ):
+ """Should not create single-constraint clusters."""
+ # Only c1 and c2 are related
+ relationships = [
+ ConstraintRelationship(
+ constraint1_id="c1",
+ constraint2_id="c2",
+ relationship_type="complementary",
+ strength=0.8,
+ ),
+ ]
+
+ result = manager._create_relationship_clusters(
+ sample_constraints, relationships
+ )
+
+ # All clusters should have more than one constraint
+ for cluster in result:
+ assert len(cluster.constraints) > 1
+
+
+# ============================================================================
+# Tests for _deduplicate_clusters
+# ============================================================================
+
+
+class TestDeduplicateClusters:
+ """Tests for _deduplicate_clusters method."""
+
+ def test_removes_exact_duplicates(self, manager, sample_constraints):
+ """Should remove exact duplicate clusters."""
+ cluster1 = ConstraintCluster(
+ constraints=sample_constraints[:2],
+ cluster_type="type_based",
+ coherence_score=0.7,
+ )
+ cluster2 = ConstraintCluster(
+ constraints=sample_constraints[:2], # Same constraints
+ cluster_type="semantic", # Different type
+ coherence_score=0.8, # Different score
+ )
+
+ result = manager._deduplicate_clusters([cluster1, cluster2])
+
+ assert len(result) == 1
+
+ def test_keeps_different_sets(self, manager, sample_constraints):
+ """Should keep clusters with different constraint sets."""
+ cluster1 = ConstraintCluster(
+ constraints=sample_constraints[:2],
+ cluster_type="type_based",
+ coherence_score=0.7,
+ )
+ cluster2 = ConstraintCluster(
+ constraints=sample_constraints[2:4], # Different constraints
+ cluster_type="type_based",
+ coherence_score=0.7,
+ )
+
+ result = manager._deduplicate_clusters([cluster1, cluster2])
+
+ assert len(result) == 2
+
+
+# ============================================================================
+# Tests for generate_cross_constraint_queries
+# ============================================================================
+
+
+class TestGenerateCrossConstraintQueries:
+ """Tests for generate_cross_constraint_queries method."""
+
+ def test_generates_multiple_query_types(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should generate multiple types of queries."""
+ cluster = ConstraintCluster(
+ constraints=sample_constraints[:3],
+ cluster_type="temporal",
+ coherence_score=0.8,
+ )
+
+ mock_response = MagicMock()
+ mock_response.content = "test query"
+ mock_model.invoke.return_value = mock_response
+
+ result = manager.generate_cross_constraint_queries(cluster)
+
+ # Should have combined, progressive, and validation queries
+ assert len(result) >= 3
+
+ def test_stores_queries_in_cluster(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should store queries in cluster.search_queries."""
+ cluster = ConstraintCluster(
+ constraints=sample_constraints[:2],
+ cluster_type="temporal",
+ coherence_score=0.8,
+ )
+
+ mock_response = MagicMock()
+ mock_response.content = "test query"
+ mock_model.invoke.return_value = mock_response
+
+ result = manager.generate_cross_constraint_queries(cluster)
+
+ assert cluster.search_queries == result
+
+
+# ============================================================================
+# Tests for _generate_intersection_query
+# ============================================================================
+
+
+class TestGenerateIntersectionQuery:
+ """Tests for _generate_intersection_query method."""
+
+ def test_returns_none_for_single_constraint(
+ self, manager, sample_constraints
+ ):
+ """Should return None for single constraint."""
+ result = manager._generate_intersection_query([sample_constraints[0]])
+
+ assert result is None
+
+ def test_handles_none_response(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should handle NONE response from model."""
+ mock_response = MagicMock()
+ mock_response.content = "NONE"
+ mock_model.invoke.return_value = mock_response
+
+ result = manager._generate_intersection_query(sample_constraints[:2])
+
+ assert result is None
+
+ def test_returns_query_on_success(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should return query when model provides one."""
+ mock_response = MagicMock()
+ mock_response.content = "Colorado events in 2020"
+ mock_model.invoke.return_value = mock_response
+
+ result = manager._generate_intersection_query(sample_constraints[:2])
+
+ assert result == "Colorado events in 2020"
+
+
+# ============================================================================
+# Tests for validate_candidate_across_constraints
+# ============================================================================
+
+
+class TestValidateCandidateAcrossConstraints:
+ """Tests for validate_candidate_across_constraints method."""
+
+ def test_with_relevant_clusters(
+ self, manager, sample_constraints, mock_model
+ ):
+ """Should validate using relevant clusters."""
+ from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+ )
+
+ # Set up a cluster
+ cluster = ConstraintCluster(
+ constraints=sample_constraints[:2],
+ cluster_type="temporal",
+ coherence_score=0.8,
+ search_queries=["test query"],
+ )
+ manager.clusters = [cluster]
+
+ # Mock validation response
+ mock_response = MagicMock()
+ mock_response.content = "Score: 0.85\nExplanation: Good match"
+ mock_model.invoke.return_value = mock_response
+
+ candidate = Candidate(name="Test Candidate")
+
+ result = manager.validate_candidate_across_constraints(
+ candidate, sample_constraints[:2]
+ )
+
+ # Should have scores for constraints
+ assert isinstance(result, dict)
+
+
+# ============================================================================
+# Tests for _calculate_cluster_coherence
+# ============================================================================
+
+
+class TestCalculateClusterCoherence:
+ """Tests for _calculate_cluster_coherence method."""
+
+ def test_single_constraint_returns_zero(self, manager, sample_constraints):
+ """Should return 0.0 for single constraint."""
+ result = manager._calculate_cluster_coherence([sample_constraints[0]])
+
+ assert result == 0.0
+
+ def test_no_relationships_returns_default(
+ self, manager, sample_constraints
+ ):
+ """Should return default 0.5 when no relationships found."""
+ result = manager._calculate_cluster_coherence(sample_constraints[:2])
+
+ assert result == 0.5
+
+ def test_uses_relationship_strengths(self, manager, sample_constraints):
+ """Should calculate based on relationship strengths."""
+ # Add a relationship
+ manager.relationships[("c1", "c2")] = ConstraintRelationship(
+ constraint1_id="c1",
+ constraint2_id="c2",
+ relationship_type="complementary",
+ strength=0.9,
+ )
+
+ result = manager._calculate_cluster_coherence(sample_constraints[:2])
+
+ # Should be > 0.5 (default) since we have strong relationship
+ assert result > 0.5
+
+
+# ============================================================================
+# Tests for optimize_search_order
+# ============================================================================
+
+
+class TestOptimizeSearchOrder:
+ """Tests for optimize_search_order method."""
+
+ def test_sorts_by_coherence_times_size(self, manager, sample_constraints):
+ """Should sort by coherence * size in descending order."""
+ cluster1 = ConstraintCluster(
+ constraints=sample_constraints[:2], # size 2
+ cluster_type="type_based",
+ coherence_score=0.5, # score = 2 * 0.5 = 1.0
+ )
+ cluster2 = ConstraintCluster(
+ constraints=sample_constraints[:3], # size 3
+ cluster_type="semantic",
+ coherence_score=0.8, # score = 3 * 0.8 = 2.4
+ )
+ cluster3 = ConstraintCluster(
+ constraints=sample_constraints[:1], # size 1
+ cluster_type="relationship_based",
+ coherence_score=0.9, # score = 1 * 0.9 = 0.9
+ )
+
+ result = manager.optimize_search_order([cluster1, cluster2, cluster3])
+
+ # cluster2 should be first (highest score), then cluster1, then cluster3
+ assert result[0] == cluster2
+ assert result[1] == cluster1
+ assert result[2] == cluster3
+
+
+# ============================================================================
+# Tests for helper methods
+# ============================================================================
+
+
+class TestFormatConstraintsForClustering:
+ """Tests for _format_constraints_for_clustering method."""
+
+ def test_formats_all_constraint_info(self, manager, sample_constraints):
+ """Should include id, description, type, and weight."""
+ result = manager._format_constraints_for_clustering(
+ sample_constraints[:1]
+ )
+
+ assert "c1" in result
+ assert "Happened in 2020" in result
+ assert "temporal" in result.lower()
+ assert "0.9" in result
+
+
+class TestFormatConstraintsForQuery:
+ """Tests for _format_constraints_for_query method."""
+
+ def test_formats_description_and_type(self, manager, sample_constraints):
+ """Should include description and type."""
+ result = manager._format_constraints_for_query(sample_constraints[:1])
+
+ assert "Happened in 2020" in result
+ assert "temporal" in result.lower()
+ assert "-" in result # Should have bullet point
diff --git a/tests/database/test_encryption_check.py b/tests/database/test_encryption_check.py
new file mode 100644
index 0000000000..31893fb7ce
--- /dev/null
+++ b/tests/database/test_encryption_check.py
@@ -0,0 +1,233 @@
+"""
+Tests for encryption_check module.
+
+Covers functions for checking SQLCipher availability and providing
+appropriate connection strings and warnings.
+"""
+
+import subprocess
+import warnings
+from unittest.mock import MagicMock, patch
+
+
+from tests.test_utils import add_src_to_path
+
+add_src_to_path()
+
+from local_deep_research.database.encryption_check import ( # noqa: E402
+ check_sqlcipher_available,
+ get_connection_string,
+ warn_if_no_encryption,
+)
+
+
+class TestCheckSqlcipherAvailable:
+ """Tests for check_sqlcipher_available function."""
+
+ def test_returns_true_when_sqlcipher3_available(self):
+ """Should return (True, None) when sqlcipher3 module is found."""
+ mock_spec = MagicMock()
+ with patch("importlib.util.find_spec", return_value=mock_spec):
+ available, message = check_sqlcipher_available()
+
+ assert available is True
+ assert message is None
+
+ def test_returns_false_when_module_not_found(self):
+ """Should return (False, message) when sqlcipher3 not found."""
+ with patch("importlib.util.find_spec", return_value=None):
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = FileNotFoundError()
+
+ available, message = check_sqlcipher_available()
+
+ assert available is False
+ assert message is not None
+ assert "not installed" in message.lower()
+
+ def test_detects_sqlcipher_without_python_bindings(self):
+ """Should detect when SQLCipher CLI exists but Python bindings missing."""
+ with patch("importlib.util.find_spec", return_value=None):
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ with patch("subprocess.run", return_value=mock_result):
+ available, message = check_sqlcipher_available()
+
+ assert available is False
+ assert message is not None
+ assert "bindings" in message.lower()
+ assert "pdm install" in message.lower()
+
+ def test_handles_subprocess_timeout(self):
+ """Should handle subprocess timeout gracefully."""
+ with patch("importlib.util.find_spec", return_value=None):
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = subprocess.TimeoutExpired(
+ cmd="sqlcipher", timeout=5
+ )
+
+ available, message = check_sqlcipher_available()
+
+ assert available is False
+ assert message is not None
+ assert "not installed" in message.lower()
+
+ def test_handles_import_error(self):
+ """Should handle ImportError during find_spec."""
+ with patch("importlib.util.find_spec") as mock_find:
+ mock_find.side_effect = ImportError("Test error")
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = FileNotFoundError()
+
+ available, message = check_sqlcipher_available()
+
+ assert available is False
+ assert message is not None
+
+ def test_subprocess_called_with_correct_args(self):
+ """Should call subprocess.run with correct arguments."""
+ with patch("importlib.util.find_spec", return_value=None):
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = FileNotFoundError()
+
+ check_sqlcipher_available()
+
+ mock_run.assert_called_once()
+ call_args = mock_run.call_args
+ assert call_args[0][0] == ["sqlcipher", "--version"]
+ assert call_args[1]["capture_output"] is True
+ assert call_args[1]["text"] is True
+ assert call_args[1]["timeout"] == 5
+
+
+class TestWarnIfNoEncryption:
+ """Tests for warn_if_no_encryption function."""
+
+ def test_returns_true_when_encryption_available(self):
+ """Should return True when SQLCipher is available."""
+ mock_spec = MagicMock()
+ with patch("importlib.util.find_spec", return_value=mock_spec):
+ result = warn_if_no_encryption()
+
+ assert result is True
+
+ def test_issues_user_warning_when_not_available(self):
+ """Should issue UserWarning with security info when not available."""
+ with patch("importlib.util.find_spec", return_value=None):
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = FileNotFoundError()
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ result = warn_if_no_encryption()
+
+ assert result is False
+ assert len(w) == 1
+ assert issubclass(w[0].category, UserWarning)
+ warning_msg = str(w[0].message)
+ assert "SECURITY WARNING" in warning_msg
+ assert "UNENCRYPTED" in warning_msg
+ assert "API keys" in warning_msg
+
+ def test_logs_warning_when_not_available(self):
+ """Should log warning when encryption not available."""
+ with patch("importlib.util.find_spec", return_value=None):
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = FileNotFoundError()
+ with patch(
+ "local_deep_research.database.encryption_check.logger"
+ ) as mock_logger:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ warn_if_no_encryption()
+
+ mock_logger.warning.assert_called_once()
+ call_args = mock_logger.warning.call_args[0][0]
+ assert "without database encryption" in call_args.lower()
+
+
+class TestGetConnectionString:
+ """Tests for get_connection_string function."""
+
+ def test_returns_encrypted_string_when_available_and_password(self):
+ """Should return encrypted connection string when SQLCipher available."""
+ mock_spec = MagicMock()
+ with patch("importlib.util.find_spec", return_value=mock_spec):
+ result = get_connection_string("/path/to/db.sqlite", "mypassword")
+
+ assert (
+ result == "sqlite+pysqlcipher://:mypassword@//path/to/db.sqlite"
+ )
+
+ def test_returns_sqlite_when_not_available(self):
+ """Should return regular SQLite string when SQLCipher not available."""
+ with patch("importlib.util.find_spec", return_value=None):
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = FileNotFoundError()
+
+ result = get_connection_string(
+ "/path/to/db.sqlite", "mypassword"
+ )
+
+ assert result == "sqlite:////path/to/db.sqlite"
+
+ def test_returns_sqlite_when_no_password(self):
+ """Should return SQLite string when no password provided."""
+ mock_spec = MagicMock()
+ with patch("importlib.util.find_spec", return_value=mock_spec):
+ result = get_connection_string("/path/to/db.sqlite")
+
+ assert result == "sqlite:////path/to/db.sqlite"
+
+ def test_returns_sqlite_when_password_is_none(self):
+ """Should return SQLite string when password is explicitly None."""
+ mock_spec = MagicMock()
+ with patch("importlib.util.find_spec", return_value=mock_spec):
+ result = get_connection_string("/path/to/db.sqlite", None)
+
+ assert result == "sqlite:////path/to/db.sqlite"
+
+ def test_logs_warning_when_password_ignored(self):
+ """Should log warning when password provided but SQLCipher unavailable."""
+ with patch("importlib.util.find_spec", return_value=None):
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = FileNotFoundError()
+ with patch(
+ "local_deep_research.database.encryption_check.logger"
+ ) as mock_logger:
+ get_connection_string("/path/to/db.sqlite", "mypassword")
+
+ mock_logger.warning.assert_called_once()
+ call_args = mock_logger.warning.call_args[0][0]
+ assert "password provided" in call_args.lower()
+ assert "unencrypted" in call_args.lower()
+
+ def test_no_warning_when_no_password_and_unavailable(self):
+ """Should not log warning when no password and SQLCipher unavailable."""
+ with patch("importlib.util.find_spec", return_value=None):
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = FileNotFoundError()
+ with patch(
+ "local_deep_research.database.encryption_check.logger"
+ ) as mock_logger:
+ get_connection_string("/path/to/db.sqlite")
+
+ mock_logger.warning.assert_not_called()
+
+ def test_connection_string_format_verification(self):
+ """Verify exact format of connection strings."""
+ # Test encrypted format
+ mock_spec = MagicMock()
+ with patch("importlib.util.find_spec", return_value=mock_spec):
+ result = get_connection_string("test.db", "secret")
+ assert result.startswith("sqlite+pysqlcipher://")
+ assert ":secret@/" in result
+ assert result.endswith("test.db")
+
+ # Test unencrypted format
+ with patch("importlib.util.find_spec", return_value=None):
+ with patch("subprocess.run") as mock_run:
+ mock_run.side_effect = FileNotFoundError()
+ result = get_connection_string("test.db")
+ assert result.startswith("sqlite:///")
+ assert result.endswith("test.db")
diff --git a/tests/web/test_server_config.py b/tests/web/test_server_config.py
new file mode 100644
index 0000000000..f94b92d986
--- /dev/null
+++ b/tests/web/test_server_config.py
@@ -0,0 +1,452 @@
+"""
+Tests for server_config module.
+
+Covers server configuration management for web app startup including
+loading, saving, and syncing configuration settings.
+"""
+
+import json
+from pathlib import Path
+from unittest.mock import patch
+
+
+from tests.test_utils import add_src_to_path
+
+add_src_to_path()
+
+
+class TestGetServerConfigPath:
+ """Tests for get_server_config_path function."""
+
+ def test_returns_path_object(self, tmp_path):
+ """Should return a Path object."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ from local_deep_research.web.server_config import (
+ get_server_config_path,
+ )
+
+ result = get_server_config_path()
+
+ assert isinstance(result, Path)
+
+ def test_correct_filename(self, tmp_path):
+ """Should use correct filename."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ from local_deep_research.web.server_config import (
+ get_server_config_path,
+ )
+
+ result = get_server_config_path()
+
+ assert result.name == "server_config.json"
+
+ def test_path_under_data_dir(self, tmp_path):
+ """Should be under the data directory."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ from local_deep_research.web.server_config import (
+ get_server_config_path,
+ )
+
+ result = get_server_config_path()
+
+ assert result.parent == tmp_path
+
+
+class TestLoadServerConfig:
+ """Tests for load_server_config function."""
+
+ def test_returns_defaults_when_no_file(self, tmp_path):
+ """Should return default config when file doesn't exist."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: default,
+ ):
+ from local_deep_research.web.server_config import (
+ load_server_config,
+ )
+
+ result = load_server_config()
+
+ assert result["host"] == "0.0.0.0"
+ assert result["port"] == 5000
+ assert result["debug"] is False
+ assert result["use_https"] is True
+
+ def test_loads_from_existing_file(self, tmp_path):
+ """Should load config from existing file."""
+ config_file = tmp_path / "server_config.json"
+ config_data = {
+ "host": "127.0.0.1",
+ "port": 8080,
+ "debug": True,
+ "use_https": False,
+ }
+ config_file.write_text(json.dumps(config_data))
+
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: val
+ if val is not None
+ else default,
+ ):
+ from local_deep_research.web.server_config import (
+ load_server_config,
+ )
+
+ result = load_server_config()
+
+ assert result["host"] == "127.0.0.1"
+ assert result["port"] == 8080
+ assert result["debug"] is True
+ assert result["use_https"] is False
+
+ def test_handles_corrupt_json(self, tmp_path):
+ """Should handle corrupt JSON gracefully."""
+ config_file = tmp_path / "server_config.json"
+ config_file.write_text("{ invalid json }")
+
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: default,
+ ):
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ from local_deep_research.web.server_config import (
+ load_server_config,
+ )
+
+ result = load_server_config()
+
+ # Should log warning
+ mock_logger.warning.assert_called_once()
+ # Should return defaults
+ assert result["host"] == "0.0.0.0"
+ assert result["port"] == 5000
+
+ def test_includes_rate_limit_settings(self, tmp_path):
+ """Should include rate limit settings."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: default,
+ ):
+ from local_deep_research.web.server_config import (
+ load_server_config,
+ )
+
+ result = load_server_config()
+
+ assert "rate_limit_default" in result
+ assert "rate_limit_login" in result
+ assert "rate_limit_registration" in result
+
+ def test_includes_allow_registrations(self, tmp_path):
+ """Should include allow_registrations setting."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: default,
+ ):
+ from local_deep_research.web.server_config import (
+ load_server_config,
+ )
+
+ result = load_server_config()
+
+ assert "allow_registrations" in result
+ assert result["allow_registrations"] is True
+
+
+class TestSaveServerConfig:
+ """Tests for save_server_config function."""
+
+ def test_saves_to_file(self, tmp_path):
+ """Should save config to file."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ from local_deep_research.web.server_config import save_server_config
+
+ config = {"host": "localhost", "port": 3000}
+ save_server_config(config)
+
+ config_file = tmp_path / "server_config.json"
+ assert config_file.exists()
+ saved_data = json.loads(config_file.read_text())
+ assert saved_data["host"] == "localhost"
+ assert saved_data["port"] == 3000
+
+ def test_creates_parent_directory(self, tmp_path):
+ """Should create parent directory if it doesn't exist."""
+ nested_path = tmp_path / "nested" / "dir"
+
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(nested_path),
+ ):
+ from local_deep_research.web.server_config import save_server_config
+
+ config = {"host": "localhost"}
+ save_server_config(config)
+
+ config_file = nested_path / "server_config.json"
+ assert config_file.exists()
+
+ def test_handles_write_errors(self, tmp_path):
+ """Should handle write errors gracefully."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "builtins.open", side_effect=PermissionError("No write access")
+ ):
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ from local_deep_research.web.server_config import (
+ save_server_config,
+ )
+
+ # Should not raise, but log exception
+ save_server_config({"host": "localhost"})
+
+ mock_logger.exception.assert_called_once()
+
+ def test_logs_success(self, tmp_path):
+ """Should log success when saved."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ from local_deep_research.web.server_config import (
+ save_server_config,
+ )
+
+ save_server_config({"host": "localhost"})
+
+ mock_logger.info.assert_called_once()
+ call_args = mock_logger.info.call_args[0][0]
+ assert "saved" in call_args.lower()
+
+ def test_formats_json_with_indent(self, tmp_path):
+ """Should format JSON with indentation."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ from local_deep_research.web.server_config import save_server_config
+
+ config = {"host": "localhost", "port": 3000}
+ save_server_config(config)
+
+ config_file = tmp_path / "server_config.json"
+ content = config_file.read_text()
+ # Indented JSON has newlines
+ assert "\n" in content
+
+
+class TestSyncFromSettings:
+ """Tests for sync_from_settings function."""
+
+ def test_updates_host_from_settings(self, tmp_path):
+ """Should update host from settings snapshot."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: val
+ if val is not None
+ else default,
+ ):
+ from local_deep_research.web.server_config import (
+ sync_from_settings,
+ )
+
+ sync_from_settings({"web.host": "192.168.1.1"})
+
+ config_file = tmp_path / "server_config.json"
+ saved_data = json.loads(config_file.read_text())
+ assert saved_data["host"] == "192.168.1.1"
+
+ def test_updates_port_from_settings(self, tmp_path):
+ """Should update port from settings snapshot."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: val
+ if val is not None
+ else default,
+ ):
+ from local_deep_research.web.server_config import (
+ sync_from_settings,
+ )
+
+ sync_from_settings({"web.port": 9000})
+
+ config_file = tmp_path / "server_config.json"
+ saved_data = json.loads(config_file.read_text())
+ assert saved_data["port"] == 9000
+
+ def test_updates_all_supported_settings(self, tmp_path):
+ """Should update all supported settings."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: val
+ if val is not None
+ else default,
+ ):
+ from local_deep_research.web.server_config import (
+ sync_from_settings,
+ )
+
+ settings = {
+ "web.host": "10.0.0.1",
+ "web.port": 4000,
+ "app.debug": True,
+ "web.use_https": False,
+ "app.allow_registrations": False,
+ "security.rate_limit_default": "100 per hour",
+ "security.rate_limit_login": "10 per minute",
+ "security.rate_limit_registration": "1 per hour",
+ }
+ sync_from_settings(settings)
+
+ config_file = tmp_path / "server_config.json"
+ saved_data = json.loads(config_file.read_text())
+
+ assert saved_data["host"] == "10.0.0.1"
+ assert saved_data["port"] == 4000
+ assert saved_data["debug"] is True
+ assert saved_data["use_https"] is False
+ assert saved_data["allow_registrations"] is False
+ assert saved_data["rate_limit_default"] == "100 per hour"
+ assert saved_data["rate_limit_login"] == "10 per minute"
+ assert saved_data["rate_limit_registration"] == "1 per hour"
+
+ def test_ignores_unknown_settings(self, tmp_path):
+ """Should ignore settings not in the known list."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: val
+ if val is not None
+ else default,
+ ):
+ from local_deep_research.web.server_config import (
+ sync_from_settings,
+ )
+
+ sync_from_settings(
+ {
+ "web.host": "localhost",
+ "unknown.setting": "should be ignored",
+ }
+ )
+
+ config_file = tmp_path / "server_config.json"
+ saved_data = json.loads(config_file.read_text())
+
+ assert saved_data["host"] == "localhost"
+ assert "unknown.setting" not in saved_data
+ assert "unknown" not in saved_data
+
+ def test_preserves_existing_values(self, tmp_path):
+ """Should preserve values not in the settings snapshot."""
+ # Create initial config
+ config_file = tmp_path / "server_config.json"
+ initial_config = {
+ "host": "original-host",
+ "port": 1234,
+ "debug": False,
+ "use_https": True,
+ }
+ config_file.write_text(json.dumps(initial_config))
+
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: val
+ if val is not None
+ else default,
+ ):
+ from local_deep_research.web.server_config import (
+ sync_from_settings,
+ )
+
+ # Only update host
+ sync_from_settings({"web.host": "new-host"})
+
+ saved_data = json.loads(config_file.read_text())
+
+ assert saved_data["host"] == "new-host"
+ assert saved_data["port"] == 1234 # Preserved
+ assert saved_data["debug"] is False # Preserved
+ assert saved_data["use_https"] is True # Preserved
+
+ def test_empty_settings_snapshot(self, tmp_path):
+ """Should handle empty settings snapshot."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: default,
+ ):
+ from local_deep_research.web.server_config import (
+ sync_from_settings,
+ )
+
+ # Should not raise
+ sync_from_settings({})
+
+ config_file = tmp_path / "server_config.json"
+ assert config_file.exists()