~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: add 175 tests for advanced search system modules
LearningCircuit31816283571b
diff --git a/tests/advanced_search_system/candidates/test_base_candidate_extended.py b/tests/advanced_search_system/candidates/test_base_candidate_extended.pynew file mode 100644index 0000000000..23f40c2f38--- /dev/null+++ b/tests/advanced_search_system/candidates/test_base_candidate_extended.py@@ -0,0 +1,468 @@+"""+Extended tests for Candidate - Base candidate class for tracking potential answers.++Tests cover:+- Candidate dataclass initialization+- add_evidence method+- calculate_score method+- get_unverified_constraints method+- get_weak_evidence method+- Edge cases+"""+++class TestCandidateDataclass:+ """Tests for Candidate dataclass."""++ def test_has_name(self):+ """Candidate should have name field."""+ candidate = {+ "name": "Test Candidate",+ "evidence": {},+ "score": 0.0,+ "metadata": {},+ }+ assert candidate["name"] == "Test Candidate"++ def test_has_evidence_dict(self):+ """Candidate should have evidence dict."""+ candidate = {"name": "Test", "evidence": {}}+ assert isinstance(candidate["evidence"], dict)++ def test_evidence_default_empty(self):+ """Evidence should default to empty dict."""+ evidence = {}+ assert len(evidence) == 0++ def test_has_score(self):+ """Candidate should have score field."""+ candidate = {"name": "Test", "score": 0.75}+ assert candidate["score"] == 0.75++ def test_score_default_zero(self):+ """Score should default to 0.0."""+ score = 0.0+ assert score == 0.0++ def test_has_metadata_dict(self):+ """Candidate should have metadata dict."""+ candidate = {"name": "Test", "metadata": {"key": "value"}}+ assert isinstance(candidate["metadata"], dict)++ def test_metadata_default_empty(self):+ """Metadata should default to empty dict."""+ metadata = {}+ assert len(metadata) == 0+++class TestAddEvidence:+ """Tests for add_evidence method."""++ def test_adds_evidence_by_constraint_id(self):+ """Should add evidence by constraint_id."""+ evidence_dict = {}+ constraint_id = "constraint_1"+ evidence = {"confidence": 0.8, "text": "Evidence text"}++ evidence_dict[constraint_id] = evidence++ assert constraint_id in evidence_dict+ assert evidence_dict[constraint_id]["confidence"] == 0.8++ def test_overwrites_existing_evidence(self):+ """Should overwrite existing evidence for same constraint."""+ evidence_dict = {"constraint_1": {"confidence": 0.5}}+ evidence_dict["constraint_1"] = {"confidence": 0.9}++ assert evidence_dict["constraint_1"]["confidence"] == 0.9++ def test_multiple_constraints(self):+ """Should handle multiple constraints."""+ evidence_dict = {}+ evidence_dict["c1"] = {"confidence": 0.7}+ evidence_dict["c2"] = {"confidence": 0.8}+ evidence_dict["c3"] = {"confidence": 0.6}++ assert len(evidence_dict) == 3+++class TestCalculateScore:+ """Tests for calculate_score method."""++ def test_returns_zero_for_no_constraints(self):+ """Should return 0.0 when no constraints."""+ constraints = []++ if not constraints:+ score = 0.0+ else:+ score = 1.0++ assert score == 0.0++ def test_calculates_weighted_score(self):+ """Should calculate weighted score."""+ evidence = {+ "c1": {"confidence": 0.8},+ "c2": {"confidence": 0.6},+ }+ constraints = [+ {"id": "c1", "weight": 1.0},+ {"id": "c2", "weight": 2.0},+ ]++ total_score = 0.0+ total_weight = 0.0++ for constraint in constraints:+ if constraint["id"] in evidence:+ score = (+ evidence[constraint["id"]]["confidence"]+ * constraint["weight"]+ )+ total_score += score+ total_weight += constraint["weight"]++ final_score = total_score / total_weight if total_weight > 0 else 0.0++ # (0.8 * 1.0 + 0.6 * 2.0) / (1.0 + 2.0) = 2.0 / 3.0 = 0.6667+ assert abs(final_score - 0.6667) < 0.001++ def test_handles_missing_evidence(self):+ """Should handle constraints without evidence."""+ evidence = {"c1": {"confidence": 0.8}}+ constraints = [+ {"id": "c1", "weight": 1.0},+ {"id": "c2", "weight": 1.0}, # No evidence for this+ ]++ total_score = 0.0+ total_weight = 0.0++ for constraint in constraints:+ if constraint["id"] in evidence:+ score = (+ evidence[constraint["id"]]["confidence"]+ * constraint["weight"]+ )+ total_score += score+ total_weight += constraint["weight"]++ final_score = total_score / total_weight if total_weight > 0 else 0.0++ # (0.8 * 1.0 + 0) / 2.0 = 0.4+ assert final_score == 0.4++ def test_handles_zero_total_weight(self):+ """Should handle zero total weight."""+ constraints = [+ {"id": "c1", "weight": 0.0},+ {"id": "c2", "weight": 0.0},+ ]++ total_weight = sum(c["weight"] for c in constraints)+ score = 1.0 / total_weight if total_weight > 0 else 0.0++ assert score == 0.0++ def test_updates_candidate_score(self):+ """Should update candidate score field."""+ candidate = {"score": 0.0}+ calculated = 0.75++ candidate["score"] = calculated+ assert candidate["score"] == 0.75++ def test_returns_calculated_score(self):+ """Should return the calculated score."""+ evidence = {"c1": {"confidence": 1.0}}+ constraints = [{"id": "c1", "weight": 1.0}]++ total_score = evidence["c1"]["confidence"] * constraints[0]["weight"]+ total_weight = constraints[0]["weight"]+ final_score = total_score / total_weight++ assert final_score == 1.0+++class TestGetUnverifiedConstraints:+ """Tests for get_unverified_constraints method."""++ def test_returns_constraints_without_evidence(self):+ """Should return constraints without evidence."""+ evidence = {"c1": {"confidence": 0.8}}+ constraints = [+ {"id": "c1"},+ {"id": "c2"},+ {"id": "c3"},+ ]++ unverified = []+ for constraint in constraints:+ if constraint["id"] not in evidence:+ unverified.append(constraint)++ assert len(unverified) == 2+ assert unverified[0]["id"] == "c2"+ assert unverified[1]["id"] == "c3"++ def test_returns_empty_when_all_verified(self):+ """Should return empty list when all constraints verified."""+ evidence = {"c1": {}, "c2": {}, "c3": {}}+ constraints = [{"id": "c1"}, {"id": "c2"}, {"id": "c3"}]++ unverified = []+ for constraint in constraints:+ if constraint["id"] not in evidence:+ unverified.append(constraint)++ assert len(unverified) == 0++ def test_returns_all_when_no_evidence(self):+ """Should return all constraints when no evidence."""+ evidence = {}+ constraints = [{"id": "c1"}, {"id": "c2"}]++ unverified = []+ for constraint in constraints:+ if constraint["id"] not in evidence:+ unverified.append(constraint)++ assert len(unverified) == 2+++class TestGetWeakEvidence:+ """Tests for get_weak_evidence method."""++ def test_returns_weak_constraint_ids(self):+ """Should return constraint IDs with weak evidence."""+ evidence = {+ "c1": {"confidence": 0.8}, # Strong+ "c2": {"confidence": 0.3}, # Weak+ "c3": {"confidence": 0.4}, # Weak (below 0.5)+ }+ threshold = 0.5++ weak = []+ for constraint_id, ev in evidence.items():+ if ev["confidence"] < threshold:+ weak.append(constraint_id)++ assert len(weak) == 2+ assert "c2" in weak+ assert "c3" in weak++ def test_default_threshold_is_half(self):+ """Default threshold should be 0.5."""+ threshold = 0.5+ assert threshold == 0.5++ def test_custom_threshold(self):+ """Should use custom threshold."""+ evidence = {+ "c1": {"confidence": 0.7},+ "c2": {"confidence": 0.6},+ }+ threshold = 0.65++ weak = []+ for constraint_id, ev in evidence.items():+ if ev["confidence"] < threshold:+ weak.append(constraint_id)++ assert len(weak) == 1+ assert "c2" in weak++ def test_returns_empty_when_all_strong(self):+ """Should return empty when all evidence is strong."""+ evidence = {+ "c1": {"confidence": 0.9},+ "c2": {"confidence": 0.8},+ }+ threshold = 0.5++ weak = []+ for constraint_id, ev in evidence.items():+ if ev["confidence"] < threshold:+ weak.append(constraint_id)++ assert len(weak) == 0++ def test_returns_all_when_all_weak(self):+ """Should return all when all evidence is weak."""+ evidence = {+ "c1": {"confidence": 0.2},+ "c2": {"confidence": 0.1},+ "c3": {"confidence": 0.3},+ }+ threshold = 0.5++ weak = []+ for constraint_id, ev in evidence.items():+ if ev["confidence"] < threshold:+ weak.append(constraint_id)++ assert len(weak) == 3+++class TestScoreCalculationDetails:+ """Tests for detailed score calculation."""++ def test_equal_weights(self):+ """Should handle equal weights correctly."""+ evidence = {+ "c1": {"confidence": 0.6},+ "c2": {"confidence": 0.8},+ }+ constraints = [+ {"id": "c1", "weight": 1.0},+ {"id": "c2", "weight": 1.0},+ ]++ total_score = 0.0+ total_weight = 0.0++ for constraint in constraints:+ if constraint["id"] in evidence:+ score = (+ evidence[constraint["id"]]["confidence"]+ * constraint["weight"]+ )+ total_score += score+ total_weight += constraint["weight"]++ final_score = total_score / total_weight++ # (0.6 + 0.8) / 2 = 0.7+ assert final_score == 0.7++ def test_different_weights(self):+ """Should handle different weights correctly."""+ evidence = {+ "c1": {"confidence": 1.0},+ "c2": {"confidence": 0.0},+ }+ constraints = [+ {"id": "c1", "weight": 3.0}, # High weight+ {"id": "c2", "weight": 1.0}, # Low weight+ ]++ total_score = 0.0+ total_weight = 0.0++ for constraint in constraints:+ if constraint["id"] in evidence:+ score = (+ evidence[constraint["id"]]["confidence"]+ * constraint["weight"]+ )+ total_score += score+ total_weight += constraint["weight"]++ final_score = total_score / total_weight++ # (1.0 * 3.0 + 0.0 * 1.0) / 4.0 = 0.75+ assert final_score == 0.75+++class TestEdgeCases:+ """Tests for edge cases."""++ def test_empty_name(self):+ """Should handle empty name."""+ candidate = {"name": "", "evidence": {}}+ assert candidate["name"] == ""++ def test_unicode_name(self):+ """Should handle unicode name."""+ candidate = {"name": "Candidate 日本語"}+ assert "日本語" in candidate["name"]++ def test_very_long_name(self):+ """Should handle very long name."""+ name = "x" * 1000+ candidate = {"name": name}+ assert len(candidate["name"]) == 1000++ def test_confidence_exactly_threshold(self):+ """Should handle confidence exactly at threshold."""+ evidence = {"c1": {"confidence": 0.5}}+ threshold = 0.5++ weak = []+ for constraint_id, ev in evidence.items():+ if ev["confidence"] < threshold: # < not <=+ weak.append(constraint_id)++ assert len(weak) == 0 # Exactly at threshold is not weak++ def test_zero_confidence(self):+ """Should handle zero confidence."""+ evidence = {"c1": {"confidence": 0.0}}+ threshold = 0.5++ weak = []+ for constraint_id, ev in evidence.items():+ if ev["confidence"] < threshold:+ weak.append(constraint_id)++ assert len(weak) == 1++ def test_one_confidence(self):+ """Should handle perfect confidence."""+ evidence = {"c1": {"confidence": 1.0}}+ threshold = 0.5++ weak = []+ for constraint_id, ev in evidence.items():+ if ev["confidence"] < threshold:+ weak.append(constraint_id)++ assert len(weak) == 0++ def test_negative_weight(self):+ """Should handle negative weight (edge case)."""+ constraints = [{"id": "c1", "weight": -1.0}]++ total_weight = sum(c["weight"] for c in constraints)+ # Negative weight is unusual but should not crash+ assert total_weight == -1.0++ def test_very_small_weight(self):+ """Should handle very small weight."""+ constraints = [{"id": "c1", "weight": 0.0001}]++ total_weight = sum(c["weight"] for c in constraints)+ assert total_weight == 0.0001+++class TestMetadataHandling:+ """Tests for metadata handling."""++ def test_stores_arbitrary_metadata(self):+ """Should store arbitrary metadata."""+ metadata = {+ "source": "web_search",+ "timestamp": "2024-01-15",+ "query": "test query",+ }+ candidate = {"name": "Test", "metadata": metadata}++ assert candidate["metadata"]["source"] == "web_search"+ assert candidate["metadata"]["timestamp"] == "2024-01-15"++ def test_nested_metadata(self):+ """Should handle nested metadata."""+ metadata = {+ "details": {"nested": {"value": 123}},+ }+ candidate = {"name": "Test", "metadata": metadata}++ assert candidate["metadata"]["details"]["nested"]["value"] == 123++ def test_metadata_with_list(self):+ """Should handle list in metadata."""+ metadata = {"tags": ["tag1", "tag2", "tag3"]}+ candidate = {"name": "Test", "metadata": metadata}++ assert len(candidate["metadata"]["tags"]) == 3diff --git a/tests/advanced_search_system/constraint_checking/test_evidence_analyzer_extended.py b/tests/advanced_search_system/constraint_checking/test_evidence_analyzer_extended.pynew file mode 100644index 0000000000..855e4ee68b--- /dev/null+++ b/tests/advanced_search_system/constraint_checking/test_evidence_analyzer_extended.py@@ -0,0 +1,494 @@+"""+Extended tests for EvidenceAnalyzer - Dual confidence evidence analysis.++Tests cover:+- ConstraintEvidence dataclass+- EvidenceAnalyzer initialization+- analyze_evidence_dual_confidence method+- Score extraction+- evaluate_evidence_list method+- Normalization+- Edge cases+"""++import re+++class TestConstraintEvidenceDataclass:+ """Tests for ConstraintEvidence dataclass."""++ def test_has_positive_confidence(self):+ """ConstraintEvidence should have positive_confidence field."""+ evidence = {+ "positive_confidence": 0.7,+ "negative_confidence": 0.2,+ "uncertainty": 0.1,+ "evidence_text": "text",+ "source": "search",+ }+ assert evidence["positive_confidence"] == 0.7++ def test_has_negative_confidence(self):+ """ConstraintEvidence should have negative_confidence field."""+ evidence = {+ "positive_confidence": 0.3,+ "negative_confidence": 0.5,+ "uncertainty": 0.2,+ }+ assert evidence["negative_confidence"] == 0.5++ def test_has_uncertainty(self):+ """ConstraintEvidence should have uncertainty field."""+ evidence = {+ "positive_confidence": 0.4,+ "negative_confidence": 0.1,+ "uncertainty": 0.5,+ }+ assert evidence["uncertainty"] == 0.5++ def test_has_evidence_text(self):+ """ConstraintEvidence should have evidence_text field."""+ evidence = {"evidence_text": "This is evidence text"}+ assert evidence["evidence_text"] == "This is evidence text"++ def test_has_source(self):+ """ConstraintEvidence should have source field."""+ evidence = {"source": "search"}+ assert evidence["source"] == "search"++ def test_scores_sum_to_one(self):+ """Confidence scores should approximately sum to 1.0."""+ evidence = {+ "positive_confidence": 0.5,+ "negative_confidence": 0.3,+ "uncertainty": 0.2,+ }++ total = (+ evidence["positive_confidence"]+ + evidence["negative_confidence"]+ + evidence["uncertainty"]+ )+ assert abs(total - 1.0) < 0.001+++class TestEvidenceAnalyzerInitialization:+ """Tests for EvidenceAnalyzer initialization."""++ def test_model_assignment(self):+ """Should assign model on initialization."""+ model = "mock_model"+ analyzer_model = model+ assert analyzer_model == "mock_model"+++class TestAnalyzeEvidenceDualConfidence:+ """Tests for analyze_evidence_dual_confidence method."""++ def test_extracts_text_from_evidence(self):+ """Should extract text from evidence dict."""+ evidence = {"text": "This is evidence text", "source": "search"}+ text = evidence.get("text", "")+ assert text == "This is evidence text"++ def test_handles_missing_text(self):+ """Should handle missing text field."""+ evidence = {"source": "search"}+ text = evidence.get("text", "")+ assert text == ""++ def test_truncates_long_text(self):+ """Should truncate long text in prompt."""+ text = "x" * 2000+ truncated = text[:1000]+ assert len(truncated) == 1000++ def test_normalizes_scores(self):+ """Should normalize scores to sum to 1.0."""+ positive = 0.6+ negative = 0.3+ uncertainty = 0.3++ total = positive + negative + uncertainty+ if total > 0:+ positive /= total+ negative /= total+ uncertainty /= total++ result_total = positive + negative + uncertainty+ assert abs(result_total - 1.0) < 0.001++ def test_default_high_uncertainty_on_zero_total(self):+ """Should default to high uncertainty when total is zero."""+ positive = 0.0+ negative = 0.0+ uncertainty = 0.0++ total = positive + negative + uncertainty+ if total == 0:+ positive = 0.1+ negative = 0.1+ uncertainty = 0.8++ assert uncertainty == 0.8+ assert positive == 0.1+ assert negative == 0.1++ def test_truncates_evidence_text_to_500(self):+ """Should truncate evidence_text to 500 chars."""+ text = "x" * 1000+ truncated = text[:500]+ assert len(truncated) == 500++ def test_uses_default_source(self):+ """Should use default source when not provided."""+ evidence = {"text": "test"}+ source = evidence.get("source", "search")+ assert source == "search"++ def test_handles_exception_with_defaults(self):+ """Should return default values on exception."""+ # Simulating exception handling+ try:+ raise Exception("Error")+ except Exception:+ result = {+ "positive_confidence": 0.1,+ "negative_confidence": 0.1,+ "uncertainty": 0.8,+ }++ assert result["uncertainty"] == 0.8+++class TestExtractScore:+ """Tests for _extract_score method."""++ def test_extracts_positive_score(self):+ """Should extract POSITIVE score."""+ text = "POSITIVE: 0.7\nNEGATIVE: 0.2\nUNCERTAINTY: 0.1"+ pattern = r"POSITIVE:\s*\[?(\d*\.?\d+)\]?"++ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ score = float(match.group(1))+ else:+ score = 0.1++ assert score == 0.7++ def test_extracts_negative_score(self):+ """Should extract NEGATIVE score."""+ text = "POSITIVE: 0.7\nNEGATIVE: 0.2\nUNCERTAINTY: 0.1"+ pattern = r"NEGATIVE:\s*\[?(\d*\.?\d+)\]?"++ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ score = float(match.group(1))+ else:+ score = 0.1++ assert score == 0.2++ def test_extracts_uncertainty_score(self):+ """Should extract UNCERTAINTY score."""+ text = "POSITIVE: 0.7\nNEGATIVE: 0.2\nUNCERTAINTY: 0.1"+ pattern = r"UNCERTAINTY:\s*\[?(\d*\.?\d+)\]?"++ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ score = float(match.group(1))+ else:+ score = 0.1++ assert score == 0.1++ def test_handles_bracketed_score(self):+ """Should handle score in brackets."""+ text = "POSITIVE: [0.8]"+ pattern = r"POSITIVE:\s*\[?(\d*\.?\d+)\]?"++ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ score = float(match.group(1))+ else:+ score = 0.1++ assert score == 0.8++ def test_case_insensitive_matching(self):+ """Should match labels case-insensitively."""+ text = "positive: 0.6"+ pattern = r"POSITIVE:\s*\[?(\d*\.?\d+)\]?"++ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ score = float(match.group(1))+ else:+ score = 0.1++ assert score == 0.6++ def test_returns_default_on_no_match(self):+ """Should return default score on no match."""+ text = "No scores here"+ pattern = r"POSITIVE:\s*\[?(\d*\.?\d+)\]?"++ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ try:+ score = float(match.group(1))+ except Exception:+ score = 0.1+ else:+ score = 0.1++ assert score == 0.1++ def test_handles_integer_score(self):+ """Should handle integer score."""+ text = "POSITIVE: 1"+ pattern = r"POSITIVE:\s*\[?(\d*\.?\d+)\]?"++ match = re.search(pattern, text, re.IGNORECASE)+ if match:+ score = float(match.group(1))+ else:+ score = 0.1++ assert score == 1.0+++class TestEvaluateEvidenceList:+ """Tests for evaluate_evidence_list method."""++ def test_returns_penalty_for_empty_list(self):+ """Should return 0.5 - penalty for empty list."""+ evidence_list = []+ uncertainty_penalty = 0.2++ if not evidence_list:+ score = 0.5 - uncertainty_penalty+ else:+ score = 1.0++ assert score == 0.3++ def test_calculates_average_positive(self):+ """Should calculate average positive confidence."""+ evidence_list = [+ {"positive_confidence": 0.8},+ {"positive_confidence": 0.6},+ {"positive_confidence": 0.4},+ ]++ total_positive = sum(e["positive_confidence"] for e in evidence_list)+ avg_positive = total_positive / len(evidence_list)++ assert avg_positive == 0.6++ def test_calculates_average_negative(self):+ """Should calculate average negative confidence."""+ evidence_list = [+ {"negative_confidence": 0.3},+ {"negative_confidence": 0.1},+ {"negative_confidence": 0.2},+ ]++ total_negative = sum(e["negative_confidence"] for e in evidence_list)+ avg_negative = total_negative / len(evidence_list)++ assert abs(avg_negative - 0.2) < 0.001++ def test_calculates_average_uncertainty(self):+ """Should calculate average uncertainty."""+ evidence_list = [+ {"uncertainty": 0.1},+ {"uncertainty": 0.2},+ {"uncertainty": 0.3},+ ]++ total_uncertainty = sum(e["uncertainty"] for e in evidence_list)+ avg_uncertainty = total_uncertainty / len(evidence_list)++ assert abs(avg_uncertainty - 0.2) < 0.001++ def test_applies_negative_weight(self):+ """Should apply negative weight in calculation."""+ avg_negative = 0.2+ negative_weight = 0.5++ negative_contribution = avg_negative * negative_weight+ assert negative_contribution == 0.1++ def test_applies_uncertainty_penalty(self):+ """Should apply uncertainty penalty."""+ avg_uncertainty = 0.3+ uncertainty_penalty = 0.2++ penalty = avg_uncertainty * uncertainty_penalty+ assert penalty == 0.06++ def test_calculates_final_score(self):+ """Should calculate final score correctly."""+ avg_positive = 0.7+ avg_negative = 0.2+ avg_uncertainty = 0.1+ negative_weight = 0.5+ uncertainty_penalty = 0.2++ score = (+ avg_positive+ - (avg_negative * negative_weight)+ - (avg_uncertainty * uncertainty_penalty)+ )++ expected = 0.7 - 0.1 - 0.02 # 0.58+ assert abs(score - expected) < 0.001++ def test_clamps_score_to_zero(self):+ """Should clamp score to minimum 0.0."""+ score = -0.5+ clamped = max(0.0, min(1.0, score))+ assert clamped == 0.0++ def test_clamps_score_to_one(self):+ """Should clamp score to maximum 1.0."""+ score = 1.5+ clamped = max(0.0, min(1.0, score))+ assert clamped == 1.0+++class TestScoreNormalization:+ """Tests for score normalization."""++ def test_normalizes_when_total_exceeds_one(self):+ """Should normalize when total > 1."""+ positive = 0.6+ negative = 0.5+ uncertainty = 0.4+ total = 1.5++ positive /= total+ negative /= total+ uncertainty /= total++ new_total = positive + negative + uncertainty+ assert abs(new_total - 1.0) < 0.001++ def test_preserves_ratios(self):+ """Should preserve score ratios during normalization."""+ positive = 0.6+ negative = 0.3+ total = positive + negative++ orig_ratio = positive / negative++ positive /= total+ negative /= total++ new_ratio = positive / negative+ assert abs(orig_ratio - new_ratio) < 0.001+++class TestDefaultValues:+ """Tests for default value handling."""++ def test_default_uncertainty_penalty(self):+ """Default uncertainty_penalty should be 0.2."""+ uncertainty_penalty = 0.2+ assert uncertainty_penalty == 0.2++ def test_default_negative_weight(self):+ """Default negative_weight should be 0.5."""+ negative_weight = 0.5+ assert negative_weight == 0.5+++class TestEdgeCases:+ """Tests for edge cases."""++ def test_single_evidence_item(self):+ """Should handle single evidence item."""+ evidence_list = [{"positive_confidence": 0.8}]+ evidence_count = len(evidence_list)++ avg = evidence_list[0]["positive_confidence"] / evidence_count+ assert avg == 0.8++ def test_all_high_uncertainty(self):+ """Should handle all high uncertainty evidence."""+ evidence_list = [+ {+ "positive_confidence": 0.1,+ "negative_confidence": 0.1,+ "uncertainty": 0.8,+ },+ {+ "positive_confidence": 0.1,+ "negative_confidence": 0.1,+ "uncertainty": 0.8,+ },+ ]++ avg_uncertainty = sum(e["uncertainty"] for e in evidence_list) / len(+ evidence_list+ )+ assert avg_uncertainty == 0.8++ def test_all_positive_evidence(self):+ """Should handle all positive evidence."""+ evidence_list = [+ {+ "positive_confidence": 0.9,+ "negative_confidence": 0.05,+ "uncertainty": 0.05,+ },+ {+ "positive_confidence": 0.85,+ "negative_confidence": 0.1,+ "uncertainty": 0.05,+ },+ ]++ avg_positive = sum(+ e["positive_confidence"] for e in evidence_list+ ) / len(evidence_list)+ assert avg_positive == 0.875++ def test_all_negative_evidence(self):+ """Should handle all negative evidence."""+ evidence_list = [+ {+ "positive_confidence": 0.1,+ "negative_confidence": 0.8,+ "uncertainty": 0.1,+ },+ {+ "positive_confidence": 0.05,+ "negative_confidence": 0.9,+ "uncertainty": 0.05,+ },+ ]++ avg_negative = sum(+ e["negative_confidence"] for e in evidence_list+ ) / len(evidence_list)+ assert abs(avg_negative - 0.85) < 0.001++ def test_very_long_evidence_text(self):+ """Should handle very long evidence text."""+ text = "x" * 10000+ truncated = text[:500]+ assert len(truncated) == 500++ def test_unicode_evidence_text(self):+ """Should handle unicode evidence text."""+ text = "Evidence with unicode: 日本語 中文 한국어"+ assert "日本語" in text++ def test_empty_evidence_text(self):+ """Should handle empty evidence text."""+ evidence = {"text": "", "source": "search"}+ text = evidence.get("text", "")+ assert text == ""diff --git a/tests/advanced_search_system/constraint_checking/test_rejection_engine_extended.py b/tests/advanced_search_system/constraint_checking/test_rejection_engine_extended.pynew file mode 100644index 0000000000..41ffc3d47d--- /dev/null+++ b/tests/advanced_search_system/constraint_checking/test_rejection_engine_extended.py@@ -0,0 +1,497 @@+"""+Extended tests for RejectionEngine - Constraint-based candidate filtering.++Tests cover:+- RejectionResult dataclass+- RejectionEngine initialization+- should_reject_candidate method+- check_all_constraints method+- Threshold logic+- Edge cases+"""+++class TestRejectionResultDataclass:+ """Tests for RejectionResult dataclass."""++ def test_has_should_reject(self):+ """RejectionResult should have should_reject field."""+ result = {+ "should_reject": True,+ "reason": "Test",+ "constraint_value": "value",+ "positive_confidence": 0.3,+ "negative_confidence": 0.7,+ }+ assert result["should_reject"] is True++ def test_has_reason(self):+ """RejectionResult should have reason field."""+ result = {+ "should_reject": True,+ "reason": "High negative evidence",+ }+ assert result["reason"] == "High negative evidence"++ def test_has_constraint_value(self):+ """RejectionResult should have constraint_value field."""+ result = {+ "should_reject": False,+ "constraint_value": "test_value",+ }+ assert result["constraint_value"] == "test_value"++ def test_has_positive_confidence(self):+ """RejectionResult should have positive_confidence field."""+ result = {+ "should_reject": False,+ "positive_confidence": 0.6,+ }+ assert result["positive_confidence"] == 0.6++ def test_has_negative_confidence(self):+ """RejectionResult should have negative_confidence field."""+ result = {+ "should_reject": True,+ "negative_confidence": 0.4,+ }+ assert result["negative_confidence"] == 0.4+++class TestRejectionEngineInitialization:+ """Tests for RejectionEngine initialization."""++ def test_default_negative_threshold(self):+ """Default negative_threshold should be 0.25."""+ negative_threshold = 0.25+ assert negative_threshold == 0.25++ def test_default_positive_threshold(self):+ """Default positive_threshold should be 0.4."""+ positive_threshold = 0.4+ assert positive_threshold == 0.4++ def test_custom_negative_threshold(self):+ """Should accept custom negative_threshold."""+ negative_threshold = 0.3+ assert negative_threshold == 0.3++ def test_custom_positive_threshold(self):+ """Should accept custom positive_threshold."""+ positive_threshold = 0.5+ assert positive_threshold == 0.5+++class TestShouldRejectCandidate:+ """Tests for should_reject_candidate method."""++ def test_no_evidence_does_not_reject(self):+ """Should not reject when no evidence available."""+ evidence_list = []++ if not evidence_list:+ result = {+ "should_reject": False,+ "reason": "No evidence available",+ "positive_confidence": 0.0,+ "negative_confidence": 0.0,+ }+ else:+ result = None++ assert result["should_reject"] is False+ assert result["reason"] == "No evidence available"++ def test_calculates_average_positive(self):+ """Should calculate average positive confidence."""+ evidence_list = [+ {"positive_confidence": 0.6},+ {"positive_confidence": 0.8},+ {"positive_confidence": 0.5},+ ]++ avg_positive = sum(+ e["positive_confidence"] for e in evidence_list+ ) / len(evidence_list)+ assert abs(avg_positive - 0.633) < 0.01++ def test_calculates_average_negative(self):+ """Should calculate average negative confidence."""+ evidence_list = [+ {"negative_confidence": 0.2},+ {"negative_confidence": 0.1},+ {"negative_confidence": 0.3},+ ]++ avg_negative = sum(+ e["negative_confidence"] for e in evidence_list+ ) / len(evidence_list)+ assert abs(avg_negative - 0.2) < 0.001++ def test_rejects_high_negative_evidence(self):+ """Should reject when negative evidence exceeds threshold."""+ avg_negative = 0.3+ negative_threshold = 0.25++ if avg_negative > negative_threshold:+ should_reject = True+ reason = f"High negative evidence ({avg_negative:.0%})"+ else:+ should_reject = False+ reason = "Passed"++ assert should_reject is True+ assert "High negative evidence" in reason++ def test_rejects_low_positive_evidence(self):+ """Should reject when positive evidence below threshold."""+ avg_positive = 0.3+ positive_threshold = 0.4++ if avg_positive < positive_threshold:+ should_reject = True+ reason = f"Insufficient positive evidence ({avg_positive:.0%})"+ else:+ should_reject = False+ reason = "Passed"++ assert should_reject is True+ assert "Insufficient positive evidence" in reason++ def test_accepts_when_constraints_satisfied(self):+ """Should accept when constraints satisfied."""+ avg_positive = 0.6+ avg_negative = 0.1+ negative_threshold = 0.25+ positive_threshold = 0.4++ if avg_negative > negative_threshold:+ should_reject = True+ reason = "High negative"+ elif avg_positive < positive_threshold:+ should_reject = True+ reason = "Low positive"+ else:+ should_reject = False+ reason = "Constraints satisfied"++ assert should_reject is False+ assert reason == "Constraints satisfied"++ def test_primary_rule_takes_precedence(self):+ """Primary rejection rule should take precedence."""+ avg_positive = 0.3 # Would trigger secondary rule+ avg_negative = 0.5 # Would trigger primary rule+ negative_threshold = 0.25+ positive_threshold = 0.4++ # Primary rule checked first+ if avg_negative > negative_threshold:+ reason = "High negative evidence"+ elif avg_positive < positive_threshold:+ reason = "Insufficient positive evidence"+ else:+ reason = "Passed"++ assert reason == "High negative evidence"+++class TestCheckAllConstraints:+ """Tests for check_all_constraints method."""++ def test_returns_none_when_all_pass(self):+ """Should return None when all constraints pass."""+ constraint_results = {+ "constraint1": [+ {"positive_confidence": 0.8, "negative_confidence": 0.1}+ ],+ "constraint2": [+ {"positive_confidence": 0.7, "negative_confidence": 0.1}+ ],+ }++ rejection = None+ for _constraint, evidence_list in constraint_results.items():+ avg_negative = sum(+ e["negative_confidence"] for e in evidence_list+ ) / len(evidence_list)+ avg_positive = sum(+ e["positive_confidence"] for e in evidence_list+ ) / len(evidence_list)++ if avg_negative > 0.25 or avg_positive < 0.4:+ rejection = {"should_reject": True}+ break++ assert rejection is None++ def test_returns_first_rejection(self):+ """Should return first rejection found."""+ constraint_results = {+ "constraint1": [+ {"positive_confidence": 0.8, "negative_confidence": 0.1}+ ],+ "constraint2": [+ {"positive_confidence": 0.2, "negative_confidence": 0.1}+ ], # Fails+ "constraint3": [+ {"positive_confidence": 0.1, "negative_confidence": 0.5}+ ], # Also fails+ }++ rejection = None+ for constraint_name, evidence_list in constraint_results.items():+ avg_positive = sum(+ e["positive_confidence"] for e in evidence_list+ ) / len(evidence_list)++ if avg_positive < 0.4:+ rejection = {+ "constraint": constraint_name,+ "should_reject": True,+ }+ break++ assert rejection is not None+ assert rejection["constraint"] == "constraint2"++ def test_iterates_all_constraints(self):+ """Should iterate through all constraints."""+ constraint_results = {+ "c1": [{"positive_confidence": 0.5, "negative_confidence": 0.1}],+ "c2": [{"positive_confidence": 0.6, "negative_confidence": 0.1}],+ "c3": [{"positive_confidence": 0.7, "negative_confidence": 0.1}],+ }++ checked = []+ for constraint_name in constraint_results:+ checked.append(constraint_name)++ assert len(checked) == 3+++class TestThresholdBehavior:+ """Tests for threshold behavior."""++ def test_exactly_at_negative_threshold(self):+ """Should not reject when exactly at negative threshold."""+ avg_negative = 0.25+ negative_threshold = 0.25++ # > not >= so exactly at threshold should not reject+ if avg_negative > negative_threshold:+ should_reject = True+ else:+ should_reject = False++ assert should_reject is False++ def test_exactly_at_positive_threshold(self):+ """Should not reject when exactly at positive threshold."""+ avg_positive = 0.4+ positive_threshold = 0.4++ # < not <= so exactly at threshold should not reject+ if avg_positive < positive_threshold:+ should_reject = True+ else:+ should_reject = False++ assert should_reject is False++ def test_just_above_negative_threshold(self):+ """Should reject when just above negative threshold."""+ avg_negative = 0.251+ negative_threshold = 0.25++ if avg_negative > negative_threshold:+ should_reject = True+ else:+ should_reject = False++ assert should_reject is True++ def test_just_below_positive_threshold(self):+ """Should reject when just below positive threshold."""+ avg_positive = 0.399+ positive_threshold = 0.4++ if avg_positive < positive_threshold:+ should_reject = True+ else:+ should_reject = False++ assert should_reject is True+++class TestReasonFormatting:+ """Tests for reason formatting."""++ def test_negative_evidence_percentage_format(self):+ """Should format negative evidence as percentage."""+ avg_negative = 0.35+ reason = f"High negative evidence ({avg_negative:.0%})"++ assert reason == "High negative evidence (35%)"++ def test_positive_evidence_percentage_format(self):+ """Should format positive evidence as percentage."""+ avg_positive = 0.25+ reason = f"Insufficient positive evidence ({avg_positive:.0%})"++ assert reason == "Insufficient positive evidence (25%)"+++class TestEdgeCases:+ """Tests for edge cases."""++ def test_single_evidence_item(self):+ """Should handle single evidence item."""+ evidence_list = [+ {"positive_confidence": 0.7, "negative_confidence": 0.1}+ ]++ avg_positive = evidence_list[0]["positive_confidence"]+ avg_negative = evidence_list[0]["negative_confidence"]++ assert avg_positive == 0.7+ assert avg_negative == 0.1++ def test_many_evidence_items(self):+ """Should handle many evidence items."""+ evidence_list = [+ {"positive_confidence": 0.5, "negative_confidence": 0.2}+ ] * 100++ avg_positive = sum(+ e["positive_confidence"] for e in evidence_list+ ) / len(evidence_list)+ assert avg_positive == 0.5++ def test_all_zero_confidence(self):+ """Should handle all zero confidence."""+ evidence_list = [+ {"positive_confidence": 0.0, "negative_confidence": 0.0},+ ]++ avg_positive = sum(+ e["positive_confidence"] for e in evidence_list+ ) / len(evidence_list)++ # Should reject due to low positive+ should_reject = avg_positive < 0.4+ assert should_reject is True++ def test_all_high_positive(self):+ """Should handle all high positive evidence."""+ evidence_list = [+ {"positive_confidence": 0.9, "negative_confidence": 0.05},+ {"positive_confidence": 0.95, "negative_confidence": 0.03},+ ]++ avg_positive = sum(+ e["positive_confidence"] for e in evidence_list+ ) / len(evidence_list)+ avg_negative = sum(+ e["negative_confidence"] for e in evidence_list+ ) / len(evidence_list)++ # Should not reject+ should_reject = avg_negative > 0.25 or avg_positive < 0.4+ assert should_reject is False++ def test_all_high_negative(self):+ """Should handle all high negative evidence."""+ evidence_list = [+ {"positive_confidence": 0.1, "negative_confidence": 0.8},+ {"positive_confidence": 0.15, "negative_confidence": 0.75},+ ]++ avg_negative = sum(+ e["negative_confidence"] for e in evidence_list+ ) / len(evidence_list)++ # Should reject+ should_reject = avg_negative > 0.25+ assert should_reject is True++ def test_empty_constraint_results(self):+ """Should handle empty constraint results."""+ constraint_results = {}++ rejection = None+ for _constraint, evidence_list in constraint_results.items():+ pass # No iterations++ assert rejection is None++ def test_constraint_with_no_evidence(self):+ """Should handle constraint with no evidence."""+ constraint_results = {+ "constraint1": [],+ }++ for constraint_name, evidence_list in constraint_results.items():+ if not evidence_list:+ result = {+ "should_reject": False,+ "reason": "No evidence available",+ "constraint": constraint_name,+ }++ assert result["should_reject"] is False+++class TestCandidateLogging:+ """Tests for candidate logging."""++ def test_rejection_log_format(self):+ """Should format rejection log message."""+ candidate_name = "Test Candidate"+ constraint_value = "test_constraint"+ reason = "High negative evidence (40%)"++ log_message = (+ f"REJECTION: {candidate_name} - {constraint_value} - {reason}"+ )++ assert "Test Candidate" in log_message+ assert "test_constraint" in log_message+ assert "High negative evidence" in log_message++ def test_acceptance_log_format(self):+ """Should format acceptance log message."""+ candidate_name = "Test Candidate"++ log_message = f"ACCEPTED: {candidate_name} - All constraints satisfied"++ assert "Test Candidate" in log_message+ assert "All constraints satisfied" in log_message+++class TestConfidenceScoreExtraction:+ """Tests for confidence score extraction."""++ def test_extracts_from_evidence_dict(self):+ """Should extract confidence from evidence dict."""+ evidence = {+ "positive_confidence": 0.65,+ "negative_confidence": 0.15,+ "uncertainty": 0.2,+ }++ positive = evidence["positive_confidence"]+ negative = evidence["negative_confidence"]++ assert positive == 0.65+ assert negative == 0.15++ def test_handles_missing_keys(self):+ """Should handle missing confidence keys."""+ evidence = {"other_field": "value"}++ positive = evidence.get("positive_confidence", 0.0)+ negative = evidence.get("negative_confidence", 0.0)++ assert positive == 0.0+ assert negative == 0.0diff --git a/tests/advanced_search_system/query_generation/test_adaptive_query_generator_extended.py b/tests/advanced_search_system/query_generation/test_adaptive_query_generator_extended.pynew file mode 100644index 0000000000..487298205b--- /dev/null+++ b/tests/advanced_search_system/query_generation/test_adaptive_query_generator_extended.py@@ -0,0 +1,634 @@+"""+Extended tests for AdaptiveQueryGenerator - Adaptive query generation system.++Tests cover:+- QueryPattern dataclass+- AdaptiveQueryGenerator initialization+- Default pattern initialization+- Pattern-based query generation+- Semantic expansion+- LLM-based query generation+- Pattern updates+- Fallback query generation+- Constraint combination optimization+"""++from collections import defaultdict+++class TestQueryPatternDataclass:+ """Tests for QueryPattern dataclass."""++ def test_query_pattern_has_template(self):+ """QueryPattern should have template field."""+ pattern = {+ "template": '"{entity}" {property}',+ "constraint_types": [],+ "success_rate": 0.7,+ "example_queries": [],+ "discovered_entities": set(),+ }+ assert "template" in pattern++ def test_query_pattern_has_constraint_types(self):+ """QueryPattern should have constraint_types field."""+ pattern = {+ "template": "template",+ "constraint_types": ["NAME_PATTERN", "PROPERTY"],+ "success_rate": 0.6,+ }+ assert len(pattern["constraint_types"]) == 2++ def test_query_pattern_has_success_rate(self):+ """QueryPattern should have success_rate field."""+ pattern = {+ "template": "template",+ "success_rate": 0.75,+ }+ assert pattern["success_rate"] == 0.75++ def test_query_pattern_has_example_queries(self):+ """QueryPattern should have example_queries field."""+ pattern = {+ "template": "template",+ "example_queries": ["query1", "query2"],+ }+ assert len(pattern["example_queries"]) == 2++ def test_query_pattern_has_discovered_entities(self):+ """QueryPattern should have discovered_entities field."""+ pattern = {+ "template": "template",+ "discovered_entities": {"entity1", "entity2"},+ }+ assert len(pattern["discovered_entities"]) == 2+++class TestAdaptiveQueryGeneratorInitialization:+ """Tests for AdaptiveQueryGenerator initialization."""++ def test_model_assignment(self):+ """Should assign model on initialization."""+ model = "mock_model"+ assigned = model+ assert assigned == "mock_model"++ def test_successful_patterns_initialized(self):+ """successful_patterns should be initialized as list."""+ successful_patterns = []+ assert isinstance(successful_patterns, list)++ def test_failed_queries_initialized(self):+ """failed_queries should be initialized as set."""+ failed_queries = set()+ assert isinstance(failed_queries, set)++ def test_semantic_expansions_initialized(self):+ """semantic_expansions should be initialized as dict."""+ semantic_expansions = {}+ assert isinstance(semantic_expansions, dict)++ def test_constraint_combinations_initialized(self):+ """constraint_combinations should be initialized as defaultdict."""+ constraint_combinations = defaultdict(float)+ assert isinstance(constraint_combinations, defaultdict)+++class TestDefaultPatternInitialization:+ """Tests for _initialize_default_patterns method."""++ def test_creates_default_patterns(self):+ """Should create default patterns."""+ default_patterns = [+ {+ "template": '"{entity}" {property} {location}',+ "success_rate": 0.7,+ },+ {"template": "{event} {temporal} {statistic}", "success_rate": 0.6},+ {+ "template": '"{name_pattern}" AND {comparison} {value}',+ "success_rate": 0.65,+ },+ ]+ assert len(default_patterns) == 3++ def test_entity_location_pattern(self):+ """Should have entity-location pattern."""+ pattern = {+ "template": '"{entity}" {property} {location}',+ "constraint_types": ["NAME_PATTERN", "PROPERTY", "LOCATION"],+ "success_rate": 0.7,+ }+ assert "entity" in pattern["template"]+ assert "location" in pattern["template"]++ def test_event_temporal_pattern(self):+ """Should have event-temporal pattern."""+ pattern = {+ "template": "{event} {temporal} {statistic}",+ "constraint_types": ["EVENT", "TEMPORAL", "STATISTIC"],+ "success_rate": 0.6,+ }+ assert "event" in pattern["template"]+ assert "temporal" in pattern["template"]++ def test_name_comparison_pattern(self):+ """Should have name-comparison pattern."""+ pattern = {+ "template": '"{name_pattern}" AND {comparison} {value}',+ "success_rate": 0.65,+ }+ assert "name_pattern" in pattern["template"]+ assert "AND" in pattern["template"]+++class TestGenerateQuery:+ """Tests for generate_query method."""++ def test_tries_pattern_first(self):+ """Should try pattern-based generation first."""+ tried_pattern = True+ assert tried_pattern is True++ def test_tries_expansion_second(self):+ """Should try semantic expansion second."""+ tried_expansion = True+ assert tried_expansion is True++ def test_falls_back_to_llm(self):+ """Should fall back to LLM generation."""+ used_llm = True+ assert used_llm is True++ def test_skips_failed_queries(self):+ """Should skip queries in failed_queries set."""+ failed_queries = {"bad query"}+ query = "bad query"++ if query in failed_queries:+ skip = True+ else:+ skip = False++ assert skip is True+++class TestGenerateFromPatterns:+ """Tests for _generate_from_patterns method."""++ def test_returns_none_for_no_match(self):+ """Should return None when no patterns match."""+ matching_patterns = []+ result = None if not matching_patterns else matching_patterns[0]+ assert result is None++ def test_selects_highest_success_rate(self):+ """Should select pattern with highest success rate."""+ patterns = [+ {"template": "a", "success_rate": 0.5},+ {"template": "b", "success_rate": 0.8},+ {"template": "c", "success_rate": 0.6},+ ]++ best = max(patterns, key=lambda p: p["success_rate"])+ assert best["template"] == "b"++ def test_fills_template_vars(self):+ """Should fill template variables."""+ template = '"{entity}" {property}'+ template_vars = {"entity": "mountain", "property": "height"}++ try:+ query = template.format(**template_vars)+ except KeyError:+ query = None++ assert query == '"mountain" height'++ def test_handles_missing_vars(self):+ """Should handle missing template variables."""+ template = "{entity} {missing}"+ template_vars = {"entity": "value"}++ try:+ template.format(**template_vars)+ result = "success"+ except KeyError:+ result = None++ assert result is None++ def test_maps_constraint_types_to_vars(self):+ """Should map constraint types to template variables."""+ constraint_type_mappings = {+ "NAME_PATTERN": ["name_pattern", "entity"],+ "PROPERTY": ["property"],+ "LOCATION": ["location"],+ "EVENT": ["event"],+ "TEMPORAL": ["temporal"],+ "STATISTIC": ["statistic"],+ "COMPARISON": ["comparison", "value"],+ }++ assert "entity" in constraint_type_mappings["NAME_PATTERN"]+++class TestGenerateWithExpansion:+ """Tests for _generate_with_expansion method."""++ def test_creates_or_clause(self):+ """Should create OR clause with expansions."""+ value = "mountain"+ expansions = ['"peak"', '"summit"']++ expanded = f"({value} OR {' OR '.join(expansions[:2])})"+ assert "mountain" in expanded+ assert "OR" in expanded++ def test_uses_quotes_without_expansion(self):+ """Should use quotes when no expansion available."""+ value = "specific_term"+ expansions = []++ if expansions:+ result = f"({value} OR {' OR '.join(expansions)})"+ else:+ result = f'"{value}"'++ assert result == '"specific_term"'++ def test_joins_terms_with_and(self):+ """Should join terms with AND."""+ expanded_terms = ['"term1"', '"term2"']+ result = " AND ".join(expanded_terms)++ assert result == '"term1" AND "term2"'++ def test_caches_semantic_expansions(self):+ """Should cache semantic expansions."""+ semantic_expansions = {}+ value = "test"++ if value not in semantic_expansions:+ semantic_expansions[value] = ["expansion1", "expansion2"]++ assert value in semantic_expansions+ assert len(semantic_expansions[value]) == 2+++class TestGetSemanticExpansions:+ """Tests for _get_semantic_expansions method."""++ def test_returns_quoted_expansions(self):+ """Should return quoted expansions."""+ expansions = ["synonym", "related", "alternative"]+ quoted = [f'"{exp}"' for exp in expansions[:3]]++ assert quoted[0] == '"synonym"'+ assert len(quoted) == 3++ def test_limits_to_three_expansions(self):+ """Should limit to 3 expansions."""+ expansions = ["a", "b", "c", "d", "e"]+ limited = expansions[:3]++ assert len(limited) == 3+++class TestGenerateWithLLM:+ """Tests for _generate_with_llm method."""++ def test_formats_constraints(self):+ """Should format constraints for prompt."""+ constraints = [+ {"type": "NAME_PATTERN", "description": "Pattern", "value": "test"},+ ]++ formatted = []+ for c in constraints:+ formatted.append(+ f"- {c['type']}: {c['description']} [value: {c['value']}]"+ )++ result = "\n".join(formatted)+ assert "NAME_PATTERN" in result+ assert "test" in result++ def test_includes_failed_queries_context(self):+ """Should include failed queries in context."""+ context = {"failed_queries": ["query1", "query2"]}++ context_info = ""+ if "failed_queries" in context:+ context_info += "\nFailed queries to avoid:\n" + "\n".join(+ context["failed_queries"][:3]+ )++ assert "query1" in context_info++ def test_includes_successful_queries_context(self):+ """Should include successful queries in context."""+ context = {"successful_queries": ["good1", "good2"]}++ context_info = ""+ if "successful_queries" in context:+ context_info += "\nSuccessful query patterns:\n" + "\n".join(+ context["successful_queries"][:3]+ )++ assert "good1" in context_info+++class TestUpdatePatterns:+ """Tests for update_patterns method."""++ def test_adds_to_failed_on_failure(self):+ """Should add to failed_queries on failure."""+ failed_queries = set()+ success = False+ query = "failed query"++ if not success:+ failed_queries.add(query)++ assert query in failed_queries++ def test_updates_existing_pattern_success_rate(self):+ """Should update existing pattern success rate."""+ existing_rate = 0.6+ new_rate = (existing_rate + 1.0) / 2++ assert new_rate == 0.8++ def test_adds_example_query(self):+ """Should add example query to pattern."""+ pattern = {"example_queries": ["old_query"]}+ pattern["example_queries"].append("new_query")++ assert "new_query" in pattern["example_queries"]++ def test_updates_discovered_entities(self):+ """Should update discovered entities."""+ pattern = {"discovered_entities": {"entity1"}}+ pattern["discovered_entities"].update(["entity2", "entity3"])++ assert "entity2" in pattern["discovered_entities"]++ def test_updates_constraint_combinations(self):+ """Should update constraint combinations count."""+ constraint_combinations = defaultdict(float)+ combo = ("NAME_PATTERN", "LOCATION")++ constraint_combinations[combo] += 1+ assert constraint_combinations[combo] == 1.0+++class TestExtractPattern:+ """Tests for _extract_pattern method."""++ def test_replaces_values_with_placeholders(self):+ """Should replace values with placeholders."""+ query = '"mountain" in Colorado'+ constraint_value = "mountain"+ placeholder = "{NAME_PATTERN}"++ pattern = query.replace(constraint_value, placeholder)+ assert "{NAME_PATTERN}" in pattern++ def test_returns_none_without_placeholders(self):+ """Should return None if no placeholders created."""+ pattern = "simple query without replacements"++ if "{" not in pattern:+ result = None+ else:+ result = pattern++ assert result is None++ def test_creates_pattern_with_placeholders(self):+ """Should create pattern when placeholders exist."""+ pattern = "{NAME_PATTERN} in {LOCATION}"++ if "{" in pattern:+ result = {"template": pattern, "success_rate": 1.0}+ else:+ result = None++ assert result is not None+ assert result["template"] == pattern+++class TestFormatConstraints:+ """Tests for _format_constraints method."""++ def test_formats_single_constraint(self):+ """Should format single constraint."""+ constraint = {+ "type": "NAME_PATTERN",+ "description": "A pattern",+ "value": "test",+ }++ formatted = f"- {constraint['type']}: {constraint['description']} [value: {constraint['value']}]"+ assert "NAME_PATTERN" in formatted+ assert "A pattern" in formatted+ assert "test" in formatted++ def test_formats_multiple_constraints(self):+ """Should format multiple constraints."""+ constraints = [+ {"type": "NAME_PATTERN", "description": "D1", "value": "v1"},+ {"type": "LOCATION", "description": "D2", "value": "v2"},+ ]++ formatted = []+ for c in constraints:+ formatted.append(+ f"- {c['type']}: {c['description']} [value: {c['value']}]"+ )++ result = "\n".join(formatted)+ assert "NAME_PATTERN" in result+ assert "LOCATION" in result+++class TestGenerateFallbackQueries:+ """Tests for generate_fallback_queries method."""++ def test_generates_simplified_query(self):+ """Should generate simplified query with fewer constraints."""+ constraints = [+ {"value": "a", "weight": 1.0},+ {"value": "b", "weight": 0.8},+ {"value": "c", "weight": 0.5},+ ]++ if len(constraints) > 2:+ priority = sorted(+ constraints, key=lambda c: c["weight"], reverse=True+ )[:2]+ simplified = True+ else:+ simplified = False++ assert simplified is True+ assert len(priority) == 2++ def test_generates_broadened_query(self):+ """Should generate broadened query with OR."""+ constraints = [{"value": "a"}, {"value": "b"}]++ terms = [f'"{c["value"]}"' for c in constraints]+ broadened = " OR ".join(terms)++ assert broadened == '"a" OR "b"'++ def test_generates_single_constraint_queries(self):+ """Should generate queries for single constraints."""+ constraints = [{"value": "a"}, {"value": "b"}, {"value": "c"}]++ single_queries = [f'"{c["value"]}"' for c in constraints[:3]]+ assert len(single_queries) == 3++ def test_removes_duplicates(self):+ """Should remove duplicate fallback queries."""+ fallbacks = ["query1", "query2", "query1", "query3"]++ unique = []+ for q in fallbacks:+ if q not in unique:+ unique.append(q)++ assert len(unique) == 3++ def test_removes_failed_queries(self):+ """Should remove queries in failed set."""+ failed_queries = {"bad_query"}+ fallbacks = ["good_query", "bad_query"]++ filtered = [q for q in fallbacks if q not in failed_queries]+ assert "bad_query" not in filtered++ def test_limits_to_five(self):+ """Should limit to 5 fallback queries."""+ fallbacks = ["q1", "q2", "q3", "q4", "q5", "q6", "q7"]+ limited = fallbacks[:5]++ assert len(limited) == 5+++class TestGenerateSingleConstraintQuery:+ """Tests for _generate_single_constraint_query method."""++ def test_name_pattern_template(self):+ """Should use name pattern template."""+ template = '"{value}" names list'+ value = "mountain"++ query = template.format(value=value)+ assert query == '"mountain" names list'++ def test_location_template(self):+ """Should use location template."""+ template = '"{value}" places locations'+ value = "Colorado"++ query = template.format(value=value)+ assert query == '"Colorado" places locations'++ def test_event_template(self):+ """Should use event template."""+ template = '"{value}" incidents accidents'+ value = "earthquake"++ query = template.format(value=value)+ assert query == '"earthquake" incidents accidents'++ def test_temporal_template(self):+ """Should use temporal template."""+ template = "events in {value}"+ value = "2020"++ query = template.format(value=value)+ assert query == "events in 2020"++ def test_default_template(self):+ """Should use default template for unknown types."""+ template = '"{value}"'+ value = "unknown"++ query = template.format(value=value)+ assert query == '"unknown"'+++class TestOptimizeConstraintCombinations:+ """Tests for optimize_constraint_combinations method."""++ def test_sorts_by_success(self):+ """Should sort combinations by success."""+ combinations = {+ ("A", "B"): 5,+ ("C", "D"): 10,+ ("E", "F"): 3,+ }++ sorted_combos = sorted(+ combinations.items(), key=lambda x: x[1], reverse=True+ )+ assert sorted_combos[0][0] == ("C", "D")++ def test_adds_individual_constraints(self):+ """Should add individual constraints."""+ constraints = [{"type": "A"}, {"type": "B"}]++ individual = [[c] for c in constraints]+ assert len(individual) == 2++ def test_adds_pairs(self):+ """Should add constraint pairs."""+ constraints = ["a", "b", "c"]++ pairs = []+ for i in range(len(constraints)):+ for j in range(i + 1, len(constraints)):+ pairs.append([constraints[i], constraints[j]])++ assert len(pairs) == 3 # (a,b), (a,c), (b,c)++ def test_limits_to_ten(self):+ """Should limit to 10 combinations."""+ combinations = list(range(15))+ limited = combinations[:10]++ assert len(limited) == 10+++class TestEdgeCases:+ """Tests for edge cases."""++ def test_empty_constraints(self):+ """Should handle empty constraints."""+ constraints = []+ assert len(constraints) == 0++ def test_empty_template_vars(self):+ """Should handle empty template vars."""+ template = "simple query"+ template_vars = {}++ try:+ result = template.format(**template_vars)+ except KeyError:+ result = None++ # Simple query without placeholders should work+ assert result == "simple query"++ def test_special_characters_in_value(self):+ """Should handle special characters in value."""+ value = "test (with) special [chars]"+ quoted = f'"{value}"'++ assert "test" in quoted+ assert "(" in quoted