Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

57.3 KB
Raw Blame
"""
Coverage tests for ArXivSearchEngine.

Targets uncovered paths in search_engine_arxiv.py including:
- __init__ with/without journal filter
- _get_search_results with various sort options
- _get_previews success and error paths (rate limit patterns)
- _get_full_content: snippets-only mode, cache hit/miss, HTML-first
  full-text fetch, fetch failure, limit reached, empty-text fallback,
  _fetch_full_text downloader routing
- run() cleanup of _papers
- get_paper_details: found/not-found, snippet-only mode, full mode, full-text fetch
- search_by_author / search_by_category with/without custom max_results
"""

from datetime import datetime
from unittest.mock import Mock, PropertyMock, patch

import requests

import pytest

from local_deep_research.utilities.arxiv_api import (
    ArxivSortCriterion,
    ArxivSortOrder,
)

FETCH_SEAM = (
    "local_deep_research.web_search_engines.engines."
    "search_engine_arxiv.fetch_arxiv_results"
)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _make_mock_author(name):
    a = Mock()
    a.name = name
    return a


_SENTINEL = object()


def _make_mock_paper(
    entry_id="http://arxiv.org/abs/2101.00001",
    title="Test Paper",
    summary="A short summary",
    authors=None,
    published=_SENTINEL,
    updated=_SENTINEL,
    journal_ref=None,
    pdf_url="http://arxiv.org/pdf/2101.00001",
    categories=None,
    comment=None,
    doi=None,
):
    paper = Mock()
    paper.entry_id = entry_id
    paper.title = title
    paper.summary = summary
    paper.authors = authors or [
        _make_mock_author("Author A"),
        _make_mock_author("Author B"),
    ]
    paper.published = (
        datetime(2021, 1, 1) if published is _SENTINEL else published
    )
    paper.updated = datetime(2021, 6, 1) if updated is _SENTINEL else updated
    paper.journal_ref = journal_ref
    paper.pdf_url = pdf_url
    paper.categories = categories or ["cs.AI"]
    paper.comment = comment
    paper.doi = doi
    paper.download_pdf = Mock(return_value="/tmp/paper.pdf")
    return paper


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture
def engine():
    """Create ArXivSearchEngine with mocked dependencies."""
    with patch(
        "local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter"
    ) as mock_jrf:
        mock_jrf.create_default.return_value = None
        from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
            ArXivSearchEngine,
        )

        eng = ArXivSearchEngine(max_results=10)
        yield eng


@pytest.fixture
def engine_with_pdf():
    """Engine configured for PDF download."""
    with patch(
        "local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter"
    ) as mock_jrf:
        mock_jrf.create_default.return_value = None
        from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
            ArXivSearchEngine,
        )

        eng = ArXivSearchEngine(
            max_results=10,
            include_full_text=True,
            download_dir="/tmp/papers",
            max_full_text=2,
        )
        yield eng


@pytest.fixture
def log_sink():
    """Capture rendered loguru output for the path-leak assertions below.

    A dedicated sink rather than ``loguru_caplog``: this module wants a
    plain rendered string per record and its own local control over the
    sink level/format, so it follows the same "enable, add, yield,
    remove, disable" dance as
    ``tests/research_library/test_download_service_contracts.py``'s
    ``log_sink`` fixture. ``local_deep_research/__init__.py`` calls
    ``logger.disable("local_deep_research")`` at import time, so package
    logging is invisible to any sink until re-enabled -- and the
    disabled state is restored afterwards so this fixture doesn't leak
    logging-enabled into later tests.
    """
    from local_deep_research.security.secure_logging import logger

    captured = []
    logger.enable("local_deep_research")
    sink_id = logger.add(
        captured.append,
        level="TRACE",
        format="{level} | {name} | {message}",
        diagnose=False,
        backtrace=True,
    )
    try:
        yield captured
    finally:
        logger.remove(sink_id)
        logger.disable("local_deep_research")


# ===========================================================================
# __init__ tests
# ===========================================================================


class TestInit:
    def test_default_init(self, engine):
        """Basic init sets expected attributes."""
        assert engine.sort_by == "relevance"
        assert engine.sort_order == "descending"
        assert engine.include_full_text is False
        assert engine.download_dir is None
        assert engine.max_full_text == 1
        # max_results is max(10, 25) = 25
        assert engine.max_results >= 25

    def test_init_with_journal_filter(self):
        """Journal filter is added to content_filters when created."""
        mock_filter = Mock()
        with patch(
            "local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter"
        ) as mock_jrf:
            mock_jrf.create_default.return_value = mock_filter
            from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
                ArXivSearchEngine,
            )

            eng = ArXivSearchEngine(max_results=5)
            assert mock_filter in eng._preview_filters

    def test_init_custom_sort(self):
        """Custom sort_by and sort_order are stored."""
        with patch(
            "local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter"
        ) as mock_jrf:
            mock_jrf.create_default.return_value = None
            from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
                ArXivSearchEngine,
            )

            eng = ArXivSearchEngine(
                sort_by="submittedDate", sort_order="ascending"
            )
            assert eng.sort_by == "submittedDate"
            assert eng.sort_order == "ascending"

    def test_max_results_at_least_25(self):
        """max_results should be at least 25 even if lower value passed."""
        with patch(
            "local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter"
        ) as mock_jrf:
            mock_jrf.create_default.return_value = None
            from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
                ArXivSearchEngine,
            )

            eng = ArXivSearchEngine(max_results=5)
            assert eng.max_results >= 25


# ===========================================================================
# _get_search_results
# ===========================================================================


class TestGetSearchResults:
    def test_search_results_default_sort(self, engine):
        """_get_search_results uses default relevance sort."""
        with patch(FETCH_SEAM, return_value=[_make_mock_paper()]) as fetch:
            results = engine._get_search_results("test query")
            assert len(results) == 1
            request = fetch.call_args.args[0]
            assert request.sort_by is ArxivSortCriterion.RELEVANCE
            assert request.sort_order is ArxivSortOrder.DESCENDING

    def test_search_results_unknown_sort_fallback(self, engine):
        """Unknown sort_by/sort_order falls back to defaults."""
        engine.sort_by = "unknown_sort"
        engine.sort_order = "unknown_order"
        with patch(FETCH_SEAM, return_value=[]) as fetch:
            results = engine._get_search_results("q")
            assert results == []
            request = fetch.call_args.args[0]
            assert request.sort_by is ArxivSortCriterion.RELEVANCE
            assert request.sort_order is ArxivSortOrder.DESCENDING

    def test_search_results_submitted_date_ascending(self):
        """Sort by submittedDate ascending."""
        with patch(
            "local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter"
        ) as mock_jrf:
            mock_jrf.create_default.return_value = None
            from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
                ArXivSearchEngine,
            )

            eng = ArXivSearchEngine(
                sort_by="submittedDate", sort_order="ascending"
            )

        with patch(FETCH_SEAM, return_value=[]) as fetch:
            eng._get_search_results("q")
            request = fetch.call_args.args[0]
            assert request.sort_by is ArxivSortCriterion.SUBMITTED_DATE
            assert request.sort_order is ArxivSortOrder.ASCENDING


# ===========================================================================
# _get_previews
# ===========================================================================


class TestGetPreviews:
    def test_previews_success(self, engine):
        """Successful previews returns formatted list."""
        paper = _make_mock_paper(summary="A" * 300)
        with patch.object(engine, "_get_search_results", return_value=[paper]):
            previews = engine._get_previews("test")
            assert len(previews) == 1
            assert previews[0]["title"] == "Test Paper"
            assert previews[0]["snippet"].endswith("...")
            assert previews[0]["source"] == "arXiv"
            assert hasattr(engine, "_papers")

    def test_previews_short_summary_no_ellipsis(self, engine):
        """Short summary is not truncated."""
        paper = _make_mock_paper(summary="Short")
        with patch.object(engine, "_get_search_results", return_value=[paper]):
            previews = engine._get_previews("test")
            assert previews[0]["snippet"] == "Short"

    def test_previews_no_published_date(self, engine):
        """Paper without published date has None."""
        paper = _make_mock_paper(published=None)
        with patch.object(engine, "_get_search_results", return_value=[paper]):
            previews = engine._get_previews("test")
            assert previews[0]["published"] is None

    def test_previews_generic_error_returns_empty(self, engine):
        """Generic exception returns empty list."""
        with patch.object(
            engine, "_get_search_results", side_effect=ValueError("oops")
        ):
            result = engine._search_previews("test")
            assert result == []

    def test_previews_429_raises_rate_limit(self, engine):
        """429 error raises RateLimitError."""
        from local_deep_research.web_search_engines.rate_limiting import (
            RateLimitError,
        )

        with patch.object(
            engine,
            "_get_search_results",
            side_effect=requests.HTTPError(
                response=Mock(status_code=429, headers={})
            ),
        ):
            with pytest.raises(RateLimitError):
                engine._search_previews("test")

    def test_previews_too_many_requests_raises(self, engine):
        """'too many requests' raises RateLimitError."""
        from local_deep_research.web_search_engines.rate_limiting import (
            RateLimitError,
        )

        with patch.object(
            engine,
            "_get_search_results",
            side_effect=Exception("too many requests"),
        ):
            with pytest.raises(RateLimitError):
                engine._search_previews("test")

    def test_previews_rate_limit_phrase_raises(self, engine):
        """'rate limit' in message raises RateLimitError."""
        from local_deep_research.web_search_engines.rate_limiting import (
            RateLimitError,
        )

        with patch.object(
            engine,
            "_get_search_results",
            side_effect=Exception("rate limit exceeded"),
        ):
            with pytest.raises(RateLimitError):
                engine._search_previews("test")

    def test_previews_sdk_unavailable_message_records_failure(self, engine):
        """An SDK error without status metadata still records a failure."""
        with patch.object(
            engine,
            "_get_search_results",
            side_effect=Exception("service unavailable"),
        ):
            assert engine._search_previews("test") == []
        assert engine.last_search_failure.cooldown_seconds == 60
        assert engine.last_search_failure is not None

    def test_previews_503_records_temporary_failure(self, engine):
        """503 error records a temporary provider failure."""
        with patch.object(
            engine,
            "_get_search_results",
            side_effect=requests.HTTPError(
                response=Mock(status_code=503, headers={})
            ),
        ):
            assert engine._search_previews("test") == []
        assert engine.last_search_failure.cooldown_seconds == 60
        assert "HTTP 503" in engine.last_search_failure.reason

    def test_previews_authors_limited_to_3(self, engine):
        """Preview only includes first 3 authors."""
        paper = _make_mock_paper(
            authors=[_make_mock_author(f"Author {i}") for i in range(5)]
        )
        with patch.object(engine, "_get_search_results", return_value=[paper]):
            previews = engine._get_previews("test")
            assert len(previews[0]["authors"]) == 3


# ===========================================================================
# _get_full_content
# ===========================================================================


class TestGetFullContent:
    def test_no_paper_in_cache(self, engine):
        """Item not in _papers cache is returned as-is."""
        engine._papers = {}
        items = [{"id": "unknown_id", "title": "T"}]
        result = engine._get_full_content(items)
        assert len(result) == 1
        assert "content" not in result[0]

    def test_no_papers_attr(self, engine):
        """If _papers not set, item returned as-is."""
        if hasattr(engine, "_papers"):
            del engine._papers
        items = [{"id": "x", "title": "T"}]
        result = engine._get_full_content(items)
        assert len(result) == 1

    @pytest.mark.parametrize(
        "journal_ref_value",
        [None, "Phys. Rev. Lett. 125, 123456 (2020)"],
    )
    def test_paper_in_cache_no_pdf(self, engine, journal_ref_value):
        """Paper in cache adds full info; no PDF download when not configured.

        Parametrized over journal_ref to regression-guard the forwarding
        wired up in commit d88de731d4 — without the assertion, dropping
        ``"journal_ref": paper.journal_ref`` from the result dict would
        go unnoticed.
        """
        paper = _make_mock_paper(journal_ref=journal_ref_value)
        engine._papers = {paper.entry_id: paper}
        items = [{"id": paper.entry_id, "title": paper.title}]
        result = engine._get_full_content(items)
        assert result[0]["content"] == paper.summary
        assert result[0]["pdf_url"] == "https://arxiv.org/pdf/2101.00001"
        assert result[0]["categories"] == ["cs.AI"]
        assert result[0]["journal_ref"] == journal_ref_value

    def test_paper_no_published_date(self, engine):
        """Paper without published/updated dates."""
        paper = _make_mock_paper(published=None, updated=None)
        engine._papers = {paper.entry_id: paper}
        items = [{"id": paper.entry_id, "title": "T"}]
        result = engine._get_full_content(items)
        assert result[0]["published"] is None
        assert result[0]["updated"] is None

    def test_full_text_via_downloader_succeeds(self, engine_with_pdf):
        """Full-text fetch through the HTML-first downloader populates content."""
        paper = _make_mock_paper()
        engine_with_pdf._papers = {paper.entry_id: paper}
        items = [{"id": paper.entry_id, "title": "T"}]

        with patch.object(
            engine_with_pdf,
            "_fetch_full_text",
            return_value="Full text from downloader",
        ) as mock_fetch:
            result = engine_with_pdf._get_full_content(items)

        mock_fetch.assert_called_once_with(paper)
        assert result[0]["content"] == "Full text from downloader"
        assert result[0]["full_content"] == "Full text from downloader"
        assert "pdf_path" not in result[0]
        paper.download_pdf.assert_not_called()

    def test_full_text_none_falls_back_to_summary(self, engine_with_pdf):
        """Downloader yielding no text leaves the summary as content."""
        paper = _make_mock_paper()
        engine_with_pdf._papers = {paper.entry_id: paper}
        items = [{"id": paper.entry_id, "title": "T"}]

        with patch.object(
            engine_with_pdf, "_fetch_full_text", return_value=None
        ):
            result = engine_with_pdf._get_full_content(items)

        assert result[0]["content"] == paper.summary
        assert result[0]["full_content"] == paper.summary
        assert "pdf_path" not in result[0]

    def test_full_text_whitespace_falls_back_to_summary(self, engine_with_pdf):
        """Whitespace-only downloader text is treated as no text."""
        paper = _make_mock_paper()
        engine_with_pdf._papers = {paper.entry_id: paper}
        items = [{"id": paper.entry_id, "title": "T"}]

        with patch.object(
            engine_with_pdf, "_fetch_full_text", return_value="   \n  "
        ):
            result = engine_with_pdf._get_full_content(items)

        assert result[0]["content"] == paper.summary

    def test_fetch_full_text_uses_downloader_with_canonical_url(
        self, engine_with_pdf
    ):
        """_fetch_full_text routes through ArxivDownloader.download_full_text.

        The downloader is built for export.arxiv.org, the host arXiv sets
        aside for programmatic access.
        """
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivFullTextOutcome,
            ArxivFullTextStatus,
            ArxivTextResult,
            ArxivTextSource,
        )

        paper = _make_mock_paper()
        text_result = ArxivTextResult(
            "equation-preserving text", ArxivTextSource.ARXIV_HTML
        )
        with patch(
            "local_deep_research.research_library.downloaders.arxiv."
            "ArxivDownloader"
        ) as downloader_cls:
            instance = downloader_cls.return_value
            instance.download_full_text.return_value = ArxivFullTextOutcome(
                ArxivFullTextStatus.TEXT, text_result
            )

            text = engine_with_pdf._fetch_full_text(paper)

            downloader_cls.assert_called_once_with(
                fetch_host="export.arxiv.org"
            )
            instance.download_full_text.assert_called_once_with(
                "https://arxiv.org/abs/2101.00001"
            )
            assert text == "equation-preserving text"
            # Downloader is cached on the engine for reuse across papers
            assert engine_with_pdf._arxiv_text_downloader is instance

    def test_fetch_full_text_invalid_id_raises(self, engine_with_pdf):
        """A paper whose entry_id yields no valid arXiv id raises."""
        paper = _make_mock_paper(entry_id="https://example.org/not-arxiv")

        with pytest.raises(ValueError):
            engine_with_pdf._fetch_full_text(paper)

    def test_paper_without_full_text_does_not_consume_budget(
        self, engine_with_pdf
    ):
        """A paper arXiv answered has no full text refunds the budget.

        Drives the real ``_fetch_full_text`` -> ``ArxivDownloader`` chain
        and fakes only the downloader's HTTP session. Both of the first
        paper's requests are answered 404 (no rendition, no PDF), which the
        downloader turns into ``None`` rather than an exception, so the
        refund must come from the "no full text" outcome and not from an
        ``except`` clause. With ``max_full_text=1``, a fetch that kept the
        budget would leave the second paper on its summary without ever
        requesting it.
        """
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivDownloader,
        )

        engine_with_pdf.max_full_text = 1
        engine_with_pdf.rate_tracker = Mock()
        paper1 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00001")
        paper2 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00002")
        engine_with_pdf._papers = {
            paper1.entry_id: paper1,
            paper2.entry_id: paper2,
        }
        items = [
            {"id": paper1.entry_id, "title": "P1"},
            {"id": paper2.entry_id, "title": "P2"},
        ]

        prose = " ".join(
            ["The second paper has a readable official HTML rendition."] * 8
        )
        rendition = (
            "<html><head><title>Paper two</title></head><body><article>"
            "<h1>Paper two</h1>"
            + "".join(f"<p>{prose} Paragraph {k}.</p>" for k in range(6))
            + "</article></body></html>"
        )
        html_url = "https://arxiv.org/html/2101.00002"

        def html_response():
            response = requests.Response()
            response.status_code = 200
            response.headers["Content-Type"] = "text/html; charset=utf-8"
            response.encoding = "utf-8"
            response._content = rendition.encode()
            response.url = html_url
            return response

        requested = []

        def fake_get(url, **kwargs):
            requested.append(url)
            if url == html_url:
                return html_response()
            return Mock(status_code=404, headers={})

        downloader = ArxivDownloader()
        downloader.rate_tracker = Mock()
        engine_with_pdf._arxiv_text_downloader = downloader
        with patch.object(downloader.session, "get", side_effect=fake_get):
            result = engine_with_pdf._get_full_content(items)

        # Both of the first paper's requests were answered 404; it kept
        # its summary
        assert [url for url in requested if "2101.00001" in url] == [
            "https://arxiv.org/html/2101.00001",
            "https://arxiv.org/pdf/2101.00001.pdf",
        ]
        assert result[0]["content"] == paper1.summary
        # The second paper still got its full-text attempt, and its text
        assert html_url in requested
        assert result[1]["content"] != paper2.summary
        assert "Paper two" in result[1]["content"]
        # The API leg would only return the abstract, so it is never asked
        assert not any("api/query" in url for url in requested)

    @pytest.mark.parametrize(
        "failure",
        [
            pytest.param(requests.exceptions.Timeout("hung"), id="timeout"),
            pytest.param(
                requests.exceptions.ConnectionError("down"), id="connection"
            ),
            pytest.param(500, id="http_500"),
            pytest.param(502, id="http_502"),
            pytest.param(504, id="http_504"),
            # SafeSession raises ValueError when validate_url refuses the
            # URL, which is also how a failed DNS lookup (offline machine)
            # surfaces; it lands in _download_pdf's catch-all branch.
            pytest.param(
                ValueError(
                    "URL failed security validation (possible SSRF): "
                    "https://arxiv.org/pdf/2101.00001.pdf"
                ),
                id="dns_failure_validator_refusal",
            ),
            pytest.param(RuntimeError("boom"), id="unexpected_error"),
        ],
    )
    def test_failing_host_stops_further_fetches(
        self, engine_with_pdf, failure, loguru_caplog
    ):
        """A hung or failing arXiv costs one paper's requests, not one per paper.

        Drives the real ``_fetch_full_text`` -> ``ArxivDownloader`` chain
        with every request failing (a timeout, a connection error, or a
        5xx). The first paper costs one HTML and one unretried PDF request;
        the remaining papers are not requested at all, keep their
        summaries, and nothing is logged at ERROR (it would reach the
        user's browser). Red under refunding a failed request: every paper
        is then requested (six requests here, ~25 HTML+PDF pairs with 30 s
        timeouts for a real search).
        """
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivDownloader,
        )

        engine_with_pdf.max_full_text = 3
        engine_with_pdf.rate_tracker = Mock()
        papers = [
            _make_mock_paper(entry_id=f"http://arxiv.org/abs/2101.0000{n}")
            for n in (1, 2, 3)
        ]
        engine_with_pdf._papers = {p.entry_id: p for p in papers}
        items = [{"id": p.entry_id, "title": "P"} for p in papers]

        requested = []

        def fake_get(url, **kwargs):
            requested.append(url)
            if isinstance(failure, Exception):
                raise failure
            return Mock(status_code=failure, headers={})

        downloader = ArxivDownloader()
        downloader.rate_tracker = Mock()
        downloader.rate_tracker.apply_rate_limit.return_value = 0
        engine_with_pdf._arxiv_text_downloader = downloader
        with (
            loguru_caplog.at_level("DEBUG"),
            patch.object(downloader.session, "get", side_effect=fake_get),
        ):
            result = engine_with_pdf._get_full_content(items)

        assert requested == [
            "https://arxiv.org/html/2101.00001",
            "https://arxiv.org/pdf/2101.00001.pdf",
        ]
        assert [r["content"] for r in result] == [p.summary for p in papers]
        assert "arXiv full-text fetch failed" in loguru_caplog.text
        assert not [r for r in loguru_caplog.records if r.levelno >= 40]

    def test_rate_limited_full_text_stops_further_fetches(
        self, engine_with_pdf
    ):
        """Under persistent 429 the engine stops after the first paper.

        Drives the real ``_fetch_full_text`` -> ``ArxivDownloader`` chain
        with every request answered 429. The first paper costs one HTML
        and one PDF request (the PDF is not retried into the rate limit);
        the remaining papers are not requested at all and keep their
        summaries.
        """
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivDownloader,
        )

        engine_with_pdf.max_full_text = 3
        engine_with_pdf.rate_tracker = Mock()
        papers = [
            _make_mock_paper(entry_id=f"http://arxiv.org/abs/2101.0000{n}")
            for n in (1, 2, 3)
        ]
        engine_with_pdf._papers = {p.entry_id: p for p in papers}
        items = [{"id": p.entry_id, "title": "P"} for p in papers]

        requested = []

        def fake_get(url, **kwargs):
            requested.append(url)
            return Mock(status_code=429, headers={})

        downloader = ArxivDownloader()
        downloader.rate_tracker = Mock()
        downloader.rate_tracker.apply_rate_limit.return_value = 0
        engine_with_pdf._arxiv_text_downloader = downloader
        with patch.object(downloader.session, "get", side_effect=fake_get):
            result = engine_with_pdf._get_full_content(items)

        assert len(requested) == 2
        assert all("2101.00001" in url for url in requested)
        assert [r["content"] for r in result] == [p.summary for p in papers]

    def test_fetch_full_text_raises_when_a_request_failed(
        self, engine_with_pdf
    ):
        """A FETCH_FAILED outcome raises FullTextFetchFailedError."""
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivFullTextOutcome,
            ArxivFullTextStatus,
        )
        from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
            FullTextFetchFailedError,
            FullTextRateLimitedError,
        )

        downloader = Mock()
        downloader.download_full_text.return_value = ArxivFullTextOutcome(
            ArxivFullTextStatus.FETCH_FAILED
        )
        engine_with_pdf._arxiv_text_downloader = downloader

        with pytest.raises(FullTextFetchFailedError) as raised:
            engine_with_pdf._fetch_full_text(_make_mock_paper())
        assert not isinstance(raised.value, FullTextRateLimitedError)

    def test_fetch_full_text_raises_when_rate_limited(self, engine_with_pdf):
        """A RATE_LIMITED outcome raises FullTextRateLimitedError."""
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivFullTextOutcome,
            ArxivFullTextStatus,
        )
        from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
            FullTextRateLimitedError,
        )

        downloader = Mock()
        downloader.download_full_text.return_value = ArxivFullTextOutcome(
            ArxivFullTextStatus.RATE_LIMITED
        )
        engine_with_pdf._arxiv_text_downloader = downloader

        with pytest.raises(FullTextRateLimitedError):
            engine_with_pdf._fetch_full_text(_make_mock_paper())

    def test_pdf_that_yields_no_text_consumes_the_budget(self, engine_with_pdf):
        """A PDF that downloaded but produced no text is not refunded.

        Only a transport failure is refunded. Here the first paper's PDF
        arrives (an image-only scan, say) and extraction yields nothing:
        the download and the extraction were paid for, so with
        ``max_full_text=1`` the second paper must keep its summary without
        a single request. Red under refunding every no-text result: the
        second paper's HTML and PDF are then requested too.
        """
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivDownloader,
        )

        engine_with_pdf.max_full_text = 1
        engine_with_pdf.rate_tracker = Mock()
        paper1 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00001")
        paper2 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00002")
        engine_with_pdf._papers = {
            paper1.entry_id: paper1,
            paper2.entry_id: paper2,
        }
        items = [
            {"id": paper1.entry_id, "title": "P1"},
            {"id": paper2.entry_id, "title": "P2"},
        ]

        requested = []

        def fake_get(url, **kwargs):
            requested.append(url)
            return Mock(status_code=404, headers={})

        downloader = ArxivDownloader()
        downloader.rate_tracker = Mock()
        engine_with_pdf._arxiv_text_downloader = downloader
        with (
            patch.object(downloader.session, "get", side_effect=fake_get),
            patch.object(
                downloader, "_download_pdf", return_value=b"%PDF-scan"
            ) as download_pdf,
            patch.object(
                downloader, "extract_text_from_pdf", return_value=None
            ) as extract,
        ):
            result = engine_with_pdf._get_full_content(items)

        # The first paper's PDF arrived and was extracted, to no text
        download_pdf.assert_called_once()
        extract.assert_called_once_with(b"%PDF-scan")
        assert result[0]["content"] == paper1.summary
        # The budget stayed spent: nothing was requested for the second
        assert not any("2101.00002" in url for url in requested)
        assert result[1]["content"] == paper2.summary

    def test_fetch_full_text_raises_when_the_pdf_yields_no_text(
        self, engine_with_pdf
    ):
        """PDF_WITHOUT_TEXT raises; NOT_FETCHED reads as None (refundable)."""
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivFullTextOutcome,
            ArxivFullTextStatus,
        )
        from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
            FullTextNotExtractedError,
        )

        downloader = Mock()
        engine_with_pdf._arxiv_text_downloader = downloader

        downloader.download_full_text.return_value = ArxivFullTextOutcome(
            ArxivFullTextStatus.PDF_WITHOUT_TEXT
        )
        with pytest.raises(FullTextNotExtractedError):
            engine_with_pdf._fetch_full_text(_make_mock_paper())

        downloader.download_full_text.return_value = ArxivFullTextOutcome(
            ArxivFullTextStatus.NOT_FETCHED
        )
        assert engine_with_pdf._fetch_full_text(_make_mock_paper()) is None

    @pytest.mark.parametrize(
        ("source_name", "expected"),
        [
            ("ARXIV_HTML", "downloader text"),
            ("LOCAL_PDF", "downloader text"),
            ("ARXIV_API", None),
        ],
    )
    def test_fetch_full_text_returns_only_full_text_sources(
        self, engine_with_pdf, source_name, expected
    ):
        """API metadata is the abstract, not full text, so it reads as None.

        The engine already holds the abstract as the paper summary; counting
        it as full text would spend the budget on no new text.
        """
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivFullTextOutcome,
            ArxivFullTextStatus,
            ArxivTextResult,
            ArxivTextSource,
        )

        downloader = Mock()
        downloader.download_full_text.return_value = ArxivFullTextOutcome(
            ArxivFullTextStatus.TEXT,
            ArxivTextResult("downloader text", ArxivTextSource[source_name]),
        )
        engine_with_pdf._arxiv_text_downloader = downloader

        assert engine_with_pdf._fetch_full_text(_make_mock_paper()) == expected

    def test_full_text_limit_reached(self, engine_with_pdf):
        """Once max_full_text fetches succeed, remaining papers use the summary.

        Uses valid arXiv ids so the first fetch actually succeeds and
        ``pdf_count`` reaches ``max_full_text`` for real, exercising the
        "Reached full-text fetch limit" ``elif`` branch in
        ``_get_full_content``.

        The elif's own body (``result["content"] = paper.summary`` /
        ``result["full_content"] = paper.summary``) re-assigns the exact
        same attribute the *default* assignment a few lines above already
        set for every item, so a plain ``result[1]["content"] ==
        paper2.summary`` equality check can't tell "the elif body ran"
        from "the elif body was deleted" -- both read the same static
        value. This is pinned instead with a ``PropertyMock`` installed
        on ``type(paper2)`` with a ``side_effect`` list, so each of the
        five reads ``_get_full_content`` makes of ``paper2.summary`` for
        this item -- the ``"summary"`` field in the initial
        ``result.update(...)``, the default ``content``/``full_content``
        assignment, then the elif's own ``content``/``full_content``
        reassignment -- returns a distinct value; ``result[1]["content"]``
        and ``["full_content"]`` can then only equal the 4th/5th value if
        the elif body actually executed.

        Installing the ``PropertyMock`` on ``type(paper2)`` (a
        class-level data descriptor) rather than on ``paper2`` itself is
        safe here specifically because ``paper1`` and ``paper2`` do NOT
        share a class: ``NonCallableMock.__new__`` gives every ``Mock()``
        instance its own freshly-created subclass, so ``type(paper1) is
        type(paper2)`` is ``False`` and this patch cannot bleed onto
        ``paper1.summary`` reads.
        """
        engine_with_pdf.max_full_text = 1
        paper1 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00001")
        paper2 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00002")
        engine_with_pdf._papers = {
            paper1.entry_id: paper1,
            paper2.entry_id: paper2,
        }
        items = [
            {"id": paper1.entry_id, "title": "P1"},
            {"id": paper2.entry_id, "title": "P2"},
        ]

        summary_reads = [
            "summary-read-1-field",
            "summary-read-2-default-content",
            "summary-read-3-default-full-content",
            "summary-read-4-elif-content",
            "summary-read-5-elif-full-content",
        ]

        with (
            patch.object(
                engine_with_pdf,
                "_fetch_full_text",
                return_value="paper1 full text",
            ) as mock_fetch,
            patch.object(
                type(paper2),
                "summary",
                new_callable=PropertyMock,
                create=True,
            ) as paper2_summary,
        ):
            paper2_summary.side_effect = summary_reads
            result = engine_with_pdf._get_full_content(items)
            # Only the first paper triggers a fetch; the second
            # must hit the "limit reached" branch and fall back to
            # the summary without calling the fetch helper again
            # (and therefore without ever touching the network).
            mock_fetch.assert_called_once()
            assert result[0]["content"] == "paper1 full text"
            assert result[0]["full_content"] == "paper1 full text"
            assert "pdf_path" not in result[0]
            assert "pdf_path" not in result[1]
            # These can only hold if the elif body's own reassignment
            # ran: deleting those two lines would leave
            # result[1]["content"]/["full_content"] at the 2nd/3rd
            # (default-assignment) read instead of the 4th/5th.
            assert result[1]["content"] == "summary-read-4-elif-content"
            assert (
                result[1]["full_content"] == "summary-read-5-elif-full-content"
            )
            assert paper2_summary.call_count == 5


# ===========================================================================
# run()
# ===========================================================================


class TestRun:
    def test_run_cleans_up_papers(self, engine):
        """run() deletes _papers after completion."""
        with patch.object(
            type(engine).__bases__[0], "run", return_value=[{"title": "T"}]
        ):
            engine._papers = {"id": "paper"}
            result = engine.run("test")
            assert not hasattr(engine, "_papers")
            assert len(result) == 1

    def test_run_no_papers_attr(self, engine):
        """run() does not fail if _papers was never set."""
        with patch.object(type(engine).__bases__[0], "run", return_value=[]):
            if hasattr(engine, "_papers"):
                del engine._papers
            result = engine.run("test")
            assert result == []


# ===========================================================================
# get_paper_details
# ===========================================================================


class TestGetPaperDetails:
    def test_paper_found_full_mode(self, engine):
        """Paper found with full content."""
        paper = _make_mock_paper()
        with patch(FETCH_SEAM, return_value=[paper]):
            result = engine.get_paper_details("2101.00001")
            assert result["title"] == "Test Paper"
            assert result["content"] == paper.summary
            assert "pdf_url" in result

    def test_paper_not_found(self, engine):
        """No paper found returns empty dict."""
        with patch(FETCH_SEAM, return_value=[]):
            result = engine.get_paper_details("9999.99999")
            assert result == {}

    def test_paper_details_exception(self, engine):
        """Exception returns empty dict."""
        with patch(FETCH_SEAM, side_effect=Exception("boom")):
            result = engine.get_paper_details("2101.00001")
            assert result == {}

    def test_paper_long_summary_snippet_truncated(self, engine):
        """Long summary gets truncated snippet with ellipsis."""
        paper = _make_mock_paper(summary="A" * 300)
        with patch(FETCH_SEAM, return_value=[paper]):
            result = engine.get_paper_details("2101.00001")
            assert result["title"] == "Test Paper"
            assert result["snippet"].endswith("...")

    def test_paper_details_full_text_fetch(self, engine_with_pdf):
        """Full text is fetched in get_paper_details when configured."""
        paper = _make_mock_paper()
        with (
            patch(FETCH_SEAM, return_value=[paper]),
            patch.object(
                engine_with_pdf,
                "_fetch_full_text",
                return_value="Full text body",
            ) as mock_fetch,
        ):
            result = engine_with_pdf.get_paper_details("2101.00001")
            assert result["content"] == "Full text body"
            assert result["full_content"] == "Full text body"
            mock_fetch.assert_called_once_with(paper)
            paper.download_pdf.assert_not_called()
            assert "pdf_path" not in result

    def test_paper_details_pdf_without_text_keeps_summary(
        self, engine_with_pdf, log_sink
    ):
        """A PDF that yielded no text leaves the summary, logged as info."""
        from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
            FullTextNotExtractedError,
        )

        paper = _make_mock_paper()
        with (
            patch(FETCH_SEAM, return_value=[paper]),
            patch.object(
                engine_with_pdf,
                "_fetch_full_text",
                side_effect=FullTextNotExtractedError("no text"),
            ),
        ):
            result = engine_with_pdf.get_paper_details("2101.00001")

        assert result["title"] == "Test Paper"
        assert result["content"] == paper.summary
        rendered = "\n".join(str(m) for m in log_sink)
        assert "yielded no text" in rendered
        assert "Error downloading" not in rendered

    @pytest.mark.parametrize(
        ("failure", "expected_log"),
        [
            pytest.param(429, "rate limited the full-text fetch", id="429"),
            pytest.param(503, "rate limited the full-text fetch", id="503"),
            pytest.param(
                requests.exceptions.Timeout("hung"),
                "full-text fetch failed",
                id="timeout",
            ),
            pytest.param(500, "full-text fetch failed", id="500"),
        ],
    )
    def test_paper_details_failed_fetch_keeps_summary_without_error(
        self, engine_with_pdf, log_sink, failure, expected_log
    ):
        """A 429/503, timeout or 5xx keeps the summary and logs no error.

        Drives the real ``_fetch_full_text`` -> ``ArxivDownloader`` ->
        ``BaseDownloader._download_pdf`` / ``_fetch_html_with_final_url``
        chain with only the HTTP session stubbed (no network), so the
        downloader's own give-up logging is part of what is checked. Red
        when any of it logs at ERROR -- the PDF leg's "HTTP 429 after 1
        attempts" give-up, the HTML leg's fetch error, or
        ``get_paper_details`` letting the exception fall into
        ``_log_full_text_error`` -- since ERROR records reach the user's
        browser through ``frontend_progress_sink``.
        """
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivDownloader,
        )

        def fake_get(url, **kwargs):
            if isinstance(failure, Exception):
                raise failure
            return Mock(status_code=failure, headers={})

        paper = _make_mock_paper()
        downloader = ArxivDownloader()
        downloader.rate_tracker = Mock()
        downloader.rate_tracker.apply_rate_limit.return_value = 0
        engine_with_pdf._arxiv_text_downloader = downloader
        engine_with_pdf.rate_tracker = Mock()
        with (
            patch(FETCH_SEAM, return_value=[paper]),
            patch.object(
                downloader.session, "get", side_effect=fake_get
            ) as get,
        ):
            result = engine_with_pdf.get_paper_details("2101.00001")

        # One HTML and one unretried PDF request
        assert get.call_count == 2
        assert result["title"] == "Test Paper"
        assert result["content"] == paper.summary
        assert result["full_content"] == paper.summary
        rendered = "\n".join(str(m) for m in log_sink)
        assert expected_log in rendered
        assert "Error downloading" not in rendered
        assert not any(m.startswith("ERROR") for m in log_sink)

    def test_paper_details_full_text_fetch_fails(self, engine_with_pdf):
        """Full-text fetch failure in get_paper_details is handled gracefully."""
        paper = _make_mock_paper()
        with (
            patch(FETCH_SEAM, return_value=[paper]),
            patch.object(
                engine_with_pdf,
                "_fetch_full_text",
                side_effect=Exception("download error"),
            ) as mock_fetch,
        ):
            result = engine_with_pdf.get_paper_details("2101.00001")
            assert result["title"] == "Test Paper"
            assert result["content"] == paper.summary
            mock_fetch.assert_called_once_with(paper)
            paper.download_pdf.assert_not_called()
            assert "pdf_path" not in result


# ===========================================================================
# PDF-download error handling: path-free logging + exception ordering
# ===========================================================================


class TestDownloadErrorLoggingOmitsPaths:
    """The path-free logging invariant for errors raised by the full-text
    step, in both ``_get_full_content`` and ``get_paper_details``.

    ``_log_full_text_error`` logs an ``OSError`` by its type name only,
    because an ``OSError`` can carry a local filesystem path in its own
    ``str()`` (``strerror``/``filename``) and ``_scrub_error`` does not
    remove paths. Letting it fall through to the scrubbed-message branch
    produces the same result dicts; only the rendered log text tells the
    two apart, so that's what these tests inspect: each asserts both that
    the static "a filesystem error occurred" text (plus the type name) is
    present, and that the path is absent -- a sink that silently
    swallowed the record would fail the first assertion instead of
    passing vacuously.
    """

    def test_get_full_content_oserror_log_omits_path(
        self, engine_with_pdf, log_sink
    ):
        """Catches dropping the ``OSError`` branch of
        ``_log_full_text_error`` for ``_get_full_content``."""
        paper = _make_mock_paper()
        engine_with_pdf._papers = {paper.entry_id: paper}
        items = [{"id": paper.entry_id, "title": "T"}]

        secret_path = "/home/researcher/.secret_key_dir/zzqleak8822"
        with patch.object(
            engine_with_pdf,
            "_fetch_full_text",
            side_effect=FileExistsError(17, f"File exists: '{secret_path}'"),
        ):
            result = engine_with_pdf._get_full_content(items)

        assert "pdf_path" not in result[0]
        rendered = "\n".join(str(m) for m in log_sink)
        # Positive: the static log line was actually emitted, and it
        # names the exception type.
        assert "a filesystem error occurred" in rendered
        assert "FileExistsError" in rendered
        # Negative: but never the path it carries.
        assert secret_path not in rendered

    def test_get_paper_details_oserror_log_omits_path(
        self, engine_with_pdf, log_sink
    ):
        """Same property for ``get_paper_details``."""
        import arxiv

        paper = _make_mock_paper()
        secret_path = "/home/researcher/.secret_key_dir/zzqleak9933"
        with (
            patch.object(arxiv, "Client") as mock_client_cls,
            patch.object(arxiv, "Search"),
            patch.object(
                engine_with_pdf,
                "_fetch_full_text",
                side_effect=FileExistsError(
                    17, f"File exists: '{secret_path}'"
                ),
            ),
        ):
            # arxiv_api._install_gated_session requires a real
            # requests.Session at _session; the guard closes it.
            mock_client = Mock()
            mock_client._session = requests.Session()
            mock_client.results.return_value = [paper]
            mock_client_cls.return_value = mock_client

            result = engine_with_pdf.get_paper_details("2101.00001")

        assert "pdf_path" not in result
        rendered = "\n".join(str(m) for m in log_sink)
        # Positive: the static log line was actually emitted, and it
        # names the exception type.
        assert "a filesystem error occurred" in rendered
        assert "FileExistsError" in rendered
        # Negative: but never the path it carries.
        assert secret_path not in rendered


class TestRequestExceptionKeepsScrubbedMessage:
    """``RequestException`` must keep the scrubbed diagnostic message and
    not take ``_log_full_text_error``'s path-free ``OSError`` branch.
    ``requests``' ``RequestException`` subclasses ``IOError``, which *is*
    ``OSError``, so dropping the ``RequestException`` exclusion from that
    branch would log every ``ConnectionError``/``Timeout``/``HTTPError``
    under the static filesystem message instead of the scrubbed network
    diagnostic.
    """

    def test_connection_error_in_get_full_content_produces_scrubbed_message(
        self, engine_with_pdf, log_sink
    ):
        from requests.exceptions import (
            ConnectionError as RequestsConnectionError,
        )

        paper = _make_mock_paper()
        engine_with_pdf._papers = {paper.entry_id: paper}
        items = [{"id": paper.entry_id, "title": "T"}]

        with patch.object(
            engine_with_pdf,
            "_fetch_full_text",
            side_effect=RequestsConnectionError("zzqnetfail1234"),
        ):
            result = engine_with_pdf._get_full_content(items)

        assert "pdf_path" not in result[0]
        rendered = "\n".join(str(m) for m in log_sink)
        assert "zzqnetfail1234" in rendered
        assert "a filesystem error occurred" not in rendered

    def test_connection_error_in_get_paper_details_produces_scrubbed_message(
        self, engine_with_pdf, log_sink
    ):
        import arxiv
        from requests.exceptions import (
            ConnectionError as RequestsConnectionError,
        )

        paper = _make_mock_paper()
        with (
            patch.object(arxiv, "Client") as mock_client_cls,
            patch.object(arxiv, "Search"),
            patch.object(
                engine_with_pdf,
                "_fetch_full_text",
                side_effect=RequestsConnectionError("zzqnetfail5678"),
            ),
        ):
            mock_client = Mock()
            mock_client._session = requests.Session()
            mock_client.results.return_value = [paper]
            mock_client_cls.return_value = mock_client

            result = engine_with_pdf.get_paper_details("2101.00001")

        assert "pdf_path" not in result
        rendered = "\n".join(str(m) for m in log_sink)
        assert "zzqnetfail5678" in rendered
        assert "a filesystem error occurred" not in rendered


# ===========================================================================
# search_by_author
# ===========================================================================


class TestSearchByAuthor:
    def test_search_by_author_default_max(self, engine):
        """search_by_author uses default max_results."""
        original = engine.max_results
        with patch.object(engine, "run", return_value=[]) as mock_run:
            engine.search_by_author("John Doe")
            mock_run.assert_called_once_with('au:"John Doe"')
            assert engine.max_results == original

    def test_search_by_author_custom_max(self, engine):
        """search_by_author temporarily sets custom max_results."""
        original = engine.max_results
        with patch.object(engine, "run", return_value=[]):
            engine.search_by_author("Jane Doe", max_results=50)
            # max_results should be restored
            assert engine.max_results == original

    def test_search_by_author_restores_on_exception(self, engine):
        """max_results restored even when run() raises."""
        original = engine.max_results
        with patch.object(engine, "run", side_effect=Exception("fail")):
            with pytest.raises(Exception):
                engine.search_by_author("Author", max_results=99)
            assert engine.max_results == original


# ===========================================================================
# search_by_category
# ===========================================================================


class TestSearchByCategory:
    def test_search_by_category_default_max(self, engine):
        """search_by_category uses default max_results."""
        original = engine.max_results
        with patch.object(engine, "run", return_value=[]) as mock_run:
            engine.search_by_category("cs.AI")
            mock_run.assert_called_once_with("cat:cs.AI")
            assert engine.max_results == original

    def test_search_by_category_custom_max(self, engine):
        """search_by_category temporarily sets custom max_results."""
        original = engine.max_results
        with patch.object(engine, "run", return_value=[]):
            engine.search_by_category("physics.optics", max_results=30)
            assert engine.max_results == original

    def test_search_by_category_restores_on_exception(self, engine):
        """max_results restored even when run() raises."""
        original = engine.max_results
        with patch.object(engine, "run", side_effect=Exception("fail")):
            with pytest.raises(Exception):
                engine.search_by_category("math.AG", max_results=15)
            assert engine.max_results == original


# ===========================================================================
# Class attributes
# ===========================================================================


class TestClose:
    """close() releases the lazily cached full-text downloader."""

    def test_close_releases_cached_downloader_and_is_idempotent(self, engine):
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivDownloader,
        )
        from local_deep_research.web_search_engines.search_engine_base import (
            BaseSearchEngine,
        )

        # Given an engine holding the downloader _fetch_full_text caches
        downloader = ArxivDownloader()
        session = downloader.session
        engine._arxiv_text_downloader = downloader

        with (
            patch.object(
                session, "close", wraps=session.close
            ) as session_close,
            patch.object(
                BaseSearchEngine, "close", autospec=True
            ) as base_close,
        ):
            # When the engine is closed twice
            engine.close()
            engine.close()

        # Then the downloader's HTTP session was closed exactly once, the
        # engine dropped the closed downloader, the second close was a
        # no-op, and the base engine's close ran each time
        session_close.assert_called_once_with()
        assert downloader.session is None
        assert getattr(engine, "_arxiv_text_downloader", None) is None
        assert base_close.call_count == 2

    def test_full_text_after_close_builds_a_fresh_downloader(self, engine):
        from local_deep_research.research_library.downloaders.arxiv import (
            ArxivFullTextOutcome,
            ArxivFullTextStatus,
            ArxivTextResult,
            ArxivTextSource,
        )
        from local_deep_research.web_search_engines.search_engine_base import (
            BaseSearchEngine,
        )

        # Given an engine whose cached downloader has been closed
        closed = Mock()
        engine._arxiv_text_downloader = closed
        with patch.object(BaseSearchEngine, "close", autospec=True):
            engine.close()
        closed.close.assert_called_once_with()

        # When full text is fetched again (downloader construction stubbed,
        # so no network seam is opened)
        with patch(
            "local_deep_research.research_library.downloaders.arxiv."
            "ArxivDownloader"
        ) as downloader_cls:
            fresh = downloader_cls.return_value
            fresh.download_full_text.return_value = ArxivFullTextOutcome(
                ArxivFullTextStatus.TEXT,
                ArxivTextResult("fresh text", ArxivTextSource.ARXIV_HTML),
            )
            text = engine._fetch_full_text(_make_mock_paper())

        # Then a new downloader was built and used; the closed one was not
        downloader_cls.assert_called_once_with(fetch_host="export.arxiv.org")
        closed.download_full_text.assert_not_called()
        assert text == "fresh text"
        assert engine._arxiv_text_downloader is fresh

    def test_close_without_cached_downloader(self, engine):
        from local_deep_research.web_search_engines.search_engine_base import (
            BaseSearchEngine,
        )

        # Given an engine that never fetched full text
        assert getattr(engine, "_arxiv_text_downloader", None) is None

        with patch.object(
            BaseSearchEngine, "close", autospec=True
        ) as base_close:
            engine.close()

        # Then only the base engine's resources are released
        base_close.assert_called_once_with(engine)


class TestClassAttributes:
    def test_is_public(self):
        from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
            ArXivSearchEngine,
        )

        assert ArXivSearchEngine.is_public is True

    def test_is_not_generic(self):
        from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
            ArXivSearchEngine,
        )

        assert ArXivSearchEngine.is_generic is False

    def test_is_scientific(self):
        from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
            ArXivSearchEngine,
        )

        assert ArXivSearchEngine.is_scientific is True