~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 38 high-value pure logic tests for IterativeRefinementStrategy (#2568)
LearningCircuit3a47ea94aaec
diff --git a/tests/advanced_search_system/strategies/test_iterative_refinement_high_value.py b/tests/advanced_search_system/strategies/test_iterative_refinement_high_value.pynew file mode 100644index 0000000000..09a48101a2--- /dev/null+++ b/tests/advanced_search_system/strategies/test_iterative_refinement_high_value.py@@ -0,0 +1,360 @@+"""+High-value pure logic tests for IterativeRefinementStrategy.++Focuses on constructor validation, _merge_results(), and _build_research_context()+without any LLM or network calls.+"""++import pytest+from unittest.mock import MagicMock, patch++from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (+ IterativeRefinementStrategy,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_strategy_no_init():+ """Create an IterativeRefinementStrategy with __init__ bypassed."""+ with patch.object(+ IterativeRefinementStrategy, "__init__", lambda self, *a, **kw: None+ ):+ strategy = IterativeRefinementStrategy.__new__(+ IterativeRefinementStrategy+ )+ # Set minimal attributes that _merge_results / _build_research_context may need+ strategy.initial_strategy = MagicMock()+ strategy.initial_strategy.__class__.__name__ = "MockStrategy"+ strategy.progress_callback = None+ strategy.refinement_history = []+ return strategy+++def _make_strategy_via_constructor(**overrides):+ """Create an IterativeRefinementStrategy through the real constructor."""+ mock_model = MagicMock()+ mock_search = MagicMock()+ mock_initial = MagicMock()+ mock_initial.__class__.__name__ = "MockStrategy"++ defaults = {+ "model": mock_model,+ "search": mock_search,+ "initial_strategy": mock_initial,+ }+ defaults.update(overrides)+ return IterativeRefinementStrategy(**defaults)+++# ===========================================================================+# Constructor validation tests+# ===========================================================================+++class TestConstructorValidation:+ """Tests for parameter validation in __init__."""++ def test_confidence_threshold_below_zero_raises(self):+ with pytest.raises(ValueError, match="confidence_threshold"):+ _make_strategy_via_constructor(confidence_threshold=-0.1)++ def test_confidence_threshold_above_one_raises(self):+ with pytest.raises(ValueError, match="confidence_threshold"):+ _make_strategy_via_constructor(confidence_threshold=1.01)++ def test_confidence_threshold_zero_accepted(self):+ strategy = _make_strategy_via_constructor(confidence_threshold=0.0)+ assert strategy.confidence_threshold == 0.0++ def test_confidence_threshold_one_accepted(self):+ strategy = _make_strategy_via_constructor(confidence_threshold=1.0)+ assert strategy.confidence_threshold == 1.0++ def test_confidence_threshold_mid_accepted(self):+ strategy = _make_strategy_via_constructor(confidence_threshold=0.5)+ assert strategy.confidence_threshold == 0.5++ def test_max_refinements_negative_raises(self):+ with pytest.raises(ValueError, match="max_refinements"):+ _make_strategy_via_constructor(max_refinements=-1)++ def test_max_refinements_zero_accepted(self):+ strategy = _make_strategy_via_constructor(max_refinements=0)+ assert strategy.max_refinements == 0++ def test_max_refinements_positive_accepted(self):+ strategy = _make_strategy_via_constructor(max_refinements=5)+ assert strategy.max_refinements == 5++ def test_evaluation_frequency_zero_raises(self):+ with pytest.raises(ValueError, match="evaluation_frequency"):+ _make_strategy_via_constructor(evaluation_frequency=0)++ def test_evaluation_frequency_negative_raises(self):+ with pytest.raises(ValueError, match="evaluation_frequency"):+ _make_strategy_via_constructor(evaluation_frequency=-2)++ def test_evaluation_frequency_one_accepted(self):+ strategy = _make_strategy_via_constructor(evaluation_frequency=1)+ assert strategy.evaluation_frequency == 1++ def test_max_evaluation_tokens_zero_raises(self):+ with pytest.raises(ValueError, match="max_evaluation_tokens"):+ _make_strategy_via_constructor(max_evaluation_tokens=0)++ def test_max_evaluation_tokens_negative_raises(self):+ with pytest.raises(ValueError, match="max_evaluation_tokens"):+ _make_strategy_via_constructor(max_evaluation_tokens=-10)++ def test_max_evaluation_tokens_none_accepted(self):+ strategy = _make_strategy_via_constructor(max_evaluation_tokens=None)+ assert strategy.max_evaluation_tokens is None++ def test_max_evaluation_tokens_positive_accepted(self):+ strategy = _make_strategy_via_constructor(max_evaluation_tokens=500)+ assert strategy.max_evaluation_tokens == 500++ def test_defaults_stored_correctly(self):+ strategy = _make_strategy_via_constructor()+ assert strategy.max_refinements == 3+ assert strategy.confidence_threshold == 0.8+ assert strategy.evaluation_frequency == 1+ assert strategy.max_evaluation_tokens is None+ assert strategy.refinement_history == []+++# ===========================================================================+# _merge_results tests+# ===========================================================================+++class TestMergeResults:+ """Tests for _merge_results() pure dict merging logic."""++ def test_findings_appended_with_separator(self):+ strategy = _make_strategy_no_init()+ original = {"findings": [{"content": "A"}]}+ followup = {"findings": [{"content": "B"}]}+ merged = strategy._merge_results(original, followup, "follow query")++ # Should have original finding + separator + followup finding = 3+ assert len(merged["findings"]) == 3+ assert merged["findings"][0]["content"] == "A"+ assert merged["findings"][1]["type"] == "refinement_separator"+ assert "follow query" in merged["findings"][1]["phase"]+ assert merged["findings"][2]["content"] == "B"++ def test_findings_created_when_missing_in_original(self):+ strategy = _make_strategy_no_init()+ original = {}+ followup = {"findings": [{"content": "new"}]}+ merged = strategy._merge_results(original, followup, "q")++ assert "findings" in merged+ # separator + new finding+ assert len(merged["findings"]) == 2++ def test_no_findings_key_when_followup_lacks_findings(self):+ strategy = _make_strategy_no_init()+ original = {"findings": [{"content": "old"}]}+ followup = {}+ merged = strategy._merge_results(original, followup, "q")++ # Original findings preserved, nothing appended+ assert len(merged["findings"]) == 1++ def test_formatted_findings_concatenation(self):+ strategy = _make_strategy_no_init()+ original = {"formatted_findings": "Initial research text"}+ followup = {"formatted_findings": "Follow-up text"}+ merged = strategy._merge_results(original, followup, "my query")++ result = merged["formatted_findings"]+ assert "Initial research text" in result+ assert "Follow-up text" in result+ assert "---" in result+ assert "## Refinement: my query" in result++ def test_formatted_findings_with_empty_original(self):+ strategy = _make_strategy_no_init()+ original = {}+ followup = {"formatted_findings": "New findings"}+ merged = strategy._merge_results(original, followup, "q")++ assert "New findings" in merged["formatted_findings"]+ assert "## Refinement: q" in merged["formatted_findings"]++ def test_current_knowledge_updated_to_followup(self):+ strategy = _make_strategy_no_init()+ original = {"current_knowledge": "old knowledge"}+ followup = {"current_knowledge": "new knowledge"}+ merged = strategy._merge_results(original, followup, "q")++ assert merged["current_knowledge"] == "new knowledge"++ def test_current_knowledge_preserved_when_followup_lacks_it(self):+ strategy = _make_strategy_no_init()+ original = {"current_knowledge": "old knowledge"}+ followup = {}+ merged = strategy._merge_results(original, followup, "q")++ assert merged["current_knowledge"] == "old knowledge"++ def test_questions_by_iteration_offset_merge(self):+ strategy = _make_strategy_no_init()+ original = {"questions_by_iteration": {1: ["q1"], 2: ["q2"]}}+ followup = {"questions_by_iteration": {1: ["fq1"], 2: ["fq2"]}}+ merged = strategy._merge_results(original, followup, "q")++ qbi = merged["questions_by_iteration"]+ # max key in original is 2, so followup keys offset by 2+ assert qbi[1] == ["q1"]+ assert qbi[2] == ["q2"]+ assert qbi[3] == ["fq1"] # 2 + 1+ assert qbi[4] == ["fq2"] # 2 + 2++ def test_questions_by_iteration_created_when_missing_in_original(self):+ strategy = _make_strategy_no_init()+ original = {}+ followup = {"questions_by_iteration": {1: ["fq1"]}}+ merged = strategy._merge_results(original, followup, "q")++ qbi = merged["questions_by_iteration"]+ # max of empty dict = 0, so offset is 0+ assert qbi[1] == ["fq1"]++ def test_questions_by_iteration_empty_original_dict(self):+ strategy = _make_strategy_no_init()+ original = {"questions_by_iteration": {}}+ followup = {"questions_by_iteration": {1: ["fq1"]}}+ merged = strategy._merge_results(original, followup, "q")++ # Empty dict -> max_iter = 0, so key = 0 + 1 = 1+ assert merged["questions_by_iteration"][1] == ["fq1"]++ def test_merge_does_not_mutate_original(self):+ strategy = _make_strategy_no_init()+ original = {+ "findings": [{"content": "A"}],+ "formatted_findings": "text",+ }+ followup = {+ "findings": [{"content": "B"}],+ "formatted_findings": "new",+ }+ strategy._merge_results(original, followup, "q")++ # The original dict's top-level keys should still be present+ # (shallow copy means top-level is not mutated)+ assert "findings" in original+ assert original["formatted_findings"] == "text"++ def test_merge_empty_dicts(self):+ strategy = _make_strategy_no_init()+ merged = strategy._merge_results({}, {}, "q")+ assert isinstance(merged, dict)++ def test_separator_finding_truncates_long_query(self):+ strategy = _make_strategy_no_init()+ long_query = "x" * 200+ original = {"findings": []}+ followup = {"findings": [{"content": "B"}]}+ merged = strategy._merge_results(original, followup, long_query)++ separator = merged["findings"][0]+ # The phase truncates to first 100 chars+ assert len(separator["phase"]) <= len("Refinement: ") + 100+++# ===========================================================================+# _build_research_context tests+# ===========================================================================+++class TestBuildResearchContext:+ """Tests for _build_research_context() pure dict construction."""++ def test_basic_context_fields(self):+ strategy = _make_strategy_no_init()+ results = {+ "formatted_findings": "some findings",+ "all_links_of_system": [{"url": "http://a.com"}],+ }+ ctx = strategy._build_research_context(results, "test query")++ assert ctx["original_query"] == "test query"+ assert ctx["past_findings"] == "some findings"+ assert ctx["past_sources"] == [{"url": "http://a.com"}]+ assert ctx["resources"] == [{"url": "http://a.com"}]++ def test_delegate_strategy_name_cleaned(self):+ strategy = _make_strategy_no_init()+ strategy.initial_strategy.__class__.__name__ = "ParallelSearchStrategy"+ ctx = strategy._build_research_context({}, "q")++ # Code does .replace("Strategy", "").replace("SearchStrategy", "").lower()+ # "ParallelSearchStrategy" -> "ParallelSearch" -> "ParallelSearch" -> "parallelsearch"+ assert ctx["delegate_strategy"] == "parallelsearch"++ def test_delegate_strategy_name_strategy_suffix(self):+ strategy = _make_strategy_no_init()+ strategy.initial_strategy.__class__.__name__ = "StandardStrategy"+ ctx = strategy._build_research_context({}, "q")++ assert ctx["delegate_strategy"] == "standard"++ def test_questions_by_iteration_included_when_present(self):+ strategy = _make_strategy_no_init()+ results = {"questions_by_iteration": {1: ["q1"]}}+ ctx = strategy._build_research_context(results, "q")++ assert ctx["questions_by_iteration"] == {1: ["q1"]}++ def test_questions_by_iteration_absent_when_not_in_results(self):+ strategy = _make_strategy_no_init()+ ctx = strategy._build_research_context({}, "q")++ assert "questions_by_iteration" not in ctx++ def test_findings_included_when_present(self):+ strategy = _make_strategy_no_init()+ results = {"findings": [{"content": "finding1"}]}+ ctx = strategy._build_research_context(results, "q")++ assert ctx["findings"] == [{"content": "finding1"}]++ def test_findings_absent_when_not_in_results(self):+ strategy = _make_strategy_no_init()+ ctx = strategy._build_research_context({}, "q")++ assert "findings" not in ctx++ def test_defaults_for_missing_keys(self):+ strategy = _make_strategy_no_init()+ ctx = strategy._build_research_context({}, "q")++ assert ctx["past_findings"] == ""+ assert ctx["past_sources"] == []+ assert ctx["resources"] == []++ def test_context_with_all_fields_populated(self):+ strategy = _make_strategy_no_init()+ results = {+ "formatted_findings": "full findings",+ "all_links_of_system": [{"url": "http://x.com"}],+ "questions_by_iteration": {1: ["a"], 2: ["b"]},+ "findings": [{"content": "c"}],+ }+ ctx = strategy._build_research_context(results, "full query")++ assert ctx["original_query"] == "full query"+ assert ctx["past_findings"] == "full findings"+ assert ctx["past_sources"] == [{"url": "http://x.com"}]+ assert ctx["resources"] == [{"url": "http://x.com"}]+ assert ctx["questions_by_iteration"] == {1: ["a"], 2: ["b"]}+ assert ctx["findings"] == [{"content": "c"}]+ assert "delegate_strategy" in ctxdiff --git a/tests/advanced_search_system/strategies/test_modular_strategy_high_value.py b/tests/advanced_search_system/strategies/test_modular_strategy_high_value.pynew file mode 100644index 0000000000..2eea5e6d68--- /dev/null+++ b/tests/advanced_search_system/strategies/test_modular_strategy_high_value.py@@ -0,0 +1,301 @@+"""High-value pure logic tests for modular_strategy.py.++Tests CandidateConfidence dataclass, LLMConstraintProcessor parsing,+and EarlyRejectionManager decision logic without any LLM or network calls.+"""++import json+from unittest.mock import MagicMock+++from local_deep_research.advanced_search_system.strategies.modular_strategy import (+ CandidateConfidence,+ EarlyRejectionManager,+ LLMConstraintProcessor,+)+++# ---------------------------------------------------------------------------+# CandidateConfidence dataclass+# ---------------------------------------------------------------------------+class TestCandidateConfidence:+ """Tests for the CandidateConfidence dataclass fields and defaults."""++ def test_required_fields(self):+ cc = CandidateConfidence(+ candidate="item_a",+ positive_confidence=0.9,+ negative_confidence=0.1,+ )+ assert cc.candidate == "item_a"+ assert cc.positive_confidence == 0.9+ assert cc.negative_confidence == 0.1++ def test_default_rejection_reason_is_none(self):+ cc = CandidateConfidence(+ candidate="x", positive_confidence=0.5, negative_confidence=0.5+ )+ assert cc.rejection_reason is None++ def test_default_should_continue_is_true(self):+ cc = CandidateConfidence(+ candidate="x", positive_confidence=0.5, negative_confidence=0.5+ )+ assert cc.should_continue is True++ def test_explicit_rejection_reason(self):+ cc = CandidateConfidence(+ candidate="x",+ positive_confidence=0.1,+ negative_confidence=0.9,+ rejection_reason="Too unlikely",+ )+ assert cc.rejection_reason == "Too unlikely"++ def test_explicit_should_continue_false(self):+ cc = CandidateConfidence(+ candidate="x",+ positive_confidence=0.1,+ negative_confidence=0.9,+ should_continue=False,+ )+ assert cc.should_continue is False++ def test_candidate_accepts_any_object(self):+ obj = {"name": "test", "score": 42}+ cc = CandidateConfidence(+ candidate=obj, positive_confidence=0.7, negative_confidence=0.3+ )+ assert cc.candidate is obj+++# ---------------------------------------------------------------------------+# LLMConstraintProcessor parsing methods+# ---------------------------------------------------------------------------+class TestLLMConstraintProcessorParseDecomposition:+ """Tests for LLMConstraintProcessor._parse_decomposition()."""++ def setup_method(self):+ self.processor = LLMConstraintProcessor(model=MagicMock())++ def test_valid_json_dict(self):+ content = json.dumps(+ {+ "constraint_1": {+ "atomic_elements": ["a", "b"],+ "variations": ["v1"],+ "granular_specifics": ["2020"],+ }+ }+ )+ result = self.processor._parse_decomposition(content)+ assert isinstance(result, dict)+ assert "constraint_1" in result++ def test_json_embedded_in_text(self):+ content = 'Here is the result:\n```json\n{"key": "value"}\n```\nDone.'+ result = self.processor._parse_decomposition(content)+ assert isinstance(result, dict)+ assert result.get("key") == "value"++ def test_invalid_json_returns_empty_dict(self):+ content = "This is not valid JSON at all {{{broken"+ result = self.processor._parse_decomposition(content)+ assert result == {}++ def test_empty_string_returns_empty_dict(self):+ result = self.processor._parse_decomposition("")+ assert result == {}++ def test_json_list_returns_empty_dict_because_expected_type_is_dict(self):+ content = json.dumps(["a", "b", "c"])+ result = self.processor._parse_decomposition(content)+ # extract_json with expected_type=dict should reject a list -> fallback {}+ assert result == {}++ def test_empty_dict_json(self):+ content = json.dumps({})+ result = self.processor._parse_decomposition(content)+ assert result == {}+++class TestLLMConstraintProcessorParseCombinations:+ """Tests for LLMConstraintProcessor._parse_combinations()."""++ def setup_method(self):+ self.processor = LLMConstraintProcessor(model=MagicMock())++ def test_valid_json_list(self):+ content = json.dumps(["query1", "query2", "query3"])+ result = self.processor._parse_combinations(content)+ assert result == ["query1", "query2", "query3"]++ def test_json_embedded_in_markdown(self):+ content = 'Some text\n```json\n["a", "b"]\n```'+ result = self.processor._parse_combinations(content)+ assert result == ["a", "b"]++ def test_invalid_json_returns_empty_list(self):+ content = "not json [[[broken"+ result = self.processor._parse_combinations(content)+ assert result == []++ def test_empty_string_returns_empty_list(self):+ result = self.processor._parse_combinations("")+ assert result == []++ def test_json_dict_returns_empty_list_because_expected_type_is_list(self):+ content = json.dumps({"key": "value"})+ result = self.processor._parse_combinations(content)+ # extract_json with expected_type=list should reject a dict -> fallback []+ assert result == []++ def test_empty_list_json(self):+ content = json.dumps([])+ result = self.processor._parse_combinations(content)+ assert result == []+++# ---------------------------------------------------------------------------+# EarlyRejectionManager+# ---------------------------------------------------------------------------+class TestEarlyRejectionManagerShouldRejectEarly:+ """Tests for EarlyRejectionManager.should_reject_early()."""++ def setup_method(self):+ self.manager = EarlyRejectionManager(model=MagicMock())++ def test_reject_when_negative_above_threshold(self):+ reject, reason = self.manager.should_reject_early(+ {"negative_confidence": 0.86}+ )+ assert reject is True+ assert reason is not None+ assert "0.86" in reason++ def test_no_reject_at_exact_boundary(self):+ """0.85 is NOT greater than 0.85, so should not reject."""+ reject, reason = self.manager.should_reject_early(+ {"negative_confidence": 0.85}+ )+ assert reject is False+ assert reason is None++ def test_no_reject_just_below_boundary(self):+ reject, reason = self.manager.should_reject_early(+ {"negative_confidence": 0.84}+ )+ assert reject is False+ assert reason is None++ def test_no_reject_low_negative(self):+ reject, reason = self.manager.should_reject_early(+ {"negative_confidence": 0.1}+ )+ assert reject is False+ assert reason is None++ def test_reject_at_1_0(self):+ reject, reason = self.manager.should_reject_early(+ {"negative_confidence": 1.0}+ )+ assert reject is True++ def test_missing_negative_confidence_uses_default(self):+ """Missing key defaults to 0.3 via dict.get, so no rejection."""+ reject, reason = self.manager.should_reject_early({})+ assert reject is False+ assert reason is None+++class TestEarlyRejectionManagerShouldContinueSearch:+ """Tests for EarlyRejectionManager.should_continue_search()."""++ def setup_method(self):+ self.manager = EarlyRejectionManager(model=MagicMock())++ def test_stop_when_5_high_confidence(self):+ candidates = list(range(10))+ should_continue, reason = self.manager.should_continue_search(+ candidates, 5+ )+ assert should_continue is False+ assert "high-confidence" in reason++ def test_stop_when_more_than_5_high_confidence(self):+ candidates = list(range(20))+ should_continue, reason = self.manager.should_continue_search(+ candidates, 7+ )+ assert should_continue is False++ def test_continue_when_4_high_confidence(self):+ candidates = list(range(10))+ should_continue, reason = self.manager.should_continue_search(+ candidates, 4+ )+ assert should_continue is True+ assert reason is None++ def test_stop_when_over_50_candidates_zero_high_confidence(self):+ candidates = list(range(51))+ should_continue, reason = self.manager.should_continue_search(+ candidates, 0+ )+ assert should_continue is False+ assert "low-quality" in reason++ def test_continue_at_exactly_50_candidates_zero_high_confidence(self):+ """50 is not > 50, so search should continue."""+ candidates = list(range(50))+ should_continue, reason = self.manager.should_continue_search(+ candidates, 0+ )+ assert should_continue is True+ assert reason is None++ def test_continue_with_few_candidates_zero_high_confidence(self):+ candidates = list(range(5))+ should_continue, reason = self.manager.should_continue_search(+ candidates, 0+ )+ assert should_continue is True++ def test_continue_with_many_candidates_some_high_confidence(self):+ """51 candidates but 1 high confidence - should continue (not 0)."""+ candidates = list(range(51))+ should_continue, reason = self.manager.should_continue_search(+ candidates, 1+ )+ assert should_continue is True+ assert reason is None+++class TestEarlyRejectionManagerParseConfidence:+ """Tests for EarlyRejectionManager._parse_confidence()."""++ def setup_method(self):+ self.manager = EarlyRejectionManager(model=MagicMock())++ def test_valid_json(self):+ content = json.dumps(+ {+ "positive_confidence": 0.8,+ "negative_confidence": 0.2,+ "reasoning": "looks good",+ }+ )+ result = self.manager._parse_confidence(content)+ assert result["positive_confidence"] == 0.8+ assert result["negative_confidence"] == 0.2++ def test_invalid_json_returns_fallback(self):+ result = self.manager._parse_confidence("totally broken json {{{")+ assert result["positive_confidence"] == 0.5+ assert result["negative_confidence"] == 0.3+ assert result["reasoning"] == "parse_error"++ def test_empty_string_returns_fallback(self):+ result = self.manager._parse_confidence("")+ assert result["positive_confidence"] == 0.5+ assert result["negative_confidence"] == 0.3diff --git a/tests/content_fetcher/test_url_classifier_high_value.py b/tests/content_fetcher/test_url_classifier_high_value.pynew file mode 100644index 0000000000..155d977133--- /dev/null+++ b/tests/content_fetcher/test_url_classifier_high_value.py@@ -0,0 +1,328 @@+"""+High-value pure logic tests for URL classifier.++Focuses on edge cases, boundary conditions, and behaviors not covered+by the basic test suite in test_url_classifier.py.+"""++import pytest++from local_deep_research.content_fetcher.url_classifier import (+ DANGEROUS_SCHEMES,+ URLClassifier,+ URLType,+)+++class TestURLTypeEnum:+ """Verify URLType enum completeness and values."""++ def test_all_enum_members_exist(self):+ """All expected URLType members are defined."""+ expected = {+ "ARXIV",+ "PUBMED",+ "PMC",+ "SEMANTIC_SCHOLAR",+ "BIORXIV",+ "MEDRXIV",+ "DOI",+ "PDF",+ "HTML",+ "INVALID",+ }+ actual = {member.name for member in URLType}+ assert actual == expected++ def test_enum_values_are_lowercase_strings(self):+ """All enum values are lowercase strings."""+ for member in URLType:+ assert isinstance(member.value, str)+ assert member.value == member.value.lower()++ def test_enum_member_count(self):+ """Exactly 10 URL types are defined."""+ assert len(URLType) == 10+++class TestDangerousSchemes:+ """Verify the DANGEROUS_SCHEMES constant."""++ def test_contains_all_expected_schemes(self):+ """All dangerous schemes are present."""+ expected = {"javascript", "data", "file", "vbscript", "about"}+ assert DANGEROUS_SCHEMES == expected++ def test_schemes_are_lowercase(self):+ """All scheme entries are lowercase."""+ for scheme in DANGEROUS_SCHEMES:+ assert scheme == scheme.lower()+++class TestClassifyDangerousAndInvalidSchemes:+ """Edge cases for scheme-based rejection."""++ def test_javascript_with_payload(self):+ """javascript: with complex payload is INVALID."""+ url = "javascript:void(document.cookie)"+ assert URLClassifier.classify(url) == URLType.INVALID++ def test_data_base64_payload(self):+ """data: with base64 content is INVALID."""+ url = "data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="+ assert URLClassifier.classify(url) == URLType.INVALID++ def test_file_windows_path(self):+ """file: with Windows-style path is INVALID."""+ url = "file:///C:/Users/test/secret.txt"+ assert URLClassifier.classify(url) == URLType.INVALID++ def test_ftp_scheme_rejected(self):+ """ftp: is not http/https and should be INVALID."""+ assert (+ URLClassifier.classify("ftp://mirror.example.com/pub")+ == URLType.INVALID+ )++ def test_ssh_scheme_rejected(self):+ """ssh: scheme should be INVALID."""+ assert URLClassifier.classify("ssh://user@host") == URLType.INVALID++ def test_mailto_scheme_rejected(self):+ """mailto: scheme should be INVALID."""+ assert (+ URLClassifier.classify("mailto:[email protected]") == URLType.INVALID+ )++ def test_tel_scheme_rejected(self):+ """tel: scheme should be INVALID."""+ assert URLClassifier.classify("tel:+1234567890") == URLType.INVALID+++class TestClassifyAcademicURLEdgeCases:+ """Edge cases for academic URL classification."""++ def test_arxiv_pdf_with_version(self):+ """arXiv PDF URL with version suffix classifies as ARXIV, not PDF."""+ url = "https://arxiv.org/pdf/2301.12345v3.pdf"+ assert URLClassifier.classify(url) == URLType.ARXIV++ def test_arxiv_mixed_case(self):+ """arXiv URL with mixed case in domain."""+ url = "https://ArXiv.Org/abs/2301.12345"+ assert URLClassifier.classify(url) == URLType.ARXIV++ def test_ar5iv_with_path(self):+ """ar5iv.org with any path classifies as ARXIV."""+ url = "https://ar5iv.org/html/2301.12345"+ assert URLClassifier.classify(url) == URLType.ARXIV++ def test_pubmed_trailing_slash(self):+ """PubMed URL with trailing slash."""+ url = "https://pubmed.ncbi.nlm.nih.gov/98765432/"+ assert URLClassifier.classify(url) == URLType.PUBMED++ def test_pmc_europe_articles_variant(self):+ """Europe PMC with /articles/ path variant."""+ url = "https://europepmc.org/articles/PMC7654321"+ assert URLClassifier.classify(url) == URLType.PMC++ def test_biorxiv_with_version(self):+ """bioRxiv URL with version suffix."""+ url = "https://www.biorxiv.org/content/10.1101/2023.05.01.538999v2"+ assert URLClassifier.classify(url) == URLType.BIORXIV++ def test_medrxiv_full_doi_path(self):+ """medRxiv URL with full DOI-style content path."""+ url = (+ "https://www.medrxiv.org/content/10.1101/2023.06.15.23291456v1.full"+ )+ assert URLClassifier.classify(url) == URLType.MEDRXIV++ def test_doi_with_complex_suffix(self):+ """DOI URL with complex suffix containing slashes and dots."""+ url = "https://doi.org/10.1038/s41586-021-03819-2"+ assert URLClassifier.classify(url) == URLType.DOI++ def test_dx_doi_org(self):+ """dx.doi.org is recognized as DOI."""+ url = "https://dx.doi.org/10.1000/xyz123"+ assert URLClassifier.classify(url) == URLType.DOI++ def test_semantic_scholar_api_url(self):+ """Semantic Scholar API URL."""+ url = "https://api.semanticscholar.org/graph/v1/paper/12345"+ assert URLClassifier.classify(url) == URLType.SEMANTIC_SCHOLAR+++class TestClassifyPDFDetection:+ """Tests for PDF URL detection and academic domain exclusion."""++ def test_pdf_extension_generic_domain(self):+ """Generic domain with .pdf extension is PDF."""+ url = "https://example.com/reports/annual-report.pdf"+ assert URLClassifier.classify(url) == URLType.PDF++ def test_pdf_path_segment(self):+ """URL with /pdf/ in path on generic domain is PDF."""+ url = "https://example.com/pdf/document123"+ assert URLClassifier.classify(url) == URLType.PDF++ def test_arxiv_pdf_not_classified_as_pdf(self):+ """arXiv PDF URL should be ARXIV, not PDF."""+ url = "https://arxiv.org/pdf/2301.12345"+ assert URLClassifier.classify(url) == URLType.ARXIV++ def test_biorxiv_pdf_not_classified_as_pdf(self):+ """bioRxiv PDF URL should be BIORXIV, not PDF."""+ url = "https://www.biorxiv.org/content/10.1101/2023.01.01.123456v1.full.pdf"+ assert URLClassifier.classify(url) == URLType.BIORXIV++ def test_ncbi_pdf_not_classified_as_pdf(self):+ """NCBI domain PDF path should not be classified as generic PDF."""+ url = "https://ncbi.nlm.nih.gov/pmc/articles/pmc123456/pdf/main.pdf"+ assert URLClassifier.classify(url) == URLType.PMC+++class TestIsPdfUrlDirectly:+ """Direct tests on the _is_pdf_url classmethod."""++ def test_pdf_extension_returns_true(self):+ """URL ending in .pdf returns True."""+ assert URLClassifier._is_pdf_url("https://example.com/file.pdf") is True++ def test_pdf_path_segment_returns_true(self):+ """/pdf/ in path returns True."""+ assert URLClassifier._is_pdf_url("https://example.com/pdf/doc1") is True++ def test_no_pdf_indicator_returns_false(self):+ """Normal URL returns False."""+ assert URLClassifier._is_pdf_url("https://example.com/page") is False++ def test_arxiv_domain_returns_false(self):+ """arXiv domain always returns False (academic exclusion)."""+ assert (+ URLClassifier._is_pdf_url("https://arxiv.org/pdf/2301.12345")+ is False+ )++ def test_semanticscholar_domain_returns_false(self):+ """Semantic Scholar domain always returns False."""+ assert (+ URLClassifier._is_pdf_url("https://semanticscholar.org/paper.pdf")+ is False+ )++ def test_europepmc_domain_returns_false(self):+ """Europe PMC domain always returns False."""+ assert (+ URLClassifier._is_pdf_url("https://europepmc.org/pdf/doc.pdf")+ is False+ )++ def test_medrxiv_domain_returns_false(self):+ """medRxiv domain always returns False."""+ assert (+ URLClassifier._is_pdf_url("https://medrxiv.org/content/file.pdf")+ is False+ )+++class TestExtractIdEdgeCases:+ """Edge cases for ID extraction."""++ def test_arxiv_five_digit_id(self):+ """arXiv ID with 5-digit suffix (newer format)."""+ url = "https://arxiv.org/abs/2301.12345"+ assert URLClassifier.extract_id(url) == "2301.12345"++ def test_arxiv_old_format_with_version(self):+ """Old arXiv format with version number."""+ url = "https://arxiv.org/abs/hep-th/9901001v3"+ assert URLClassifier.extract_id(url) == "hep-th/9901001v3"++ def test_pmc_id_case_insensitive(self):+ """PMC ID extraction is case-insensitive."""+ url = "https://www.ncbi.nlm.nih.gov/pmc/articles/pmc9876543/"+ extracted = URLClassifier.extract_id(url, URLType.PMC)+ assert extracted == "PMC9876543"++ def test_doi_complex_suffix(self):+ """DOI with complex characters in suffix."""+ url = "https://doi.org/10.1038/s41586-021-03819-2"+ assert URLClassifier.extract_id(url) == "10.1038/s41586-021-03819-2"++ def test_extract_id_with_explicit_type_html(self):+ """Passing url_type=HTML returns None (no ID for HTML)."""+ url = "https://example.com/article/123"+ assert URLClassifier.extract_id(url, URLType.HTML) is None++ def test_extract_id_with_explicit_type_pdf(self):+ """Passing url_type=PDF returns None (no ID for PDF)."""+ url = "https://example.com/paper.pdf"+ assert URLClassifier.extract_id(url, URLType.PDF) is None++ def test_extract_id_with_explicit_type_invalid(self):+ """Passing url_type=INVALID returns None."""+ url = "javascript:alert(1)"+ assert URLClassifier.extract_id(url, URLType.INVALID) is None++ def test_pubmed_id_no_trailing_slash(self):+ """PubMed ID extraction without trailing slash."""+ url = "https://pubmed.ncbi.nlm.nih.gov/55555555"+ assert URLClassifier.extract_id(url) == "55555555"+++class TestGetSourceNameCompleteness:+ """Verify get_source_name covers all URLType values."""++ @pytest.mark.parametrize(+ "url_type,expected_name",+ [+ (URLType.ARXIV, "arXiv"),+ (URLType.PUBMED, "PubMed"),+ (URLType.PMC, "PubMed Central"),+ (URLType.SEMANTIC_SCHOLAR, "Semantic Scholar"),+ (URLType.BIORXIV, "bioRxiv"),+ (URLType.MEDRXIV, "medRxiv"),+ (URLType.DOI, "DOI"),+ (URLType.PDF, "PDF"),+ (URLType.HTML, "Web Page"),+ (URLType.INVALID, "Invalid URL"),+ ],+ )+ def test_source_name_mapping(self, url_type, expected_name):+ """Every URLType has the correct human-readable name."""+ assert URLClassifier.get_source_name(url_type) == expected_name++ def test_all_url_types_have_source_names(self):+ """Every URLType member returns a non-'Unknown' source name."""+ for member in URLType:+ name = URLClassifier.get_source_name(member)+ assert name != "Unknown", f"{member} has no source name mapping"+++class TestClassifyDefaultToHTML:+ """URLs that don't match any special pattern default to HTML."""++ def test_plain_http_url(self):+ """Plain HTTP URL defaults to HTML."""+ assert URLClassifier.classify("http://example.com") == URLType.HTML++ def test_url_without_scheme(self):+ """URL without scheme defaults to HTML (empty scheme is allowed)."""+ assert URLClassifier.classify("example.com/page") == URLType.HTML++ def test_url_with_port(self):+ """URL with port number defaults to HTML."""+ assert (+ URLClassifier.classify("https://example.com:8080/page")+ == URLType.HTML+ )++ def test_url_with_auth(self):+ """URL with authentication info defaults to HTML."""+ assert (+ URLClassifier.classify("https://user:[email protected]/page")+ == URLType.HTML+ )