~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 323 high-value tests across 10 modules (round 9) (#2581)
LearningCircuitc66df848690c
diff --git a/src/local_deep_research/advanced_search_system/findings/topic.py b/src/local_deep_research/advanced_search_system/findings/topic.pyindex bc110d7333..6aac952f97 100644--- a/src/local_deep_research/advanced_search_system/findings/topic.py+++ b/src/local_deep_research/advanced_search_system/findings/topic.py@@ -44,7 +44,7 @@ class Topic:The old lead becomes a supporting source."""if self.lead_source:- self.supporting_sources.append(self.lead_source)+ self.add_supporting_source(self.lead_source)self.lead_source = new_lead# Remove new lead from supporting if it was thereif new_lead in self.supporting_sources:@@ -145,7 +145,11 @@ class TopicGraph:if new_title:topic1.title = new_title- # Add topic2's sources to topic1+ # Add topic2's lead source to topic1's supporting sources+ if topic2.lead_source:+ topic1.add_supporting_source(topic2.lead_source)++ # Add topic2's supporting sources to topic1for source in topic2.supporting_sources:topic1.add_supporting_source(source)diff --git a/src/local_deep_research/config/thread_settings.py b/src/local_deep_research/config/thread_settings.pyindex 51629289e0..f561774ea9 100644--- a/src/local_deep_research/config/thread_settings.py+++ b/src/local_deep_research/config/thread_settings.py@@ -104,7 +104,7 @@ def get_setting_from_snapshot(# Handle both full format {"value": x} and simplified format (just x)if isinstance(v, dict) and "value" in v:v = get_typed_setting_value(- key, v["value"], v.get("ui_element", "text")+ k, v["value"], v.get("ui_element", "text"))# else: v is already the raw value from simplified snapshotif value is None:diff --git a/src/local_deep_research/utilities/json_utils.py b/src/local_deep_research/utilities/json_utils.pyindex 63b42d393b..573da25dbb 100644--- a/src/local_deep_research/utilities/json_utils.py+++ b/src/local_deep_research/utilities/json_utils.py@@ -176,6 +176,9 @@ def _clean_llm_json_artifacts(text: str) -> str:text = re.sub(r",\s*([}\]])", r"\1", text)# Remove // line commentstext = re.sub(r"//[^\n]*", "", text)- # Remove ellipsis entries- text = re.sub(r',?\s*"?\.\.\.+"?\s*,?', "", text)+ # Remove ellipsis entries, preserving comma separator when between items+ text = re.sub(+ r',\s*"?\.\.\.+"?\s*,', ",", text+ ) # between items: keep one comma+ text = re.sub(r',?\s*"?\.\.\.+"?\s*', "", text) # trailing/leading ellipsisreturn textdiff --git a/tests/advanced_search_system/findings/test_topic_high_value.py b/tests/advanced_search_system/findings/test_topic_high_value.pynew file mode 100644index 0000000000..0bcbc30b9a--- /dev/null+++ b/tests/advanced_search_system/findings/test_topic_high_value.py@@ -0,0 +1,293 @@+"""High-value tests for findings/topic.py pure dataclass logic."""++import unittest++from local_deep_research.advanced_search_system.findings.topic import (+ Topic,+ TopicGraph,+)+++def _make_topic(topic_id="t1", title="Topic 1", lead=None, **kwargs):+ return Topic(+ id=topic_id,+ title=title,+ lead_source=lead or {"url": f"http://{topic_id}.com", "title": title},+ **kwargs,+ )+++class TestTopicDefaults(unittest.TestCase):+ def test_supporting_sources_empty(self):+ t = _make_topic()+ assert t.supporting_sources == []++ def test_rejected_sources_empty(self):+ t = _make_topic()+ assert t.rejected_sources == []++ def test_related_topic_ids_empty(self):+ t = _make_topic()+ assert t.related_topic_ids == []++ def test_parent_topic_id_none(self):+ t = _make_topic()+ assert t.parent_topic_id is None+++class TestTopicAddSupportingSource(unittest.TestCase):+ def test_add_new_source(self):+ t = _make_topic()+ src = {"url": "http://new.com", "title": "New"}+ t.add_supporting_source(src)+ assert src in t.supporting_sources++ def test_duplicate_not_added(self):+ t = _make_topic()+ src = {"url": "http://new.com", "title": "New"}+ t.add_supporting_source(src)+ t.add_supporting_source(src)+ assert len(t.supporting_sources) == 1+++class TestTopicRejectSource(unittest.TestCase):+ def test_moves_from_supporting_to_rejected(self):+ t = _make_topic()+ src = {"url": "http://s.com"}+ t.add_supporting_source(src)+ t.reject_source(src)+ assert src not in t.supporting_sources+ assert src in t.rejected_sources++ def test_reject_not_in_supporting(self):+ t = _make_topic()+ src = {"url": "http://s.com"}+ t.reject_source(src)+ assert src in t.rejected_sources++ def test_duplicate_reject_not_added(self):+ t = _make_topic()+ src = {"url": "http://s.com"}+ t.reject_source(src)+ t.reject_source(src)+ assert len(t.rejected_sources) == 1+++class TestTopicUpdateLeadSource(unittest.TestCase):+ def test_old_lead_becomes_supporting(self):+ t = _make_topic()+ old_lead = t.lead_source+ new_lead = {"url": "http://new.com"}+ t.update_lead_source(new_lead)+ assert t.lead_source == new_lead+ assert old_lead in t.supporting_sources++ def test_update_lead_twice_no_duplicate_supporting(self):+ t = _make_topic()+ lead_a = {"url": "http://a.com"}+ lead_b = {"url": "http://b.com"}+ t.update_lead_source(lead_a)+ t.update_lead_source(lead_b)+ # Original lead and lead_a should each appear exactly once in supporting+ supporting_urls = [s.get("url") for s in t.supporting_sources]+ assert supporting_urls.count("http://a.com") == 1++ def test_new_lead_removed_from_supporting(self):+ t = _make_topic()+ src = {"url": "http://s.com"}+ t.add_supporting_source(src)+ t.update_lead_source(src)+ assert t.lead_source == src+ # Should appear exactly once (not in supporting anymore)+ assert src not in t.supporting_sources+++class TestTopicGetAllSources(unittest.TestCase):+ def test_includes_lead_and_supporting(self):+ t = _make_topic()+ src = {"url": "http://s.com"}+ t.add_supporting_source(src)+ all_sources = t.get_all_sources()+ assert len(all_sources) == 2+ assert t.lead_source in all_sources+ assert src in all_sources+++class TestTopicToDict(unittest.TestCase):+ def test_all_fields_present(self):+ t = _make_topic()+ d = t.to_dict()+ assert d["id"] == "t1"+ assert d["title"] == "Topic 1"+ assert "lead_source" in d+ assert "supporting_sources" in d+ assert "rejected_sources" in d+ assert "created_at" in d+ assert "related_topic_ids" in d+ assert "parent_topic_id" in d+ assert "child_topic_ids" in d++ def test_created_at_is_isoformat(self):+ t = _make_topic()+ d = t.to_dict()+ assert isinstance(d["created_at"], str)+ assert "T" in d["created_at"] # ISO format has T separator+++class TestTopicGraphBasic(unittest.TestCase):+ def test_add_and_get_topic(self):+ g = TopicGraph()+ t = _make_topic()+ g.add_topic(t)+ assert g.get_topic("t1") is t++ def test_get_missing_returns_none(self):+ g = TopicGraph()+ assert g.get_topic("nonexistent") is None++ def test_empty_graph(self):+ g = TopicGraph()+ assert g.topics == {}+++class TestTopicGraphLinkTopics(unittest.TestCase):+ def test_bidirectional_link(self):+ g = TopicGraph()+ t1 = _make_topic("t1")+ t2 = _make_topic("t2")+ g.add_topic(t1)+ g.add_topic(t2)+ g.link_topics("t1", "t2")+ assert "t2" in t1.related_topic_ids+ assert "t1" in t2.related_topic_ids++ def test_no_duplicate_links(self):+ g = TopicGraph()+ t1 = _make_topic("t1")+ t2 = _make_topic("t2")+ g.add_topic(t1)+ g.add_topic(t2)+ g.link_topics("t1", "t2")+ g.link_topics("t1", "t2")+ assert t1.related_topic_ids.count("t2") == 1++ def test_invalid_topic_ids(self):+ g = TopicGraph()+ t1 = _make_topic("t1")+ g.add_topic(t1)+ g.link_topics("t1", "missing") # Should not raise+ assert t1.related_topic_ids == [] # No mutation+++class TestTopicGraphParentChild(unittest.TestCase):+ def test_parent_child_set(self):+ g = TopicGraph()+ parent = _make_topic("p1")+ child = _make_topic("c1")+ g.add_topic(parent)+ g.add_topic(child)+ g.set_parent_child("p1", "c1")+ assert "c1" in parent.child_topic_ids+ assert child.parent_topic_id == "p1"++ def test_invalid_ids(self):+ g = TopicGraph()+ p1 = _make_topic("p1")+ g.add_topic(p1)+ g.set_parent_child("p1", "missing") # Should not raise+ assert p1.child_topic_ids == [] # No mutation+++class TestTopicGraphRootTopics(unittest.TestCase):+ def test_root_topics_no_parent(self):+ g = TopicGraph()+ t1 = _make_topic("t1")+ t2 = _make_topic("t2")+ g.add_topic(t1)+ g.add_topic(t2)+ g.set_parent_child("t1", "t2")+ roots = g.get_root_topics()+ assert len(roots) == 1+ assert roots[0].id == "t1"+++class TestTopicGraphGetRelated(unittest.TestCase):+ def test_returns_related_topics(self):+ g = TopicGraph()+ t1 = _make_topic("t1")+ t2 = _make_topic("t2")+ t3 = _make_topic("t3")+ g.add_topic(t1)+ g.add_topic(t2)+ g.add_topic(t3)+ g.link_topics("t1", "t2")+ g.link_topics("t1", "t3")+ related = g.get_related_topics("t1")+ assert len(related) == 2++ def test_missing_topic_returns_empty(self):+ g = TopicGraph()+ assert g.get_related_topics("missing") == []+++class TestTopicGraphMerge(unittest.TestCase):+ def test_merge_combines_sources(self):+ g = TopicGraph()+ t1 = _make_topic("t1")+ t2 = _make_topic("t2")+ t2.add_supporting_source({"url": "http://extra.com"})+ g.add_topic(t1)+ g.add_topic(t2)+ t2_lead = t2.lead_source+ merged = g.merge_topics("t1", "t2")+ assert merged is t1+ assert "t2" not in g.topics+ # t2's lead_source must end up in t1's supporting sources+ assert t2_lead in t1.supporting_sources+ # t2's supporting sources are merged into t1+ assert any(+ s.get("url") == "http://extra.com" for s in t1.supporting_sources+ )++ def test_merge_with_custom_title(self):+ g = TopicGraph()+ t1 = _make_topic("t1")+ t2 = _make_topic("t2")+ g.add_topic(t1)+ g.add_topic(t2)+ merged = g.merge_topics("t1", "t2", new_title="Merged")+ assert merged.title == "Merged"++ def test_merge_invalid_ids(self):+ g = TopicGraph()+ g.add_topic(_make_topic("t1"))+ assert g.merge_topics("t1", "missing") is None++ def test_merge_updates_references(self):+ g = TopicGraph()+ t1 = _make_topic("t1")+ t2 = _make_topic("t2")+ t3 = _make_topic("t3")+ g.add_topic(t1)+ g.add_topic(t2)+ g.add_topic(t3)+ g.link_topics("t2", "t3")+ g.merge_topics("t1", "t2")+ # t3 should now reference t1 instead of t2+ assert "t1" in t3.related_topic_ids+ assert "t2" not in t3.related_topic_ids+++class TestTopicGraphToDict(unittest.TestCase):+ def test_serializes_all_topics(self):+ g = TopicGraph()+ g.add_topic(_make_topic("t1"))+ g.add_topic(_make_topic("t2"))+ d = g.to_dict()+ assert "t1" in d+ assert "t2" in d+ assert d["t1"]["id"] == "t1"+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/advanced_search_system/strategies/test_constrained_search_high_value.py b/tests/advanced_search_system/strategies/test_constrained_search_high_value.pynew file mode 100644index 0000000000..a3e0085fb9--- /dev/null+++ b/tests/advanced_search_system/strategies/test_constrained_search_high_value.py@@ -0,0 +1,509 @@+"""+High-value pure logic tests for ConstrainedSearchStrategy.++Tests focus on:+- _calculate_restrictiveness_score and _rank_constraints_by_restrictiveness+- Formatting methods (_format_constraint_analysis, _format_stage_results, etc.)+- Filtering/deduplication logic+- _quick_evidence_check scoring+- _validate_search_results+- _group_similar_candidates++All tests bypass __init__ to avoid LLM/network dependencies.+"""++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.evidence.base_evidence import (+ Evidence,+ EvidenceType,+)+from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (+ ConstrainedSearchStrategy,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_strategy(**overrides):+ """Create a ConstrainedSearchStrategy with __init__ bypassed."""+ with patch.object(+ ConstrainedSearchStrategy, "__init__", lambda self, *a, **kw: None+ ):+ strat = ConstrainedSearchStrategy.__new__(ConstrainedSearchStrategy)++ # Defaults that the real __init__ would set+ defaults = dict(+ constraints=[],+ constraint_ranking=[],+ stage_candidates={},+ candidates=[],+ evidence_threshold=0.6,+ candidate_limit=100,+ search_history=[],+ )+ defaults.update(overrides)+ for key, val in defaults.items():+ setattr(strat, key, val)+ return strat+++def _make_constraint(+ id_="c1",+ ctype=ConstraintType.PROPERTY,+ value="test value",+ description="Test constraint",+ weight=0.5,+):+ """Create a Constraint with convenient defaults."""+ return Constraint(+ id=id_, type=ctype, value=value, description=description, weight=weight+ )+++# ---------------------------------------------------------------------------+# Tests: _calculate_restrictiveness_score+# ---------------------------------------------------------------------------+++class TestCalculateRestrictivenessScore:+ """Tests for the _calculate_restrictiveness_score method."""++ def test_statistic_type_gets_10(self):+ """STATISTIC constraint type adds +10 to score."""+ strat = _make_strategy()+ c = _make_constraint(ctype=ConstraintType.STATISTIC, value="abc")+ assert strat._calculate_restrictiveness_score(c) == 10++ def test_event_type_gets_8(self):+ """EVENT constraint type adds +8 to score."""+ strat = _make_strategy()+ c = _make_constraint(ctype=ConstraintType.EVENT, value="abc")+ assert strat._calculate_restrictiveness_score(c) == 8++ def test_location_type_gets_6(self):+ """LOCATION constraint type adds +6 to score."""+ strat = _make_strategy()+ c = _make_constraint(ctype=ConstraintType.LOCATION, value="abc")+ assert strat._calculate_restrictiveness_score(c) == 6++ def test_property_type_gets_4(self):+ """PROPERTY constraint type adds +4 to score."""+ strat = _make_strategy()+ c = _make_constraint(ctype=ConstraintType.PROPERTY, value="abc")+ assert strat._calculate_restrictiveness_score(c) == 4++ def test_value_with_digits_adds_5(self):+ """Presence of digits in value adds +5."""+ strat = _make_strategy()+ c = _make_constraint(ctype=ConstraintType.PROPERTY, value="year 2020")+ # PROPERTY=4, digits=5 => 9+ assert strat._calculate_restrictiveness_score(c) == 9++ def test_long_value_adds_3(self):+ """Value with >3 words adds +3."""+ strat = _make_strategy()+ c = _make_constraint(+ ctype=ConstraintType.PROPERTY,+ value="a very long descriptive phrase",+ )+ # PROPERTY=4, >3 words=3 => 7+ assert strat._calculate_restrictiveness_score(c) == 7++ def test_specific_keyword_adds_2(self):+ """Values containing 'specific', 'exact', 'only', or 'must' add +2."""+ strat = _make_strategy()+ for keyword in ["specific", "exact", "only", "must"]:+ c = _make_constraint(+ ctype=ConstraintType.PROPERTY, value=f"{keyword} item"+ )+ score = strat._calculate_restrictiveness_score(c)+ # PROPERTY=4, keyword=2 => 6+ assert score == 6, f"Keyword '{keyword}' should add +2"++ def test_combined_bonuses_stack(self):+ """All specificity bonuses stack correctly."""+ strat = _make_strategy()+ # STATISTIC(10) + digits(5) + >3 words(3) + keyword(2) = 20+ c = _make_constraint(+ ctype=ConstraintType.STATISTIC,+ value="must be exactly 42 units long",+ )+ assert strat._calculate_restrictiveness_score(c) == 20++ def test_none_value_skips_specificity(self):+ """Constraint with value=None gets only type-based score."""+ strat = _make_strategy()+ c = _make_constraint(ctype=ConstraintType.EVENT, value=None)+ assert strat._calculate_restrictiveness_score(c) == 8++ def test_empty_string_value_skips_specificity(self):+ """Constraint with empty string value gets only type-based score."""+ strat = _make_strategy()+ c = _make_constraint(ctype=ConstraintType.LOCATION, value="")+ assert strat._calculate_restrictiveness_score(c) == 6+++# ---------------------------------------------------------------------------+# Tests: _rank_constraints_by_restrictiveness+# ---------------------------------------------------------------------------+++class TestRankConstraintsByRestrictiveness:+ """Tests for _rank_constraints_by_restrictiveness method."""++ def test_sorts_by_score_descending(self):+ """Constraints are sorted from highest to lowest score."""+ strat = _make_strategy()+ strat.constraints = [+ _make_constraint(+ id_="p", ctype=ConstraintType.PROPERTY, value="abc"+ ),+ _make_constraint(+ id_="s", ctype=ConstraintType.STATISTIC, value="123"+ ),+ _make_constraint(id_="e", ctype=ConstraintType.EVENT, value="abc"),+ ]+ ranked = strat._rank_constraints_by_restrictiveness()+ # STATISTIC(10)+digits(5)=15, EVENT=8, PROPERTY=4+ assert ranked[0].id == "s"+ assert ranked[1].id == "e"+ assert ranked[2].id == "p"++ def test_empty_constraints_returns_empty(self):+ """Empty constraints list returns empty ranked list."""+ strat = _make_strategy()+ strat.constraints = []+ assert strat._rank_constraints_by_restrictiveness() == []++ def test_single_constraint(self):+ """Single constraint is returned as-is."""+ strat = _make_strategy()+ c = _make_constraint(id_="only")+ strat.constraints = [c]+ ranked = strat._rank_constraints_by_restrictiveness()+ assert len(ranked) == 1+ assert ranked[0].id == "only"++ def test_preserves_all_constraints(self):+ """All constraints appear in ranked output."""+ strat = _make_strategy()+ strat.constraints = [+ _make_constraint(+ id_=str(i), ctype=ConstraintType.PROPERTY, value="x"+ )+ for i in range(5)+ ]+ ranked = strat._rank_constraints_by_restrictiveness()+ assert len(ranked) == 5+++# ---------------------------------------------------------------------------+# Tests: Format methods+# ---------------------------------------------------------------------------+++class TestFormatMethods:+ """Tests for formatting helper methods."""++ def test_format_constraint_analysis_includes_header(self):+ """_format_constraint_analysis includes query constraint header."""+ strat = _make_strategy()+ c = _make_constraint(description="Height over 100m")+ strat.constraints = [c]+ strat.constraint_ranking = [c]+ result = strat._format_constraint_analysis()+ assert "Query Constraint Analysis" in result++ def test_format_constraint_analysis_includes_description(self):+ """_format_constraint_analysis includes each constraint description."""+ strat = _make_strategy()+ c = _make_constraint(description="Height over 100m")+ strat.constraints = [c]+ strat.constraint_ranking = [c]+ result = strat._format_constraint_analysis()+ assert "Height over 100m" in result++ def test_format_constraint_analysis_includes_score(self):+ """_format_constraint_analysis shows restrictiveness score."""+ strat = _make_strategy()+ c = _make_constraint(ctype=ConstraintType.STATISTIC, value="42")+ strat.constraints = [c]+ strat.constraint_ranking = [c]+ result = strat._format_constraint_analysis()+ assert "15" in result # STATISTIC(10) + digits(5)++ def test_format_stage_results_with_candidates(self):+ """_format_stage_results shows stage number and candidates."""+ strat = _make_strategy()+ c = _make_constraint(description="Located in Colorado")+ candidates = [+ Candidate(name="Pike's Peak"),+ Candidate(name="Mt Elbert"),+ ]+ result = strat._format_stage_results(0, c, candidates)+ assert "Stage 1" in result+ assert "Located in Colorado" in result+ assert "Pike's Peak" in result+ assert "Mt Elbert" in result++ def test_format_stage_results_empty_candidates(self):+ """_format_stage_results handles empty candidate list."""+ strat = _make_strategy()+ c = _make_constraint()+ result = strat._format_stage_results(0, c, [])+ assert "No candidates found" in result++ def test_format_search_summary_includes_final_count(self):+ """_format_search_summary includes final candidate count."""+ strat = _make_strategy()+ c = _make_constraint()+ strat.constraint_ranking = [c]+ strat.stage_candidates = {0: [Candidate(name="A")]}+ strat.candidates = [Candidate(name="A")]+ result = strat._format_search_summary()+ assert "1 candidates selected" in result++ def test_format_debug_summary_includes_debug_header(self):+ """_format_debug_summary includes Debug Summary header."""+ strat = _make_strategy()+ c = _make_constraint()+ strat.constraints = [c]+ strat.constraint_ranking = [c]+ strat.stage_candidates = {}+ strat.candidates = []+ result = strat._format_debug_summary()+ assert "Debug Summary" in result++ def test_format_evidence_summary_no_candidates(self):+ """_format_evidence_summary works with zero candidates."""+ strat = _make_strategy()+ strat.constraints = [_make_constraint()]+ strat.candidates = []+ result = strat._format_evidence_summary()+ assert "Evidence Gathering Summary" in result+++# ---------------------------------------------------------------------------+# Tests: _deduplicate_candidates+# ---------------------------------------------------------------------------+++class TestDeduplicateCandidates:+ """Tests for candidate deduplication."""++ def test_removes_case_insensitive_duplicates(self):+ """Candidates with same name (case-insensitive) are deduplicated."""+ strat = _make_strategy()+ candidates = [+ Candidate(name="Alpha"),+ Candidate(name="alpha"),+ Candidate(name="ALPHA"),+ ]+ result = strat._deduplicate_candidates(candidates)+ assert len(result) == 1+ assert result[0].name == "Alpha" # first seen wins++ def test_keeps_distinct_candidates(self):+ """Distinct candidates are all kept."""+ strat = _make_strategy()+ candidates = [+ Candidate(name="Alpha"),+ Candidate(name="Beta"),+ Candidate(name="Gamma"),+ ]+ result = strat._deduplicate_candidates(candidates)+ assert len(result) == 3++ def test_empty_list(self):+ """Empty input returns empty output."""+ strat = _make_strategy()+ assert strat._deduplicate_candidates([]) == []+++# ---------------------------------------------------------------------------+# Tests: _group_similar_candidates+# ---------------------------------------------------------------------------+++class TestGroupSimilarCandidates:+ """Tests for candidate grouping logic."""++ def test_ai_model_group(self):+ """Candidates with AI model keywords go to 'AI Models' group."""+ strat = _make_strategy()+ candidates = [Candidate(name="GPT-4"), Candidate(name="Claude 3")]+ grouped = strat._group_similar_candidates(candidates)+ assert "AI Models" in grouped+ assert len(grouped["AI Models"]) == 2++ def test_numeric_items_group(self):+ """Candidates with digits go to 'Numeric Items' group."""+ strat = _make_strategy()+ candidates = [Candidate(name="Highway 66")]+ grouped = strat._group_similar_candidates(candidates)+ assert "Numeric Items" in grouped++ def test_default_grouping_uses_first_word(self):+ """Candidates without keyword matches use first-word grouping."""+ strat = _make_strategy()+ candidates = [Candidate(name="Evergreen Forest")]+ grouped = strat._group_similar_candidates(candidates)+ assert "Evergreen Items" in grouped++ def test_empty_candidates(self):+ """Empty candidate list returns empty dict."""+ strat = _make_strategy()+ assert strat._group_similar_candidates([]) == {}+++# ---------------------------------------------------------------------------+# Tests: _validate_search_results+# ---------------------------------------------------------------------------+++class TestValidateSearchResults:+ """Tests for search result validation."""++ def test_rejects_none_results(self):+ """None results are rejected."""+ strat = _make_strategy()+ c = _make_constraint()+ assert strat._validate_search_results(None, c) is False++ def test_rejects_empty_content(self):+ """Empty content string is rejected."""+ strat = _make_strategy()+ c = _make_constraint()+ results = {"current_knowledge": "", "search_results": []}+ assert strat._validate_search_results(results, c) is False++ def test_rejects_short_content(self):+ """Content under 50 chars is rejected."""+ strat = _make_strategy()+ c = _make_constraint()+ results = {"current_knowledge": "Too short", "search_results": []}+ assert strat._validate_search_results(results, c) is False++ def test_rejects_no_results_found_message(self):+ """Content containing 'No results found' is rejected."""+ strat = _make_strategy()+ c = _make_constraint()+ results = {+ "current_knowledge": "No results found for this query. " * 5,+ "search_results": [],+ }+ assert strat._validate_search_results(results, c) is False++ def test_accepts_valid_property_content(self):+ """Valid content matching property constraint terms is accepted."""+ strat = _make_strategy()+ c = _make_constraint(+ ctype=ConstraintType.PROPERTY,+ value="mountain hiking trail overview",+ )+ results = {+ "current_knowledge": (+ "This mountain hiking trail overview covers several popular "+ "destinations. The trail system includes many routes for "+ "experienced hikers and beginners alike."+ ),+ "search_results": [{"title": "Trails", "snippet": "hiking info"}],+ }+ assert strat._validate_search_results(results, c) is True+++# ---------------------------------------------------------------------------+# Tests: _quick_evidence_check scoring+# ---------------------------------------------------------------------------+++class TestQuickEvidenceCheck:+ """Tests for the _quick_evidence_check scoring logic."""++ def test_returns_evidence_object(self):+ """Returns an Evidence instance."""+ strat = _make_strategy()+ candidate = Candidate(name="Test Entity")+ constraint = _make_constraint()+ results = {"current_knowledge": "Some content", "search_results": []}+ evidence = strat._quick_evidence_check(results, candidate, constraint)+ assert isinstance(evidence, Evidence)++ def test_base_confidence_when_nothing_matches(self):+ """When no components match, confidence falls back to Evidence type base (INFERENCE=0.5).++ The _quick_evidence_check computes 0.0 but Evidence.__post_init__+ replaces 0.0 with the EvidenceType.INFERENCE base_confidence of 0.5.+ """+ strat = _make_strategy()+ candidate = Candidate(name="Nonexistent Entity")+ constraint = _make_constraint(value="irrelevant zzzz")+ results = {+ "current_knowledge": "Completely unrelated topic about weather patterns.",+ "search_results": [],+ }+ evidence = strat._quick_evidence_check(results, candidate, constraint)+ # All scoring components are zero+ assert evidence.metadata["name_presence"] == 0.0+ assert evidence.metadata["constraint_presence"] == 0.0+ assert evidence.metadata["co_occurrence"] == 0.0+ assert evidence.metadata["context_quality"] == 0.0+ # But Evidence post_init sets INFERENCE base_confidence+ assert evidence.confidence == EvidenceType.INFERENCE.base_confidence++ def test_higher_confidence_with_co_occurrence(self):+ """Confidence is higher when both candidate and constraint value co-occur."""+ strat = _make_strategy()+ candidate = Candidate(name="Mount Elbert")+ constraint = _make_constraint(value="14000 feet")+ # Both terms present and close together+ content = (+ "Mount Elbert rises to 14000 feet above sea level in Colorado."+ )+ results = {"current_knowledge": content, "search_results": []}+ evidence = strat._quick_evidence_check(results, candidate, constraint)+ assert evidence.confidence > 0.5++ def test_statistic_type_multiplier(self):+ """STATISTIC constraint type applies 1.1x multiplier to confidence."""+ strat = _make_strategy()+ candidate = Candidate(name="Entity A")+ content = (+ "Entity A has exactly the value abc as expected in this context."+ )++ c_stat = _make_constraint(ctype=ConstraintType.STATISTIC, value="abc")+ c_prop = _make_constraint(ctype=ConstraintType.PROPERTY, value="abc")++ results = {"current_knowledge": content, "search_results": []}+ ev_stat = strat._quick_evidence_check(results, candidate, c_stat)+ ev_prop = strat._quick_evidence_check(results, candidate, c_prop)+ # STATISTIC multiplier (1.1) > PROPERTY multiplier (0.95)+ assert ev_stat.confidence > ev_prop.confidence++ def test_confidence_capped_at_one(self):+ """Confidence never exceeds 1.0."""+ strat = _make_strategy()+ candidate = Candidate(name="x")+ constraint = _make_constraint(ctype=ConstraintType.STATISTIC, value="x")+ # Lots of repetition to push score up+ content = ("x " * 500).strip()+ results = {+ "current_knowledge": content,+ "search_results": [+ {"title": "x", "snippet": "x"} for _ in range(20)+ ],+ }+ evidence = strat._quick_evidence_check(results, candidate, constraint)+ assert evidence.confidence <= 1.0diff --git a/tests/advanced_search_system/strategies/test_llm_driven_modular_high_value.py b/tests/advanced_search_system/strategies/test_llm_driven_modular_high_value.pynew file mode 100644index 0000000000..58b2fa0477--- /dev/null+++ b/tests/advanced_search_system/strategies/test_llm_driven_modular_high_value.py@@ -0,0 +1,214 @@+"""High-value tests for llm_driven_modular_strategy.py pure logic."""++import unittest+from unittest.mock import MagicMock++from local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy import (+ CandidateConfidence,+ EarlyRejectionManager,+ LLMConstraintProcessor,+)+++class TestCandidateConfidence(unittest.TestCase):+ def test_required_fields(self):+ cc = CandidateConfidence(+ candidate="test", positive_confidence=0.8, negative_confidence=0.2+ )+ assert cc.candidate == "test"+ assert cc.positive_confidence == 0.8+ assert cc.negative_confidence == 0.2++ def test_default_should_continue(self):+ cc = CandidateConfidence(+ candidate="x", positive_confidence=0.5, negative_confidence=0.5+ )+ assert cc.should_continue is True++ def test_default_rejection_reason(self):+ cc = CandidateConfidence(+ candidate="x", positive_confidence=0.5, negative_confidence=0.5+ )+ assert cc.rejection_reason is None++ def test_override_defaults(self):+ cc = CandidateConfidence(+ candidate="x",+ positive_confidence=0.1,+ negative_confidence=0.9,+ should_continue=False,+ rejection_reason="too negative",+ )+ assert cc.should_continue is False+ assert cc.rejection_reason == "too negative"+++class TestLLMConstraintProcessorParsing(unittest.TestCase):+ def setUp(self):+ self.processor = LLMConstraintProcessor(model=MagicMock())++ def test_parse_decomposition_valid_json(self):+ content = '{"c1": {"atomic_elements": ["a"], "variations": ["b"], "granular_specifics": ["c"]}}'+ result = self.processor._parse_decomposition(content)+ assert "c1" in result+ assert result["c1"]["atomic_elements"] == ["a"]++ def test_parse_decomposition_invalid_json_fallback(self):+ result = self.processor._parse_decomposition("not json at all")+ assert "time_constraint" in result+ assert "atomic_elements" in result["time_constraint"]++ def test_parse_decomposition_with_code_fence(self):+ content = '```json\n{"key": {"atomic_elements": ["x"]}}\n```'+ result = self.processor._parse_decomposition(content)+ assert "key" in result++ def test_parse_combinations_valid_list(self):+ content = '["query1", "query2", "query3"]'+ result = self.processor._parse_combinations(content)+ assert result == ["query1", "query2", "query3"]++ def test_parse_combinations_invalid_fallback(self):+ result = self.processor._parse_combinations("no json here")+ assert isinstance(result, list)+ assert len(result) > 0+ assert all(isinstance(q, str) for q in result)++ def test_parse_creative_searches_valid(self):+ content = '["creative1", "creative2"]'+ result = self.processor._parse_creative_searches(content)+ assert result == ["creative1", "creative2"]++ def test_parse_creative_searches_fallback(self):+ result = self.processor._parse_creative_searches("bad")+ assert isinstance(result, list)+ assert len(result) > 0+ assert all(isinstance(q, str) for q in result)++ def test_parse_optimized_searches_valid(self):+ content = '{"high_priority": ["q1"], "fallback_broad": ["q2"]}'+ result = self.processor._parse_optimized_searches(content)+ assert "high_priority" in result++ def test_parse_optimized_searches_fallback(self):+ result = self.processor._parse_optimized_searches("invalid")+ assert isinstance(result, dict)+ assert "high_priority" in result+ assert "systematic_granular" in result+ assert "creative_angles" in result+ assert "contextual_searches" in result+ assert "fallback_broad" in result+++class TestEarlyRejectionManagerInit(unittest.TestCase):+ def test_default_thresholds(self):+ mgr = EarlyRejectionManager(model=MagicMock())+ assert mgr.positive_threshold == 0.6+ assert mgr.negative_threshold == 0.3++ def test_custom_thresholds(self):+ mgr = EarlyRejectionManager(+ model=MagicMock(), positive_threshold=0.8, negative_threshold=0.1+ )+ assert mgr.positive_threshold == 0.8+ assert mgr.negative_threshold == 0.1++ def test_rejected_candidates_empty(self):+ mgr = EarlyRejectionManager(model=MagicMock())+ assert mgr.rejected_candidates == set()+++class TestShouldRejectEarly(unittest.TestCase):+ def setUp(self):+ self.mgr = EarlyRejectionManager(model=MagicMock())++ def test_high_negative_rejects(self):+ reject, reason = self.mgr.should_reject_early(+ {"positive_confidence": 0.5, "negative_confidence": 0.8}+ )+ assert reject is True++ def test_very_low_positive_rejects(self):+ reject, reason = self.mgr.should_reject_early(+ {"positive_confidence": 0.05, "negative_confidence": 0.3}+ )+ assert reject is True++ def test_boundary_negative_0_7_no_reject(self):+ reject, reason = self.mgr.should_reject_early(+ {"positive_confidence": 0.5, "negative_confidence": 0.7}+ )+ assert reject is False++ def test_boundary_positive_0_1_no_reject(self):+ reject, reason = self.mgr.should_reject_early(+ {"positive_confidence": 0.1, "negative_confidence": 0.3}+ )+ assert reject is False++ def test_moderate_no_reject(self):+ reject, reason = self.mgr.should_reject_early(+ {"positive_confidence": 0.5, "negative_confidence": 0.5}+ )+ assert reject is False++ def test_missing_keys_use_defaults(self):+ reject, reason = self.mgr.should_reject_early({})+ # defaults: positive=0.5, negative=0.3 -> no reject+ assert reject is False+++class TestShouldContinueSearch(unittest.TestCase):+ def setUp(self):+ self.mgr = EarlyRejectionManager(model=MagicMock())++ def test_enough_high_confidence_stops(self):+ cont, reason = self.mgr.should_continue_search(+ all_candidates=list(range(10)), high_confidence_count=5+ )+ assert cont is False++ def test_4_high_confidence_continues(self):+ cont, reason = self.mgr.should_continue_search(+ all_candidates=list(range(10)), high_confidence_count=4+ )+ assert cont is True++ def test_many_low_quality_stops(self):+ cont, reason = self.mgr.should_continue_search(+ all_candidates=list(range(51)), high_confidence_count=0+ )+ assert cont is False++ def test_50_candidates_0_quality_continues(self):+ cont, reason = self.mgr.should_continue_search(+ all_candidates=list(range(50)), high_confidence_count=0+ )+ assert cont is True++ def test_normal_continues(self):+ cont, reason = self.mgr.should_continue_search(+ all_candidates=list(range(20)), high_confidence_count=2+ )+ assert cont is True+++class TestParseConfidence(unittest.TestCase):+ def setUp(self):+ self.mgr = EarlyRejectionManager(model=MagicMock())++ def test_valid_json(self):+ content = '{"positive_confidence": 0.8, "negative_confidence": 0.1, "reasoning": "good match"}'+ result = self.mgr._parse_confidence(content)+ assert result["positive_confidence"] == 0.8+ assert result["negative_confidence"] == 0.1++ def test_invalid_json_fallback(self):+ result = self.mgr._parse_confidence("not json")+ assert result["positive_confidence"] == 0.5+ assert result["negative_confidence"] == 0.3+ assert result["reasoning"] == "parse_error"+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/config/test_thread_settings_extended.py b/tests/config/test_thread_settings_extended.pyindex bb1e8c5cfe..74720a374e 100644--- a/tests/config/test_thread_settings_extended.py+++ b/tests/config/test_thread_settings_extended.py@@ -183,7 +183,7 @@ class TestGetSettingFromSnapshotChildKeys:"parent.child": {"value": "raw_child", "ui_element": "checkbox"},}result = get_setting_from_snapshot("parent", settings_snapshot=snapshot)- mock_gtsv.assert_called_once_with("parent", "raw_child", "checkbox")+ mock_gtsv.assert_called_once_with("child", "raw_child", "checkbox")assert result == {"child": "typed_child"}def test_no_partial_prefix_confusion(self, clean_thread_local):diff --git a/tests/config/test_thread_settings_high_value.py b/tests/config/test_thread_settings_high_value.pynew file mode 100644index 0000000000..ab68ad8a26--- /dev/null+++ b/tests/config/test_thread_settings_high_value.py@@ -0,0 +1,207 @@+"""High-value tests for config/thread_settings.py pure logic."""++import os+import unittest+from unittest.mock import MagicMock, patch++from local_deep_research.config.thread_settings import (+ NoSettingsContextError,+ clear_settings_context,+ get_bool_setting_from_snapshot,+ get_llm_setting_from_snapshot,+ get_setting_from_snapshot,+ get_settings_context,+ set_settings_context,+ settings_context,+ _thread_local,+)+++class TestSettingsContextBasic(unittest.TestCase):+ def tearDown(self):+ clear_settings_context()++ def test_set_and_get_roundtrip(self):+ ctx = MagicMock()+ set_settings_context(ctx)+ assert get_settings_context() is ctx++ def test_clear_removes_context(self):+ set_settings_context(MagicMock())+ clear_settings_context()+ assert get_settings_context() is None++ def test_get_returns_none_when_not_set(self):+ clear_settings_context()+ assert get_settings_context() is None++ def test_clear_when_never_set(self):+ # Should not raise+ if hasattr(_thread_local, "settings_context"):+ del _thread_local.settings_context+ clear_settings_context()+++class TestSettingsContextManager(unittest.TestCase):+ def tearDown(self):+ clear_settings_context()++ def test_sets_and_clears(self):+ ctx = MagicMock()+ with settings_context(ctx):+ assert get_settings_context() is ctx+ assert get_settings_context() is None++ def test_clears_on_exception(self):+ ctx = MagicMock()+ try:+ with settings_context(ctx):+ raise ValueError("test")+ except ValueError:+ pass+ assert get_settings_context() is None+++class TestGetSettingFromSnapshot(unittest.TestCase):+ def tearDown(self):+ clear_settings_context()++ def test_key_in_snapshot_simple_value(self):+ snapshot = {"my_key": "my_value"}+ result = get_setting_from_snapshot("my_key", settings_snapshot=snapshot)+ assert result == "my_value"++ def test_key_in_snapshot_dict_with_value(self):+ snapshot = {"my_key": {"value": 42, "ui_element": "text"}}+ result = get_setting_from_snapshot("my_key", settings_snapshot=snapshot)+ # ui_element="text" maps to str converter, so result is "42"+ assert result == "42"++ def test_child_key_search(self):+ snapshot = {"parent.child1": "v1", "parent.child2": "v2"}+ result = get_setting_from_snapshot("parent", settings_snapshot=snapshot)+ assert isinstance(result, dict)+ assert result["child1"] == "v1"+ assert result["child2"] == "v2"++ def test_child_key_with_value_dict(self):+ snapshot = {"parent.child": {"value": "hello", "ui_element": "text"}}+ result = get_setting_from_snapshot("parent", settings_snapshot=snapshot)+ assert isinstance(result, dict)+ assert result["child"] == "hello"++ def test_fallback_to_thread_context(self):+ ctx = MagicMock()+ ctx.get_setting.return_value = "from_context"+ set_settings_context(ctx)+ result = get_setting_from_snapshot("some_key")+ assert result == "from_context"++ def test_thread_context_dict_with_value(self):+ ctx = MagicMock()+ ctx.get_setting.return_value = {"value": "extracted"}+ set_settings_context(ctx)+ result = get_setting_from_snapshot("some_key")+ assert result == "extracted"++ def test_default_returned_when_no_context(self):+ clear_settings_context()+ result = get_setting_from_snapshot("missing", default="fallback")+ assert result == "fallback"++ def test_raises_when_no_context_no_default(self):+ clear_settings_context()+ with self.assertRaises(NoSettingsContextError):+ get_setting_from_snapshot("missing")++ @patch.dict(+ os.environ, {"LDR_USE_FALLBACK_LLM": "1", "LDR_TESTING_WITH_MOCKS": ""}+ )+ def test_fallback_llm_returns_default(self):+ clear_settings_context()+ result = get_setting_from_snapshot(+ "key", default="fb_default", check_fallback_llm=True+ )+ assert result == "fb_default"++ @patch.dict(+ os.environ, {"LDR_USE_FALLBACK_LLM": "1", "LDR_TESTING_WITH_MOCKS": "1"}+ )+ def test_fallback_llm_skipped_with_mocks(self):+ clear_settings_context()+ # With mocks set, fallback LLM check is skipped — no default means raises+ with self.assertRaises(NoSettingsContextError):+ get_setting_from_snapshot("key", check_fallback_llm=True)++ def test_snapshot_takes_priority_over_context(self):+ ctx = MagicMock()+ ctx.get_setting.return_value = "from_context"+ set_settings_context(ctx)+ snapshot = {"key": "from_snapshot"}+ result = get_setting_from_snapshot("key", settings_snapshot=snapshot)+ assert result == "from_snapshot"++ def test_none_value_in_snapshot_not_treated_as_found(self):+ # None in snapshot means key exists but value is None+ clear_settings_context()+ # Should fall through to default since value is None -> not truthy for `if value is not None`+ result = get_setting_from_snapshot(+ "key", default="default_val", settings_snapshot={"key": None}+ )+ assert result == "default_val"+++class TestGetBoolSettingFromSnapshot(unittest.TestCase):+ def tearDown(self):+ clear_settings_context()++ def test_returns_true_from_string(self):+ snapshot = {"flag": "true"}+ result = get_bool_setting_from_snapshot(+ "flag", settings_snapshot=snapshot+ )+ assert result is True++ def test_returns_false_from_string(self):+ snapshot = {"flag": "false"}+ result = get_bool_setting_from_snapshot(+ "flag", settings_snapshot=snapshot+ )+ assert result is False++ def test_default_when_missing(self):+ result = get_bool_setting_from_snapshot(+ "missing", default=True, settings_snapshot={}+ )+ assert result is True++ def test_integer_one_is_true(self):+ snapshot = {"flag": 1}+ result = get_bool_setting_from_snapshot(+ "flag", settings_snapshot=snapshot+ )+ assert result is True+++class TestGetLlmSettingFromSnapshot(unittest.TestCase):+ def tearDown(self):+ clear_settings_context()++ def test_basic_retrieval(self):+ snapshot = {"llm_key": "model_name"}+ result = get_llm_setting_from_snapshot(+ "llm_key", settings_snapshot=snapshot+ )+ assert result == "model_name"++ @patch.dict(+ os.environ, {"LDR_USE_FALLBACK_LLM": "1", "LDR_TESTING_WITH_MOCKS": ""}+ )+ def test_fallback_llm_enabled(self):+ clear_settings_context()+ result = get_llm_setting_from_snapshot("key", default="default_model")+ assert result == "default_model"+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/metrics/test_token_counter_high_value.py b/tests/metrics/test_token_counter_high_value.pynew file mode 100644index 0000000000..c0697b6363--- /dev/null+++ b/tests/metrics/test_token_counter_high_value.py@@ -0,0 +1,536 @@+"""High-value pure logic tests for TokenCountingCallback.++Covers initialization, on_llm_start model/provider detection,+on_llm_end token extraction and accumulation, on_llm_error tracking,+and context overflow detection.+"""++import time+from unittest.mock import MagicMock++from langchain_core.outputs import LLMResult++from local_deep_research.metrics.token_counter import TokenCountingCallback+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_callback(**kw):+ """Create a TokenCountingCallback with sensible defaults."""+ return TokenCountingCallback(+ research_id=kw.get("research_id"),+ research_context=kw.get("research_context"),+ )+++def _make_llm_result(llm_output=None, generations=None):+ """Build a minimal mock LLMResult."""+ result = MagicMock(spec=LLMResult)+ result.llm_output = llm_output+ result.generations = generations if generations is not None else []+ return result+++def _setup_model(cb, model="test-model", provider="unknown"):+ """Run on_llm_start so current_model and by_model are initialised."""+ cb.on_llm_start(+ {"kwargs": {"model": model}},+ ["prompt"],+ )+++# ===========================================================================+# 1. Initialisation+# ===========================================================================+++class TestTokenCountingCallbackInit:+ """Verify default and custom initialisation."""++ def test_default_research_id_is_none(self):+ cb = TokenCountingCallback()+ assert cb.research_id is None++ def test_custom_research_id(self):+ cb = TokenCountingCallback(research_id="abc-123")+ assert cb.research_id == "abc-123"++ def test_default_research_context_is_empty_dict(self):+ cb = TokenCountingCallback()+ assert cb.research_context == {}++ def test_custom_research_context(self):+ ctx = {"research_query": "test", "research_mode": "deep"}+ cb = TokenCountingCallback(research_context=ctx)+ assert cb.research_context is ctx++ def test_counts_structure_has_required_keys(self):+ cb = TokenCountingCallback()+ assert cb.counts["total_tokens"] == 0+ assert cb.counts["total_prompt_tokens"] == 0+ assert cb.counts["total_completion_tokens"] == 0+ assert cb.counts["by_model"] == {}++ def test_start_time_initially_none(self):+ cb = TokenCountingCallback()+ assert cb.start_time is None++ def test_success_status_initially_success(self):+ cb = TokenCountingCallback()+ assert cb.success_status == "success"+++# ===========================================================================+# 2. on_llm_start — model detection+# ===========================================================================+++class TestOnLlmStartModelDetection:+ """Verify model name is extracted from the right source in priority order."""++ def test_model_from_invocation_params_model_name_key(self):+ """invocation_params.model_name should be used when model key absent."""+ cb = _make_callback()+ cb.on_llm_start(+ {},+ ["prompt"],+ invocation_params={"model_name": "gpt-4o-mini"},+ )+ assert cb.current_model == "gpt-4o-mini"++ def test_model_from_kwargs_model_name_key(self):+ """kwargs.model_name (direct) should be used as fallback."""+ cb = _make_callback()+ cb.on_llm_start({}, ["prompt"], model_name="claude-3-haiku")+ assert cb.current_model == "claude-3-haiku"++ def test_serialized_kwargs_model_name_key(self):+ """serialized['kwargs']['model_name'] should be used."""+ cb = _make_callback()+ cb.on_llm_start(+ {"kwargs": {"model_name": "gemma-7b"}},+ ["prompt"],+ )+ assert cb.current_model == "gemma-7b"++ def test_preset_model_overrides_all(self):+ """Preset model takes absolute priority."""+ cb = _make_callback()+ cb.preset_model = "preset-llm"+ cb.on_llm_start(+ {"kwargs": {"model": "ignored"}, "name": "also-ignored"},+ ["prompt"],+ invocation_params={"model": "still-ignored"},+ )+ assert cb.current_model == "preset-llm"++ def test_invocation_params_model_beats_serialized(self):+ """invocation_params.model wins over serialized.kwargs.model."""+ cb = _make_callback()+ cb.on_llm_start(+ {"kwargs": {"model": "serialized-model"}},+ ["prompt"],+ invocation_params={"model": "invocation-model"},+ )+ assert cb.current_model == "invocation-model"++ def test_ollama_without_kwargs_key_defaults_to_ollama(self):+ """ChatOllama type without kwargs dict at all defaults to 'ollama'."""+ cb = _make_callback()+ cb.on_llm_start({"_type": "ChatOllama"}, ["prompt"])+ assert cb.current_model == "ollama"++ def test_by_model_entry_created_on_first_call(self):+ """First call with a model creates the by_model entry."""+ cb = _make_callback()+ cb.on_llm_start({"kwargs": {"model": "new-model"}}, ["prompt"])+ entry = cb.counts["by_model"]["new-model"]+ assert entry["prompt_tokens"] == 0+ assert entry["completion_tokens"] == 0+ assert entry["total_tokens"] == 0+ assert entry["calls"] == 1++ def test_call_count_increments_same_model(self):+ """Repeated calls with the same model increment calls counter."""+ cb = _make_callback()+ for _ in range(4):+ cb.on_llm_start({"kwargs": {"model": "m1"}}, ["p"])+ assert cb.counts["by_model"]["m1"]["calls"] == 4++ def test_multiple_models_tracked_separately(self):+ """Different models get separate by_model entries."""+ cb = _make_callback()+ cb.on_llm_start({"kwargs": {"model": "model-a"}}, ["p"])+ cb.on_llm_start({"kwargs": {"model": "model-b"}}, ["p"])+ assert "model-a" in cb.counts["by_model"]+ assert "model-b" in cb.counts["by_model"]+ assert cb.counts["by_model"]["model-a"]["calls"] == 1+ assert cb.counts["by_model"]["model-b"]["calls"] == 1+++# ===========================================================================+# 3. on_llm_start — provider detection+# ===========================================================================+++class TestOnLlmStartProviderDetection:+ """Verify provider extracted from _type or kwargs."""++ def test_preset_provider_overrides(self):+ cb = _make_callback()+ cb.preset_provider = "custom-provider"+ cb.on_llm_start({"_type": "ChatOpenAI"}, ["p"])+ assert cb.current_provider == "custom-provider"++ def test_provider_kwarg_fallback(self):+ """Unknown _type falls back to provider kwarg."""+ cb = _make_callback()+ cb.on_llm_start(+ {"_type": "UnknownLLM"},+ ["p"],+ provider="my-custom",+ )+ assert cb.current_provider == "my-custom"++ def test_provider_stored_in_by_model(self):+ """Provider should be stored in the by_model entry."""+ cb = _make_callback()+ cb.on_llm_start(+ {"_type": "ChatAnthropic", "kwargs": {"model": "claude"}},+ ["p"],+ )+ assert cb.counts["by_model"]["claude"]["provider"] == "anthropic"+++# ===========================================================================+# 4. on_llm_start — prompt estimation+# ===========================================================================+++class TestOnLlmStartPromptEstimation:+ """Verify prompt token estimation from prompt text."""++ def test_single_prompt_estimate(self):+ cb = _make_callback()+ cb.on_llm_start({}, ["a" * 100]) # 100 chars => 25 tokens+ assert cb.original_prompt_estimate == 25++ def test_empty_prompts_leaves_estimate_unchanged(self):+ """Empty prompts list skips estimation (guarded by `if prompts:`)."""+ cb = _make_callback()+ cb.original_prompt_estimate = 999+ cb.on_llm_start({}, [])+ # Empty prompts are skipped, so the estimate stays at its prior value+ assert cb.original_prompt_estimate == 999++ def test_start_time_set(self):+ cb = _make_callback()+ before = time.time()+ cb.on_llm_start({}, ["p"])+ assert cb.start_time >= before+++# ===========================================================================+# 5. on_llm_end — token extraction and accumulation+# ===========================================================================+++class TestOnLlmEnd:+ """Verify token extraction from various LLMResult shapes."""++ def test_total_tokens_calculated_when_missing(self):+ """When total_tokens is missing, prompt + completion is used."""+ cb = _make_callback()+ _setup_model(cb, "m1")++ result = _make_llm_result(+ llm_output={+ "token_usage": {+ "prompt_tokens": 40,+ "completion_tokens": 60,+ # no total_tokens key+ }+ }+ )+ cb.on_llm_end(result)+ assert cb.counts["total_tokens"] == 100++ def test_by_model_updated_after_on_llm_end(self):+ """Per-model counts should be updated after on_llm_end."""+ cb = _make_callback()+ _setup_model(cb, "gpt-4")++ result = _make_llm_result(+ llm_output={+ "token_usage": {+ "prompt_tokens": 10,+ "completion_tokens": 20,+ "total_tokens": 30,+ }+ }+ )+ cb.on_llm_end(result)++ model_stats = cb.counts["by_model"]["gpt-4"]+ assert model_stats["prompt_tokens"] == 10+ assert model_stats["completion_tokens"] == 20+ assert model_stats["total_tokens"] == 30++ def test_response_time_calculated(self):+ """response_time_ms should be set when start_time is present."""+ cb = _make_callback()+ _setup_model(cb, "m1")+ cb.start_time = time.time() - 0.2 # 200ms ago++ result = _make_llm_result()+ cb.on_llm_end(result)++ assert cb.response_time_ms is not None+ assert cb.response_time_ms >= 150++ def test_response_time_none_without_start_time(self):+ """response_time_ms stays None if start_time was never set."""+ cb = _make_callback()+ cb.current_model = "m1"+ cb.counts["by_model"]["m1"] = {+ "prompt_tokens": 0,+ "completion_tokens": 0,+ "total_tokens": 0,+ "calls": 1,+ "provider": "unknown",+ }+ cb.start_time = None++ result = _make_llm_result()+ cb.on_llm_end(result)++ assert cb.response_time_ms is None++ def test_ollama_raw_metrics_captured(self):+ """Ollama response_metadata durations stored in ollama_metrics."""+ cb = _make_callback()+ _setup_model(cb, "llama3")++ msg = MagicMock()+ msg.usage_metadata = None+ msg.response_metadata = {+ "prompt_eval_count": 50,+ "eval_count": 30,+ "total_duration": 9000000,+ "load_duration": 1000000,+ "prompt_eval_duration": 4000000,+ "eval_duration": 4000000,+ }+ gen = MagicMock()+ gen.message = msg++ result = _make_llm_result(generations=[[gen]])+ cb.on_llm_end(result)++ assert cb.ollama_metrics["total_duration"] == 9000000+ assert cb.ollama_metrics["eval_count"] == 30++ def test_usage_metadata_none_skipped(self):+ """Generation with usage_metadata=None falls through to response_metadata."""+ cb = _make_callback()+ _setup_model(cb, "llama3")++ msg = MagicMock()+ msg.usage_metadata = None+ msg.response_metadata = {+ "prompt_eval_count": 15,+ "eval_count": 10,+ }+ gen = MagicMock()+ gen.message = msg++ result = _make_llm_result(generations=[[gen]])+ cb.on_llm_end(result)++ assert cb.counts["total_prompt_tokens"] == 15+ assert cb.counts["total_completion_tokens"] == 10++ def test_accumulation_across_two_different_models(self):+ """Tokens from different models accumulate in totals and separate by_model."""+ cb = _make_callback()++ # First model+ cb.on_llm_start({"kwargs": {"model": "model-a"}}, ["p"])+ result_a = _make_llm_result(+ llm_output={+ "token_usage": {+ "prompt_tokens": 10,+ "completion_tokens": 5,+ "total_tokens": 15,+ }+ }+ )+ cb.on_llm_end(result_a)++ # Second model+ cb.on_llm_start({"kwargs": {"model": "model-b"}}, ["p"])+ result_b = _make_llm_result(+ llm_output={+ "token_usage": {+ "prompt_tokens": 20,+ "completion_tokens": 10,+ "total_tokens": 30,+ }+ }+ )+ cb.on_llm_end(result_b)++ # Totals+ assert cb.counts["total_tokens"] == 45+ assert cb.counts["total_prompt_tokens"] == 30++ # Per-model+ assert cb.counts["by_model"]["model-a"]["total_tokens"] == 15+ assert cb.counts["by_model"]["model-b"]["total_tokens"] == 30++ def test_llm_output_usage_key_alternative(self):+ """'usage' key in llm_output (not 'token_usage') should work."""+ cb = _make_callback()+ _setup_model(cb, "m1")++ result = _make_llm_result(+ llm_output={+ "usage": {+ "prompt_tokens": 7,+ "completion_tokens": 3,+ "total_tokens": 10,+ }+ }+ )+ cb.on_llm_end(result)+ assert cb.counts["total_tokens"] == 10+++# ===========================================================================+# 6. on_llm_error+# ===========================================================================+++class TestOnLlmError:+ """Verify error tracking behaviour."""++ def test_sets_success_status_to_error(self):+ cb = _make_callback()+ cb.on_llm_error(ValueError("bad input"))+ assert cb.success_status == "error"++ def test_captures_error_type_name(self):+ cb = _make_callback()+ cb.on_llm_error(RuntimeError("timeout"))+ assert cb.error_type == "RuntimeError"++ def test_response_time_calculated_on_error(self):+ cb = _make_callback()+ cb.start_time = time.time() - 0.3+ cb.on_llm_error(Exception("fail"))+ assert cb.response_time_ms is not None+ assert cb.response_time_ms >= 250++ def test_response_time_none_without_start_time(self):+ cb = _make_callback()+ cb.on_llm_error(Exception("fail"))+ assert cb.response_time_ms is None+++# ===========================================================================+# 7. Context overflow detection+# ===========================================================================+++class TestContextOverflow:+ """Verify context overflow detection and _get_context_overflow_fields."""++ def _make_cb_with_context_limit(self, limit=4096):+ """Create a callback with context_limit set via research_context."""+ cb = TokenCountingCallback(research_context={"context_limit": limit})+ _setup_model(cb, "llama3")+ return cb++ def test_context_truncated_detected_at_95_percent(self):+ """prompt_eval_count >= context_limit * 0.95 sets context_truncated."""+ cb = self._make_cb_with_context_limit(4096)++ msg = MagicMock()+ msg.usage_metadata = None+ msg.response_metadata = {+ "prompt_eval_count": 3900, # >= 4096 * 0.95 = 3891.2+ "eval_count": 50,+ }+ gen = MagicMock()+ gen.message = msg++ result = _make_llm_result(generations=[[gen]])+ cb.on_llm_end(result)++ assert cb.context_truncated is True++ def test_context_not_truncated_below_threshold(self):+ """prompt_eval_count below 95% does not set truncated."""+ cb = self._make_cb_with_context_limit(4096)++ msg = MagicMock()+ msg.usage_metadata = None+ msg.response_metadata = {+ "prompt_eval_count": 3000, # < 4096 * 0.95+ "eval_count": 50,+ }+ gen = MagicMock()+ gen.message = msg++ result = _make_llm_result(generations=[[gen]])+ cb.on_llm_end(result)++ assert cb.context_truncated is False++ def test_tokens_truncated_calculated(self):+ """tokens_truncated = original_prompt_estimate - prompt_eval_count."""+ cb = self._make_cb_with_context_limit(4096)+ cb.original_prompt_estimate = 5000++ msg = MagicMock()+ msg.usage_metadata = None+ msg.response_metadata = {+ "prompt_eval_count": 3900,+ "eval_count": 50,+ }+ gen = MagicMock()+ gen.message = msg++ result = _make_llm_result(generations=[[gen]])+ cb.on_llm_end(result)++ assert cb.tokens_truncated == 1100 # 5000 - 3900+ assert abs(cb.truncation_ratio - 0.22) < 0.01 # 1100/5000++ def test_get_context_overflow_fields_when_truncated(self):+ """_get_context_overflow_fields returns values when truncated."""+ cb = _make_callback()+ cb.context_limit = 4096+ cb.context_truncated = True+ cb.tokens_truncated = 500+ cb.truncation_ratio = 0.1++ fields = cb._get_context_overflow_fields()+ assert fields["context_limit"] == 4096+ assert fields["context_truncated"] is True+ assert fields["tokens_truncated"] == 500+ assert fields["truncation_ratio"] == 0.1++ def test_get_context_overflow_fields_when_not_truncated(self):+ """_get_context_overflow_fields returns None for truncation fields when not truncated."""+ cb = _make_callback()+ cb.context_limit = 4096+ cb.context_truncated = False++ fields = cb._get_context_overflow_fields()+ assert fields["context_truncated"] is False+ assert fields["tokens_truncated"] is None+ assert fields["truncation_ratio"] is Nonediff --git a/tests/notifications/test_templates_high_value.py b/tests/notifications/test_templates_high_value.pynew file mode 100644index 0000000000..094df66ac4--- /dev/null+++ b/tests/notifications/test_templates_high_value.py@@ -0,0 +1,225 @@+"""High-value tests for notifications/templates.py pure logic."""++import unittest+from unittest.mock import MagicMock, patch++from local_deep_research.notifications.templates import (+ EventType,+ NotificationTemplate,+)+++class TestEventType(unittest.TestCase):+ def test_research_completed_value(self):+ assert EventType.RESEARCH_COMPLETED.value == "research_completed"++ def test_research_failed_value(self):+ assert EventType.RESEARCH_FAILED.value == "research_failed"++ def test_test_event_value(self):+ assert EventType.TEST.value == "test"++ def test_all_events_have_string_values(self):+ for event in EventType:+ assert isinstance(event.value, str)++ def test_event_categories_present(self):+ values = {e.value for e in EventType}+ assert "research_completed" in values+ assert "subscription_update" in values+ assert "rate_limit_warning" in values+ assert "test" in values+++class TestFallbackTemplate(unittest.TestCase):+ def test_returns_dict_with_title_and_body(self):+ result = NotificationTemplate._get_fallback_template(+ EventType.RESEARCH_COMPLETED, {"query": "test"}+ )+ assert "title" in result+ assert "body" in result++ def test_title_contains_event_name(self):+ result = NotificationTemplate._get_fallback_template(+ EventType.RESEARCH_COMPLETED, {}+ )+ assert "Research Completed" in result["title"]++ def test_body_contains_context(self):+ result = NotificationTemplate._get_fallback_template(+ EventType.RESEARCH_FAILED, {"error": "timeout"}+ )+ assert "timeout" in result["body"]++ def test_underscores_replaced(self):+ result = NotificationTemplate._get_fallback_template(+ EventType.SUBSCRIPTION_UPDATE, {}+ )+ assert "_" not in result["title"]+ assert "Subscription Update" in result["title"]++ def test_different_event_types(self):+ for event_type in [+ EventType.RESEARCH_QUEUED,+ EventType.AUTH_ISSUE,+ EventType.TEST,+ ]:+ result = NotificationTemplate._get_fallback_template(event_type, {})+ assert "title" in result+ assert "body" in result+++class TestFormatCustomTemplate(unittest.TestCase):+ def setUp(self):+ NotificationTemplate._jinja_env = None++ def test_custom_template_with_context(self):+ custom = {"title": "Hello {name}", "body": "Query: {query}"}+ result = NotificationTemplate.format(+ EventType.TEST,+ {"name": "user", "query": "test"},+ custom_template=custom,+ )+ assert result["title"] == "Hello user"+ assert result["body"] == "Query: test"++ def test_custom_template_missing_variable(self):+ custom = {"title": "Hello {name}", "body": "Query: {query}"}+ result = NotificationTemplate.format(+ EventType.TEST, {"name": "user"}, custom_template=custom+ )+ # Missing {query} triggers KeyError, both title and body get error fallback+ assert "Template error" in result["body"]+ assert "Missing variable" in result["body"]++ def test_custom_template_sanitizes_values(self):+ custom = {"title": "{val}", "body": "ok"}+ result = NotificationTemplate.format(+ EventType.TEST, {"val": 42}, custom_template=custom+ )+ assert result["title"] == "42"++ def test_custom_template_none_value_becomes_empty(self):+ custom = {"title": "{val}", "body": "ok"}+ result = NotificationTemplate.format(+ EventType.TEST, {"val": None}, custom_template=custom+ )+ assert result["title"] == ""+++class TestFormatUnknownEvent(unittest.TestCase):+ def setUp(self):+ NotificationTemplate._jinja_env = None++ def test_unknown_event_not_in_template_files(self):+ # RATE_LIMIT_WARNING is not in TEMPLATE_FILES+ result = NotificationTemplate.format(+ EventType.RATE_LIMIT_WARNING, {"detail": "slow"}+ )+ assert "title" in result+ assert "body" in result+++class TestFormatWithJinja(unittest.TestCase):+ def setUp(self):+ NotificationTemplate._jinja_env = None++ def test_jinja_env_not_available_uses_fallback(self):+ with patch.object(+ NotificationTemplate, "_get_jinja_env", return_value=None+ ):+ result = NotificationTemplate.format(+ EventType.RESEARCH_COMPLETED, {"query": "test"}+ )+ assert "title" in result+ assert "body" in result++ def test_jinja_template_render_error_uses_fallback(self):+ mock_env = MagicMock()+ mock_template = MagicMock()+ mock_template.render.side_effect = Exception("render error")+ mock_env.get_template.return_value = mock_template++ with patch.object(+ NotificationTemplate, "_get_jinja_env", return_value=mock_env+ ):+ result = NotificationTemplate.format(+ EventType.RESEARCH_COMPLETED, {"query": "test"}+ )+ assert "title" in result+ assert "body" in result+ # Verify the render path was actually exercised+ mock_template.render.assert_called_once()++ def test_jinja_successful_render(self):+ mock_env = MagicMock()+ mock_template = MagicMock()+ mock_template.render.return_value = (+ "My Title\nMy body content\nMore body"+ )+ mock_env.get_template.return_value = mock_template++ with patch.object(+ NotificationTemplate, "_get_jinja_env", return_value=mock_env+ ):+ result = NotificationTemplate.format(+ EventType.RESEARCH_COMPLETED, {"query": "test"}+ )+ assert result["title"] == "My Title"+ assert "My body content" in result["body"]+++class TestGetRequiredContext(unittest.TestCase):+ def setUp(self):+ NotificationTemplate._jinja_env = None++ def test_unknown_event_returns_empty(self):+ result = NotificationTemplate.get_required_context(+ EventType.RATE_LIMIT_WARNING+ )+ assert result == []++ def test_no_jinja_env_returns_empty(self):+ with patch.object(+ NotificationTemplate, "_get_jinja_env", return_value=None+ ):+ result = NotificationTemplate.get_required_context(+ EventType.RESEARCH_COMPLETED+ )+ assert result == []++ def test_returns_sorted_list(self):+ mock_env = MagicMock()+ mock_loader = MagicMock()+ mock_loader.get_source.return_value = (+ "{{ query }} {{ status }}",+ None,+ None,+ )+ mock_env.loader = mock_loader+ mock_env.parse.return_value = MagicMock()++ mock_template = MagicMock()+ mock_template.environment = mock_env+ mock_env.get_template.return_value = mock_template++ import jinja2.meta # noqa: F401 - ensure submodule is loaded++ with (+ patch.object(+ NotificationTemplate, "_get_jinja_env", return_value=mock_env+ ),+ patch.object(+ jinja2.meta,+ "find_undeclared_variables",+ return_value={"query", "status"},+ ),+ ):+ result = NotificationTemplate.get_required_context(+ EventType.RESEARCH_COMPLETED+ )+ assert result == ["query", "status"]+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/utilities/test_json_utils_high_value.py b/tests/utilities/test_json_utils_high_value.pynew file mode 100644index 0000000000..00769c2eb6--- /dev/null+++ b/tests/utilities/test_json_utils_high_value.py@@ -0,0 +1,227 @@+"""High-value tests for utilities/json_utils.py pure logic."""++import json+import unittest+from unittest.mock import MagicMock++from local_deep_research.utilities.json_utils import (+ extract_json,+ get_llm_response_text,+ _clean_llm_json_artifacts,+ _extract_by_brackets,+ _remove_think_tags,+ _strip_code_fences,+)+++class TestGetLlmResponseText(unittest.TestCase):+ def test_none_returns_empty_string(self):+ assert get_llm_response_text(None) == ""++ def test_content_attribute(self):+ msg = MagicMock()+ msg.content = "hello world"+ assert get_llm_response_text(msg) == "hello world"++ def test_text_attribute_when_no_content(self):+ msg = MagicMock(spec=[])+ msg.text = "from text"+ assert get_llm_response_text(msg) == "from text"++ def test_str_fallback(self):+ assert get_llm_response_text(42) == "42"++ def test_think_tags_removed(self):+ msg = MagicMock()+ msg.content = "before <think>inner</think> after"+ assert get_llm_response_text(msg) == "before after"++ def test_content_none_falls_to_text(self):+ msg = MagicMock()+ msg.content = None+ msg.text = "fallback"+ assert get_llm_response_text(msg) == "fallback"++ def test_non_string_content_converted(self):+ msg = MagicMock()+ msg.content = 123+ result = get_llm_response_text(msg)+ assert result == "123"+++class TestRemoveThinkTags(unittest.TestCase):+ def test_paired_tags(self):+ assert _remove_think_tags("a <think>b</think> c") == "a c"++ def test_orphaned_closing(self):+ assert _remove_think_tags("text </think> more") == "text more"++ def test_orphaned_opening(self):+ assert _remove_think_tags("text <think> more") == "text more"++ def test_multiline_think(self):+ text = "start <think>\nline1\nline2\n</think> end"+ assert _remove_think_tags(text) == "start end"++ def test_no_tags(self):+ assert _remove_think_tags("plain text") == "plain text"++ def test_empty_string(self):+ assert _remove_think_tags("") == ""+++class TestStripCodeFences(unittest.TestCase):+ def test_json_fence(self):+ text = '```json\n{"key": "val"}\n```'+ assert _strip_code_fences(text) == '{"key": "val"}'++ def test_plain_fence(self):+ text = '```\n{"key": "val"}\n```'+ assert _strip_code_fences(text) == '{"key": "val"}'++ def test_no_fence(self):+ text = '{"key": "val"}'+ assert _strip_code_fences(text) == text++ def test_json_fence_with_surrounding_prose(self):+ text = 'Here is the result:\n```json\n{"a": 1}\n```\nDone.'+ assert _strip_code_fences(text) == '{"a": 1}'++ def test_unclosed_fence_returns_original(self):+ text = "```only one fence"+ assert _strip_code_fences(text) == text+++class TestExtractByBrackets(unittest.TestCase):+ def test_curly_brackets(self):+ text = 'prefix {"a": 1} suffix'+ assert _extract_by_brackets(text, "{", "}") == '{"a": 1}'++ def test_square_brackets(self):+ text = "before [1, 2, 3] after"+ assert _extract_by_brackets(text, "[", "]") == "[1, 2, 3]"++ def test_nested_brackets(self):+ text = '{"a": {"b": 1}}'+ assert _extract_by_brackets(text, "{", "}") == '{"a": {"b": 1}}'++ def test_no_brackets_returns_none(self):+ assert _extract_by_brackets("no brackets", "{", "}") is None++ def test_mismatched_order_returns_none(self):+ assert _extract_by_brackets("} before {", "{", "}") is None++ def test_only_open_returns_none(self):+ assert _extract_by_brackets("{ no close", "{", "}") is None+++class TestCleanLlmJsonArtifacts(unittest.TestCase):+ def test_trailing_comma_before_brace(self):+ text = '{"a": 1,}'+ assert _clean_llm_json_artifacts(text) == '{"a": 1}'++ def test_trailing_comma_before_bracket(self):+ text = "[1, 2, 3,]"+ assert _clean_llm_json_artifacts(text) == "[1, 2, 3]"++ def test_line_comments(self):+ text = '{"a": 1 // comment\n}'+ result = _clean_llm_json_artifacts(text)+ assert "//" not in result++ def test_ellipsis_entries(self):+ text = '["a", ..., "b"]'+ result = _clean_llm_json_artifacts(text)+ assert "..." not in result+ parsed = json.loads(result)+ assert parsed == ["a", "b"]++ def test_quoted_ellipsis(self):+ text = '["a", "...", "b"]'+ result = _clean_llm_json_artifacts(text)+ assert "..." not in result+ parsed = json.loads(result)+ assert parsed == ["a", "b"]++ def test_no_artifacts_unchanged(self):+ text = '{"a": 1}'+ assert _clean_llm_json_artifacts(text) == text+++class TestExtractJsonDirect(unittest.TestCase):+ def test_none_returns_none(self):+ assert extract_json(None) is None++ def test_empty_string_returns_none(self):+ assert extract_json("") is None++ def test_whitespace_only_returns_none(self):+ assert extract_json(" ") is None++ def test_valid_dict(self):+ assert extract_json('{"key": "val"}') == {"key": "val"}++ def test_valid_list(self):+ assert extract_json("[1, 2, 3]") == [1, 2, 3]++ def test_invalid_json_returns_none(self):+ assert extract_json("not json at all") is None+++class TestExtractJsonExpectedType(unittest.TestCase):+ def test_expect_dict_gets_dict(self):+ result = extract_json('{"a": 1}', expected_type=dict)+ assert result == {"a": 1}++ def test_expect_list_gets_list(self):+ result = extract_json("[1, 2]", expected_type=list)+ assert result == [1, 2]++ def test_expect_dict_skips_list(self):+ # Text has both a list and a dict+ text = 'Here is [1] and {"a": 1}'+ result = extract_json(text, expected_type=dict)+ assert isinstance(result, dict)++ def test_expect_list_skips_dict(self):+ text = 'Here is {"a": 1} and [1, 2]'+ result = extract_json(text, expected_type=list)+ assert isinstance(result, list)++ def test_type_mismatch_falls_through(self):+ # Only a list in text, but dict expected — returns None+ result = extract_json("[1, 2]", expected_type=dict)+ assert result is None+++class TestExtractJsonComplex(unittest.TestCase):+ def test_json_in_code_fence(self):+ text = '```json\n{"a": 1}\n```'+ assert extract_json(text) == {"a": 1}++ def test_json_with_surrounding_prose(self):+ text = 'The answer is: {"result": true} as shown.'+ assert extract_json(text) == {"result": True}++ def test_json_with_think_tags(self):+ text = '<think>reasoning</think>{"answer": 42}'+ assert extract_json(text) == {"answer": 42}++ def test_json_with_trailing_comma(self):+ text = '{"a": 1, "b": 2,}'+ result = extract_json(text)+ assert result == {"a": 1, "b": 2}++ def test_json_with_comments(self):+ text = '{"a": 1 // this is a comment\n}'+ result = extract_json(text)+ assert result == {"a": 1}++ def test_nested_json(self):+ text = '{"outer": {"inner": [1, 2, 3]}}'+ result = extract_json(text)+ assert result == {"outer": {"inner": [1, 2, 3]}}+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/utilities/test_search_utilities_high_value.py b/tests/utilities/test_search_utilities_high_value.pynew file mode 100644index 0000000000..87fcead6ee--- /dev/null+++ b/tests/utilities/test_search_utilities_high_value.py@@ -0,0 +1,73 @@+"""High-value tests for utilities/search_utilities.py pure logic."""++import unittest++from local_deep_research.utilities.search_utilities import (+ LANGUAGE_CODE_MAP,+ format_findings,+)+++class TestLanguageCodeMap(unittest.TestCase):+ def test_english_maps_to_en(self):+ assert LANGUAGE_CODE_MAP["english"] == "en"++ def test_contains_major_languages(self):+ for lang in ("french", "german", "spanish", "japanese", "chinese"):+ assert lang in LANGUAGE_CODE_MAP+++class TestFormatFindings(unittest.TestCase):+ def test_followup_phase_parsing(self):+ findings = [+ {+ "phase": "Follow-up Iteration 1.2",+ "content": "Content.",+ "search_results": [],+ }+ ]+ questions = {1: ["First Q", "Second Q"]}+ result = format_findings(findings, "Sum.", questions)+ # "Second Q" must appear in the DETAILED FINDINGS section (phase-parsed),+ # not just in the questions-by-iteration listing+ detailed_section = result.split("DETAILED FINDINGS")[-1]+ assert "Second Q" in detailed_section++ def test_subquery_phase_parsing(self):+ findings = [+ {+ "phase": "Sub-query 1",+ "content": "Content.",+ "search_results": [],+ }+ ]+ questions = {0: ["Sub Q1", "Sub Q2"]}+ result = format_findings(findings, "Sum.", questions)+ # "Sub Q1" must appear in the DETAILED FINDINGS section (phase-parsed),+ # not just in the questions-by-iteration listing+ detailed_section = result.split("DETAILED FINDINGS")[-1]+ assert "Sub Q1" in detailed_section++ def test_question_in_finding_dict(self):+ findings = [+ {+ "phase": "Custom Phase",+ "content": "Content.",+ "question": "My question?",+ "search_results": [],+ }+ ]+ result = format_findings(findings, "Sum.", {})+ assert "My question?" in result++ def test_detailed_findings_section(self):+ findings = [+ {"phase": "Phase 1", "content": "Details.", "search_results": []}+ ]+ result = format_findings(findings, "Sum.", {})+ assert "DETAILED FINDINGS" in result+ assert "Phase 1" in result+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/utilities/test_small_utilities_high_value.py b/tests/utilities/test_small_utilities_high_value.pynew file mode 100644index 0000000000..40f84e3fb8--- /dev/null+++ b/tests/utilities/test_small_utilities_high_value.py@@ -0,0 +1,202 @@+"""High-value tests for small utility modules: url_utils, network_utils, type_utils, text_cleaner."""++import unittest++from local_deep_research.security.network_utils import is_private_ip+from local_deep_research.utilities.type_utils import to_bool+from local_deep_research.utilities.url_utils import normalize_url+from local_deep_research.text_processing.text_cleaner import remove_surrogates+++# ── is_private_ip ──────────────────────────────────────────────────────+++class TestIsPrivateIpLocalhost(unittest.TestCase):+ def test_localhost_string(self):+ assert is_private_ip("localhost") is True++ def test_127_0_0_1(self):+ assert is_private_ip("127.0.0.1") is True++ def test_ipv6_loopback_bracketed(self):+ assert is_private_ip("[::1]") is True++ def test_0_0_0_0(self):+ assert is_private_ip("0.0.0.0") is True+++class TestIsPrivateIpRanges(unittest.TestCase):+ def test_10_network(self):+ assert is_private_ip("10.0.0.1") is True++ def test_172_16_network(self):+ assert is_private_ip("172.16.0.50") is True++ def test_192_168_network(self):+ assert is_private_ip("192.168.1.100") is True++ def test_public_ip_8888(self):+ assert is_private_ip("8.8.8.8") is False++ def test_public_ip_1111(self):+ assert is_private_ip("1.1.1.1") is False+++class TestIsPrivateIpDomains(unittest.TestCase):+ def test_local_domain(self):+ assert is_private_ip("myhost.local") is True++ def test_external_domain(self):+ assert is_private_ip("api.openai.com") is False++ def test_random_hostname(self):+ assert is_private_ip("somehost") is False+++class TestIsPrivateIpIpv6(unittest.TestCase):+ def test_ipv6_link_local(self):+ assert is_private_ip("fe80::1") is True++ def test_ipv6_private(self):+ assert is_private_ip("fc00::1") is True++ def test_bracketed_ipv6_private(self):+ assert is_private_ip("[fc00::1]") is True+++# ── normalize_url ──────────────────────────────────────────────────────+++class TestNormalizeUrl(unittest.TestCase):+ def test_already_http(self):+ assert normalize_url("http://example.com") == "http://example.com"++ def test_already_https(self):+ assert normalize_url("https://example.com") == "https://example.com"++ def test_malformed_http_colon(self):+ assert normalize_url("http:example.com") == "http://example.com"++ def test_malformed_https_colon(self):+ assert normalize_url("https:example.com") == "https://example.com"++ def test_localhost_gets_http(self):+ result = normalize_url("localhost:11434")+ assert result == "http://localhost:11434"++ def test_external_host_gets_https(self):+ result = normalize_url("api.openai.com:443")+ assert result == "https://api.openai.com:443"++ def test_empty_raises_value_error(self):+ with self.assertRaises(ValueError):+ normalize_url("")++ def test_whitespace_stripped(self):+ result = normalize_url(" http://example.com ")+ assert result == "http://example.com"++ def test_double_slash_prefix(self):+ result = normalize_url("//localhost:8080")+ assert result == "http://localhost:8080"++ def test_private_ip_gets_http(self):+ result = normalize_url("192.168.1.1:8080")+ assert result == "http://192.168.1.1:8080"+++# ── to_bool ────────────────────────────────────────────────────────────+++class TestToBoolPassthrough(unittest.TestCase):+ def test_true(self):+ assert to_bool(True) is True++ def test_false(self):+ assert to_bool(False) is False+++class TestToBoolStrings(unittest.TestCase):+ def test_true_string(self):+ assert to_bool("true") is True++ def test_yes(self):+ assert to_bool("yes") is True++ def test_one_string(self):+ assert to_bool("1") is True++ def test_on(self):+ assert to_bool("on") is True++ def test_enabled(self):+ assert to_bool("enabled") is True++ def test_false_string(self):+ assert to_bool("false") is False++ def test_zero_string(self):+ assert to_bool("0") is False++ def test_no_string(self):+ assert to_bool("no") is False++ def test_empty_string(self):+ assert to_bool("") is False++ def test_case_insensitive(self):+ assert to_bool("TRUE") is True+ assert to_bool("True") is True++ def test_whitespace_handling(self):+ assert to_bool(" true ") is True+++class TestToBoolNoneAndOther(unittest.TestCase):+ def test_none_default_false(self):+ assert to_bool(None) is False++ def test_none_default_true(self):+ assert to_bool(None, default=True) is True++ def test_integer_zero(self):+ assert to_bool(0) is False++ def test_integer_one(self):+ assert to_bool(1) is True++ def test_integer_negative(self):+ assert to_bool(-1) is True++ def test_empty_list(self):+ assert to_bool([]) is False++ def test_nonempty_list(self):+ assert to_bool([1]) is True+++# ── remove_surrogates ──────────────────────────────────────────────────+++class TestRemoveSurrogates(unittest.TestCase):+ def test_normal_text(self):+ assert remove_surrogates("hello world") == "hello world"++ def test_empty_string_returns_empty(self):+ assert remove_surrogates("") == ""++ def test_unicode_preserved(self):+ assert remove_surrogates("café résumé") == "café résumé"++ def test_surrogate_characters_handled(self):+ # Create text with a surrogate character+ text = "hello \ud800 world"+ result = remove_surrogates(text)+ # Should not raise and should produce valid UTF-8+ result.encode("utf-8")+ assert "hello" in result+ assert "world" in result+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/web_search_engines/rate_limiting/test_tracker_high_value.py b/tests/web_search_engines/rate_limiting/test_tracker_high_value.pyindex dc4bafc8ba..f15bb1e50b 100644--- a/tests/web_search_engines/rate_limiting/test_tracker_high_value.py+++ b/tests/web_search_engines/rate_limiting/test_tracker_high_value.py@@ -8,6 +8,7 @@ Focuses on core algorithm correctness that existing tests do not cover:- _update_estimate: mixed success/failure, settings_context learning rate override"""+import randomimport timefrom collections import dequefrom unittest.mock import MagicMock, patch@@ -195,6 +196,7 @@ class TestGetWaitTime:def test_exploration_tends_lower_than_exploitation(self):"""Exploration (0.5-0.9x) should produce lower average than exploitation (0.9-1.1x)."""+ random.seed(42) # Deterministic for CI reproducibilitytracker = _make_tracker()tracker.current_estimates["Eng"] = {"base": 2.0,@@ -416,24 +418,25 @@ class TestEndToEndLearning:# After many updates, base should converge near 0.5assert abs(est["base"] - 0.5) < 0.2- def test_failures_increase_wait_estimate(self):- """Recording failures pushes the estimate upward."""- tracker = _make_tracker()+ def test_all_failures_produce_higher_estimate_than_successes(self):+ """All-failure path caps higher than all-success path at same wait time."""+ tracker_fail = _make_tracker()+ tracker_success = _make_tracker()with patch(f"{MODULE}.get_settings_context", return_value=None):- # First record 3 successes at 1.0 to create initial estimate- for _ in range(3):- tracker.record_outcome("Eng", 1.0, True, 1)+ # All failures at 2.0+ for _ in range(5):+ tracker_fail.record_outcome("Eng", 2.0, False, 0)- # Now record failures at higher wait times+ # All successes at 2.0for _ in range(5):- tracker.record_outcome("Eng", 3.0, False, 1)+ tracker_success.record_outcome("Eng", 2.0, True, 1)- final_base = tracker.current_estimates["Eng"]["base"]- # Failures should push base up (or at least not decrease from successes-only path)- # The exact behavior depends on the mix - with 3 successes and 5 failures,- # the successful_waits median (1.0) is used but EMA blends it- assert final_base > 0+ fail_base = tracker_fail.current_estimates["Eng"]["base"]+ success_base = tracker_success.current_estimates["Eng"]["base"]+ # All-failures path uses max(waits)*1.5, capped at 10+ # All-successes path uses median of waits+ assert fail_base > success_basedef test_reset_then_relearn(self):"""After reset_engine, tracker starts fresh and can learn again."""