~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 86 tests for RIS entry parsing, strategy pure logic, and PubMed metadata edges (#2483)
LearningCircuita79e2c170086
diff --git a/tests/advanced_search_system/strategies/test_strategy_pure_logic.py b/tests/advanced_search_system/strategies/test_strategy_pure_logic.pynew file mode 100644index 0000000000..9f5a3e65eb--- /dev/null+++ b/tests/advanced_search_system/strategies/test_strategy_pure_logic.py@@ -0,0 +1,627 @@+"""+Tests for pure logic functions in search strategies.++These functions have zero existing test coverage despite being+testable without mocking LLMs or search engines:++- SourceBasedSearchStrategy._format_search_results_as_context()+- AdaptiveDecompositionStrategy._calculate_confidence()+- AdaptiveDecompositionStrategy StepType enum and StepResult dataclass+- NewsAggregationStrategy._format_news_summary()+- NewsAggregationStrategy._fallback_news_extraction()+- BaseSearchStrategy.check_termination()+"""++from unittest.mock import Mock++import pytest+++# ---------------------------------------------------------------------------+# StepType and StepResult (adaptive_decomposition_strategy.py)+# ---------------------------------------------------------------------------+++class TestStepType:+ """Tests for StepType enum values."""++ def test_all_step_types_exist(self):+ """All expected step types exist."""+ from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (+ StepType,+ )++ assert StepType.CONSTRAINT_EXTRACTION.value == "constraint_extraction"+ assert StepType.INITIAL_SEARCH.value == "initial_search"+ assert StepType.VERIFICATION.value == "verification"+ assert StepType.REFINEMENT.value == "refinement"+ assert StepType.SYNTHESIS.value == "synthesis"++ def test_step_type_count(self):+ """Exactly 5 step types defined."""+ from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (+ StepType,+ )++ assert len(StepType) == 5++ def test_step_type_comparison(self):+ """Step types support equality comparison."""+ from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (+ StepType,+ )++ assert StepType.VERIFICATION == StepType.VERIFICATION+ assert StepType.VERIFICATION != StepType.REFINEMENT+++class TestStepResult:+ """Tests for StepResult dataclass."""++ def test_create_with_required_fields(self):+ """Create StepResult with required fields."""+ from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (+ StepResult,+ StepType,+ )++ result = StepResult(+ step_type=StepType.INITIAL_SEARCH,+ description="Initial search",+ findings={"data": [1, 2, 3]},+ )++ assert result.step_type == StepType.INITIAL_SEARCH+ assert result.description == "Initial search"+ assert result.findings == {"data": [1, 2, 3]}++ def test_default_values(self):+ """Default values for optional fields."""+ from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (+ StepResult,+ StepType,+ )++ result = StepResult(+ step_type=StepType.SYNTHESIS,+ description="Synthesize",+ findings={},+ )++ assert result.next_action is None+ assert result.confidence == 0.0++ def test_create_with_all_fields(self):+ """Create StepResult with all fields."""+ from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (+ StepResult,+ StepType,+ )++ result = StepResult(+ step_type=StepType.VERIFICATION,+ description="Verify facts",+ findings={"verified": True},+ next_action="refine",+ confidence=0.85,+ )++ assert result.next_action == "refine"+ assert result.confidence == 0.85+++# ---------------------------------------------------------------------------+# _calculate_confidence (adaptive_decomposition_strategy.py)+# ---------------------------------------------------------------------------+++class TestCalculateConfidence:+ """Tests for AdaptiveDecompositionStrategy._calculate_confidence()."""++ def _make_strategy(self, constraints, verified_facts, candidates=None):+ """Create a strategy with specific working_knowledge state."""+ from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (+ AdaptiveDecompositionStrategy,+ )++ model = Mock()+ search = Mock()+ strategy = AdaptiveDecompositionStrategy(+ model=model, search=search, all_links_of_system=[]+ )+ strategy.working_knowledge = {+ "original_query": "test",+ "constraints": constraints,+ "candidates": candidates or [],+ "verified_facts": verified_facts,+ "uncertainties": [],+ }+ return strategy++ def test_no_constraints_returns_zero(self):+ """Zero constraints returns 0.0 confidence."""+ strategy = self._make_strategy(constraints=[], verified_facts=["fact1"])+ assert strategy._calculate_confidence() == 0.0++ def test_all_constraints_verified(self):+ """All constraints verified gives high confidence."""+ strategy = self._make_strategy(+ constraints=["c1", "c2"],+ verified_facts=["f1", "f2"],+ )+ confidence = strategy._calculate_confidence()+ assert confidence == pytest.approx(0.95) # Capped at 0.95++ def test_half_constraints_verified(self):+ """Half constraints verified gives 0.5."""+ strategy = self._make_strategy(+ constraints=["c1", "c2"],+ verified_facts=["f1"],+ )+ confidence = strategy._calculate_confidence()+ assert confidence == pytest.approx(0.5)++ def test_candidates_boost(self):+ """Having candidates adds 0.1 to confidence."""+ strategy = self._make_strategy(+ constraints=["c1", "c2"],+ verified_facts=["f1"],+ candidates=["candidate_a"],+ )+ confidence = strategy._calculate_confidence()+ assert confidence == pytest.approx(0.6) # 0.5 + 0.1++ def test_confidence_capped_at_095(self):+ """Confidence capped at 0.95 even with candidates boost."""+ strategy = self._make_strategy(+ constraints=["c1"],+ verified_facts=["f1"],+ candidates=["c_a"],+ )+ confidence = strategy._calculate_confidence()+ # 1.0 + 0.1 = 1.1, capped to 0.95+ assert confidence == pytest.approx(0.95)++ def test_no_verified_facts(self):+ """No verified facts gives 0.0 confidence."""+ strategy = self._make_strategy(+ constraints=["c1", "c2", "c3"],+ verified_facts=[],+ )+ assert strategy._calculate_confidence() == pytest.approx(0.0)++ def test_more_verified_than_constraints(self):+ """More verified facts than constraints still capped at 0.95."""+ strategy = self._make_strategy(+ constraints=["c1"],+ verified_facts=["f1", "f2", "f3"],+ )+ confidence = strategy._calculate_confidence()+ # 3/1 = 3.0, capped to 0.95+ assert confidence == pytest.approx(0.95)+++# ---------------------------------------------------------------------------+# _format_search_results_as_context (source_based_strategy.py)+# ---------------------------------------------------------------------------+++class TestFormatSearchResultsAsContext:+ """Tests for SourceBasedSearchStrategy._format_search_results_as_context()."""++ def _make_strategy(self):+ """Create a SourceBasedSearchStrategy with mocked dependencies."""+ from local_deep_research.advanced_search_system.strategies.source_based_strategy import (+ SourceBasedSearchStrategy,+ )++ model = Mock()+ search = Mock()+ strategy = SourceBasedSearchStrategy(+ model=model, search=search, all_links_of_system=[]+ )+ return strategy++ def test_empty_results(self):+ """Empty results list produces empty string."""+ strategy = self._make_strategy()+ result = strategy._format_search_results_as_context([])+ assert result == ""++ def test_single_result(self):+ """Single result formatted correctly."""+ strategy = self._make_strategy()+ results = [+ {+ "title": "Python Docs",+ "snippet": "Official documentation",+ "link": "https://docs.python.org",+ }+ ]+ result = strategy._format_search_results_as_context(results)+ assert "Source 1: Python Docs" in result+ assert "URL: https://docs.python.org" in result+ assert "Snippet: Official documentation" in result++ def test_multiple_results_numbered(self):+ """Multiple results numbered sequentially."""+ strategy = self._make_strategy()+ results = [+ {"title": "First", "snippet": "A", "link": "https://a.com"},+ {"title": "Second", "snippet": "B", "link": "https://b.com"},+ {"title": "Third", "snippet": "C", "link": "https://c.com"},+ ]+ result = strategy._format_search_results_as_context(results)+ assert "Source 1: First" in result+ assert "Source 2: Second" in result+ assert "Source 3: Third" in result++ def test_missing_title_uses_untitled(self):+ """Missing title defaults to 'Untitled'."""+ strategy = self._make_strategy()+ results = [{"snippet": "Content", "link": "https://example.com"}]+ result = strategy._format_search_results_as_context(results)+ assert "Source 1: Untitled" in result++ def test_missing_snippet_skips_result(self):+ """Result with empty snippet is skipped from output."""+ strategy = self._make_strategy()+ results = [+ {"title": "No Snippet", "snippet": "", "link": "https://a.com"},+ {+ "title": "Has Snippet",+ "snippet": "Content",+ "link": "https://b.com",+ },+ ]+ result = strategy._format_search_results_as_context(results)+ assert "No Snippet" not in result+ # Numbering uses original enumerate index, so second result is Source 2+ assert "Source 2: Has Snippet" in result++ def test_missing_link_uses_empty(self):+ """Missing link defaults to empty string."""+ strategy = self._make_strategy()+ results = [{"title": "Test", "snippet": "Content"}]+ result = strategy._format_search_results_as_context(results)+ assert "URL: \n" in result++ def test_results_separated_by_double_newline(self):+ """Results are separated by double newlines."""+ strategy = self._make_strategy()+ results = [+ {"title": "A", "snippet": "Content A", "link": "https://a.com"},+ {"title": "B", "snippet": "Content B", "link": "https://b.com"},+ ]+ result = strategy._format_search_results_as_context(results)+ assert "\n\n" in result++ def test_does_not_modify_input(self):+ """Method does not modify the input list or dicts."""+ strategy = self._make_strategy()+ results = [+ {"title": "Test", "snippet": "Content", "link": "https://a.com"}+ ]+ original_result = dict(results[0])+ strategy._format_search_results_as_context(results)+ assert results[0] == original_result+++# ---------------------------------------------------------------------------+# _format_news_summary (news_strategy.py)+# ---------------------------------------------------------------------------+++class TestFormatNewsSummary:+ """Tests for NewsAggregationStrategy._format_news_summary()."""++ def _make_strategy(self):+ """Create a NewsAggregationStrategy with mocked dependencies."""+ from local_deep_research.advanced_search_system.strategies.news_strategy import (+ NewsAggregationStrategy,+ )++ model = Mock()+ search = Mock()+ strategy = NewsAggregationStrategy(+ model=model, search=search, all_links_of_system=[]+ )+ return strategy++ def test_empty_items_returns_no_stories(self):+ """Empty list returns 'no stories' message."""+ strategy = self._make_strategy()+ result = strategy._format_news_summary([])+ assert "No significant news stories found" in result++ def test_single_item_formatted(self):+ """Single news item is formatted with headline and impact."""+ strategy = self._make_strategy()+ items = [+ {+ "headline": "Major Event",+ "category": "Politics",+ "impact_score": 8,+ "summary": "Something happened.",+ }+ ]+ result = strategy._format_news_summary(items)+ assert "Major Event" in result+ assert "8/10" in result+ assert "Politics" in result++ def test_groups_by_category(self):+ """Items are grouped by category."""+ strategy = self._make_strategy()+ items = [+ {"headline": "Tech News", "category": "Tech", "impact_score": 7},+ {"headline": "War Update", "category": "War", "impact_score": 9},+ {"headline": "More Tech", "category": "Tech", "impact_score": 6},+ ]+ result = strategy._format_news_summary(items)+ assert "**Tech** (2 stories)" in result+ assert "**War** (1 stories)" in result++ def test_top_story_highlighted(self):+ """Top story (highest impact) is highlighted."""+ strategy = self._make_strategy()+ items = [+ {"headline": "Minor Event", "category": "Other", "impact_score": 3},+ {+ "headline": "Major Event",+ "category": "War",+ "impact_score": 10,+ "summary": "Big thing happened.",+ },+ ]+ result = strategy._format_news_summary(items)+ assert "**Top Story**: Major Event" in result+ assert "Big thing happened." in result++ def test_max_three_per_category(self):+ """At most 3 items shown per category."""+ strategy = self._make_strategy()+ items = [+ {"headline": f"Item {i}", "category": "Tech", "impact_score": i}+ for i in range(5)+ ]+ result = strategy._format_news_summary(items)+ # Count lines starting with "- " under Tech+ tech_items = [+ line for line in result.split("\n") if line.startswith("- Item")+ ]+ assert len(tech_items) == 3++ def test_missing_impact_score_shows_na(self):+ """Missing impact_score shows N/A."""+ strategy = self._make_strategy()+ items = [+ {"headline": "No Score", "category": "Other"},+ ]+ result = strategy._format_news_summary(items)+ assert "N/A/10" in result++ def test_top_story_missing_summary(self):+ """Top story with missing summary shows fallback."""+ strategy = self._make_strategy()+ items = [+ {"headline": "No Summary", "category": "Other", "impact_score": 5},+ ]+ result = strategy._format_news_summary(items)+ assert "No summary available" in result++ def test_total_count_in_header(self):+ """Header includes total story count."""+ strategy = self._make_strategy()+ items = [+ {"headline": f"Story {i}", "category": "Other", "impact_score": i}+ for i in range(4)+ ]+ result = strategy._format_news_summary(items)+ assert "Found 4 significant news stories" in result+++# ---------------------------------------------------------------------------+# _fallback_news_extraction (news_strategy.py)+# ---------------------------------------------------------------------------+++class TestFallbackNewsExtraction:+ """Tests for NewsAggregationStrategy._fallback_news_extraction()."""++ def _make_strategy(self):+ from local_deep_research.advanced_search_system.strategies.news_strategy import (+ NewsAggregationStrategy,+ )++ model = Mock()+ search = Mock()+ return NewsAggregationStrategy(+ model=model, search=search, all_links_of_system=[]+ )++ def test_empty_snippets(self):+ """Empty snippets produces empty result."""+ strategy = self._make_strategy()+ result = strategy._fallback_news_extraction([])+ assert result["status"] == "Fallback extraction"+ assert result["news_items"] == []+ assert "0 news stories" in result["answer"]++ def test_extracts_from_valid_snippets(self):+ """Extracts news items from snippets with valid titles."""+ strategy = self._make_strategy()+ snippets = [+ {+ "id": 1,+ "title": "Major breakthrough in AI research announced today",+ "url": "https://example.com/ai",+ "snippet": "Scientists announced...",+ "content": "",+ },+ ]+ result = strategy._fallback_news_extraction(snippets)+ assert len(result["news_items"]) == 1+ item = result["news_items"][0]+ assert item["category"] == "Other"+ assert item["impact_score"] == 5+ assert item["source_url"] == "https://example.com/ai"++ def test_skips_short_titles(self):+ """Titles <= 10 characters are skipped."""+ strategy = self._make_strategy()+ snippets = [+ {+ "id": 1,+ "title": "Short",+ "url": "https://a.com",+ "snippet": "s",+ "content": "",+ },+ {+ "id": 2,+ "title": "1234567890",+ "url": "https://b.com",+ "snippet": "s",+ "content": "",+ },+ {+ "id": 3,+ "title": "Long enough title for news",+ "url": "https://c.com",+ "snippet": "ok",+ "content": "",+ },+ ]+ result = strategy._fallback_news_extraction(snippets)+ assert len(result["news_items"]) == 1+ assert result["news_items"][0]["source_url"] == "https://c.com"++ def test_skips_empty_titles(self):+ """Empty titles are skipped."""+ strategy = self._make_strategy()+ snippets = [+ {+ "id": 1,+ "title": "",+ "url": "https://a.com",+ "snippet": "content",+ "content": "",+ },+ ]+ result = strategy._fallback_news_extraction(snippets)+ assert len(result["news_items"]) == 0++ def test_truncates_long_headlines(self):+ """Headlines are truncated to 60 characters."""+ strategy = self._make_strategy()+ long_title = "A" * 100+ snippets = [+ {+ "id": 1,+ "title": long_title,+ "url": "https://a.com",+ "snippet": "s",+ "content": "",+ },+ ]+ result = strategy._fallback_news_extraction(snippets)+ assert len(result["news_items"][0]["headline"]) == 60++ def test_max_ten_items(self):+ """At most 10 items extracted."""+ strategy = self._make_strategy()+ snippets = [+ {+ "id": i,+ "title": f"Valid news headline number {i} here",+ "url": f"https://example{i}.com",+ "snippet": "content",+ "content": "",+ }+ for i in range(20)+ ]+ result = strategy._fallback_news_extraction(snippets)+ assert len(result["news_items"]) == 10++ def test_uses_snippet_for_summary(self):+ """Snippet is used as summary."""+ strategy = self._make_strategy()+ snippets = [+ {+ "id": 1,+ "title": "Breaking news about something important",+ "url": "https://a.com",+ "snippet": "Detailed snippet content",+ "content": "",+ },+ ]+ result = strategy._fallback_news_extraction(snippets)+ assert result["news_items"][0]["summary"] == "Detailed snippet content"++ def test_fallback_summary_when_no_snippet(self):+ """Falls back to default summary when no snippet."""+ strategy = self._make_strategy()+ snippets = [+ {+ "id": 1,+ "title": "Breaking news about something important",+ "url": "https://a.com",+ "snippet": "",+ "content": "",+ },+ ]+ result = strategy._fallback_news_extraction(snippets)+ assert result["news_items"][0]["summary"] == "No summary available"+++# ---------------------------------------------------------------------------+# BaseSearchStrategy.check_termination() (base_strategy.py)+# ---------------------------------------------------------------------------+++class TestCheckTermination:+ """Tests for BaseSearchStrategy.check_termination() method.++ This method was untested in the existing test_base_strategy.py.+ """++ def _make_strategy(self):+ from local_deep_research.advanced_search_system.strategies.base_strategy import (+ BaseSearchStrategy,+ )++ class ConcreteStrategy(BaseSearchStrategy):+ def analyze_topic(self, query):+ return {}++ return ConcreteStrategy()++ def test_check_termination_calls_callback(self):+ """check_termination() calls progress_callback with termination_check phase."""+ strategy = self._make_strategy()+ callback = Mock()+ strategy.set_progress_callback(callback)++ strategy.check_termination()++ callback.assert_called_once()+ args = callback.call_args[0]+ assert args[2]["phase"] == "termination_check"++ def test_check_termination_without_callback(self):+ """check_termination() does nothing without callback."""+ strategy = self._make_strategy()+ # Should not raise+ strategy.check_termination()++ def test_check_termination_passes_none_progress(self):+ """check_termination() passes None as progress_percent."""+ strategy = self._make_strategy()+ callback = Mock()+ strategy.set_progress_callback(callback)++ strategy.check_termination()++ args = callback.call_args[0]+ assert args[1] is Nonediff --git a/tests/text_optimization/test_ris_entry_edge_cases.py b/tests/text_optimization/test_ris_entry_edge_cases.pynew file mode 100644index 0000000000..f26318afd5--- /dev/null+++ b/tests/text_optimization/test_ris_entry_edge_cases.py@@ -0,0 +1,441 @@+"""+Tests for RISExporter._create_ris_entry() edge cases.++Existing tests cover: basic ID, year extraction, DOI from metadata,+GitHub publisher, and arXiv publisher.++This file adds coverage for the many remaining branches:+- Author parsing (split by 'and', '&', commas)+- DOI extraction from text (not just metadata)+- Publisher detection for Reddit, YouTube, Medium, PyPI, generic domains+- www. prefix stripping+- Title cleaning (DOI, "Published in", "Volume", "Pages" patterns)+- Empty/minimal inputs+- Author match overlapping with title cleaning+"""++from freezegun import freeze_time++from local_deep_research.text_optimization.citation_formatter import RISExporter+++class TestRISEntryAuthorParsing:+ """Tests for author extraction from 'by Author1, Author2' patterns."""++ def _make(self):+ return RISExporter()++ def test_single_author(self):+ """Extracts a single author."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Some Title\nWritten by Jane Doe."+ )+ assert "AU - Jane Doe" in result++ def test_authors_separated_by_and(self):+ """Authors separated by 'and' are split correctly."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title\nby Alice Smith and Bob Jones."+ )+ assert "AU - Alice Smith" in result+ assert "AU - Bob Jones" in result++ def test_authors_separated_by_ampersand(self):+ """Authors separated by '&' are split correctly."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title\nby Alice Smith & Bob Jones."+ )+ assert "AU - Alice Smith" in result+ assert "AU - Bob Jones" in result++ def test_authors_separated_by_comma(self):+ """Authors separated by commas are split correctly."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title\nby Alice Smith, Bob Jones, Carol White."+ )+ assert "AU - Alice Smith" in result+ assert "AU - Bob Jones" in result+ assert "AU - Carol White" in result++ def test_authors_mixed_separators(self):+ """Authors with mixed 'and' and comma separators."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title\nby Alice, Bob and Carol."+ )+ assert "AU - Alice" in result+ assert "AU - Bob" in result+ assert "AU - Carol" in result++ def test_no_authors(self):+ """No author line produces no AU entries."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title with no authors")+ assert "AU -" not in result++ def test_by_keyword_case_insensitive(self):+ """The 'by' keyword match is case-insensitive."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title\nBY John Smith.")+ assert "AU - John Smith" in result++ def test_empty_author_parts_filtered(self):+ """Empty parts from splitting are filtered out."""+ exporter = self._make()+ # Trailing comma leaves an empty part+ result = exporter._create_ris_entry("1", "Title\nby Alice, , Bob.")+ lines = [+ line for line in result.split("\n") if line.startswith("AU -")+ ]+ # Should only have real authors, not empty strings+ for line in lines:+ assert line.strip() != "AU -"+++class TestRISEntryDOIExtraction:+ """Tests for DOI extraction from metadata and text."""++ def _make(self):+ return RISExporter()++ def test_doi_from_metadata_takes_precedence(self):+ """DOI from metadata dict is used over DOI in text."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1",+ "Title DOI: 10.9999/text-doi",+ metadata={"doi": "10.1234/meta-doi"},+ )+ assert "DO - 10.1234/meta-doi" in result+ assert (+ "10.9999/text-doi" not in result.split("DO - ")[1].split("\n")[0]+ )++ def test_doi_from_text(self):+ """DOI extracted from text when not in metadata."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title\nDOI: 10.1234/test.5678"+ )+ assert "DO - 10.1234/test.5678" in result++ def test_doi_from_text_case_insensitive(self):+ """DOI extraction from text is case-insensitive."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title\ndoi: 10.1234/lowercase"+ )+ assert "DO - 10.1234/lowercase" in result++ def test_no_doi(self):+ """No DOI produces no DO entry."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title with no DOI")+ assert "DO -" not in result++ def test_metadata_none_falls_back_to_text(self):+ """When metadata is None, DOI is extracted from text."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title\nDOI: 10.5555/fallback")+ assert "DO - 10.5555/fallback" in result++ def test_metadata_without_doi_key(self):+ """Metadata dict without 'doi' key falls back to text."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1",+ "Title\nDOI: 10.7777/textdoi",+ metadata={"other": "value"},+ )+ assert "DO - 10.7777/textdoi" in result+++class TestRISEntryPublisherDetection:+ """Tests for publisher extraction from URL domains."""++ def _make(self):+ return RISExporter()++ def test_reddit_publisher(self):+ """Reddit URL produces Reddit publisher."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://www.reddit.com/r/python/post"+ )+ assert "PB - Reddit" in result++ def test_reddit_subdomain(self):+ """Reddit subdomain also detected."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://old.reddit.com/r/science"+ )+ assert "PB - Reddit" in result++ def test_youtube_publisher(self):+ """YouTube URL produces YouTube publisher."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://www.youtube.com/watch?v=abc123"+ )+ assert "PB - YouTube" in result++ def test_youtube_mobile(self):+ """Mobile YouTube URL produces YouTube publisher."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://m.youtube.com/watch?v=abc123"+ )+ assert "PB - YouTube" in result++ def test_medium_publisher(self):+ """Medium URL produces Medium publisher."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://medium.com/@author/article"+ )+ assert "PB - Medium" in result++ def test_medium_subdomain(self):+ """Medium subdomain (custom publication) detected."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://blog.medium.com/post"+ )+ assert "PB - Medium" in result++ def test_pypi_publisher(self):+ """PyPI URL produces PyPI publisher."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://pypi.org/project/requests/"+ )+ assert "PB - Python Package Index (PyPI)" in result++ def test_generic_domain_as_publisher(self):+ """Unknown domain used as publisher name."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://example.com/article"+ )+ assert "PB - example.com" in result++ def test_www_stripped_from_domain(self):+ """www. prefix is stripped from domain."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://www.example.org/page"+ )+ assert "PB - example.org" in result++ def test_no_url_no_publisher(self):+ """No URL produces no PB or UR entries."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title")+ assert "PB -" not in result+ assert "UR -" not in result++ def test_empty_url_no_publisher(self):+ """Empty string URL produces no PB or UR entries."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title", url="")+ assert "PB -" not in result+ assert "UR -" not in result++ def test_github_subdomain(self):+ """GitHub subdomain detected as GitHub."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://pages.github.com/project"+ )+ assert "PB - GitHub" in result++ def test_arxiv_subdomain(self):+ """arXiv subdomain detected as arXiv."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://export.arxiv.org/abs/1234"+ )+ assert "PB - arXiv" in result+++class TestRISEntryTitleCleaning:+ """Tests for title cleaning patterns."""++ def _make(self):+ return RISExporter()++ def test_doi_removed_from_title(self):+ """DOI text is removed from the title."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "My Paper DOI: 10.1234/test\nMore content"+ )+ # The title line should not contain DOI+ ti_line = [+ line for line in result.split("\n") if line.startswith("TI -")+ ][0]+ assert "DOI:" not in ti_line++ def test_published_in_removed_from_title(self):+ """'Published in ...' is removed from the title."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "My Paper Published in Nature 2023\nContent"+ )+ ti_line = [+ line for line in result.split("\n") if line.startswith("TI -")+ ][0]+ assert "Published in" not in ti_line++ def test_volume_removed_from_title(self):+ """'Volume ...' is removed from the title."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "My Paper Volume 42 Issue 3\nContent"+ )+ ti_line = [+ line for line in result.split("\n") if line.startswith("TI -")+ ][0]+ assert "Volume" not in ti_line++ def test_pages_removed_from_title(self):+ """'Pages ...' is removed from the title."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "My Paper Pages 100-120\nContent"+ )+ ti_line = [+ line for line in result.split("\n") if line.startswith("TI -")+ ][0]+ assert "Pages" not in ti_line++ def test_fallback_to_original_title_when_clean_empty(self):+ """If cleaning empties the title, original title is used."""+ exporter = self._make()+ # Title that's entirely "by Author" where author match starts at 0+ result = exporter._create_ris_entry("1", "by John Smith\nContent")+ # Should still have a TI entry (either cleaned or fallback)+ ti_line = [+ line for line in result.split("\n") if line.startswith("TI -")+ ][0]+ assert "TI - " in ti_line+++class TestRISEntryStructure:+ """Tests for overall RIS entry structure."""++ def _make(self):+ return RISExporter()++ def test_contains_ty_elec(self):+ """Entry contains TY - ELEC type marker."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title")+ assert "TY - ELEC" in result++ def test_ends_with_er(self):+ """Entry ends with ER marker."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title")+ lines = result.split("\n")+ assert lines[-1] == "ER - "++ def test_contains_language(self):+ """Entry contains language tag."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title")+ assert "LA - en" in result++ @freeze_time("2025-06-15")+ def test_contains_access_year(self):+ """Entry contains current access year."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title")+ assert "Y1 - 2025" in result++ @freeze_time("2025-06-15")+ def test_contains_access_date(self):+ """Entry contains formatted access date."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title")+ assert "DA - 2025/06/15" in result++ def test_ref_id_format(self):+ """Reference ID formatted as 'refN'."""+ exporter = self._make()+ result = exporter._create_ris_entry("42", "Title")+ assert "ID - ref42" in result+++class TestRISEntryYearExtraction:+ """Tests for year extraction from text."""++ def _make(self):+ return RISExporter()++ def test_year_1990s(self):+ """Extracts 1990s year."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Published in 1995")+ assert "PY - 1995" in result++ def test_year_2000s(self):+ """Extracts 2000s year."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Released 2003")+ assert "PY - 2003" in result++ def test_no_year(self):+ """No year in text produces no PY entry."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Title with no date")+ assert "PY -" not in result++ def test_first_year_extracted(self):+ """First valid year in text is extracted."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Written in 2020, revised in 2023"+ )+ assert "PY - 2020" in result++ def test_year_boundary_1900(self):+ """Year 1900 is valid (19xx pattern)."""+ exporter = self._make()+ result = exporter._create_ris_entry("1", "Historical text from 1900")+ assert "PY - 1900" in result++ def test_non_year_four_digit_ignored(self):+ """Four-digit numbers outside 19xx-20xx range are not matched."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Article number 3456 in series"+ )+ assert "PY -" not in result+++class TestRISEntryURLHandling:+ """Tests for URL handling in RIS entries."""++ def _make(self):+ return RISExporter()++ def test_url_included(self):+ """URL is included as UR entry."""+ exporter = self._make()+ result = exporter._create_ris_entry(+ "1", "Title", url="https://example.com"+ )+ assert "UR - https://example.com" in result++ def test_url_with_path(self):+ """Full URL with path is preserved."""+ exporter = self._make()+ url = "https://example.com/path/to/article?id=123"+ result = exporter._create_ris_entry("1", "Title", url=url)+ assert f"UR - {url}" in resultdiff --git a/tests/web_search_engines/engines/test_pubmed_enriched_content_edges.py b/tests/web_search_engines/engines/test_pubmed_enriched_content_edges.pynew file mode 100644index 0000000000..be37db6990--- /dev/null+++ b/tests/web_search_engines/engines/test_pubmed_enriched_content_edges.py@@ -0,0 +1,348 @@+"""+Tests for PubMedSearchEngine._create_enriched_content() edge cases.++Existing tests cover: study type prefix, MeSH terms, grants, and+minimal result (no metadata). This file adds coverage for untested branches:++- Keywords metadata+- Affiliations (single vs multiple)+- Conflict of interest (trivial, non-trivial, "but" exceptions)+- Multiple grants with various fields+- Publication type filtering (non-significant types filtered out)+- Empty/missing metadata fields+- Combined metadata interactions+"""++import pytest++defusedxml = pytest.importorskip(+ "defusedxml", reason="defusedxml not installed"+)+++def _make_engine():+ """Import and instantiate PubMedSearchEngine inside function to avoid import issues."""+ from local_deep_research.web_search_engines.engines.search_engine_pubmed import (+ PubMedSearchEngine,+ )++ return PubMedSearchEngine()+++class TestEnrichedContentKeywords:+ """Tests for keywords metadata in enriched content."""++ def test_keywords_included(self):+ """Keywords from result are included."""+ engine = _make_engine()+ result = {"keywords": ["machine learning", "neural networks", "AI"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Keywords: machine learning, neural networks, AI" in enriched++ def test_empty_keywords_not_shown(self):+ """Empty keywords list is not included."""+ engine = _make_engine()+ result = {"keywords": []}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Keywords" not in enriched++ def test_single_keyword(self):+ """Single keyword is shown."""+ engine = _make_engine()+ result = {"keywords": ["pharmacology"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Keywords: pharmacology" in enriched+++class TestEnrichedContentAffiliations:+ """Tests for affiliations metadata."""++ def test_single_affiliation_uses_institution(self):+ """Single affiliation uses 'Institution:' label."""+ engine = _make_engine()+ result = {"affiliations": ["Harvard Medical School"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Institution: Harvard Medical School" in enriched+ assert "Institutions:" not in enriched++ def test_multiple_affiliations_uses_institutions(self):+ """Multiple affiliations use 'Institutions:' label with list."""+ engine = _make_engine()+ result = {+ "affiliations": [+ "Harvard Medical School",+ "MIT",+ "Stanford University",+ ]+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Institutions:" in enriched+ assert "Harvard Medical School" in enriched+ assert "MIT" in enriched+ assert "Stanford University" in enriched++ def test_empty_affiliations_not_shown(self):+ """Empty affiliations list is not included."""+ engine = _make_engine()+ result = {"affiliations": []}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Institution" not in enriched+ assert "Institutions" not in enriched+++class TestEnrichedContentConflictOfInterest:+ """Tests for conflict of interest handling."""++ def test_non_trivial_coi_included(self):+ """Non-trivial conflict of interest is included."""+ engine = _make_engine()+ result = {+ "conflict_of_interest": "Author A received consulting fees from Pharma Corp."+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest:" in enriched+ assert "consulting fees" in enriched++ def test_trivial_no_conflict_excluded(self):+ """Trivial 'no conflict' statement is excluded."""+ engine = _make_engine()+ result = {+ "conflict_of_interest": "The authors declare no conflict of interest."+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" not in enriched++ def test_trivial_no_competing_excluded(self):+ """Trivial 'no competing' statement is excluded."""+ engine = _make_engine()+ result = {"conflict_of_interest": "No competing interests exist."}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" not in enriched++ def test_trivial_nothing_to_disclose_excluded(self):+ """Trivial 'nothing to disclose' statement is excluded."""+ engine = _make_engine()+ result = {+ "conflict_of_interest": "The authors have nothing to disclose."+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" not in enriched++ def test_trivial_none_declared_excluded(self):+ """Trivial 'none declared' statement is excluded."""+ engine = _make_engine()+ result = {"conflict_of_interest": "None declared."}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" not in enriched++ def test_trivial_authors_declare_no_excluded(self):+ """Trivial 'authors declare no' statement is excluded."""+ engine = _make_engine()+ result = {"conflict_of_interest": "The authors declare no conflicts."}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" not in enriched++ def test_coi_with_but_exception_included(self):+ """CoI with 'but' exception is still included."""+ engine = _make_engine()+ result = {+ "conflict_of_interest": "The authors declare no conflict of interest, but Author B is on the advisory board of Pharma Inc."+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" in enriched+ assert "advisory board" in enriched++ def test_coi_with_except_exception_included(self):+ """CoI with 'except' exception is still included."""+ engine = _make_engine()+ result = {+ "conflict_of_interest": "No competing interests except for grant funding from Industry Corp."+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" in enriched++ def test_coi_with_however_exception_included(self):+ """CoI with 'however' exception is still included."""+ engine = _make_engine()+ result = {+ "conflict_of_interest": "Authors declare no conflicts; however, Author C owns stock in BioTech Ltd."+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" in enriched++ def test_empty_coi_not_shown(self):+ """Empty string CoI is not included."""+ engine = _make_engine()+ result = {"conflict_of_interest": ""}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" not in enriched++ def test_none_coi_not_shown(self):+ """None CoI (key absent) is not included."""+ engine = _make_engine()+ result = {}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Conflict of Interest" not in enriched+++class TestEnrichedContentGrants:+ """Tests for grant/funding metadata."""++ def test_single_grant_with_agency_and_id(self):+ """Single grant with both agency and ID."""+ engine = _make_engine()+ result = {"grants": [{"agency": "NIH", "id": "R01-12345"}]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Funded by: NIH (Grant ID: R01-12345)" in enriched++ def test_single_grant_agency_only(self):+ """Single grant with agency only."""+ engine = _make_engine()+ result = {"grants": [{"agency": "NSF"}]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Funded by: NSF" in enriched+ assert "Grant ID" not in enriched++ def test_single_grant_id_only(self):+ """Single grant with ID only."""+ engine = _make_engine()+ result = {"grants": [{"id": "ABC-789"}]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Funded by:" in enriched+ assert "ABC-789" in enriched++ def test_multiple_grants(self):+ """Multiple grants shown as a list."""+ engine = _make_engine()+ result = {+ "grants": [+ {"agency": "NIH", "id": "R01-111"},+ {"agency": "NSF", "id": "DMS-222"},+ ]+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Funding Sources:" in enriched+ assert "NIH" in enriched+ assert "NSF" in enriched++ def test_empty_grants_not_shown(self):+ """Empty grants list is not shown."""+ engine = _make_engine()+ result = {"grants": []}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Fund" not in enriched++ def test_grant_with_empty_fields(self):+ """Grant with no agency or id fields is skipped."""+ engine = _make_engine()+ result = {"grants": [{"country": "USA"}]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ # No "Funded by" because the grant_text list is empty+ assert "Fund" not in enriched+++class TestEnrichedContentPublicationTypes:+ """Tests for publication type filtering."""++ def test_clinical_trial_is_significant(self):+ """Clinical trial is a significant publication type."""+ engine = _make_engine()+ result = {"publication_types": ["Clinical Trial", "Journal Article"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "[Study Type: Clinical Trial]" in enriched++ def test_meta_analysis_is_significant(self):+ """Meta-analysis is a significant publication type."""+ engine = _make_engine()+ result = {"publication_types": ["Meta-Analysis"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "[Study Type: Meta-Analysis]" in enriched++ def test_systematic_review_is_significant(self):+ """Systematic review is a significant publication type."""+ engine = _make_engine()+ result = {"publication_types": ["Systematic Review"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "[Study Type: Systematic Review]" in enriched++ def test_case_report_is_significant(self):+ """Case report is a significant publication type."""+ engine = _make_engine()+ result = {"publication_types": ["Case Report"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "[Study Type: Case Report]" in enriched++ def test_guideline_is_significant(self):+ """Practice guideline is a significant publication type."""+ engine = _make_engine()+ result = {"publication_types": ["Practice Guideline"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Guideline" in enriched++ def test_journal_article_not_significant(self):+ """Plain 'Journal Article' is not a significant type."""+ engine = _make_engine()+ result = {"publication_types": ["Journal Article"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "[Study Type:" not in enriched++ def test_multiple_significant_types(self):+ """Multiple significant types are joined."""+ engine = _make_engine()+ result = {+ "publication_types": [+ "Randomized Controlled Trial",+ "Multicenter Study",+ "Journal Article",+ ]+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Randomized Controlled Trial" in enriched+ assert "Multicenter Study" in enriched++ def test_empty_publication_types_not_shown(self):+ """Empty publication_types list doesn't add study type."""+ engine = _make_engine()+ result = {"publication_types": []}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "[Study Type:" not in enriched+++class TestEnrichedContentMetadataFooter:+ """Tests for the metadata footer section."""++ def test_metadata_footer_has_separator(self):+ """Metadata footer is preceded by a separator."""+ engine = _make_engine()+ result = {"keywords": ["test"]}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "---\nStudy Metadata:" in enriched++ def test_no_metadata_no_footer(self):+ """No metadata produces no footer separator."""+ engine = _make_engine()+ result = {}+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Study Metadata" not in enriched++ def test_base_content_always_present(self):+ """Base content is always present in output."""+ engine = _make_engine()+ result = {}+ enriched = engine._create_enriched_content(+ result, "The full abstract text."+ )+ assert "The full abstract text." in enriched++ def test_combined_metadata(self):+ """Multiple metadata types combined in footer."""+ engine = _make_engine()+ result = {+ "keywords": ["drug", "therapy"],+ "mesh_terms": ["Humans", "Neoplasms"],+ "affiliations": ["MGH"],+ }+ enriched = engine._create_enriched_content(result, "Abstract.")+ assert "Keywords:" in enriched+ assert "Medical Topics (MeSH):" in enriched+ assert "Institution: MGH" in enriched