~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 27 verified-unique edge-case tests (round 2) (#2385)
LearningCircuitfbd3df7bbc26
diff --git a/tests/metrics/test_pricing_edge_cases.py b/tests/metrics/test_pricing_edge_cases.pynew file mode 100644index 0000000000..6b3ba50f3a--- /dev/null+++ b/tests/metrics/test_pricing_edge_cases.py@@ -0,0 +1,116 @@+"""Edge-case tests for pricing modules — boundary, sync, and provider lookups."""++from unittest.mock import patch+++class TestIsExpiredBoundaryExactlyAtTTL:+ """Verify strict '>' comparison: at exactly TTL seconds, entry is NOT expired."""++ def test_is_expired_boundary_exactly_at_ttl(self):+ """At exactly TTL seconds elapsed, _is_expired must return False (strict >)."""+ from local_deep_research.metrics.pricing.pricing_cache import (+ PricingCache,+ )++ cache = PricingCache(cache_ttl=100)+ now = 1000.0++ with patch(+ "local_deep_research.metrics.pricing.pricing_cache.time"+ ) as mock_time:+ mock_time.time.return_value = now+ # Timestamp is exactly TTL seconds in the past: now - timestamp == TTL+ timestamp = now - 100 # exactly 100 seconds ago+ result = cache._is_expired(timestamp)++ # (1000 - 900) > 100 → 100 > 100 → False+ assert result is False, (+ "At exactly TTL, entry should NOT be expired (strict >)"+ )+++class TestSyncModelWithMultipleSlashes:+ """Verify split('/')[-1] correctly extracts model from multi-slash names."""++ def test_sync_model_with_multiple_slashes(self):+ """'openai/org/gpt-4'.split('/')[-1] should resolve to 'gpt-4' pricing."""+ from local_deep_research.metrics.pricing.cost_calculator import (+ CostCalculator,+ )++ calc = CostCalculator()+ result = calc.calculate_cost_sync(+ model_name="openai/org/gpt-4",+ prompt_tokens=1000,+ completion_tokens=1000,+ )++ # Should find gpt-4 pricing via split("/")[-1]+ assert result["pricing_used"] is not None, (+ "Should resolve multi-slash model name"+ )+ assert result["prompt_cost"] > 0+++class TestSyncZeroPromptTokens:+ """Verify 0 prompt + nonzero completion → prompt_cost=0.0."""++ def test_sync_zero_prompt_tokens(self):+ """Zero prompt tokens with nonzero completion should yield prompt_cost=0.0."""+ from local_deep_research.metrics.pricing.cost_calculator import (+ CostCalculator,+ )++ calc = CostCalculator()+ result = calc.calculate_cost_sync(+ model_name="gpt-4",+ prompt_tokens=0,+ completion_tokens=500,+ )++ assert result["prompt_cost"] == 0.0+ assert result["completion_cost"] > 0+ assert result["total_cost"] == result["completion_cost"]+++class TestSyncVeryLargeTokenCount:+ """Verify 1M tokens doesn't overflow float arithmetic."""++ def test_sync_very_large_token_count(self):+ """1,000,000 tokens should produce valid (large) cost without overflow."""+ from local_deep_research.metrics.pricing.cost_calculator import (+ CostCalculator,+ )++ calc = CostCalculator()+ result = calc.calculate_cost_sync(+ model_name="gpt-4",+ prompt_tokens=1_000_000,+ completion_tokens=1_000_000,+ )++ assert result["pricing_used"] is not None+ # gpt-4: prompt=0.03/1K, completion=0.06/1K+ # Expected: 1M/1K * 0.03 = 30.0, 1M/1K * 0.06 = 60.0+ assert result["prompt_cost"] == 30.0+ assert result["completion_cost"] == 60.0+ assert result["total_cost"] == 90.0+++class TestGetModelsByProviderCaseInsensitive:+ """Verify provider.lower() normalizes uppercase provider names."""++ def test_get_models_by_provider_case_insensitive(self):+ """'OPENAI' should return same models as 'openai' via provider.lower()."""+ from local_deep_research.metrics.pricing.pricing_fetcher import (+ PricingFetcher,+ )++ fetcher = PricingFetcher()+ lower_models = fetcher._get_models_by_provider("openai")+ upper_models = fetcher._get_models_by_provider("OPENAI")++ assert lower_models == upper_models+ assert len(lower_models) > 0+ for model_name in upper_models:+ assert model_name.startswith("gpt")diff --git a/tests/security/test_path_validator_edge_cases.py b/tests/security/test_path_validator_edge_cases.pynew file mode 100644index 0000000000..991c67d2e8--- /dev/null+++ b/tests/security/test_path_validator_edge_cases.py@@ -0,0 +1,77 @@+"""Edge-case tests for path_validator — control chars, null bytes, and case normalization."""++import tempfile+from pathlib import Path++import pytest++from local_deep_research.security.path_validator import PathValidator+++class TestControlCharactersRejected:+ """Verify various control characters (ord < 32) are rejected."""++ def test_tab_character_rejected(self):+ """Tab (\\t, ord 9) should be rejected by validate_local_filesystem_path."""+ with pytest.raises(ValueError, match="[Cc]ontrol"):+ PathValidator.validate_local_filesystem_path("/tmp/test\tdir")++ def test_bell_character_rejected(self):+ """Bell (\\x07, ord 7) should be rejected by validate_local_filesystem_path."""+ with pytest.raises(ValueError, match="[Cc]ontrol"):+ PathValidator.validate_local_filesystem_path("/tmp/test\x07dir")++ def test_newline_in_path_rejected(self):+ """Newline (\\n, ord 10) should be rejected by validate_local_filesystem_path."""+ with pytest.raises(ValueError, match="[Cc]ontrol"):+ PathValidator.validate_local_filesystem_path("/tmp/test\ndir")+++class TestMultipleNullBytesStripped:+ """Verify validate_config_path strips ALL null bytes, not just the first."""++ def test_multiple_null_bytes_all_stripped(self):+ """Multiple null bytes in config path should all be removed."""+ with tempfile.TemporaryDirectory() as tmpdir:+ # Create a settings.json file+ config_file = Path(tmpdir) / "settings.json"+ config_file.write_text('{"key": "value"}')++ # "s\x00e\x00ttings.json" → "settings.json" after null removal+ result = PathValidator.validate_config_path(+ "s\x00e\x00ttings.json",+ config_root=tmpdir,+ )+ assert result.exists()+ assert result.name == "settings.json"+++class TestEtcWithDifferentCasingBlocked:+ """Verify .lower() normalization blocks case-varied restricted paths."""++ def test_etc_with_different_casing_blocked(self):+ """/ETC/passwd should be blocked via .lower() normalization in validate_config_path."""+ with pytest.raises(ValueError, match="restricted"):+ PathValidator.validate_config_path("/ETC/passwd")++ def test_etc_mixed_case_blocked(self):+ """/Etc/shadow should also be blocked."""+ with pytest.raises(ValueError, match="restricted"):+ PathValidator.validate_config_path("/Etc/shadow")+++class TestSafeJoinReturnsNoneRaisesValueError:+ """Verify path traversal via safe_join → None → ValueError."""++ @pytest.fixture+ def temp_base_dir(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ yield Path(tmpdir)++ def test_safe_join_returns_none_raises_valueerror(self, temp_base_dir):+ """Path traversal attempt where safe_join returns None must raise ValueError."""+ with pytest.raises(ValueError):+ PathValidator.validate_safe_path(+ "../../../../../etc/passwd",+ temp_base_dir,+ )diff --git a/tests/test_report_generator_edge_cases.py b/tests/test_report_generator_edge_cases.pynew file mode 100644index 0000000000..fbb9f99a24--- /dev/null+++ b/tests/test_report_generator_edge_cases.py@@ -0,0 +1,155 @@+"""Edge-case tests for report_generator — structure parsing boundaries."""++from unittest.mock import Mock++import pytest++from local_deep_research.report_generator import IntegratedReportGenerator+++def mock_llm():+ """Create a mock LLM."""+ mock = Mock()+ mock.invoke.return_value = Mock(content="Mocked response")+ return mock+++def mock_search_system():+ """Create a mock search system."""+ mock = Mock()+ mock.all_links_of_system = []+ return mock+++def generator(mock_llm, mock_search_system, monkeypatch):+ """Create a report generator with mocked dependencies."""+ monkeypatch.setattr(+ "local_deep_research.report_generator.get_llm", lambda: mock_llm+ )+ return IntegratedReportGenerator(+ search_system=mock_search_system, llm=mock_llm+ )+++class TestDetermineReportStructureNoDelimiters:+ """Verify LLM response without STRUCTURE/END_STRUCTURE returns empty structure."""++ def test_no_structure_delimiters(self, generator):+ """Response without STRUCTURE markers → empty structure list."""+ generator.model.invoke.return_value = Mock(+ content="Here is my analysis of the topic. It covers many areas."+ )++ findings = {"current_knowledge": "Some knowledge about the topic."}+ structure = generator._determine_report_structure(+ findings, "test query"+ )++ # No numbered section lines → empty structure+ assert structure == []+++class TestDetermineReportStructureSectionWithoutPeriod:+ """Verify section line without period (e.g. '1 Section Name') causes IndexError.++ BUG DISCOVERED: line.split('.')[1] at report_generator.py:139 has no guard+ for section lines without a period separator. This test documents the bug.+ """++ def test_section_without_period_raises_index_error(self, generator):+ """'1 Section Name' (no period) → split('.')[1] raises IndexError (unhandled bug)."""+ generator.model.invoke.return_value = Mock(+ content=("STRUCTURE\n1 Section Without Period\nEND_STRUCTURE")+ )++ findings = {"current_knowledge": "Some knowledge."}+ # This is a real bug: line.split(".")[1] with no "." raises IndexError+ with pytest.raises(IndexError):+ generator._determine_report_structure(findings, "test query")+++class TestDetermineReportStructureSubsectionBeforeAnySection:+ """Verify subsection line before any numbered section doesn't crash."""++ def test_subsection_before_any_section(self, generator):+ """'- Subsection' before any numbered section → current_section is None."""+ generator.model.invoke.return_value = Mock(+ content=(+ "STRUCTURE\n"+ "- Orphan Subsection | some purpose\n"+ "1. Actual Section\n"+ " - Valid Subsection | valid purpose\n"+ "END_STRUCTURE"+ )+ )++ findings = {"current_knowledge": "Some knowledge."}+ structure = generator._determine_report_structure(+ findings, "test query"+ )++ # The orphan subsection should be safely skipped (current_section guard)+ # Only the actual section with its valid subsection should be parsed+ assert len(structure) == 1+ assert structure[0]["name"] == "Actual Section"+ assert len(structure[0]["subsections"]) == 1+ assert structure[0]["subsections"][0]["name"] == "Valid Subsection"+++class TestDetermineReportStructureRemovesSourcesSection:+ """Verify last section named 'References' or 'Sources' is auto-removed."""++ def test_removes_references_section(self, generator):+ """Last section named 'References' should be auto-removed."""+ generator.model.invoke.return_value = Mock(+ content=(+ "STRUCTURE\n"+ "1. Introduction\n"+ " - Overview | provide overview\n"+ "2. Key Findings\n"+ " - Results | present results\n"+ "3. References\n"+ " - Bibliography | list sources\n"+ "END_STRUCTURE"+ )+ )++ findings = {"current_knowledge": "Some knowledge."}+ structure = generator._determine_report_structure(+ findings, "test query"+ )++ # "References" matches source_keywords → removed+ assert len(structure) == 2+ assert structure[0]["name"] == "Introduction"+ assert structure[1]["name"] == "Key Findings"+ # "References" section should be gone+ section_names = [s["name"] for s in structure]+ assert "References" not in section_names++ def test_does_not_remove_non_last_source_section(self, generator):+ """Source-related section that is NOT last should be kept."""+ generator.model.invoke.return_value = Mock(+ content=(+ "STRUCTURE\n"+ "1. Sources Overview\n"+ " - Data Sources | describe data origins\n"+ "2. Analysis\n"+ " - Methods | explain methods\n"+ "END_STRUCTURE"+ )+ )++ findings = {"current_knowledge": "Some knowledge."}+ structure = generator._determine_report_structure(+ findings, "test query"+ )++ # "Sources Overview" is first, not last → should NOT be removed+ # "Analysis" is last and doesn't match source keywords → kept+ assert len(structure) == 2+ assert structure[0]["name"] == "Sources Overview"+ assert structure[1]["name"] == "Analysis"diff --git a/tests/text_optimization/test_citation_exporter_edge_cases.py b/tests/text_optimization/test_citation_exporter_edge_cases.pynew file mode 100644index 0000000000..3053cdab8d--- /dev/null+++ b/tests/text_optimization/test_citation_exporter_edge_cases.py@@ -0,0 +1,101 @@+"""Edge-case tests for citation exporters — math mode, list EOF, BibTeX URL, and RIS unicode."""+++class TestInlineMathPreservedBetweenDollars:+ """Verify content between $ markers is NOT escaped during LaTeX export."""++ def test_inline_math_preserved_between_dollars(self):+ """$x^2 + y^2$ should keep ^ and + unescaped inside math mode."""+ from local_deep_research.text_optimization.citation_formatter import (+ LaTeXExporter,+ )++ exporter = LaTeXExporter()+ content = "# Title\n\nThe formula $x^2 + y^2 = r^2$ is important."+ result = exporter.export_to_latex(content)++ # Math content between $ should be preserved (not escaped)+ assert "$x^2 + y^2 = r^2$" in result+++class TestDisplayMathDoubleDollarPreserved:+ """Verify $$...$$ display math blocks are preserved during LaTeX export."""++ def test_display_math_double_dollar_preserved(self):+ """$$E = mc^2$$ should preserve the math content unescaped."""+ from local_deep_research.text_optimization.citation_formatter import (+ LaTeXExporter,+ )++ exporter = LaTeXExporter()+ content = "# Title\n\n$$E = mc^2$$\n\nSome text."+ result = exporter.export_to_latex(content)++ # The display math content should be preserved+ assert "E = mc^2" in result+ # The ^ should NOT be escaped to \textasciicircum{} inside math+ assert r"\textasciicircum" not in result+++class TestListAtEndOfContentGetsClosingTag:+ """Verify list items at EOF trigger \\end{itemize} via _convert_lists lines 940-941."""++ def test_list_at_end_of_content_gets_closing_tag(self):+ """List items at end of content (no trailing text) should get \\end{itemize}."""+ from local_deep_research.text_optimization.citation_formatter import (+ LaTeXExporter,+ )++ exporter = LaTeXExporter()+ # Content ends with list items, no trailing non-list text+ content = "# Title\n\nSome intro text.\n\n- Item one\n- Item two\n- Item three"+ result = exporter.export_to_latex(content)++ begin_count = result.count("\\begin{itemize}")+ end_count = result.count("\\end{itemize}")+ assert begin_count == end_count == 1+ # The last \end{itemize} should be after the last \item+ last_item_pos = result.rfind("\\item")+ last_end_pos = result.rfind("\\end{itemize}")+ assert last_end_pos > last_item_pos+++class TestSourceWithoutUrlOmitsBibtexUrlField:+ """Verify BibTeX entry omits url= field when source has no URL."""++ def test_source_without_url_omits_bibtex_url_field(self):+ """[1] Title without URL line → BibTeX entry should not contain url = {...}."""+ from local_deep_research.text_optimization.citation_formatter import (+ QuartoExporter,+ )++ exporter = QuartoExporter()+ # Source without URL line+ content = "# Report\n\nSome text [1].\n\n## Sources\n[1] A Book Title Without URL"+ bib_content = exporter._generate_bibliography(content)++ assert "ref1" in bib_content+ assert "A Book Title Without URL" in bib_content+ # Should NOT have url field since no URL was provided+ assert "url = " not in bib_content+ assert "howpublished" not in bib_content+++class TestRisExporterHandlesUnicodeTitle:+ """Verify RIS exporter preserves Unicode characters in TI field."""++ def test_ris_exporter_handles_unicode_title(self):+ """Unicode title '日本語' in RIS TI field should be preserved."""+ from local_deep_research.text_optimization.citation_formatter import (+ RISExporter,+ )++ exporter = RISExporter()+ content = (+ "## Sources\n[1] 日本語の研究論文\n URL: https://example.jp/paper"+ )+ ris = exporter.export_to_ris(content)++ assert "TI - " in ris+ assert "日本語" in ris+ assert "UR - https://example.jp/paper" in risdiff --git a/tests/utilities/test_search_utilities_edge_cases.py b/tests/utilities/test_search_utilities_edge_cases.pynew file mode 100644index 0000000000..b45b85b3f6--- /dev/null+++ b/tests/utilities/test_search_utilities_edge_cases.py@@ -0,0 +1,119 @@+"""Edge-case tests for search_utilities — format_findings phase parsing and graceful handling."""+++class TestFormatFindingsMalformedPhaseNonNumeric:+ """Verify ValueError from int() on non-numeric phase is caught gracefully."""++ def test_format_findings_malformed_phase_non_numeric(self):+ """'Follow-up Iteration abc.1' → int('abc') raises ValueError, caught gracefully."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [+ {+ "phase": "Follow-up Iteration abc.1",+ "content": "Some content here.",+ "search_results": [],+ "question": "Fallback question text",+ }+ ]+ questions = {1: ["Question one"]}++ result = format_findings(findings, "Synthesized content", questions)++ # Should not raise — ValueError is caught+ assert "Some content here." in result+ # Since parsing failed, the finding's own question should be displayed as fallback+ assert "Fallback question text" in result+++class TestFormatFindingsOutOfBoundsIteration:+ """Verify out-of-bounds iteration index is handled gracefully."""++ def test_format_findings_out_of_bounds_iteration(self):+ """Phase 'Follow-up Iteration 999.1' with missing iteration key → warning, no crash."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [+ {+ "phase": "Follow-up Iteration 999.1",+ "content": "Out of bounds content.",+ "search_results": [],+ "question": "OOB fallback question",+ }+ ]+ # Only iteration 1 exists, not 999+ questions = {1: ["Only question in iteration 1"]}++ result = format_findings(findings, "Summary", questions)++ assert "Out of bounds content." in result+ # Iteration 999 doesn't exist, so fallback to finding's own question+ assert "OOB fallback question" in result+++class TestFormatFindingsNoneSearchResults:+ """Verify None search_results (instead of list) is handled gracefully."""++ def test_format_findings_none_search_results(self):+ """finding['search_results'] = None should not crash extract_links_from_search_results."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [+ {+ "phase": "Initial Search",+ "content": "Content with None results.",+ "search_results": None,+ }+ ]++ # Should not raise TypeError+ result = format_findings(findings, "Summary", {})+ assert "Content with None results." in result+++class TestFormatFindingsEmptyFindingsList:+ """Verify empty findings_list produces valid output structure."""++ def test_format_findings_empty_findings_list(self):+ """Empty findings_list should produce output with synthesized content but no DETAILED FINDINGS."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ result = format_findings([], "My synthesized summary", {})++ assert "My synthesized summary" in result+ # With empty findings, the DETAILED FINDINGS header should NOT appear+ assert "DETAILED FINDINGS" not in result+++class TestFormatFindingsSubqueryPhaseParsing:+ """Verify 'Sub-query X' phase correctly parsed for IterDRAG-style results."""++ def test_format_findings_subquery_phase_parsing(self):+ """'Sub-query 2' should look up questions_by_iteration[0][1] (index 1)."""+ from local_deep_research.utilities.search_utilities import (+ format_findings,+ )++ findings = [+ {+ "phase": "Sub-query 2",+ "content": "Sub-query content.",+ "search_results": [],+ }+ ]+ # IterDRAG stores sub-queries in iteration 0+ questions = {0: ["First sub-query?", "Second sub-query?"]}++ result = format_findings(findings, "Summary", questions)++ assert "Sub-query content." in result+ # "Sub-query 2" → index 1 → "Second sub-query?"+ assert "Second sub-query?" in result