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 coverage for exception/edge-case branches (#3031)

LearningCircuiteffc4c7e4bdd
diff --git a/tests/advanced_search_system/constraint_checking/test_evidence_analyzer_coverage.py b/tests/advanced_search_system/constraint_checking/test_evidence_analyzer_coverage.py
new file mode 100644
index 0000000000..0c24ac7ceb
--- /dev/null
+++ b/tests/advanced_search_system/constraint_checking/test_evidence_analyzer_coverage.py
@@ -0,0 +1,62 @@
+"""Tests for EvidenceAnalyzer._extract_score and ConstraintEvidence dataclass."""
+
+from unittest.mock import MagicMock
+
+from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
+ ConstraintEvidence,
+ EvidenceAnalyzer,
+)
+
+
+class TestExtractScore:
+ def setup_method(self):
+ mock_model = MagicMock()
+ self.analyzer = EvidenceAnalyzer(model=mock_model)
+
+ def test_valid_decimal_score(self):
+ result = self.analyzer._extract_score("POSITIVE: 0.8", "POSITIVE")
+ assert result == 0.8
+
+ def test_bracketed_score(self):
+ result = self.analyzer._extract_score("POSITIVE: [0.75]", "POSITIVE")
+ assert result == 0.75
+
+ def test_no_match_returns_default(self):
+ result = self.analyzer._extract_score("no score here", "POSITIVE")
+ assert result == 0.1
+
+ def test_integer_score(self):
+ result = self.analyzer._extract_score("POSITIVE: 1", "POSITIVE")
+ assert result == 1.0
+
+ def test_case_insensitive(self):
+ result = self.analyzer._extract_score("positive: 0.6", "POSITIVE")
+ assert result == 0.6
+
+ def test_different_label(self):
+ result = self.analyzer._extract_score(
+ "NEGATIVE: 0.3\nPOSITIVE: 0.7", "NEGATIVE"
+ )
+ assert result == 0.3
+
+ def test_uncertainty_label(self):
+ result = self.analyzer._extract_score(
+ "UNCERTAINTY: [0.2]", "UNCERTAINTY"
+ )
+ assert result == 0.2
+
+
+class TestConstraintEvidenceDataclass:
+ def test_creation(self):
+ evidence = ConstraintEvidence(
+ positive_confidence=0.7,
+ negative_confidence=0.2,
+ uncertainty=0.1,
+ evidence_text="some text",
+ source="search",
+ )
+ assert evidence.positive_confidence == 0.7
+ assert evidence.negative_confidence == 0.2
+ assert evidence.uncertainty == 0.1
+ assert evidence.evidence_text == "some text"
+ assert evidence.source == "search"
diff --git a/tests/advanced_search_system/findings/test_topic_coverage.py b/tests/advanced_search_system/findings/test_topic_coverage.py
new file mode 100644
index 0000000000..5c9bbcbe1f
--- /dev/null
+++ b/tests/advanced_search_system/findings/test_topic_coverage.py
@@ -0,0 +1,159 @@
+"""Tests for uncovered branches in topic module."""
+
+from local_deep_research.advanced_search_system.findings.topic import (
+ Topic,
+ TopicGraph,
+)
+
+
+class TestTopicRejectSource:
+ def test_reject_source_not_in_supporting(self):
+ """Rejecting a source not in supporting_sources only adds to rejected."""
+ topic = Topic(
+ id="t1",
+ title="Test",
+ lead_source={"url": "lead"},
+ supporting_sources=[{"url": "s1"}],
+ )
+ new_source = {"url": "new"}
+ topic.reject_source(new_source)
+
+ # Should NOT remove anything from supporting
+ assert {"url": "s1"} in topic.supporting_sources
+ # Should add to rejected
+ assert new_source in topic.rejected_sources
+
+ def test_reject_source_in_supporting(self):
+ """Rejecting a source in supporting_sources removes it and adds to rejected."""
+ source = {"url": "s1"}
+ topic = Topic(
+ id="t1",
+ title="Test",
+ lead_source={"url": "lead"},
+ supporting_sources=[source],
+ )
+ topic.reject_source(source)
+
+ assert source not in topic.supporting_sources
+ assert source in topic.rejected_sources
+
+
+class TestTopicGraphLinkTopics:
+ def test_link_topics_one_missing(self):
+ """link_topics should be a no-op when one topic doesn't exist."""
+ graph = TopicGraph()
+ t1 = Topic(id="t1", title="T1", lead_source={"url": "a"})
+ graph.add_topic(t1)
+
+ graph.link_topics("t1", "nonexistent")
+
+ assert t1.related_topic_ids == []
+
+ def test_link_topics_both_missing(self):
+ """link_topics should be a no-op when both topics don't exist."""
+ graph = TopicGraph()
+ graph.link_topics("x", "y")
+ assert len(graph.topics) == 0
+
+
+class TestTopicGraphSetParentChild:
+ def test_set_parent_child_parent_missing(self):
+ """set_parent_child should be a no-op when parent doesn't exist."""
+ graph = TopicGraph()
+ child = Topic(id="c1", title="Child", lead_source={"url": "c"})
+ graph.add_topic(child)
+
+ graph.set_parent_child("nonexistent", "c1")
+
+ assert child.parent_topic_id is None
+
+ def test_set_parent_child_child_missing(self):
+ """set_parent_child should be a no-op when child doesn't exist."""
+ graph = TopicGraph()
+ parent = Topic(id="p1", title="Parent", lead_source={"url": "p"})
+ graph.add_topic(parent)
+
+ graph.set_parent_child("p1", "nonexistent")
+
+ assert parent.child_topic_ids == []
+
+
+class TestTopicGraphMergeTopics:
+ def test_merge_with_children_and_parent_refs(self):
+ """merge_topics transfers topic2's children to topic1."""
+ graph = TopicGraph()
+ t1 = Topic(id="t1", title="T1", lead_source={"url": "a"})
+ t2 = Topic(id="t2", title="T2", lead_source={"url": "b"})
+ child = Topic(
+ id="child",
+ title="Child",
+ lead_source={"url": "c"},
+ parent_topic_id="t2",
+ )
+ graph.add_topic(t1)
+ graph.add_topic(t2)
+ graph.add_topic(child)
+ graph.set_parent_child("t2", "child")
+
+ result = graph.merge_topics("t1", "t2")
+
+ assert result is not None
+ assert "child" in result.child_topic_ids
+ assert child.parent_topic_id == "t1"
+ assert "t2" not in graph.topics
+
+ def test_merge_with_parent_topic_id_reference(self):
+ """After merge, topics referencing topic2 as parent get updated to topic1."""
+ graph = TopicGraph()
+ t1 = Topic(id="t1", title="T1", lead_source={"url": "a"})
+ t2 = Topic(id="t2", title="T2", lead_source={"url": "b"})
+ orphan = Topic(
+ id="orphan",
+ title="Orphan",
+ lead_source={"url": "o"},
+ parent_topic_id="t2",
+ )
+ graph.add_topic(t1)
+ graph.add_topic(t2)
+ graph.add_topic(orphan)
+
+ graph.merge_topics("t1", "t2")
+
+ assert orphan.parent_topic_id == "t1"
+
+ def test_merge_with_duplicate_rejected_sources(self):
+ """Rejected sources already in topic1 are not duplicated."""
+ shared_rejected = {"url": "rejected"}
+ t1 = Topic(
+ id="t1",
+ title="T1",
+ lead_source={"url": "a"},
+ rejected_sources=[shared_rejected],
+ )
+ t2 = Topic(
+ id="t2",
+ title="T2",
+ lead_source={"url": "b"},
+ rejected_sources=[shared_rejected, {"url": "other_rejected"}],
+ )
+ graph = TopicGraph()
+ graph.add_topic(t1)
+ graph.add_topic(t2)
+
+ result = graph.merge_topics("t1", "t2")
+
+ assert result is not None
+ # shared_rejected should appear only once
+ count = result.rejected_sources.count(shared_rejected)
+ assert count == 1
+ # other_rejected should be present
+ assert {"url": "other_rejected"} in result.rejected_sources
+
+ def test_merge_nonexistent_topic_returns_none(self):
+ """merge_topics returns None when one topic doesn't exist."""
+ graph = TopicGraph()
+ t1 = Topic(id="t1", title="T1", lead_source={"url": "a"})
+ graph.add_topic(t1)
+
+ assert graph.merge_topics("t1", "nonexistent") is None
+ assert graph.merge_topics("nonexistent", "t1") is None
diff --git a/tests/advanced_search_system/test_base_class_coverage.py b/tests/advanced_search_system/test_base_class_coverage.py
new file mode 100644
index 0000000000..4d802785c7
--- /dev/null
+++ b/tests/advanced_search_system/test_base_class_coverage.py
@@ -0,0 +1,268 @@
+"""
+Tests for base class concrete methods in the advanced_search_system.
+
+Each test class creates a minimal concrete subclass that inherits from the ABC,
+implements abstract methods as no-ops, then exercises the concrete helper methods.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+)
+from local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker import (
+ BaseConstraintChecker,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.findings.base_findings import (
+ BaseFindingsRepository,
+)
+from local_deep_research.advanced_search_system.knowledge.base_knowledge import (
+ BaseKnowledgeGenerator,
+)
+from local_deep_research.advanced_search_system.questions.base_question import (
+ BaseQuestionGenerator,
+)
+from local_deep_research.advanced_search_system.questions.followup.base_followup_question import (
+ BaseFollowUpQuestionGenerator,
+)
+
+
+# ---------------------------------------------------------------------------
+# Minimal concrete subclasses
+# ---------------------------------------------------------------------------
+
+
+class ConcreteKnowledgeGenerator(BaseKnowledgeGenerator):
+ def generate(self, query, context):
+ return ""
+
+ def generate_knowledge(
+ self, query, context="", current_knowledge="", questions=None
+ ):
+ return ""
+
+ def generate_sub_knowledge(self, sub_query, context=""):
+ return ""
+
+ def compress_knowledge(
+ self, current_knowledge, query, section_links, **kwargs
+ ):
+ return ""
+
+ def format_citations(self, links):
+ return ""
+
+
+class ConcreteConstraintChecker(BaseConstraintChecker):
+ def check_candidate(self, candidate, constraints):
+ return None
+
+ def should_reject_candidate(self, candidate, constraint, evidence_data):
+ return (False, "")
+
+
+class ConcreteQuestionGenerator(BaseQuestionGenerator):
+ def generate_questions(
+ self,
+ current_knowledge,
+ query,
+ questions_per_iteration,
+ questions_by_iteration,
+ ):
+ return []
+
+
+class ConcreteFollowUpQuestionGenerator(BaseFollowUpQuestionGenerator):
+ def generate_contextualized_query(
+ self, follow_up_query, original_query, past_findings, **kwargs
+ ):
+ return ""
+
+
+class ConcreteFindingsRepository(BaseFindingsRepository):
+ def add_finding(self, query, finding):
+ pass
+
+ def get_findings(self, query):
+ return []
+
+ def clear_findings(self, query):
+ pass
+
+ def synthesize_findings(
+ self, query, sub_queries, findings, accumulated_knowledge
+ ):
+ return ""
+
+
+# ---------------------------------------------------------------------------
+# Tests
+# ---------------------------------------------------------------------------
+
+
+class TestBaseKnowledgeGenerator:
+ def setup_method(self):
+ self.gen = ConcreteKnowledgeGenerator(model=Mock())
+
+ def test_validate_knowledge_valid(self):
+ assert self.gen._validate_knowledge("some knowledge") is True
+
+ def test_validate_knowledge_empty_string(self):
+ assert self.gen._validate_knowledge("") is False
+
+ def test_validate_knowledge_none(self):
+ assert self.gen._validate_knowledge(None) is False
+
+ def test_validate_knowledge_non_string(self):
+ assert self.gen._validate_knowledge(123) is False
+
+ def test_validate_links_valid(self):
+ assert (
+ self.gen._validate_links(["http://a.com", "http://b.com"]) is True
+ )
+
+ def test_validate_links_empty_list(self):
+ assert self.gen._validate_links([]) is True
+
+ def test_validate_links_not_list(self):
+ assert self.gen._validate_links("not a list") is False
+
+ def test_validate_links_non_string_element(self):
+ assert self.gen._validate_links(["ok", 42]) is False
+
+ def test_extract_key_points(self):
+ result = self.gen._extract_key_points("line1\nline2\nline3")
+ assert result == ["line1", "line2", "line3"]
+
+ def test_extract_key_points_single_line(self):
+ result = self.gen._extract_key_points("single")
+ assert result == ["single"]
+
+
+class TestBaseConstraintChecker:
+ def _make_candidate(self, name="TestCandidate"):
+ return Candidate(name=name)
+
+ def _make_constraint(self, value="must be blue", weight=1.0):
+ return Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="test",
+ value=value,
+ weight=weight,
+ )
+
+ def test_gather_evidence_with_gatherer(self):
+ gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ConcreteConstraintChecker(
+ model=Mock(), evidence_gatherer=gatherer
+ )
+ candidate = self._make_candidate()
+ constraint = self._make_constraint()
+
+ result = checker._gather_evidence_for_constraint(candidate, constraint)
+
+ gatherer.assert_called_once_with(candidate, constraint)
+ assert result == [{"text": "evidence"}]
+
+ def test_gather_evidence_without_gatherer(self):
+ checker = ConcreteConstraintChecker(
+ model=Mock(), evidence_gatherer=None
+ )
+ result = checker._gather_evidence_for_constraint(
+ self._make_candidate(), self._make_constraint()
+ )
+ assert result == []
+
+ def test_log_constraint_result_high_score(self):
+ checker = ConcreteConstraintChecker(model=Mock())
+ checker._log_constraint_result(
+ self._make_candidate(), self._make_constraint(), 0.9, {}
+ )
+
+ def test_log_constraint_result_medium_score(self):
+ checker = ConcreteConstraintChecker(model=Mock())
+ checker._log_constraint_result(
+ self._make_candidate(), self._make_constraint(), 0.6, {}
+ )
+
+ def test_log_constraint_result_low_score(self):
+ checker = ConcreteConstraintChecker(model=Mock())
+ checker._log_constraint_result(
+ self._make_candidate(), self._make_constraint(), 0.3, {}
+ )
+
+ def test_calculate_weighted_score(self):
+ checker = ConcreteConstraintChecker(model=Mock())
+ scores = [0.8, 0.6]
+ weights = [2.0, 1.0]
+ result = checker._calculate_weighted_score(scores, weights)
+ expected = (0.8 * 2.0 + 0.6 * 1.0) / (2.0 + 1.0)
+ assert abs(result - expected) < 1e-9
+
+ def test_calculate_weighted_score_empty(self):
+ checker = ConcreteConstraintChecker(model=Mock())
+ assert checker._calculate_weighted_score([], []) == 0.0
+
+ def test_calculate_weighted_score_empty_scores(self):
+ checker = ConcreteConstraintChecker(model=Mock())
+ assert checker._calculate_weighted_score([], [1.0]) == 0.0
+
+ def test_calculate_weighted_score_empty_weights(self):
+ checker = ConcreteConstraintChecker(model=Mock())
+ assert checker._calculate_weighted_score([0.5], []) == 0.0
+
+
+class TestBaseQuestionGenerator:
+ def setup_method(self):
+ self.gen = ConcreteQuestionGenerator(model=Mock())
+
+ def test_format_previous_questions(self):
+ questions_by_iteration = {
+ 1: ["What is X?", "What is Y?"],
+ 2: ["How does Z work?"],
+ }
+ result = self.gen._format_previous_questions(questions_by_iteration)
+ assert "Iteration 1:" in result
+ assert "- What is X?" in result
+ assert "- What is Y?" in result
+ assert "Iteration 2:" in result
+ assert "- How does Z work?" in result
+
+ def test_format_previous_questions_empty(self):
+ result = self.gen._format_previous_questions({})
+ assert result == ""
+
+
+class TestBaseFollowUpQuestionGenerator:
+ def setup_method(self):
+ self.gen = ConcreteFollowUpQuestionGenerator(model=Mock())
+
+ def test_init_sets_empty_context(self):
+ assert self.gen.follow_up_context == {}
+
+ def test_set_follow_up_context(self):
+ ctx = {"past_findings": "some findings", "original_query": "test query"}
+ self.gen.set_follow_up_context(ctx)
+ assert self.gen.follow_up_context is ctx
+
+ def test_generate_questions_returns_query(self):
+ result = self.gen.generate_questions(
+ current_knowledge="knowledge",
+ query="my query",
+ questions_per_iteration=3,
+ questions_by_iteration={},
+ )
+ assert result == ["my query"]
+
+
+class TestBaseFindingsRepository:
+ def test_init_sets_model_and_findings(self):
+ model = Mock()
+ repo = ConcreteFindingsRepository(model=model)
+ assert repo.model is model
+ assert repo.findings == {}
diff --git a/tests/defaults/test_defaults.py b/tests/defaults/test_defaults.py
index df05cfe26d..8459162d37 100644
--- a/tests/defaults/test_defaults.py
+++ b/tests/defaults/test_defaults.py
@@ -1,6 +1,7 @@
"""Tests for defaults module."""
from pathlib import Path
+from unittest.mock import patch
class TestDefaultsDir:
@@ -73,3 +74,19 @@ class TestEnsureDefaultsExist:
result = ensure_defaults_exist()
# Don't assert True because some files may be missing in test env
assert result is True or result is False
+
+ def test_returns_false_when_files_missing(self):
+ """Cover the 'return False' branch when files are missing."""
+ from local_deep_research.defaults import (
+ DEFAULTS_DIR,
+ ensure_defaults_exist,
+ )
+
+ fake_files = {
+ "nonexistent_file.toml": DEFAULTS_DIR / "does_not_exist.toml",
+ }
+ with patch.dict(
+ "local_deep_research.defaults.DEFAULT_FILES", fake_files, clear=True
+ ):
+ result = ensure_defaults_exist()
+ assert result is False
diff --git a/tests/domain_classifier/test_lazy_imports.py b/tests/domain_classifier/test_lazy_imports.py
new file mode 100644
index 0000000000..b945fe39c4
--- /dev/null
+++ b/tests/domain_classifier/test_lazy_imports.py
@@ -0,0 +1,21 @@
+"""Tests for domain_classifier lazy import __getattr__."""
+
+import pytest
+
+
+class TestDomainClassifierLazyImports:
+ def test_import_domain_classifier(self):
+ from local_deep_research.domain_classifier import DomainClassifier
+
+ assert DomainClassifier is not None
+
+ def test_import_domain_classification(self):
+ from local_deep_research.domain_classifier import DomainClassification
+
+ assert DomainClassification is not None
+
+ def test_invalid_attribute_raises(self):
+ with pytest.raises(AttributeError, match="has no attribute"):
+ from local_deep_research import domain_classifier
+
+ domain_classifier.__getattr__("NonexistentThing")
diff --git a/tests/exporters/test_base_exporter_coverage.py b/tests/exporters/test_base_exporter_coverage.py
new file mode 100644
index 0000000000..06a45d50ae
--- /dev/null
+++ b/tests/exporters/test_base_exporter_coverage.py
@@ -0,0 +1,202 @@
+"""Tests for BaseExporter, ExportResult, ExportOptions, and BaseFileVerifier."""
+
+import hashlib
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from local_deep_research.exporters.base import (
+ BaseExporter,
+ ExportOptions,
+ ExportResult,
+)
+from local_deep_research.security.file_integrity.base_verifier import (
+ BaseFileVerifier,
+ FileType,
+)
+
+
+# --- Concrete subclasses for testing abstract bases ---
+
+
+class StubExporter(BaseExporter):
+ @property
+ def format_name(self) -> str:
+ return "stub"
+
+ @property
+ def file_extension(self) -> str:
+ return ".stub"
+
+ @property
+ def mimetype(self) -> str:
+ return "application/x-stub"
+
+ def export(self, markdown_content, options=None):
+ return ExportResult(
+ content=markdown_content.encode(),
+ filename="out.stub",
+ mimetype=self.mimetype,
+ )
+
+
+class StubVerifier(BaseFileVerifier):
+ def should_verify(self, file_path: Path) -> bool:
+ return file_path.suffix == ".stub"
+
+ def get_file_type(self) -> FileType:
+ return FileType.EXPORT
+
+ def allows_modifications(self) -> bool:
+ return False
+
+
+# --- ExportResult tests ---
+
+
+class TestExportResult:
+ def test_fields(self):
+ result = ExportResult(
+ content=b"hello", filename="f.txt", mimetype="text/plain"
+ )
+ assert result.content == b"hello"
+ assert result.filename == "f.txt"
+ assert result.mimetype == "text/plain"
+
+
+# --- ExportOptions tests ---
+
+
+class TestExportOptions:
+ def test_defaults(self):
+ opts = ExportOptions()
+ assert opts.title is None
+ assert opts.metadata is None
+ assert opts.custom_options == {}
+
+ def test_with_values(self):
+ opts = ExportOptions(
+ title="My Report",
+ metadata={"author": "Alice"},
+ custom_options={"css": "body{}"},
+ )
+ assert opts.title == "My Report"
+ assert opts.metadata == {"author": "Alice"}
+ assert opts.custom_options == {"css": "body{}"}
+
+
+# --- BaseExporter._validate_content_size tests ---
+
+
+class TestValidateContentSize:
+ def test_under_limit_no_error(self):
+ exporter = StubExporter()
+ exporter._validate_content_size("short content")
+
+ def test_over_limit_raises(self):
+ exporter = StubExporter()
+ oversized = "x" * (exporter.MAX_CONTENT_SIZE + 1)
+ with pytest.raises(ValueError, match="exceeds maximum size"):
+ exporter._validate_content_size(oversized)
+
+ def test_exactly_at_limit_no_error(self):
+ exporter = StubExporter()
+ exact = "x" * exporter.MAX_CONTENT_SIZE
+ exporter._validate_content_size(exact)
+
+
+# --- BaseExporter._generate_safe_filename tests ---
+
+
+class TestGenerateSafeFilename:
+ def test_with_title(self):
+ exporter = StubExporter()
+ filename = exporter._generate_safe_filename("My Report")
+ assert filename == "My_Report.stub"
+
+ def test_without_title(self):
+ exporter = StubExporter()
+ assert exporter._generate_safe_filename(None) == "research_report.stub"
+ assert exporter._generate_safe_filename("") == "research_report.stub"
+
+ def test_special_chars_stripped(self):
+ exporter = StubExporter()
+ filename = exporter._generate_safe_filename("Hello! @World# (2024)")
+ # Only word chars, spaces, hyphens survive; spaces become underscores
+ assert "!" not in filename
+ assert "@" not in filename
+ assert "#" not in filename
+ assert filename.endswith(".stub")
+
+ def test_long_title_truncated(self):
+ exporter = StubExporter()
+ long_title = "A" * 100
+ filename = exporter._generate_safe_filename(long_title)
+ # safe_title is truncated to 50 chars, plus extension
+ assert filename == "A" * 50 + ".stub"
+
+
+# --- BaseExporter._prepend_title_if_needed tests ---
+
+
+class TestPrependTitleIfNeeded:
+ def test_no_title_returns_content(self):
+ exporter = StubExporter()
+ content = "Some body text"
+ assert exporter._prepend_title_if_needed(content, None) == content
+ assert exporter._prepend_title_if_needed(content, "") == content
+
+ def test_content_starts_with_same_title(self):
+ exporter = StubExporter()
+ content = "# My Title\n\nBody text"
+ result = exporter._prepend_title_if_needed(content, "My Title")
+ assert result == content # unchanged
+
+ def test_content_starts_with_different_heading(self):
+ exporter = StubExporter()
+ content = "## Section One\n\nBody text"
+ result = exporter._prepend_title_if_needed(content, "My Title")
+ # Has a heading already, so title is NOT prepended
+ assert result == content
+
+ def test_content_without_heading_gets_title(self):
+ exporter = StubExporter()
+ content = "Just some plain text"
+ result = exporter._prepend_title_if_needed(content, "My Title")
+ assert result == "# My Title\n\nJust some plain text"
+
+ def test_content_with_leading_whitespace_and_heading(self):
+ exporter = StubExporter()
+ content = " # Existing Heading\n\nBody"
+ result = exporter._prepend_title_if_needed(content, "New Title")
+ # lstrip() finds '#', so title is NOT prepended
+ assert result == content
+
+
+# --- BaseFileVerifier tests ---
+
+
+class TestBaseFileVerifier:
+ def test_calculate_checksum(self):
+ verifier = StubVerifier()
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".stub") as f:
+ f.write(b"test data for checksum")
+ f.flush()
+ tmp_path = Path(f.name)
+
+ try:
+ result = verifier.calculate_checksum(tmp_path)
+ expected = hashlib.sha256(b"test data for checksum").hexdigest()
+ assert result == expected
+ finally:
+ tmp_path.unlink()
+
+ def test_get_algorithm(self):
+ verifier = StubVerifier()
+ assert verifier.get_algorithm() == "sha256"
+
+ def test_checksum_file_not_found(self):
+ verifier = StubVerifier()
+ with pytest.raises(FileNotFoundError):
+ verifier.calculate_checksum(Path("/nonexistent/file.stub"))
diff --git a/tests/news/test_storage_base_coverage.py b/tests/news/test_storage_base_coverage.py
new file mode 100644
index 0000000000..6fc2e64818
--- /dev/null
+++ b/tests/news/test_storage_base_coverage.py
@@ -0,0 +1,49 @@
+"""Tests for BaseStorage.generate_id concrete method."""
+
+import uuid
+from typing import Any, Dict, List, Optional
+
+from local_deep_research.news.core.storage import BaseStorage
+
+
+class ConcreteStorage(BaseStorage):
+ """Minimal concrete subclass for testing the base generate_id method."""
+
+ def create(self, data: Dict[str, Any]) -> str:
+ return ""
+
+ def get(self, id: str) -> Optional[Dict[str, Any]]:
+ return None
+
+ def update(self, id: str, data: Dict[str, Any]) -> bool:
+ return False
+
+ def delete(self, id: str) -> bool:
+ return False
+
+ def list(
+ self,
+ filters: Optional[Dict[str, Any]] = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> List[Dict[str, Any]]:
+ return []
+
+
+class TestBaseStorageGenerateId:
+ def test_returns_valid_uuid_string(self):
+ storage = ConcreteStorage()
+ result = storage.generate_id()
+ # Should be a valid UUID4 string
+ parsed = uuid.UUID(result, version=4)
+ assert str(parsed) == result
+
+ def test_returns_unique_ids(self):
+ storage = ConcreteStorage()
+ ids = {storage.generate_id() for _ in range(100)}
+ assert len(ids) == 100
+
+ def test_returns_string_type(self):
+ storage = ConcreteStorage()
+ result = storage.generate_id()
+ assert isinstance(result, str)
diff --git a/tests/text_processing/test_text_cleaner.py b/tests/text_processing/test_text_cleaner.py
index 5eb23f01bc..330ad275ed 100644
--- a/tests/text_processing/test_text_cleaner.py
+++ b/tests/text_processing/test_text_cleaner.py
@@ -75,3 +75,28 @@ class TestRemoveSurrogates:
result.encode("utf-8")
assert "Start" in result
assert "End" in result
+
+ def test_exception_handler_fallback(self):
+ """Should use ignore-based fallback when encode raises an exception.
+
+ Uses a str subclass whose encode method raises on surrogatepass,
+ forcing the except branch (lines 32-38) to execute.
+ """
+
+ class BadString(str):
+ _call_count = 0
+
+ def encode(self, encoding="utf-8", errors="strict"):
+ BadString._call_count += 1
+ if errors == "surrogatepass":
+ raise RuntimeError("Simulated encode failure")
+ return super().encode(encoding, errors=errors)
+
+ BadString._call_count = 0
+ text = BadString("hello world")
+ result = remove_surrogates(text)
+ assert isinstance(result, str)
+ assert "hello" in result
+ # surrogatepass was attempted (triggering exception),
+ # then ignore was used as fallback
+ assert BadString._call_count >= 2