~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(downloaders): cover generic PDF fallback behavior (#6984)
LearningCircuitec9e59b31a13
diff --git a/tests/research_library/downloaders/test_generic_downloader_fallback_contracts.py b/tests/research_library/downloaders/test_generic_downloader_fallback_contracts.pynew file mode 100644index 0000000000..50018eb3cb--- /dev/null+++ b/tests/research_library/downloaders/test_generic_downloader_fallback_contracts.py@@ -0,0 +1,243 @@+"""Exercise PDF fallbacks through BaseDownloader and the real SafeSession."""++import io+import socket++import pytest+import requests++from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+)+from local_deep_research.research_library.downloaders import base+from local_deep_research.research_library.downloaders.base import ContentType+from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+ HTML_NOT_PDF_REASON,+)+from local_deep_research.security import dns_pinning, safe_requests+++def downloader(mocker, mock_rate_tracker):+ mocker.patch.object(+ base, "AdaptiveRateLimitTracker", return_value=mock_rate_tracker+ )+ with GenericDownloader() as instance:+ instance.session.trust_env = False+ yield instance+++def http_transport(monkeypatch):+ """Fake only DNS and adapter I/O; keep validation and redirects real."""+ routes = {}+ sent = []++ def resolve(host, port, *args, **kwargs):+ return [+ (+ socket.AF_INET,+ socket.SOCK_STREAM,+ socket.IPPROTO_TCP,+ "",+ ("93.184.216.34", port or 443),+ )+ ]++ def add_response(+ url,+ *,+ status=200,+ body=b"<html>Landing page</html>",+ content_type="text/html",+ location=None,+ ):+ routes[url] = status, body, content_type, location++ def send(adapter, request, **kwargs):+ sent.append(request.url)+ if request.url not in routes:+ # pytest.fail is not swallowed by the downloader's except Exception.+ pytest.fail(f"Unexpected HTTP request: {request.url}")+ status, body, content_type, location = routes[request.url]+ response = requests.Response()+ response.request = request+ response.url = request.url+ response.status_code = status+ response.headers["Content-Type"] = content_type+ response.headers["Content-Length"] = str(len(body))+ response._content = body+ response.raw = io.BytesIO(body)+ if location:+ response.headers["Location"] = location+ return response++ monkeypatch.setattr(dns_pinning, "_real_getaddrinfo", resolve)+ monkeypatch.setattr(requests.adapters.HTTPAdapter, "send", send)+ return add_response, sent++[email protected]("method", ["download", "download_with_result"])[email protected]("content_type", [ContentType.PDF, ContentType.TEXT])+ "url,fallback",+ [+ ("https://example.com/", "https://example.com/index.pdf"),+ (+ "https://example.com/paper/?id=42#part",+ "https://example.com/paper.pdf?id=42#part",+ ),+ ],+)+def test_successful_fallback_reaches_public_entry_points(+ downloader,+ http_transport,+ mock_pdf_content,+ mocker,+ method,+ content_type,+ url,+ fallback,+):+ add_response, sent = http_transport+ add_response(url)+ add_response(+ fallback, body=mock_pdf_content, content_type="application/pdf"+ )+ extract_text = mocker.patch.object(+ downloader, "extract_text_from_pdf", return_value="Extracted text"+ )++ result = getattr(downloader, method)(url, content_type)++ expected = (+ b"Extracted text"+ if content_type == ContentType.TEXT+ else mock_pdf_content+ )+ if method == "download_with_result":+ assert result.is_success+ assert result.skip_reason is None+ assert result.content == expected+ else:+ assert result == expected+ assert sent == [url, fallback]+ if content_type == ContentType.TEXT:+ extract_text.assert_called_once_with(mock_pdf_content)+ else:+ extract_text.assert_not_called()+++ "original_status,error_type,permanent",+ [+ (200, "html_not_pdf", False),+ (403, "forbidden", True),+ (404, "not_found", True),+ ],+)+def test_missing_fallback_does_not_override_original_diagnostic(+ downloader,+ http_transport,+ original_status,+ error_type,+ permanent,+):+ add_response, sent = http_transport+ url = "https://example.com/?id=42#part"+ fallback = "https://example.com/index.pdf?id=42#part"+ add_response(url, status=original_status)+ add_response(fallback, status=404)++ result = downloader.download_with_result(url)++ assert not result.is_success+ assert result.content is None+ assert result.status_code == original_status+ assert sent == [url, fallback, url]+ if original_status == 200:+ assert result.skip_reason == HTML_NOT_PDF_REASON+ failure = FailureClassifier().classify_failure(+ error_type="download_failed",+ status_code=result.status_code,+ url=url,+ details=result.skip_reason,+ )+ assert failure.error_type == error_type+ assert failure.is_permanent() is permanent++[email protected]("method", ["download", "download_with_result"])[email protected]("scheme", ["https", "http"])+ "target_path",+ [+ "127.0.0.1/private",+ "169.254.169.254/latest/meta-data/",+ "[::1]/private",+ ],+)+def test_fallback_redirect_to_private_address_never_reaches_transport(+ downloader,+ http_transport,+ monkeypatch,+ method,+ scheme,+ target_path,+):+ # Every hop keeps the fallback's scheme, so a guard against HTTPS-to-HTTP+ # downgrades cannot be what stops the redirect; only SSRF validation can.+ add_response, sent = http_transport+ url = f"{scheme}://example.com/"+ fallback = f"{scheme}://example.com/index.pdf"+ target = f"{scheme}://{target_path}"+ add_response(url)+ add_response(fallback, status=302, location=target)+ real_validate_url = safe_requests.ssrf_validator.validate_url+ verdicts = []++ def recording_validate_url(candidate, *args, **kwargs):+ verdict = real_validate_url(candidate, *args, **kwargs)+ verdicts.append((candidate, verdict))+ return verdict++ monkeypatch.setattr(+ safe_requests.ssrf_validator, "validate_url", recording_validate_url+ )++ result = getattr(downloader, method)(url)++ if method == "download_with_result":+ assert not result.is_success+ assert result.skip_reason == HTML_NOT_PDF_REASON+ assert sent == [url, fallback, url]+ else:+ assert result is None+ assert sent == [url, fallback]+ assert (target, False) in verdicts++[email protected]("method", ["download", "download_with_result"])+def test_fallback_can_follow_public_redirect(+ downloader,+ http_transport,+ mock_pdf_content,+ method,+):+ add_response, sent = http_transport+ url = "https://example.com/"+ fallback = "https://example.com/index.pdf"+ target = "https://cdn.example.com/paper.pdf"+ add_response(url)+ add_response(fallback, status=302, location=target)+ add_response(target, body=mock_pdf_content, content_type="application/pdf")++ result = getattr(downloader, method)(url)++ if method == "download_with_result":+ assert result.is_success+ assert result.content == mock_pdf_content+ else:+ assert result == mock_pdf_content+ assert sent == [url, fallback, target]diff --git a/tests/research_library/downloaders/test_generic_downloader_pdf_suffix.py b/tests/research_library/downloaders/test_generic_downloader_pdf_suffix.pyindex 4611780d5c..ab434a9af1 100644--- a/tests/research_library/downloaders/test_generic_downloader_pdf_suffix.py+++ b/tests/research_library/downloaders/test_generic_downloader_pdf_suffix.py@@ -47,6 +47,8 @@ from contextlib import contextmanagerfrom unittest.mock import patchimport pytest+import requests+from urllib3.util import parse_urlfrom local_deep_research.research_library.downloaders.generic import (GenericDownloader,@@ -178,19 +180,65 @@ class TestWithPdfSuffix:assert parsed.path == "/index.pdf"assert ".pdf" not in parsed.hostname- def test_unparseable_url_returns_none(self):- """``urlparse`` is permissive, but the helper still has to be- defensive about pathological inputs. A URL that triggers a- ``ValueError`` short-circuits to ``None`` -- the same fail-soft- contract the original try/except block aimed at."""- # An unparseable scheme-side fragment -- urlparse does not- # raise on this in practice, so we use a synthetic ValueError- # via a mocked urlparse to pin the branch.- with patch(- "local_deep_research.research_library.downloaders.generic.urlparse",- side_effect=ValueError("synthetic"),- ):- assert _with_pdf_suffix("https://example.com/paper") is None+ @pytest.mark.parametrize(+ "url,expected",+ [+ (+ "https://u%40ser:p%[email protected]:8443/paper;session=abc?x=1&x=2#part",+ "https://u%40ser:p%[email protected]:8443/paper.pdf;session=abc?x=1&x=2#part",+ ),+ (+ "https://[2606:4700:4700::1111]:8443/paper?q=1",+ "https://[2606:4700:4700::1111]:8443/paper.pdf?q=1",+ ),+ (+ "http://[fe80::1%25eth0]/paper",+ "http://[fe80::1%25eth0]/paper.pdf",+ ),+ (+ "https://bücher.example/paper",+ "https://bücher.example/paper.pdf",+ ),+ (+ "https://example.com/a%2Fb%3Fc%23d?token=a%2Fb%3Fc%23d",+ "https://example.com/a%2Fb%3Fc%23d.pdf?token=a%2Fb%3Fc%23d",+ ),+ (+ "https://example.com//other.example/paper///?next=https://other.example/",+ "https://example.com//other.example/paper.pdf?next=https://other.example/",+ ),+ (+ "https://example.com.////?q=1#/section/",+ "https://example.com./index.pdf?q=1#/section/",+ ),+ ],+ )+ def test_preserves_components_and_http_client_origin(self, url, expected):+ rebuilt = _with_pdf_suffix(url)+ assert rebuilt == expected+ assert _with_pdf_suffix(rebuilt) is None++ # Compare the destinations interpreted by the HTTP client, which uses+ # urllib3 rather than the helper's urllib.parse parser.+ original = parse_url(requests.Request("GET", url).prepare().url)+ fallback = parse_url(requests.Request("GET", rebuilt).prepare().url)+ assert (fallback.scheme, fallback.host, fallback.port) == (+ original.scheme,+ original.host,+ original.port,+ )++ @pytest.mark.parametrize(+ "url",+ [+ "https://[broken/paper",+ "https://[not-ip]/paper",+ "https://example.com\uff0fevil/paper",+ ],+ )+ def test_unparseable_url_returns_none(self, url):+ """Malformed authorities must fail softly without mocking urlparse."""+ assert _with_pdf_suffix(url) is None# ---------------------------------------------------------------------------