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 220 high-value tests across 8 modules (round 6) (#2560)

LearningCircuitd108d32172fd
diff --git a/tests/advanced_search_system/answer_decoding/test_browsecomp_decoder_high_value.py b/tests/advanced_search_system/answer_decoding/test_browsecomp_decoder_high_value.py
new file mode 100644
index 0000000000..8b2890860d
--- /dev/null
+++ b/tests/advanced_search_system/answer_decoding/test_browsecomp_decoder_high_value.py
@@ -0,0 +1,219 @@
+"""High-value tests for BrowseCompAnswerDecoder internal scoring/validation methods."""
+
+import pytest
+
+from local_deep_research.advanced_search_system.answer_decoding.browsecomp_answer_decoder import (
+ BrowseCompAnswerDecoder,
+)
+
+
+def decoder():
+ return BrowseCompAnswerDecoder()
+
+
+# --- _caesar_shift tests ---
+
+
+class TestCaesarShift:
+ def test_shift_zero(self, decoder):
+ assert decoder._caesar_shift("abc", 0) == "abc"
+
+ def test_shift_one_lowercase(self, decoder):
+ assert decoder._caesar_shift("abc", 1) == "bcd"
+
+ def test_shift_one_uppercase(self, decoder):
+ assert decoder._caesar_shift("ABC", 1) == "BCD"
+
+ def test_wraparound_lowercase(self, decoder):
+ assert decoder._caesar_shift("xyz", 3) == "abc"
+
+ def test_wraparound_uppercase(self, decoder):
+ assert decoder._caesar_shift("XYZ", 3) == "ABC"
+
+ def test_non_alpha_passthrough(self, decoder):
+ assert decoder._caesar_shift("a1!b", 1) == "b1!c"
+
+ def test_shift_25(self, decoder):
+ assert decoder._caesar_shift("b", 25) == "a"
+
+ def test_shift_13_rot13(self, decoder):
+ assert decoder._caesar_shift("hello", 13) == "uryyb"
+
+ def test_mixed_case_and_symbols(self, decoder):
+ assert decoder._caesar_shift("Hello, World!", 5) == "Mjqqt, Btwqi!"
+
+ def test_empty_string(self, decoder):
+ assert decoder._caesar_shift("", 10) == ""
+
+
+# --- _english_score tests ---
+
+
+class TestEnglishScore:
+ def test_empty_text(self, decoder):
+ assert decoder._english_score("") == 0.0
+
+ def test_no_letters(self, decoder):
+ assert decoder._english_score("12345!@#") == 0.0
+
+ def test_common_letters_high_score(self, decoder):
+ score = decoder._english_score("the rain in spain")
+ assert score > 0.5
+
+ def test_uncommon_letters_lower_score(self, decoder):
+ score_common = decoder._english_score("the")
+ score_uncommon = decoder._english_score("zqx")
+ assert score_common > score_uncommon
+
+ def test_common_word_bonus(self, decoder):
+ score_with_words = decoder._english_score("the cat is in the hat")
+ score_without = decoder._english_score("blrk mnop qrst")
+ assert score_with_words >= score_without
+
+ def test_single_letter(self, decoder):
+ score = decoder._english_score("e")
+ assert score > 0.0
+
+ def test_score_capped_at_one(self, decoder):
+ score = decoder._english_score(
+ "the and of to a in is it you that the and of to"
+ )
+ assert score <= 1.0
+
+
+# --- validate_decoded_answer tests ---
+
+
+class TestValidateDecodedAnswer:
+ def test_empty_string_invalid(self, decoder):
+ assert decoder.validate_decoded_answer("") is False
+
+ def test_none_invalid(self, decoder):
+ assert decoder.validate_decoded_answer(None) is False
+
+ def test_whitespace_only_invalid(self, decoder):
+ assert decoder.validate_decoded_answer(" ") is False
+
+ def test_length_one_valid(self, decoder):
+ # Single alpha character: length ok, 100% printable, 100% alpha, 0% punct
+ assert decoder.validate_decoded_answer("A") is True
+
+ def test_length_1000_valid(self, decoder):
+ text = "Hello world " * 83 + "Hello wo" # 1000 chars
+ text = text[:1000]
+ assert len(text.strip()) <= 1000
+ assert decoder.validate_decoded_answer(text) is True
+
+ def test_length_1001_invalid(self, decoder):
+ text = "a" * 1001
+ assert decoder.validate_decoded_answer(text) is False
+
+ def test_low_printable_ratio_invalid(self, decoder):
+ # Mostly non-printable (control chars with ord > 31 won't trigger ctrl check,
+ # but let's use non-printable surrogates - actually just use many non-printable)
+ text = "ab" + "\x00" * 10 # has control chars
+ assert decoder.validate_decoded_answer(text) is False
+
+ def test_control_characters_invalid(self, decoder):
+ text = "Hello\x01World"
+ assert decoder.validate_decoded_answer(text) is False
+
+ def test_tab_newline_allowed(self, decoder):
+ text = "Hello\tWorld\nFoo Bar"
+ assert decoder.validate_decoded_answer(text) is True
+
+ def test_low_alpha_ratio_invalid(self, decoder):
+ text = "1234567890!@#$%^&*()"
+ assert decoder.validate_decoded_answer(text) is False
+
+ def test_high_punctuation_ratio_invalid(self, decoder):
+ text = "a!@#$%^&*()!@#$%^&*()"
+ assert decoder.validate_decoded_answer(text) is False
+
+ def test_normal_text_valid(self, decoder):
+ assert decoder.validate_decoded_answer("Mount Everest") is True
+
+
+# --- is_likely_direct_answer tests ---
+
+
+class TestIsLikelyDirectAnswer:
+ def test_short_answer_plaintext(self, decoder):
+ assert decoder.is_likely_direct_answer("Yes") is True
+
+ def test_three_char_plaintext(self, decoder):
+ assert decoder.is_likely_direct_answer("No!") is True
+
+ def test_english_indicator_the(self, decoder):
+ assert decoder.is_likely_direct_answer("the company") is True
+
+ def test_english_indicator_corporation(self, decoder):
+ assert decoder.is_likely_direct_answer("Acme Corporation") is True
+
+ def test_multi_word_plaintext(self, decoder):
+ assert decoder.is_likely_direct_answer("John Smith") is True
+
+ def test_year_pattern(self, decoder):
+ assert decoder.is_likely_direct_answer("2024") is True
+
+ def test_money_pattern(self, decoder):
+ assert decoder.is_likely_direct_answer("$500") is True
+
+ def test_name_format_pattern(self, decoder):
+ assert decoder.is_likely_direct_answer("John Smith") is True
+
+ def test_low_char_diversity_not_plaintext(self, decoder):
+ # Repetitive characters: needs >= 4 chars, no English indicators,
+ # no spaces, no common patterns, and diversity < 0.3
+ # "xzxzxzxzxzxzxzxz" -> diversity = 2/16 = 0.125 < 0.3
+ # No English indicators match (no "the", "and", "a", etc. as substrings -
+ # but "a" matches as substring! Use chars that avoid all indicators)
+ result = decoder.is_likely_direct_answer("qxqxqxqxqxqxqxqx")
+ assert result is False
+
+ def test_encoded_base64_pattern(self, decoder):
+ # Looks like base64: long string of alphanumeric + /+= chars
+ result = decoder.is_likely_direct_answer("Y00Qhep12345")
+ assert result is False
+
+ def test_percentage_pattern(self, decoder):
+ assert decoder.is_likely_direct_answer("75%") is True
+
+
+# --- analyze_answer_encoding tests ---
+
+
+class TestAnalyzeAnswerEncoding:
+ def test_returns_dict_with_required_keys(self, decoder):
+ result = decoder.analyze_answer_encoding("Hello")
+ assert "original" in result
+ assert "length" in result
+ assert "likely_plaintext" in result
+ assert "pattern_matches" in result
+ assert "attempted_decodings" in result
+
+ def test_plaintext_analysis(self, decoder):
+ result = decoder.analyze_answer_encoding("Mount Everest")
+ assert result["likely_plaintext"] is True
+ assert result["original"] == "Mount Everest"
+ assert result["length"] == 13
+
+ def test_encoded_pattern_matches(self, decoder):
+ # Hex-like string
+ result = decoder.analyze_answer_encoding("48656c6c6f")
+ matches = result["pattern_matches"]
+ types = [m["type"] for m in matches]
+ assert "hex" in types
+
+ def test_attempted_decodings_all_schemes(self, decoder):
+ result = decoder.analyze_answer_encoding("SGVsbG8=")
+ assert "base64" in result["attempted_decodings"]
+ assert "rot13" in result["attempted_decodings"]
+ assert "caesar_cipher" in result["attempted_decodings"]
+
+ def test_base64_decoded_valid(self, decoder):
+ result = decoder.analyze_answer_encoding("SGVsbG8=")
+ b64 = result["attempted_decodings"]["base64"]
+ assert b64["decoded"] == "Hello"
+ assert b64["valid"] is True
diff --git a/tests/advanced_search_system/candidate_exploration/test_constraint_guided_high_value.py b/tests/advanced_search_system/candidate_exploration/test_constraint_guided_high_value.py
new file mode 100644
index 0000000000..6e3815e448
--- /dev/null
+++ b/tests/advanced_search_system/candidate_exploration/test_constraint_guided_high_value.py
@@ -0,0 +1,249 @@
+"""High-value tests for ConstraintGuidedExplorer pure logic methods."""
+
+import pytest
+from unittest.mock import patch
+
+from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+)
+
+
+def make_constraint(ctype, value, weight=1.0, cid=None):
+ return Constraint(
+ id=cid or f"c_{value[:8]}",
+ type=ctype,
+ description=value,
+ value=value,
+ weight=weight,
+ )
+
+
+def explorer():
+ """Create a ConstraintGuidedExplorer with mocked parent init."""
+ with patch.object(
+ ConstraintGuidedExplorer, "__init__", lambda self, *a, **kw: None
+ ):
+ e = ConstraintGuidedExplorer.__new__(ConstraintGuidedExplorer)
+ e.constraint_weight_threshold = 0.7
+ e.early_validation = True
+ e.max_candidates = 20
+ return e
+
+
+# --- _prioritize_constraints ---
+
+
+class TestPrioritizeConstraints:
+ def test_sort_by_weight_descending(self, explorer):
+ constraints = [
+ make_constraint(ConstraintType.PROPERTY, "low", weight=0.3),
+ make_constraint(ConstraintType.PROPERTY, "high", weight=0.9),
+ make_constraint(ConstraintType.PROPERTY, "mid", weight=0.6),
+ ]
+ result = explorer._prioritize_constraints(constraints)
+ assert result[0].value == "high"
+ assert result[1].value == "mid"
+ assert result[2].value == "low"
+
+ def test_same_weight_sort_by_type_priority(self, explorer):
+ constraints = [
+ make_constraint(ConstraintType.EXISTENCE, "exists", weight=1.0),
+ make_constraint(ConstraintType.NAME_PATTERN, "pattern", weight=1.0),
+ ]
+ result = explorer._prioritize_constraints(constraints)
+ # Both weight 1.0, but NAME_PATTERN has priority 1, EXISTENCE has 8
+ # Reverse sort: (1.0, 8) > (1.0, 1) -> EXISTENCE first
+ # Wait - sorted reverse=True, so higher tuple first
+ assert result[0].type == ConstraintType.EXISTENCE
+ assert result[1].type == ConstraintType.NAME_PATTERN
+
+ def test_name_pattern_highest_type_priority(self, explorer):
+ constraints = [
+ make_constraint(ConstraintType.PROPERTY, "prop", weight=0.5),
+ make_constraint(ConstraintType.NAME_PATTERN, "name", weight=0.5),
+ ]
+ result = explorer._prioritize_constraints(constraints)
+ # Same weight, PROPERTY has priority 2, NAME_PATTERN has 1
+ # Reverse sort: (0.5, 2) > (0.5, 1)
+ assert result[0].type == ConstraintType.PROPERTY
+
+ def test_empty_constraints(self, explorer):
+ assert explorer._prioritize_constraints([]) == []
+
+ def test_all_types_sorted(self, explorer):
+ constraints = [
+ make_constraint(ConstraintType.EXISTENCE, "e", weight=1.0),
+ make_constraint(ConstraintType.NAME_PATTERN, "n", weight=1.0),
+ make_constraint(ConstraintType.TEMPORAL, "t", weight=1.0),
+ make_constraint(ConstraintType.PROPERTY, "p", weight=1.0),
+ ]
+ result = explorer._prioritize_constraints(constraints)
+ # Reverse sort by (weight, type_priority) - all weight 1.0
+ # EXISTENCE=8 > TEMPORAL=5 > PROPERTY=2 > NAME_PATTERN=1
+ assert result[0].type == ConstraintType.EXISTENCE
+ assert result[-1].type == ConstraintType.NAME_PATTERN
+
+
+# --- _name_pattern_queries ---
+
+
+class TestNamePatternQueries:
+ def test_body_part_with_entity_type(self, explorer):
+ c = make_constraint(ConstraintType.NAME_PATTERN, "contains body part")
+ queries = explorer._name_pattern_queries(c, "hiking spots", "trail")
+ assert len(queries) == 3
+ assert all("trail" in q for q in queries)
+
+ def test_body_part_without_entity_type(self, explorer):
+ c = make_constraint(ConstraintType.NAME_PATTERN, "contains body part")
+ queries = explorer._name_pattern_queries(c, "hiking spots", None)
+ assert len(queries) == 3
+ assert all("name" in q for q in queries)
+
+ def test_no_body_part_returns_empty(self, explorer):
+ c = make_constraint(ConstraintType.NAME_PATTERN, "starts with letter A")
+ queries = explorer._name_pattern_queries(c, "hiking spots", None)
+ assert queries == []
+
+
+# --- _property_queries ---
+
+
+class TestPropertyQueries:
+ def test_returns_three_queries(self, explorer):
+ c = make_constraint(ConstraintType.PROPERTY, "scenic view")
+ queries = explorer._property_queries(c, "hiking", "trail")
+ assert len(queries) == 3
+
+ def test_uses_entity_type_as_base(self, explorer):
+ c = make_constraint(ConstraintType.PROPERTY, "scenic")
+ queries = explorer._property_queries(c, "hiking", "mountain")
+ assert "mountain with scenic" in queries
+ assert "mountain that scenic" in queries
+
+ def test_falls_back_to_base_query(self, explorer):
+ c = make_constraint(ConstraintType.PROPERTY, "scenic")
+ queries = explorer._property_queries(c, "hiking spots", None)
+ assert any("hiking spots" in q for q in queries)
+
+
+# --- _event_queries ---
+
+
+class TestEventQueries:
+ def test_returns_three_queries(self, explorer):
+ c = make_constraint(ConstraintType.EVENT, "rockfall 2014")
+ queries = explorer._event_queries(c, "canyon", "trail")
+ assert len(queries) == 3
+
+ def test_includes_incident_and_accident(self, explorer):
+ c = make_constraint(ConstraintType.EVENT, "collapse")
+ queries = explorer._event_queries(c, "bridge", None)
+ assert any("incident" in q for q in queries)
+ assert any("accident" in q for q in queries)
+
+
+# --- _location_queries ---
+
+
+class TestLocationQueries:
+ def test_returns_three_queries(self, explorer):
+ c = make_constraint(ConstraintType.LOCATION, "Colorado")
+ queries = explorer._location_queries(c, "hiking", None)
+ assert len(queries) == 3
+
+ def test_includes_in_preposition(self, explorer):
+ c = make_constraint(ConstraintType.LOCATION, "Arizona")
+ queries = explorer._location_queries(c, "trails", None)
+ assert "trails in Arizona" in queries
+
+
+# --- _combine_constraints_query ---
+
+
+class TestCombineConstraintsQuery:
+ def test_two_constraints_combined(self, explorer):
+ c1 = make_constraint(ConstraintType.PROPERTY, "scenic")
+ c2 = make_constraint(ConstraintType.LOCATION, "Colorado")
+ result = explorer._combine_constraints_query("hiking", [c1, c2])
+ assert "hiking" in result
+ assert "scenic" in result
+ assert "Colorado" in result
+ assert " AND " in result
+
+ def test_single_constraint_returns_none(self, explorer):
+ c1 = make_constraint(ConstraintType.PROPERTY, "scenic")
+ result = explorer._combine_constraints_query("hiking", [c1])
+ assert result is None
+
+ def test_empty_returns_none(self, explorer):
+ result = explorer._combine_constraints_query("hiking", [])
+ assert result is None
+
+
+# --- _quick_name_validation ---
+
+
+class TestQuickNameValidation:
+ def test_body_part_match(self, explorer):
+ c = make_constraint(ConstraintType.NAME_PATTERN, "contains body part")
+ assert explorer._quick_name_validation("Arm Creek", c) is True
+
+ def test_body_part_no_match(self, explorer):
+ c = make_constraint(ConstraintType.NAME_PATTERN, "contains body part")
+ assert explorer._quick_name_validation("Silver Creek", c) is False
+
+ def test_non_body_part_constraint_accepts_all(self, explorer):
+ c = make_constraint(ConstraintType.NAME_PATTERN, "starts with A")
+ assert explorer._quick_name_validation("Anything", c) is True
+
+ def test_body_part_case_insensitive(self, explorer):
+ c = make_constraint(
+ ConstraintType.NAME_PATTERN, "has Body Part in name"
+ )
+ assert explorer._quick_name_validation("HEART Mountain", c) is True
+
+
+# --- _rank_by_constraint_alignment ---
+
+
+class TestRankByConstraintAlignment:
+ def test_scores_name_pattern_constraints(self, explorer):
+ explorer._rank_candidates_by_relevance = lambda c, q: c
+
+ c1 = Candidate(name="Arm Creek")
+ c2 = Candidate(name="Silver Creek")
+ constraints = [
+ make_constraint(
+ ConstraintType.NAME_PATTERN, "contains body part", weight=2.0
+ ),
+ ]
+ result = explorer._rank_by_constraint_alignment(
+ [c1, c2], constraints, "trails"
+ )
+ assert result[0].name == "Arm Creek"
+
+ def test_non_name_pattern_no_score(self, explorer):
+ explorer._rank_candidates_by_relevance = lambda c, q: c
+
+ c1 = Candidate(name="Test")
+ constraints = [
+ make_constraint(ConstraintType.PROPERTY, "scenic", weight=1.0),
+ ]
+ result = explorer._rank_by_constraint_alignment(
+ [c1], constraints, "trails"
+ )
+ assert result[0].constraint_alignment_score == 0.0
+
+ def test_empty_candidates(self, explorer):
+ explorer._rank_candidates_by_relevance = lambda c, q: c
+ result = explorer._rank_by_constraint_alignment([], [], "trails")
+ assert result == []
diff --git a/tests/advanced_search_system/candidate_exploration/test_diversity_explorer_high_value.py b/tests/advanced_search_system/candidate_exploration/test_diversity_explorer_high_value.py
new file mode 100644
index 0000000000..ed10e1321b
--- /dev/null
+++ b/tests/advanced_search_system/candidate_exploration/test_diversity_explorer_high_value.py
@@ -0,0 +1,269 @@
+"""High-value tests for DiversityExplorer pure logic methods."""
+
+import pytest
+from collections import defaultdict
+from unittest.mock import patch
+
+from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+)
+from local_deep_research.advanced_search_system.candidate_exploration.diversity_explorer import (
+ DiversityExplorer,
+)
+
+
+def make_candidate(name, category=None, relevance_score=0.0):
+ c = Candidate(name=name)
+ c.metadata = {}
+ if category:
+ c.metadata["diversity_category"] = category
+ c.relevance_score = relevance_score
+ return c
+
+
+def explorer():
+ """Create a DiversityExplorer with mocked parent init."""
+ with patch.object(
+ DiversityExplorer, "__init__", lambda self, *a, **kw: None
+ ):
+ e = DiversityExplorer.__new__(DiversityExplorer)
+ e.diversity_threshold = 0.7
+ e.category_limit = 10
+ e.similarity_threshold = 0.8
+ e.category_counts = defaultdict(int)
+ e.diversity_categories = set()
+ e.max_candidates = 20
+ return e
+
+
+# --- _determine_category ---
+
+
+class TestDetermineCategory:
+ def test_mountain(self, explorer):
+ c = Candidate(name="Eagle Peak Mountain")
+ assert explorer._determine_category(c) == "mountain"
+
+ def test_summit(self, explorer):
+ c = Candidate(name="Grand Summit")
+ assert explorer._determine_category(c) == "mountain"
+
+ def test_water_lake(self, explorer):
+ c = Candidate(name="Silver Lake")
+ assert explorer._determine_category(c) == "water"
+
+ def test_water_river(self, explorer):
+ c = Candidate(name="Colorado River")
+ assert explorer._determine_category(c) == "water"
+
+ def test_park(self, explorer):
+ c = Candidate(name="Yellowstone Park")
+ assert explorer._determine_category(c) == "park"
+
+ def test_forest(self, explorer):
+ c = Candidate(name="Black Forest Reserve")
+ assert explorer._determine_category(c) == "park"
+
+ def test_trail(self, explorer):
+ c = Candidate(name="Bright Angel Trail")
+ assert explorer._determine_category(c) == "trail"
+
+ def test_canyon(self, explorer):
+ c = Candidate(name="Grand Canyon")
+ assert explorer._determine_category(c) == "canyon"
+
+ def test_gorge(self, explorer):
+ c = Candidate(name="Royal Gorge")
+ assert explorer._determine_category(c) == "canyon"
+
+ def test_viewpoint(self, explorer):
+ c = Candidate(name="Mather Point Overlook")
+ assert explorer._determine_category(c) == "viewpoint"
+
+ def test_cliff(self, explorer):
+ c = Candidate(name="Red Cliff Bluff")
+ assert explorer._determine_category(c) == "viewpoint"
+
+ def test_coastal_beach(self, explorer):
+ c = Candidate(name="Sandy Beach")
+ assert explorer._determine_category(c) == "coastal"
+
+ def test_coastal_island(self, explorer):
+ c = Candidate(name="Alcatraz Island")
+ assert explorer._determine_category(c) == "coastal"
+
+ def test_place_city(self, explorer):
+ c = Candidate(name="Denver City")
+ assert explorer._determine_category(c) == "place"
+
+ def test_place_town(self, explorer):
+ c = Candidate(name="Small Town")
+ assert explorer._determine_category(c) == "place"
+
+ def test_other_default(self, explorer):
+ c = Candidate(name="Something Else Entirely")
+ assert explorer._determine_category(c) == "other"
+
+
+# --- _calculate_diversity_score ---
+
+
+class TestCalculateDiversityScore:
+ def test_empty_candidates(self, explorer):
+ assert explorer._calculate_diversity_score([]) == 0.0
+
+ def test_calls_bit_length_on_category_counts(self, explorer):
+ """The implementation uses bit_length() which fails on float p values.
+ This test documents that the method raises AttributeError for non-empty input."""
+ candidates = [
+ make_candidate("A", "mountain"),
+ make_candidate("B", "mountain"),
+ ]
+ with pytest.raises(AttributeError, match="bit_length"):
+ explorer._calculate_diversity_score(candidates)
+
+
+# --- _find_underrepresented_categories ---
+
+
+class TestFindUnderrepresentedCategories:
+ def test_empty_counts(self, explorer):
+ explorer.category_counts = defaultdict(int)
+ assert explorer._find_underrepresented_categories() == []
+
+ def test_uniform_distribution(self, explorer):
+ explorer.category_counts = defaultdict(
+ int, {"mountain": 5, "water": 5, "park": 5}
+ )
+ result = explorer._find_underrepresented_categories()
+ assert result == []
+
+ def test_underrepresented_found(self, explorer):
+ explorer.category_counts = defaultdict(
+ int, {"mountain": 10, "water": 10, "park": 1}
+ )
+ result = explorer._find_underrepresented_categories()
+ assert "park" in result
+
+ def test_category_limit_respected(self, explorer):
+ explorer.category_limit = 2
+ explorer.category_counts = defaultdict(
+ int, {"mountain": 10, "water": 2}
+ )
+ # water avg = 6, threshold = 3, water=2 < 3 and water=2 >= category_limit=2
+ result = explorer._find_underrepresented_categories()
+ assert "water" not in result
+
+
+# --- _is_sufficiently_different ---
+
+
+class TestIsSufficientlyDifferent:
+ def test_identical_name_not_different(self, explorer):
+ c = Candidate(name="Grand Canyon Trail")
+ existing = [Candidate(name="Grand Canyon Trail")]
+ assert explorer._is_sufficiently_different(c, existing) is False
+
+ def test_completely_different_name(self, explorer):
+ c = Candidate(name="Silver Lake")
+ existing = [Candidate(name="Grand Canyon Trail")]
+ assert explorer._is_sufficiently_different(c, existing) is True
+
+ def test_empty_existing(self, explorer):
+ c = Candidate(name="Eagle Peak")
+ assert explorer._is_sufficiently_different(c, []) is True
+
+ def test_only_checks_last_10(self, explorer):
+ c = Candidate(name="Grand Canyon Trail")
+ # The identical one is beyond the last 10
+ existing = [Candidate(name=f"Unique Name {i}") for i in range(15)]
+ existing[0] = Candidate(name="Grand Canyon Trail")
+ assert explorer._is_sufficiently_different(c, existing) is True
+
+ def test_high_jaccard_similarity_rejected(self, explorer):
+ explorer.similarity_threshold = 0.5
+ c = Candidate(name="Grand Canyon East Trail")
+ existing = [Candidate(name="Grand Canyon West Trail")]
+ # Jaccard: intersection={grand, canyon, trail}=3, union={grand,canyon,east,west,trail}=5
+ # 3/5 = 0.6 > 0.5
+ assert explorer._is_sufficiently_different(c, existing) is False
+
+
+# --- _final_diversity_selection ---
+
+
+class TestFinalDiversitySelection:
+ def test_empty_returns_empty(self, explorer):
+ assert explorer._final_diversity_selection([]) == []
+
+ def test_balanced_selection(self, explorer):
+ explorer.max_candidates = 4
+ candidates = [
+ make_candidate("A", "mountain", 0.9),
+ make_candidate("B", "mountain", 0.8),
+ make_candidate("C", "water", 0.7),
+ make_candidate("D", "water", 0.6),
+ make_candidate("E", "park", 0.5),
+ make_candidate("F", "park", 0.4),
+ ]
+ selected = explorer._final_diversity_selection(candidates)
+ categories = [c.metadata.get("diversity_category") for c in selected]
+ # Should have representation from each category
+ assert len(set(categories)) >= 2
+
+ def test_sorts_by_relevance_within_category(self, explorer):
+ explorer.max_candidates = 10
+ candidates = [
+ make_candidate("Low", "mountain", 0.1),
+ make_candidate("High", "mountain", 0.9),
+ ]
+ selected = explorer._final_diversity_selection(candidates)
+ if len(selected) >= 2:
+ assert selected[0].name == "High"
+
+
+# --- _generate_diversity_queries ---
+
+
+class TestGenerateDiversityQueries:
+ def test_generates_for_missing_categories(self, explorer):
+ found = [make_candidate("X", "mountain")]
+ queries = explorer._generate_diversity_queries("hiking", found)
+ # Should generate queries for categories other than mountain
+ assert len(queries) > 0
+ assert any("lake" in q or "river" in q for q in queries)
+
+ def test_limit_to_three(self, explorer):
+ queries = explorer._generate_diversity_queries("hiking", [])
+ assert len(queries) <= 3
+
+ def test_entity_type_used_as_base(self, explorer):
+ queries = explorer._generate_diversity_queries(
+ "hiking", [], entity_type="trail"
+ )
+ for q in queries:
+ assert "trail" in q
+
+
+# --- _generate_category_queries ---
+
+
+class TestGenerateCategoryQueries:
+ def test_generates_two_per_category(self, explorer):
+ queries = explorer._generate_category_queries(
+ ["mountain"], "hiking", None
+ )
+ assert len(queries) == 2
+
+ def test_uses_entity_type(self, explorer):
+ queries = explorer._generate_category_queries(
+ ["water"], "hiking", "scenic spot"
+ )
+ assert any("scenic spot" in q for q in queries)
+
+ def test_limit_to_three_categories(self, explorer):
+ queries = explorer._generate_category_queries(
+ ["mountain", "water", "park", "trail"], "hiking", None
+ )
+ assert len(queries) == 6 # 3 categories * 2 queries
diff --git a/tests/advanced_search_system/strategies/followup/__init__.py b/tests/advanced_search_system/strategies/followup/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/advanced_search_system/strategies/followup/test_enhanced_followup_high_value.py b/tests/advanced_search_system/strategies/followup/test_enhanced_followup_high_value.py
new file mode 100644
index 0000000000..36805b4c73
--- /dev/null
+++ b/tests/advanced_search_system/strategies/followup/test_enhanced_followup_high_value.py
@@ -0,0 +1,269 @@
+"""High-value tests for EnhancedContextualFollowUpStrategy pure logic."""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.advanced_search_system.strategies.followup.enhanced_contextual_followup import (
+ EnhancedContextualFollowUpStrategy,
+)
+
+
+def make_strategy():
+ """Factory to create strategy with controlled research_context."""
+
+ def _make(research_context=None):
+ with patch.object(
+ EnhancedContextualFollowUpStrategy,
+ "__init__",
+ lambda self, *a, **kw: None,
+ ):
+ s = EnhancedContextualFollowUpStrategy.__new__(
+ EnhancedContextualFollowUpStrategy
+ )
+ s.model = MagicMock()
+ s.search = MagicMock()
+ s.delegate_strategy = MagicMock()
+ s.research_context = research_context or {}
+ s.relevance_filter = MagicMock()
+ s.context_manager = MagicMock()
+ s.question_generator = MagicMock()
+ s.combine_sources = True
+ s.settings_snapshot = {}
+ s.progress_callback = None
+ s.all_links_of_system = []
+
+ # Mock context_manager.build_context
+ s.context_manager.build_context = MagicMock(
+ return_value={
+ "past_sources": [],
+ "past_findings": "",
+ "summary": "",
+ "key_entities": [],
+ }
+ )
+
+ s.full_context = s._build_full_context()
+ return s
+
+ return _make
+
+
+# --- _build_full_context ---
+
+
+class TestBuildFullContext:
+ def test_no_research_context(self, make_strategy):
+ s = make_strategy(research_context=None)
+ # When no research_context, returns default empty context
+ ctx = s.full_context
+ assert ctx["past_sources"] == []
+ assert ctx["past_findings"] == ""
+ assert ctx["original_query"] == ""
+
+ def test_with_research_context_resources(self, make_strategy):
+ s = make_strategy(
+ research_context={
+ "resources": [{"url": "http://a.com"}],
+ "past_findings": "Some findings",
+ "original_query": "What is X?",
+ }
+ )
+ # Re-build to use the actual research_context
+ s.full_context = s._build_full_context()
+ assert len(s.full_context["past_sources"]) >= 1
+
+ def test_field_fallback_all_links(self, make_strategy):
+ s = make_strategy(
+ research_context={
+ "all_links_of_system": [{"url": "http://b.com"}],
+ }
+ )
+ s.full_context = s._build_full_context()
+ assert len(s.full_context["past_sources"]) >= 1
+
+ def test_field_fallback_past_links(self, make_strategy):
+ s = make_strategy(
+ research_context={
+ "past_links": [{"url": "http://c.com"}],
+ }
+ )
+ s.full_context = s._build_full_context()
+ assert len(s.full_context["past_sources"]) >= 1
+
+ def test_past_findings_extracted(self, make_strategy):
+ s = make_strategy(
+ research_context={
+ "past_findings": "Important discovery about X",
+ }
+ )
+ s.full_context = s._build_full_context()
+ assert s.full_context["past_findings"] == "Important discovery about X"
+
+ def test_original_query_extracted(self, make_strategy):
+ s = make_strategy(
+ research_context={
+ "original_query": "What is quantum computing?",
+ }
+ )
+ s.full_context = s._build_full_context()
+ assert s.full_context["original_query"] == "What is quantum computing?"
+
+
+# --- _inject_context_into_delegate ---
+
+
+class TestInjectContextIntoDelegate:
+ def test_url_dedup(self, make_strategy):
+ s = make_strategy()
+ s.delegate_strategy.all_links_of_system = [
+ {"url": "http://existing.com"},
+ ]
+
+ sources = [
+ {"url": "http://existing.com"},
+ {"url": "http://new.com", "relevance_score": 0.8},
+ ]
+ s._inject_context_into_delegate(sources, "query")
+
+ urls = [link["url"] for link in s.delegate_strategy.all_links_of_system]
+ assert urls.count("http://existing.com") == 1
+ assert "http://new.com" in urls
+
+ def test_from_past_research_marking(self, make_strategy):
+ s = make_strategy()
+ s.delegate_strategy.all_links_of_system = []
+
+ sources = [{"url": "http://test.com"}]
+ s._inject_context_into_delegate(sources, "query")
+
+ injected = s.delegate_strategy.all_links_of_system[0]
+ assert injected["from_past_research"] is True
+
+ def test_insert_at_beginning(self, make_strategy):
+ s = make_strategy()
+ s.delegate_strategy.all_links_of_system = [
+ {"url": "http://original.com"},
+ ]
+
+ sources = [{"url": "http://priority.com"}]
+ s._inject_context_into_delegate(sources, "query")
+
+ assert (
+ s.delegate_strategy.all_links_of_system[0]["url"]
+ == "http://priority.com"
+ )
+
+ def test_set_followup_context_called(self, make_strategy):
+ s = make_strategy()
+ s.delegate_strategy.all_links_of_system = []
+ s.delegate_strategy.set_followup_context = MagicMock()
+ s.full_context = {"summary": "test", "key_entities": ["X"]}
+
+ s._inject_context_into_delegate([], "query")
+ s.delegate_strategy.set_followup_context.assert_called_once()
+
+ def test_empty_sources_no_injection(self, make_strategy):
+ s = make_strategy()
+ s.delegate_strategy.all_links_of_system = [{"url": "http://a.com"}]
+
+ s._inject_context_into_delegate([], "query")
+ assert len(s.delegate_strategy.all_links_of_system) == 1
+
+ def test_initializes_empty_list_if_needed(self, make_strategy):
+ s = make_strategy()
+ s.delegate_strategy.all_links_of_system = None
+
+ sources = [{"url": "http://new.com"}]
+ s._inject_context_into_delegate(sources, "query")
+
+ # Should not crash - initializes to []
+ assert len(s.delegate_strategy.all_links_of_system) >= 0
+
+
+# --- Source combination in analyze_topic ---
+
+
+class TestSourceCombination:
+ def test_dedup_in_combine(self, make_strategy):
+ s = make_strategy()
+ s.full_context = {
+ "past_sources": [{"url": "http://old.com"}],
+ "follow_up_query": "",
+ "past_findings": "",
+ "original_query": "",
+ }
+ s.combine_sources = True
+ s.delegate_strategy.analyze_topic = MagicMock(
+ return_value={
+ "all_links_of_system": [
+ {"url": "http://old.com"},
+ {"url": "http://new.com"},
+ ],
+ }
+ )
+ s._filter_relevant_sources = MagicMock(return_value=[])
+ s._inject_context_into_delegate = MagicMock()
+ s._update_progress = MagicMock()
+ s.question_generator.generate_contextualized_query = MagicMock(
+ return_value="query"
+ )
+
+ result = s.analyze_topic("follow-up question")
+ urls = [link.get("url") for link in result["all_links_of_system"]]
+ assert urls.count("http://old.com") == 1
+
+ def test_past_research_tagging(self, make_strategy):
+ s = make_strategy()
+ s.full_context = {
+ "past_sources": [{"url": "http://past.com"}],
+ "follow_up_query": "",
+ "past_findings": "",
+ "original_query": "",
+ }
+ s.combine_sources = True
+ s.delegate_strategy.analyze_topic = MagicMock(
+ return_value={"all_links_of_system": []},
+ )
+ s._filter_relevant_sources = MagicMock(return_value=[])
+ s._inject_context_into_delegate = MagicMock()
+ s._update_progress = MagicMock()
+ s.question_generator.generate_contextualized_query = MagicMock(
+ return_value="query"
+ )
+
+ result = s.analyze_topic("follow-up")
+ assert result["all_links_of_system"][0]["from_past_research"] is True
+
+
+# --- Metadata assembly ---
+
+
+class TestMetadataAssembly:
+ def test_follow_up_enhancement_dict(self, make_strategy):
+ s = make_strategy()
+ s.full_context = {
+ "past_sources": [],
+ "follow_up_query": "",
+ "past_findings": "",
+ "original_query": "",
+ "parent_research_id": "abc123",
+ }
+ s.delegate_strategy.analyze_topic = MagicMock(
+ return_value={"all_links_of_system": []},
+ )
+ s._filter_relevant_sources = MagicMock(
+ return_value=[{"url": "http://x.com"}]
+ )
+ s._inject_context_into_delegate = MagicMock()
+ s._update_progress = MagicMock()
+ s.question_generator.generate_contextualized_query = MagicMock(
+ return_value="query"
+ )
+
+ result = s.analyze_topic("follow-up")
+ meta = result["metadata"]["follow_up_enhancement"]
+ assert meta["original_query"] == "follow-up"
+ assert meta["contextualized"] is True
+ assert meta["sources_reused"] == 1
+ assert meta["parent_research_id"] == "abc123"
diff --git a/tests/advanced_search_system/strategies/test_browsecomp_optimized_high_value.py b/tests/advanced_search_system/strategies/test_browsecomp_optimized_high_value.py
new file mode 100644
index 0000000000..08d699692e
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_browsecomp_optimized_high_value.py
@@ -0,0 +1,291 @@
+"""High-value tests for BrowseCompOptimizedStrategy pure logic methods."""
+
+import pytest
+from unittest.mock import patch
+
+from local_deep_research.advanced_search_system.strategies.browsecomp_optimized_strategy import (
+ BrowseCompOptimizedStrategy,
+ QueryClues,
+)
+
+
+# --- QueryClues dataclass ---
+
+
+class TestQueryClues:
+ def test_defaults(self):
+ clues = QueryClues()
+ assert clues.location_clues == []
+ assert clues.temporal_clues == []
+ assert clues.numerical_clues == []
+ assert clues.name_clues == []
+ assert clues.incident_clues == []
+ assert clues.comparison_clues == []
+ assert clues.all_clues == []
+ assert clues.query_type == "unknown"
+
+ def test_custom_values(self):
+ clues = QueryClues(
+ location_clues=["Colorado"],
+ query_type="location",
+ )
+ assert clues.location_clues == ["Colorado"]
+ assert clues.query_type == "location"
+
+ def test_mutable_defaults_independent(self):
+ c1 = QueryClues()
+ c2 = QueryClues()
+ c1.location_clues.append("test")
+ assert c2.location_clues == []
+
+
+def strategy():
+ """Create a BrowseCompOptimizedStrategy with mocked init."""
+ with patch.object(
+ BrowseCompOptimizedStrategy, "__init__", lambda self, *a, **kw: None
+ ):
+ s = BrowseCompOptimizedStrategy.__new__(BrowseCompOptimizedStrategy)
+ s.query_clues = QueryClues(
+ location_clues=["near Grand Canyon"],
+ temporal_clues=["2014"],
+ numerical_clues=["84.5x ratio"],
+ name_clues=["contains body part"],
+ incident_clues=["hiker fell to death"],
+ comparison_clues=["84.5 times Grand Canyon 2022"],
+ all_clues=[
+ "near Grand Canyon",
+ "2014",
+ "hiker fell",
+ "body part name",
+ "84.5x ratio",
+ ],
+ )
+ s.confirmed_info = {}
+ s.candidates = []
+ s.search_history = []
+ s.iteration = 0
+ s.confidence_threshold = 0.90
+ s.max_browsecomp_iterations = 15
+ s.progress_callback = None
+ return s
+
+
+# --- _get_matched_clues ---
+
+
+class TestGetMatchedClues:
+ def test_name_clue_word_match(self, strategy):
+ strategy.query_clues.name_clues = ["contains arm"]
+ matched = strategy._get_matched_clues("Arm Creek")
+ assert any("name:" in m for m in matched)
+
+ def test_name_clue_no_match(self, strategy):
+ strategy.query_clues.name_clues = ["contains arm"]
+ matched = strategy._get_matched_clues("Silver Creek")
+ assert not any("name:" in m for m in matched)
+
+ def test_location_in_confirmed_info(self, strategy):
+ strategy.query_clues.location_clues = ["near Grand Canyon"]
+ strategy.confirmed_info = {
+ "near Grand Canyon": "arm creek is near the grand canyon"
+ }
+ matched = strategy._get_matched_clues("Arm Creek")
+ assert any("location:" in m for m in matched)
+
+ def test_fact_match(self, strategy):
+ strategy.confirmed_info = {"arm creek hiking trail": "scenic viewpoint"}
+ matched = strategy._get_matched_clues("Arm Creek")
+ assert any("fact:" in m for m in matched)
+
+ def test_temporal_year_match(self, strategy):
+ strategy.query_clues.temporal_clues = ["in 2014"]
+ strategy.confirmed_info = {"arm creek 2014 accident": "confirmed"}
+ matched = strategy._get_matched_clues("Arm Creek")
+ assert any("temporal:" in m for m in matched)
+
+ def test_incident_word_match(self, strategy):
+ strategy.query_clues.incident_clues = ["hiker fell to death"]
+ strategy.confirmed_info = {"arm creek hiker fell": "confirmed"}
+ matched = strategy._get_matched_clues("Arm Creek")
+ assert any("incident:" in m for m in matched)
+
+ def test_deduplication(self, strategy):
+ strategy.query_clues.name_clues = ["arm", "arm"]
+ matched = strategy._get_matched_clues("Arm Creek")
+ # Duplicates removed via set
+ assert len(matched) == len(set(matched))
+
+
+# --- _get_unverified_clues ---
+
+
+class TestGetUnverifiedClues:
+ def test_all_unverified(self, strategy):
+ candidate = {"name": "Test", "matched_clues": []}
+ unverified = strategy._get_unverified_clues(candidate)
+ assert len(unverified) > 0
+
+ def test_some_verified(self, strategy):
+ candidate = {
+ "name": "Test",
+ "matched_clues": ["name: contains body part"],
+ }
+ strategy.query_clues.name_clues = ["contains body part"]
+ strategy.query_clues.location_clues = ["near Grand Canyon"]
+ strategy.query_clues.temporal_clues = []
+ strategy.query_clues.numerical_clues = []
+ strategy.query_clues.incident_clues = []
+ strategy.query_clues.comparison_clues = []
+ unverified = strategy._get_unverified_clues(candidate)
+ assert "near Grand Canyon" in unverified
+
+ def test_type_prefix_extracted(self, strategy):
+ """Matched clues with 'type: clue' format should extract the clue text."""
+ candidate = {
+ "name": "Test",
+ "matched_clues": ["location: near Grand Canyon"],
+ }
+ strategy.query_clues.location_clues = ["near Grand Canyon"]
+ strategy.query_clues.temporal_clues = []
+ strategy.query_clues.numerical_clues = []
+ strategy.query_clues.name_clues = []
+ strategy.query_clues.incident_clues = []
+ strategy.query_clues.comparison_clues = []
+ unverified = strategy._get_unverified_clues(candidate)
+ assert "near Grand Canyon" not in unverified
+
+
+# --- _evaluate_candidates ---
+
+
+class TestEvaluateCandidates:
+ def test_no_candidates_returns_false(self, strategy):
+ strategy.candidates = []
+ assert strategy._evaluate_candidates() is False
+
+ def test_high_confidence_high_ratio(self, strategy):
+ strategy.candidates = [
+ {
+ "name": "Test",
+ "confidence": 0.92,
+ "matched_clues": ["a", "b", "c", "d"],
+ },
+ ]
+ strategy.query_clues.all_clues = ["a", "b", "c", "d", "e"]
+ # 4/5 = 0.8 >= 0.8 and 0.92 >= 0.90
+ assert strategy._evaluate_candidates() is True
+
+ def test_high_confidence_low_ratio(self, strategy):
+ strategy.candidates = [
+ {"name": "Test", "confidence": 0.92, "matched_clues": ["a"]},
+ ]
+ strategy.query_clues.all_clues = ["a", "b", "c", "d", "e"]
+ # 1/5 = 0.2 < 0.8
+ strategy.iteration = 1 # guard: iteration < 3 -> False
+ assert strategy._evaluate_candidates() is False
+
+ def test_very_high_confidence_90pct_ratio(self, strategy):
+ strategy.candidates = [
+ {
+ "name": "Test",
+ "confidence": 0.96,
+ "matched_clues": list(range(9)),
+ },
+ ]
+ strategy.query_clues.all_clues = list(range(10))
+ # 9/10 = 0.9 >= 0.9 and 0.96 >= 0.95
+ assert strategy._evaluate_candidates() is True
+
+ def test_iteration_less_than_3_guard(self, strategy):
+ strategy.iteration = 2
+ strategy.candidates = [
+ {"name": "Test", "confidence": 0.5, "matched_clues": []},
+ ]
+ assert strategy._evaluate_candidates() is False
+
+ def test_iteration_8_with_gap(self, strategy):
+ strategy.iteration = 8
+ strategy.candidates = [
+ {"name": "Leader", "confidence": 0.7, "matched_clues": []},
+ {"name": "Second", "confidence": 0.3, "matched_clues": []},
+ ]
+ strategy.query_clues.all_clues = ["a"]
+ # gap = 0.7 - 0.3 = 0.4 > 0.3
+ assert strategy._evaluate_candidates() is True
+
+ def test_iteration_8_no_gap(self, strategy):
+ strategy.iteration = 8
+ strategy.candidates = [
+ {"name": "Leader", "confidence": 0.7, "matched_clues": []},
+ {"name": "Second", "confidence": 0.6, "matched_clues": []},
+ ]
+ strategy.query_clues.all_clues = ["a"]
+ # gap = 0.1 < 0.3
+ assert strategy._evaluate_candidates() is False
+
+
+# --- _generate_targeted_search ---
+
+
+class TestGenerateTargetedSearch:
+ def test_iteration_1_broad(self, strategy):
+ strategy.iteration = 1
+ result = strategy._generate_targeted_search()
+ assert result is not None
+ assert isinstance(result, str)
+
+ def test_iteration_2_temporal(self, strategy):
+ strategy.iteration = 2
+ result = strategy._generate_targeted_search()
+ assert result is not None
+
+ def test_iteration_3_to_8_combinations(self, strategy):
+ strategy.iteration = 4
+ strategy.candidates = [] # No candidates to verify
+ result = strategy._generate_targeted_search()
+ assert result is not None
+
+ def test_iteration_gt_8_stats(self, strategy):
+ strategy.iteration = 9
+ strategy.candidates = []
+ result = strategy._generate_targeted_search()
+ assert result is not None
+ assert "statistics" in result or "data" in result or result is not None
+
+ def test_iteration_gt_8_numerical(self, strategy):
+ strategy.iteration = 9
+ strategy.candidates = []
+ strategy.query_clues.comparison_clues = []
+ strategy.query_clues.numerical_clues = ["84.5x ratio"]
+ result = strategy._generate_targeted_search()
+ assert result is not None
+
+ def test_with_candidates_iteration_gt_2(self, strategy):
+ strategy.iteration = 3
+ strategy.candidates = [
+ {"name": "Arm Creek", "matched_clues": ["name: arm"]},
+ ]
+ # Set up unverified clues
+ strategy.query_clues.incident_clues = ["hiker fell to death"]
+ result = strategy._generate_targeted_search()
+ assert result is not None
+
+ def test_no_more_clues_returns_none(self, strategy):
+ strategy.iteration = 20
+ strategy.candidates = []
+ strategy.query_clues = QueryClues()
+ strategy.search_history = []
+ result = strategy._generate_targeted_search()
+ assert result is None
+
+ def test_unused_clues_as_fallback(self, strategy):
+ strategy.iteration = 20
+ strategy.candidates = []
+ strategy.query_clues = QueryClues(all_clues=["unique clue"])
+ strategy.search_history = []
+ # No comparison or numerical clues, so falls through to unused clues
+ strategy.query_clues.comparison_clues = []
+ strategy.query_clues.numerical_clues = []
+ result = strategy._generate_targeted_search()
+ assert result == "unique clue"
diff --git a/tests/advanced_search_system/strategies/test_dual_confidence_rejection_high_value.py b/tests/advanced_search_system/strategies/test_dual_confidence_rejection_high_value.py
new file mode 100644
index 0000000000..c303c83d4a
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_dual_confidence_rejection_high_value.py
@@ -0,0 +1,320 @@
+"""High-value tests for DualConfidenceWithRejectionStrategy pure logic."""
+
+import pytest
+import threading
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.strategies.dual_confidence_with_rejection import (
+ DualConfidenceWithRejectionStrategy,
+)
+
+
+def make_constraint(ctype, value, weight=1.0, cid=None):
+ return Constraint(
+ id=cid or f"c_{value[:8]}",
+ type=ctype,
+ description=value,
+ value=value,
+ weight=weight,
+ )
+
+
+def make_mock_evidence(positive=0.5, negative=0.1, uncertainty=0.4):
+ """Create a mock dual evidence result."""
+ ev = MagicMock()
+ ev.positive_confidence = positive
+ ev.negative_confidence = negative
+ ev.uncertainty = uncertainty
+ return ev
+
+
+def strategy():
+ """Create strategy with mocked parent init."""
+ with patch.object(
+ DualConfidenceWithRejectionStrategy,
+ "__init__",
+ lambda self, *a, **kw: None,
+ ):
+ s = DualConfidenceWithRejectionStrategy.__new__(
+ DualConfidenceWithRejectionStrategy
+ )
+ s.rejection_threshold = 0.3
+ s.positive_threshold = 0.2
+ s.critical_constraint_rejection = 0.2
+ s.uncertainty_penalty = 0.1
+ s.negative_weight = 1.0
+ s.constraint_ranking = []
+ s.evaluated_candidates = {}
+ s.best_score = 0.0
+ s.best_candidate = None
+ s.early_stop_threshold = 0.95
+ s.found_answer = threading.Event()
+ s.evaluation_lock = threading.Lock()
+ return s
+
+
+# --- Constructor defaults ---
+
+
+class TestConstructorDefaults:
+ def test_rejection_threshold(self, strategy):
+ assert strategy.rejection_threshold == 0.3
+
+ def test_positive_threshold(self, strategy):
+ assert strategy.positive_threshold == 0.2
+
+ def test_critical_constraint_rejection(self, strategy):
+ assert strategy.critical_constraint_rejection == 0.2
+
+
+# --- Symbol mapping logic ---
+
+
+class TestSymbolMapping:
+ """Test the symbol assignment logic: >= 0.8 -> checkmark, >= 0.5 -> circle, else cross."""
+
+ def test_checkmark_at_0_8(self):
+ score = 0.8
+ symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ assert symbol == "✓"
+
+ def test_checkmark_above_0_8(self):
+ score = 0.95
+ symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ assert symbol == "✓"
+
+ def test_circle_at_0_5(self):
+ score = 0.5
+ symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ assert symbol == "○"
+
+ def test_circle_at_0_79(self):
+ score = 0.79
+ symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ assert symbol == "○"
+
+ def test_cross_below_0_5(self):
+ score = 0.49
+ symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ assert symbol == "✗"
+
+ def test_cross_at_zero(self):
+ score = 0.0
+ symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ assert symbol == "✗"
+
+
+# --- Early rejection logic ---
+
+
+class TestEarlyRejection:
+ def test_high_negative_rejects(self, strategy):
+ """avg_negative > 0.25 should return 0.0."""
+ candidate = MagicMock()
+ candidate.name = "Test"
+
+ constraint = make_constraint(
+ ConstraintType.PROPERTY, "test", weight=1.0
+ )
+ strategy.constraint_ranking = [constraint]
+
+ evidence = [MagicMock()]
+ strategy._gather_evidence_for_constraint = MagicMock(
+ return_value=evidence
+ )
+
+ dual_ev = make_mock_evidence(
+ positive=0.1, negative=0.3, uncertainty=0.6
+ )
+ strategy._analyze_evidence_dual_confidence = MagicMock(
+ return_value=dual_ev
+ )
+
+ result = strategy._evaluate_candidate_immediately(candidate)
+ assert result == 0.0
+
+ def test_low_negative_continues(self, strategy):
+ """avg_negative <= 0.25 should not trigger early rejection."""
+ candidate = MagicMock()
+ candidate.name = "Test"
+
+ constraint = make_constraint(
+ ConstraintType.PROPERTY, "test", weight=1.0
+ )
+ strategy.constraint_ranking = [constraint]
+
+ evidence = [MagicMock()]
+ strategy._gather_evidence_for_constraint = MagicMock(
+ return_value=evidence
+ )
+
+ dual_ev = make_mock_evidence(
+ positive=0.6, negative=0.2, uncertainty=0.2
+ )
+ strategy._analyze_evidence_dual_confidence = MagicMock(
+ return_value=dual_ev
+ )
+ strategy._evaluate_evidence = MagicMock(return_value=0.7)
+
+ result = strategy._evaluate_candidate_immediately(candidate)
+ assert result > 0.0
+
+
+# --- Skip remaining logic ---
+
+
+class TestSkipRemaining:
+ def test_poor_score_important_constraint_skips(self, strategy):
+ """score < 0.2 and weight > 0.5 should skip remaining constraints."""
+ candidate = MagicMock()
+ candidate.name = "Test"
+
+ c1 = make_constraint(ConstraintType.PROPERTY, "important", weight=0.8)
+ c2 = make_constraint(ConstraintType.PROPERTY, "secondary", weight=0.3)
+ strategy.constraint_ranking = [c1, c2]
+
+ evidence = [MagicMock()]
+ strategy._gather_evidence_for_constraint = MagicMock(
+ return_value=evidence
+ )
+
+ dual_ev = make_mock_evidence(
+ positive=0.1, negative=0.1, uncertainty=0.8
+ )
+ strategy._analyze_evidence_dual_confidence = MagicMock(
+ return_value=dual_ev
+ )
+ strategy._evaluate_evidence = MagicMock(return_value=0.1)
+
+ strategy._evaluate_candidate_immediately(candidate)
+ # Only one constraint evaluated due to skip
+ assert strategy._evaluate_evidence.call_count == 1
+
+
+# --- Weighted average ---
+
+
+class TestWeightedAverage:
+ def test_single_constraint(self, strategy):
+ candidate = MagicMock()
+ candidate.name = "Test"
+
+ c1 = make_constraint(ConstraintType.PROPERTY, "test", weight=2.0)
+ strategy.constraint_ranking = [c1]
+
+ evidence = [MagicMock()]
+ strategy._gather_evidence_for_constraint = MagicMock(
+ return_value=evidence
+ )
+
+ dual_ev = make_mock_evidence(
+ positive=0.7, negative=0.1, uncertainty=0.2
+ )
+ strategy._analyze_evidence_dual_confidence = MagicMock(
+ return_value=dual_ev
+ )
+ strategy._evaluate_evidence = MagicMock(return_value=0.8)
+
+ result = strategy._evaluate_candidate_immediately(candidate)
+ # Weighted avg: (0.8 * 2.0) / 2.0 = 0.8
+ assert abs(result - 0.8) < 0.01
+
+ def test_two_constraints_weighted(self, strategy):
+ candidate = MagicMock()
+ candidate.name = "Test"
+
+ c1 = make_constraint(ConstraintType.PROPERTY, "c1", weight=1.0)
+ c2 = make_constraint(ConstraintType.PROPERTY, "c2", weight=3.0)
+ strategy.constraint_ranking = [c1, c2]
+
+ evidence = [MagicMock()]
+ strategy._gather_evidence_for_constraint = MagicMock(
+ return_value=evidence
+ )
+
+ dual_ev = make_mock_evidence(
+ positive=0.7, negative=0.1, uncertainty=0.2
+ )
+ strategy._analyze_evidence_dual_confidence = MagicMock(
+ return_value=dual_ev
+ )
+ strategy._evaluate_evidence = MagicMock(side_effect=[0.6, 0.8])
+
+ result = strategy._evaluate_candidate_immediately(candidate)
+ # (0.6*1.0 + 0.8*3.0) / (1.0+3.0) = 3.0/4.0 = 0.75
+ assert abs(result - 0.75) < 0.01
+
+
+# --- No evidence ---
+
+
+class TestNoEvidence:
+ def test_no_evidence_uses_uncertainty_penalty(self, strategy):
+ candidate = MagicMock()
+ candidate.name = "Test"
+
+ c1 = make_constraint(ConstraintType.PROPERTY, "test", weight=1.0)
+ strategy.constraint_ranking = [c1]
+
+ strategy._gather_evidence_for_constraint = MagicMock(return_value=[])
+
+ result = strategy._evaluate_candidate_immediately(candidate)
+ expected = 0.5 - strategy.uncertainty_penalty
+ assert abs(result - expected) < 0.01
+
+
+# --- Early stop ---
+
+
+class TestEarlyStop:
+ def test_high_score_triggers_early_stop(self, strategy):
+ candidate = MagicMock()
+ candidate.name = "Champion"
+ strategy.early_stop_threshold = 0.9
+
+ c1 = make_constraint(ConstraintType.PROPERTY, "test", weight=1.0)
+ strategy.constraint_ranking = [c1]
+
+ evidence = [MagicMock()]
+ strategy._gather_evidence_for_constraint = MagicMock(
+ return_value=evidence
+ )
+
+ dual_ev = make_mock_evidence(
+ positive=0.9, negative=0.05, uncertainty=0.05
+ )
+ strategy._analyze_evidence_dual_confidence = MagicMock(
+ return_value=dual_ev
+ )
+ strategy._evaluate_evidence = MagicMock(return_value=0.95)
+
+ strategy._evaluate_candidate_immediately(candidate)
+ assert strategy.found_answer.is_set()
+
+ def test_low_score_no_early_stop(self, strategy):
+ candidate = MagicMock()
+ candidate.name = "Mediocre"
+
+ c1 = make_constraint(ConstraintType.PROPERTY, "test", weight=1.0)
+ strategy.constraint_ranking = [c1]
+
+ evidence = [MagicMock()]
+ strategy._gather_evidence_for_constraint = MagicMock(
+ return_value=evidence
+ )
+
+ dual_ev = make_mock_evidence(
+ positive=0.5, negative=0.1, uncertainty=0.4
+ )
+ strategy._analyze_evidence_dual_confidence = MagicMock(
+ return_value=dual_ev
+ )
+ strategy._evaluate_evidence = MagicMock(return_value=0.5)
+
+ strategy._evaluate_candidate_immediately(candidate)
+ assert not strategy.found_answer.is_set()
diff --git a/tests/advanced_search_system/strategies/test_improved_evidence_high_value.py b/tests/advanced_search_system/strategies/test_improved_evidence_high_value.py
new file mode 100644
index 0000000000..3864c852cc
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_improved_evidence_high_value.py
@@ -0,0 +1,336 @@
+"""High-value tests for ImprovedEvidenceBasedStrategy pure logic methods."""
+
+import pytest
+from unittest.mock import MagicMock, patch
+from collections import defaultdict
+
+from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.evidence.base_evidence import (
+ Evidence,
+ EvidenceType,
+)
+from local_deep_research.advanced_search_system.strategies.improved_evidence_based_strategy import (
+ ImprovedEvidenceBasedStrategy,
+ SearchAttempt,
+)
+
+
+def make_constraint(ctype, value, weight=1.0, cid=None):
+ return Constraint(
+ id=cid or f"c_{value[:8]}",
+ type=ctype,
+ description=value,
+ value=value,
+ weight=weight,
+ )
+
+
+def make_evidence(
+ etype=EvidenceType.DIRECT_STATEMENT, confidence=0.8, source="web"
+):
+ ev = MagicMock(spec=Evidence)
+ ev.type = etype
+ ev.confidence = confidence
+ ev.source = source
+ return ev
+
+
+def strategy():
+ """Create strategy with mocked parent init."""
+ with patch.object(
+ ImprovedEvidenceBasedStrategy, "__init__", lambda self, *a, **kw: None
+ ):
+ s = ImprovedEvidenceBasedStrategy.__new__(ImprovedEvidenceBasedStrategy)
+ s.model = MagicMock()
+ s.search = MagicMock()
+ s.all_links_of_system = []
+ s.max_iterations = 20
+ s.confidence_threshold = 0.85
+ s.candidate_limit = 15
+ s.evidence_threshold = 0.6
+ s.max_search_iterations = 3
+ s.questions_per_iteration = 3
+ s.min_source_diversity = 3
+ s.adaptive_query_count = 3
+ s.constraints = []
+ s.candidates = []
+ s.search_history = []
+ s.search_attempts = []
+ s.failed_queries = set()
+ s.successful_patterns = []
+ s.source_types = defaultdict(set)
+ s.iteration = 0
+ s.progress_callback = None
+ return s
+
+
+# --- SearchAttempt dataclass ---
+
+
+class TestSearchAttempt:
+ def test_fields(self):
+ attempt = SearchAttempt(
+ query="test query",
+ constraint_ids=["c1", "c2"],
+ results_count=5,
+ candidates_found=3,
+ timestamp="2024-01-01T00:00:00",
+ strategy_type="single",
+ )
+ assert attempt.query == "test query"
+ assert attempt.constraint_ids == ["c1", "c2"]
+ assert attempt.results_count == 5
+ assert attempt.candidates_found == 3
+ assert attempt.strategy_type == "single"
+
+ def test_strategy_types(self):
+ for stype in ["single", "combined", "exploratory"]:
+ attempt = SearchAttempt(
+ query="q",
+ constraint_ids=[],
+ results_count=0,
+ candidates_found=0,
+ timestamp="",
+ strategy_type=stype,
+ )
+ assert attempt.strategy_type == stype
+
+
+# --- _generate_constraint_combinations ---
+
+
+class TestGenerateConstraintCombinations:
+ def test_single_constraint(self, strategy):
+ c = [make_constraint(ConstraintType.PROPERTY, "A")]
+ combos = strategy._generate_constraint_combinations(c, max_size=3)
+ assert len(combos) == 1
+ assert combos[0] == [c[0]]
+
+ def test_two_constraints(self, strategy):
+ constraints = [
+ make_constraint(ConstraintType.PROPERTY, "A"),
+ make_constraint(ConstraintType.PROPERTY, "B"),
+ ]
+ combos = strategy._generate_constraint_combinations(
+ constraints, max_size=3
+ )
+ # Singles: [A], [B] + Pairs: [A,B] = 3
+ assert len(combos) == 3
+
+ def test_three_constraints(self, strategy):
+ constraints = [
+ make_constraint(ConstraintType.PROPERTY, "A"),
+ make_constraint(ConstraintType.PROPERTY, "B"),
+ make_constraint(ConstraintType.PROPERTY, "C"),
+ ]
+ combos = strategy._generate_constraint_combinations(
+ constraints, max_size=3
+ )
+ # Singles: 3 + Pairs: 3 + Triples: 1 = 7
+ assert len(combos) == 7
+
+ def test_max_size_limits(self, strategy):
+ constraints = [
+ make_constraint(ConstraintType.PROPERTY, "A"),
+ make_constraint(ConstraintType.PROPERTY, "B"),
+ make_constraint(ConstraintType.PROPERTY, "C"),
+ ]
+ combos = strategy._generate_constraint_combinations(
+ constraints, max_size=2
+ )
+ # Singles: 3 + Pairs: 3 = 6 (no triples)
+ assert len(combos) == 6
+ assert all(len(c) <= 2 for c in combos)
+
+ def test_empty_constraints(self, strategy):
+ combos = strategy._generate_constraint_combinations([], max_size=3)
+ assert combos == []
+
+
+# --- _format_constraints_for_prompt ---
+
+
+class TestFormatConstraintsForPrompt:
+ def test_single_constraint(self, strategy):
+ constraints = [
+ make_constraint(ConstraintType.PROPERTY, "scenic view", weight=0.75)
+ ]
+ result = strategy._format_constraints_for_prompt(constraints)
+ assert "property" in result
+ assert "scenic view" in result
+ assert "0.75" in result
+
+ def test_multiple_constraints(self, strategy):
+ constraints = [
+ make_constraint(ConstraintType.PROPERTY, "scenic", weight=0.5),
+ make_constraint(ConstraintType.TEMPORAL, "in 2020", weight=0.8),
+ ]
+ result = strategy._format_constraints_for_prompt(constraints)
+ assert "property" in result
+ assert "temporal" in result
+ lines = result.strip().split("\n")
+ assert len(lines) == 2
+
+ def test_empty_constraints(self, strategy):
+ result = strategy._format_constraints_for_prompt([])
+ assert result == ""
+
+
+# --- _needs_diversity ---
+
+
+class TestNeedsDiversity:
+ def test_few_candidates_needs_diversity(self, strategy):
+ strategy.candidates = [Candidate(name="A")]
+ assert strategy._needs_diversity() is True
+
+ def test_three_or_more_with_sources(self, strategy):
+ strategy.candidates = [
+ Candidate(name="A"),
+ Candidate(name="B"),
+ Candidate(name="C"),
+ ]
+ strategy.source_types["A"] = {"s1", "s2", "s3"}
+ assert strategy._needs_diversity() is False
+
+ def test_three_candidates_few_sources(self, strategy):
+ strategy.candidates = [
+ Candidate(name="A"),
+ Candidate(name="B"),
+ Candidate(name="C"),
+ ]
+ strategy.source_types["A"] = {"s1"}
+ assert strategy._needs_diversity() is True
+
+ def test_empty_candidates(self, strategy):
+ strategy.candidates = []
+ assert strategy._needs_diversity() is True
+
+
+# --- _calculate_diversity_score ---
+
+
+class TestCalculateDiversityScore:
+ def test_no_evidence(self, strategy):
+ c = Candidate(name="Empty")
+ assert strategy._calculate_diversity_score(c) == 0.0
+
+ def test_single_source_type(self, strategy):
+ c = Candidate(name="Test")
+ c.evidence = {"c1": make_evidence(EvidenceType.DIRECT_STATEMENT, 0.8)}
+ strategy.source_types["Test"] = {"web"}
+ score = strategy._calculate_diversity_score(c)
+ assert 0.0 < score < 1.0
+
+ def test_multiple_sources_higher_score(self, strategy):
+ c1 = Candidate(name="Few")
+ c1.evidence = {"c1": make_evidence()}
+ strategy.source_types["Few"] = {"web"}
+
+ c2 = Candidate(name="Many")
+ c2.evidence = {
+ "c1": make_evidence(EvidenceType.DIRECT_STATEMENT),
+ "c2": make_evidence(EvidenceType.NEWS_REPORT),
+ }
+ strategy.source_types["Many"] = {"web", "academic", "news"}
+
+ score1 = strategy._calculate_diversity_score(c1)
+ score2 = strategy._calculate_diversity_score(c2)
+ assert score2 > score1
+
+
+# --- _adds_diversity ---
+
+
+class TestAddsDiversity:
+ def test_new_source_adds_diversity(self, strategy):
+ c = Candidate(name="New")
+ strategy.source_types["New"] = {"unique_source"}
+
+ existing = [Candidate(name="Old")]
+ strategy.source_types["Old"] = {"web"}
+
+ assert strategy._adds_diversity(c, existing) is True
+
+ def test_same_source_no_diversity(self, strategy):
+ c = Candidate(name="New")
+ c.evidence = {}
+ strategy.source_types["New"] = {"web"}
+
+ existing = [Candidate(name="Old")]
+ existing[0].evidence = {}
+ strategy.source_types["Old"] = {"web"}
+
+ assert strategy._adds_diversity(c, existing) is False
+
+ def test_new_constraint_adds_diversity(self, strategy):
+ c = Candidate(name="New")
+ c.evidence = {"c_new": make_evidence()}
+ strategy.source_types["New"] = set() # Same sources
+
+ existing = [Candidate(name="Old")]
+ existing[0].evidence = {"c_old": make_evidence()}
+ strategy.source_types["Old"] = set()
+
+ assert strategy._adds_diversity(c, existing) is True
+
+ def test_empty_existing(self, strategy):
+ c = Candidate(name="New")
+ c.evidence = {}
+ strategy.source_types["New"] = set()
+ assert strategy._adds_diversity(c, []) is False
+
+
+# --- _prune_with_diversity ---
+
+
+class TestPruneWithDiversity:
+ def test_no_pruning_if_under_limit(self, strategy):
+ strategy.candidate_limit = 10
+ strategy.candidates = [Candidate(name=f"C{i}") for i in range(5)]
+ for c in strategy.candidates:
+ c.evidence = {}
+ strategy._prune_with_diversity()
+ assert len(strategy.candidates) == 5
+
+ def test_pruning_keeps_limit(self, strategy):
+ strategy.candidate_limit = 4
+ strategy.candidates = [Candidate(name=f"C{i}") for i in range(10)]
+ for c in strategy.candidates:
+ c.evidence = {}
+ strategy._prune_with_diversity()
+ assert len(strategy.candidates) == 4
+
+ def test_top_half_kept(self, strategy):
+ strategy.candidate_limit = 4
+ candidates = [Candidate(name=f"C{i}") for i in range(10)]
+ for c in candidates:
+ c.evidence = {}
+ strategy.candidates = candidates
+ strategy._prune_with_diversity()
+ # Top half (2) should be kept
+ assert strategy.candidates[0].name == "C0"
+ assert strategy.candidates[1].name == "C1"
+
+ def test_diverse_candidates_preferred(self, strategy):
+ strategy.candidate_limit = 3
+ c0 = Candidate(name="Top1")
+ c0.evidence = {}
+ c1 = Candidate(name="Diverse")
+ c1.evidence = {"unique_constraint": make_evidence()}
+ c2 = Candidate(name="Regular")
+ c2.evidence = {}
+
+ strategy.candidates = [c0, c1, c2]
+ strategy.source_types["Diverse"] = {"unique_source"}
+
+ strategy._prune_with_diversity()
+ names = [c.name for c in strategy.candidates]
+ assert "Diverse" in names
diff --git a/tests/advanced_search_system/strategies/test_parallel_constrained_high_value.py b/tests/advanced_search_system/strategies/test_parallel_constrained_high_value.py
new file mode 100644
index 0000000000..2c8c7f7cc8
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_parallel_constrained_high_value.py
@@ -0,0 +1,300 @@
+"""High-value tests for ParallelConstrainedStrategy pure logic methods."""
+
+import pytest
+from unittest.mock import patch
+
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.strategies.parallel_constrained_strategy import (
+ ParallelConstrainedStrategy,
+ SearchCombination,
+)
+
+
+def make_constraint(ctype, value, weight=1.0, cid=None):
+ return Constraint(
+ id=cid or f"c_{value[:8]}",
+ type=ctype,
+ description=value,
+ value=value,
+ weight=weight,
+ )
+
+
+# --- SearchCombination dataclass ---
+
+
+class TestSearchCombination:
+ def test_hash_by_query(self):
+ c1 = SearchCombination(constraints=[], query="foo", priority=1)
+ c2 = SearchCombination(constraints=[], query="foo", priority=2)
+ assert hash(c1) == hash(c2)
+
+ def test_different_query_different_hash(self):
+ c1 = SearchCombination(constraints=[], query="foo", priority=1)
+ c2 = SearchCombination(constraints=[], query="bar", priority=1)
+ assert hash(c1) != hash(c2)
+
+ def test_fields(self):
+ constraints = [make_constraint(ConstraintType.PROPERTY, "test")]
+ combo = SearchCombination(
+ constraints=constraints, query="test query", priority=5
+ )
+ assert combo.constraints == constraints
+ assert combo.query == "test query"
+ assert combo.priority == 5
+
+ def test_same_hash_for_same_query(self):
+ c1 = SearchCombination(constraints=[], query="foo", priority=1)
+ c2 = SearchCombination(constraints=[], query="foo", priority=2)
+ # Same hash but no __eq__ override, so set uses identity
+ assert hash(c1) == hash(c2)
+
+
+# --- _classify_constraints ---
+
+
+def strategy():
+ """Create a ParallelConstrainedStrategy with mocked parent init."""
+ with patch.object(
+ ParallelConstrainedStrategy, "__init__", lambda self, *a, **kw: None
+ ):
+ s = ParallelConstrainedStrategy.__new__(ParallelConstrainedStrategy)
+ s.parallel_workers = 100
+ s.min_results_threshold = 10
+ s.hard_constraint_keywords = [
+ "aired between",
+ "aired during",
+ "air date",
+ "broadcast",
+ "episodes",
+ "season",
+ "year",
+ "decade",
+ "male",
+ "female",
+ "gender",
+ "tv show",
+ "series",
+ "program",
+ ]
+ return s
+
+
+class TestClassifyConstraints:
+ def test_temporal_is_hard(self, strategy):
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.TEMPORAL, "in 2020"),
+ ]
+ strategy._classify_constraints()
+ assert len(strategy.hard_constraints) == 1
+ assert len(strategy.soft_constraints) == 0
+
+ def test_statistic_is_hard(self, strategy):
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.STATISTIC, "84.5x ratio"),
+ ]
+ strategy._classify_constraints()
+ assert len(strategy.hard_constraints) == 1
+
+ def test_keyword_makes_hard(self, strategy):
+ strategy.constraint_ranking = [
+ make_constraint(
+ ConstraintType.PROPERTY, "aired between 2010 and 2015"
+ ),
+ ]
+ strategy._classify_constraints()
+ assert len(strategy.hard_constraints) == 1
+
+ def test_season_keyword_hard(self, strategy):
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.PROPERTY, "season 3 episode"),
+ ]
+ strategy._classify_constraints()
+ assert len(strategy.hard_constraints) == 1
+
+ def test_gender_keyword_hard(self, strategy):
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.PROPERTY, "female character"),
+ ]
+ strategy._classify_constraints()
+ assert len(strategy.hard_constraints) == 1
+
+ def test_property_without_keyword_is_soft(self, strategy):
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.PROPERTY, "has blue eyes"),
+ ]
+ strategy._classify_constraints()
+ assert len(strategy.soft_constraints) == 1
+ assert len(strategy.hard_constraints) == 0
+
+ def test_mixed_hard_and_soft(self, strategy):
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.TEMPORAL, "in 2020"),
+ make_constraint(ConstraintType.PROPERTY, "has blue eyes"),
+ make_constraint(ConstraintType.PROPERTY, "aired during 2019"),
+ ]
+ strategy._classify_constraints()
+ assert len(strategy.hard_constraints) == 2
+ assert len(strategy.soft_constraints) == 1
+
+
+# --- _build_query ---
+
+
+class TestBuildQuery:
+ def test_single_constraint(self, strategy):
+ strategy.entity_type = None
+ c = make_constraint(ConstraintType.PROPERTY, "blue eyes")
+ result = strategy._build_query([c])
+ assert '"blue eyes"' in result
+
+ def test_multi_word_quoted(self, strategy):
+ strategy.entity_type = None
+ c = make_constraint(ConstraintType.PROPERTY, "has blue eyes")
+ result = strategy._build_query([c])
+ assert '"has blue eyes"' in result
+
+ def test_single_word_not_quoted(self, strategy):
+ strategy.entity_type = None
+ c = make_constraint(ConstraintType.PROPERTY, "Colorado")
+ result = strategy._build_query([c])
+ assert result == "Colorado"
+
+ def test_and_joining(self, strategy):
+ strategy.entity_type = None
+ c1 = make_constraint(ConstraintType.PROPERTY, "Colorado")
+ c2 = make_constraint(ConstraintType.PROPERTY, "mountain")
+ result = strategy._build_query([c1, c2])
+ assert " AND " in result
+
+ def test_entity_type_prefix(self, strategy):
+ strategy.entity_type = "TV show"
+ c = make_constraint(ConstraintType.PROPERTY, "comedy")
+ result = strategy._build_query([c])
+ assert '"TV show"' in result
+ assert "comedy" in result
+
+ def test_entity_type_unknown_skipped(self, strategy):
+ strategy.entity_type = "unknown entity"
+ c = make_constraint(ConstraintType.PROPERTY, "comedy")
+ result = strategy._build_query([c])
+ assert "unknown" not in result
+
+
+# --- _generate_query_variations ---
+
+
+class TestGenerateQueryVariations:
+ def test_statistic_variations(self, strategy):
+ c = make_constraint(ConstraintType.STATISTIC, "84.5x ratio")
+ variations = strategy._generate_query_variations(c)
+ assert "84.5x ratio" in variations
+ assert any("list" in v for v in variations)
+ assert any("complete" in v for v in variations)
+ assert len(variations) <= 3
+
+ def test_property_variations(self, strategy):
+ c = make_constraint(ConstraintType.PROPERTY, "blue eyes")
+ variations = strategy._generate_query_variations(c)
+ assert any("with" in v for v in variations)
+ assert any("featuring" in v for v in variations)
+ assert len(variations) <= 3
+
+ def test_other_type_base_only(self, strategy):
+ c = make_constraint(ConstraintType.TEMPORAL, "in 2020")
+ variations = strategy._generate_query_variations(c)
+ assert variations == ["in 2020"]
+
+ def test_limit_to_three(self, strategy):
+ c = make_constraint(ConstraintType.STATISTIC, "test stat")
+ variations = strategy._generate_query_variations(c)
+ assert len(variations) <= 3
+
+
+# --- _create_strict_combinations ---
+
+
+class TestCreateStrictCombinations:
+ def test_top_two_combination(self, strategy):
+ strategy.entity_type = None
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.PROPERTY, "A"),
+ make_constraint(ConstraintType.PROPERTY, "B"),
+ ]
+ combos = strategy._create_strict_combinations()
+ assert len(combos) >= 1
+ assert len(combos[0].constraints) == 2
+
+ def test_temporal_property_combination(self, strategy):
+ strategy.entity_type = None
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.EVENT, "fall in 2014"),
+ make_constraint(ConstraintType.PROPERTY, "scenic view"),
+ ]
+ combos = strategy._create_strict_combinations()
+ assert any(len(c.constraints) == 2 for c in combos)
+
+ def test_limit_five(self, strategy):
+ strategy.entity_type = None
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.PROPERTY, f"prop{i}")
+ for i in range(10)
+ ]
+ combos = strategy._create_strict_combinations()
+ assert len(combos) <= 5
+
+ def test_single_constraint_no_crash(self, strategy):
+ strategy.entity_type = None
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.PROPERTY, "solo"),
+ ]
+ combos = strategy._create_strict_combinations()
+ assert isinstance(combos, list)
+
+
+# --- _create_relaxed_combinations ---
+
+
+class TestCreateRelaxedCombinations:
+ def test_single_constraints_from_top_three(self, strategy):
+ strategy.entity_type = None
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.PROPERTY, f"c{i}") for i in range(5)
+ ]
+ combos = strategy._create_relaxed_combinations()
+ single_combos = [c for c in combos if len(c.constraints) == 1]
+ assert len(single_combos) == 3
+
+ def test_weaker_group_included(self, strategy):
+ strategy.entity_type = None
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.PROPERTY, f"c{i}") for i in range(6)
+ ]
+ combos = strategy._create_relaxed_combinations()
+ multi = [c for c in combos if len(c.constraints) > 1]
+ assert len(multi) >= 1
+
+
+# --- _create_individual_combinations ---
+
+
+class TestCreateIndividualCombinations:
+ def test_two_variations_per_constraint(self, strategy):
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.STATISTIC, "stat1"),
+ ]
+ combos = strategy._create_individual_combinations()
+ assert len(combos) == 2
+
+ def test_max_five_constraints(self, strategy):
+ strategy.constraint_ranking = [
+ make_constraint(ConstraintType.PROPERTY, f"c{i}") for i in range(10)
+ ]
+ combos = strategy._create_individual_combinations()
+ # 5 constraints * 2 variations = 10 max (but PROPERTY only gives 1 base)
+ # Actually PROPERTY gives: base + with + featuring + known for = 4 -> [:2] = 2
+ assert len(combos) <= 10