~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
fix: fetch actual book text in Gutenberg search engine (#3045)
LearningCircuit2838224eaa42
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.py b/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.pyindex 4bc46d2967..adfbfbc28a 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.py@@ -33,6 +33,7 @@ class GutenbergSearchEngine(BaseSearchEngine):author_year_end: Optional[int] = None,copyright_filter: Optional[bool] = None,sort: str = "popular",+ max_content_chars: int = 50000,llm: Optional[BaseLLM] = None,max_filtered_results: Optional[int] = None,settings_snapshot: Optional[Dict[str, Any]] = None,@@ -49,6 +50,7 @@ class GutenbergSearchEngine(BaseSearchEngine):author_year_end: Filter authors born before this yearcopyright_filter: Filter by copyright status (True/False/None)sort: Sort order ('popular', 'ascending', 'descending')+ max_content_chars: Maximum characters of book text to retrievellm: Language model for relevance filteringmax_filtered_results: Maximum results after filteringsettings_snapshot: Settings snapshot for thread context@@ -67,6 +69,7 @@ class GutenbergSearchEngine(BaseSearchEngine):self.author_year_end = author_year_endself.copyright_filter = copyright_filterself.sort = sort+ self.max_content_chars = max_content_charsself.base_url = "https://gutendex.com"self.search_url = f"{self.base_url}/books/"@@ -124,6 +127,71 @@ class GutenbergSearchEngine(BaseSearchEngine):return next(iter(formats.values()))return None+ def _get_text_url(self, formats: Dict[str, str]) -> Optional[str]:+ """Get the plain text URL for content retrieval."""+ for mime_type in [+ "text/plain; charset=utf-8",+ "text/plain; charset=us-ascii",+ "text/plain",+ ]:+ if mime_type in formats:+ return formats[mime_type]+ return None++ def _fetch_book_text(self, text_url: str) -> Optional[str]:+ """Fetch and return the plain text content of a book."""+ try:+ response = safe_get(text_url, headers=self.headers, timeout=30)+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()++ text = response.text+ if not text:+ return None++ # Strip the Project Gutenberg header/footer boilerplate+ start_markers = [+ "*** START OF THE PROJECT GUTENBERG EBOOK",+ "*** START OF THIS PROJECT GUTENBERG EBOOK",+ "***START OF THE PROJECT GUTENBERG EBOOK",+ ]+ end_markers = [+ "*** END OF THE PROJECT GUTENBERG EBOOK",+ "*** END OF THIS PROJECT GUTENBERG EBOOK",+ "***END OF THE PROJECT GUTENBERG EBOOK",+ ]++ for marker in start_markers:+ idx = text.find(marker)+ if idx != -1:+ # Skip past the marker line+ newline = text.find("\n", idx)+ if newline != -1:+ text = text[newline + 1 :]+ break++ for marker in end_markers:+ idx = text.find(marker)+ if idx != -1:+ text = text[:idx]+ break++ text = text.strip()++ # Truncate to max_content_chars+ if len(text) > self.max_content_chars:+ text = (+ text[: self.max_content_chars] + "\n\n[... truncated ...]"+ )++ return text++ except (RateLimitError, ValueError):+ raise+ except Exception:+ logger.warning(f"Failed to fetch book text from {text_url}")+ return None+def _parse_authors(self, authors: List[Dict]) -> List[str]:"""Parse author information."""result = []@@ -264,6 +332,8 @@ class GutenbergSearchEngine(BaseSearchEngine):"""Get full content for the relevant Gutenberg books.+ Fetches the actual plain text of each book from Project Gutenberg.+Args:relevant_items: List of relevant preview dictionaries@@ -290,7 +360,24 @@ class GutenbergSearchEngine(BaseSearchEngine):translators = raw.get("translators", [])result["translators"] = self._parse_authors(translators)- # Build content summary+ # Fetch actual book text+ formats = raw.get("formats", {})+ text_url = self._get_text_url(formats)++ book_text = None+ if text_url and text_url.startswith(+ "https://www.gutenberg.org/"+ ):+ logger.info(+ f"Fetching book text for '{result.get('title')}' from {text_url}"+ )+ book_text = self._fetch_book_text(text_url)+ elif text_url:+ logger.warning(+ f"Skipping text_url with unexpected origin: {text_url}"+ )++ # Build content with metadata header + actual textcontent_parts = []if result.get("authors"):content_parts.append(@@ -300,16 +387,29 @@ class GutenbergSearchEngine(BaseSearchEngine):content_parts.append(f"Subjects: {', '.join(result['subjects'][:5])}")- if result.get("bookshelves"):- content_parts.append(- f"Bookshelves: {', '.join(result['bookshelves'])}"++ if book_text:+ content_parts.append("")+ content_parts.append(book_text)+ logger.info(+ f"Retrieved {len(book_text)} chars of text for '{result.get('title')}'")- if result.get("download_count"):- content_parts.append(- f"Downloads: {result['download_count']}"+ else:+ if result.get("bookshelves"):+ content_parts.append(+ f"Bookshelves: {', '.join(result['bookshelves'])}"+ )+ if result.get("download_count"):+ content_parts.append(+ f"Downloads: {result['download_count']}"+ )+ if result.get("read_url"):+ content_parts.append(+ f"Read online: {result['read_url']}"+ )+ logger.warning(+ f"Could not fetch text for '{result.get('title')}', using metadata only")- if result.get("read_url"):- content_parts.append(f"Read online: {result['read_url']}")result["content"] = "\n".join(content_parts)diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.py b/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.pyindex 8197869fc3..f90fd106a8 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.py@@ -199,16 +199,16 @@ class OpenLibrarySearchEngine(BaseSearchEngine):# Build snippet with description for richer contentsnippet_parts = []if description:- snippet_parts.append(description[:300])+ snippet_parts.append(description[:800])if authors:snippet_parts.append(f"By {', '.join(authors[:3])}")if first_publish_year:snippet_parts.append(f"First published: {first_publish_year}")- if subjects and not description:+ if subjects:snippet_parts.append(- f"Subjects: {', '.join(subjects[:3])}"+ f"Subjects: {', '.join(subjects[:5])}")snippet = ". ".join(snippet_parts)@@ -257,6 +257,9 @@ class OpenLibrarySearchEngine(BaseSearchEngine):"""Get full content for the relevant Open Library books.+ Fetches detailed information from the Works API including+ full descriptions and excerpts.+Args:relevant_items: List of relevant preview dictionaries@@ -289,7 +292,11 @@ class OpenLibrarySearchEngine(BaseSearchEngine):if isinstance(result["publishers"], str):result["publishers"] = [result["publishers"]]- # Build content summary+ # Fetch detailed info from Works API+ work_key = item.get("id", "")+ work_data = self._fetch_work_details(work_key)++ # Build content with metadata + description + excerptscontent_parts = []if result.get("authors"):content_parts.append(@@ -299,17 +306,47 @@ class OpenLibrarySearchEngine(BaseSearchEngine):content_parts.append(f"First published: {result['first_publish_year']}")- if result.get("edition_count"):- content_parts.append(f"Editions: {result['edition_count']}")if result.get("subjects"):subjects = result["subjects"]if isinstance(subjects, list):content_parts.append(f"Subjects: {', '.join(subjects[:10])}")++ # Use full description from Works API if available+ description = ""+ if work_data:+ desc = work_data.get("description", "")+ if isinstance(desc, dict):+ desc = desc.get("value", "")+ elif isinstance(desc, list):+ desc = " ".join(str(d) for d in desc)+ if isinstance(desc, str) and desc:+ description = desc+ if not description:+ desc = raw.get("description", "")+ if isinstance(desc, dict):+ desc = desc.get("value", "")+ elif isinstance(desc, list):+ desc = " ".join(str(d) for d in desc)+ if isinstance(desc, str) and desc:+ description = desc+ if description:+ content_parts.append(f"\n{description}")++ # Add excerpts from Works API+ if work_data:+ excerpts = work_data.get("excerpts", [])+ if excerpts:+ content_parts.append("\nExcerpts:")+ for exc in excerpts[:5]:+ text = exc.get("excerpt", "")+ if text:+ content_parts.append(f' "{text}"')+if result.get("has_fulltext"):content_parts.append(- "Full text available on Internet Archive"+ "\nFull text available on Internet Archive")result["content"] = "\n".join(content_parts)@@ -322,6 +359,26 @@ class OpenLibrarySearchEngine(BaseSearchEngine):return results+ def _fetch_work_details(self, work_key: str) -> Optional[Dict[str, Any]]:+ """Fetch detailed work information from the Works API."""+ if not work_key or not work_key.startswith("/works/"):+ if work_key:+ logger.warning(+ "Invalid work_key format: expected '/works/...' prefix"+ )+ return None+ try:+ url = f"{self.base_url}{work_key}.json"+ response = safe_get(url, headers=self.headers, timeout=15)+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ return response.json() # type: ignore[no-any-return]+ except (RateLimitError, ValueError):+ raise+ except Exception:+ logger.warning(f"Failed to fetch work details for {work_key}")+ return None+def get_book_by_isbn(self, isbn: str) -> Optional[Dict[str, Any]]:"""Get a specific book by ISBN.diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.py b/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.pyindex 2be86fa9fb..a2159a4c08 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.py@@ -278,9 +278,8 @@ class StackExchangeSearchEngine(BaseSearchEngine):# Get body (snippet)body = question.get("body", "")# Strip HTML for snippet- body_text = html.unescape(re.sub(r"<[^>]+>", " ", body))[- :500- ]+ body_text = html.unescape(re.sub(r"<[^>]+>", " ", body))+ body_text = " ".join(body_text.split())[:1000]snippet = f"{prefix} | {body_text}" if prefix else body_text# Get dates@@ -336,6 +335,8 @@ class StackExchangeSearchEngine(BaseSearchEngine):"""Get full content for the relevant Stack Exchange questions.+ Fetches the question body and top answers from the API.+Args:relevant_items: List of relevant preview dictionaries@@ -354,29 +355,45 @@ class StackExchangeSearchEngine(BaseSearchEngine):if raw:# Get full bodybody = raw.get("body", "")- # Clean HTML for contentclean_body = html.unescape(re.sub(r"<[^>]+>", " ", body))- clean_body = " ".join(- clean_body.split()- ) # Normalize whitespace+ clean_body = " ".join(clean_body.split())- # Build content summary+ # Build content with question + answerscontent_parts = []content_parts.append(f"Question: {result.get('title', 'Untitled')}")- content_parts.append(- f"Author: {result.get('author', 'Unknown')}"- )- content_parts.append(f"Score: {result.get('score', 0)}")- content_parts.append(- f"Answers: {result.get('answer_count', 0)}"- )- if result.get("has_accepted_answer"):- content_parts.append("Has accepted answer: Yes")if result.get("tags"):content_parts.append(f"Tags: {', '.join(result['tags'])}")- content_parts.append(f"\nContent:\n{clean_body[:2000]}")+ content_parts.append(f"\n{clean_body}")++ # Fetch top answers+ question_id = raw.get("question_id")+ if question_id:+ try:+ question_id = int(question_id)+ except (TypeError, ValueError):+ question_id = None+ if question_id:+ answers = self._fetch_top_answers(+ question_id, max_answers=3+ )+ if answers:+ content_parts.append(+ f"\n--- Top Answers ({len(answers)}) ---"+ )+ for ans in answers:+ ans_body = html.unescape(+ re.sub(r"<[^>]+>", " ", ans.get("body", ""))+ )+ ans_body = " ".join(ans_body.split())[:3000]+ score = ans.get("score", 0)+ accepted = ans.get("is_accepted", False)+ label = f"[Score: {score}"+ if accepted:+ label += ", Accepted"+ label += "]"+ content_parts.append(f"\n{label}\n{ans_body}")result["content"] = "\n".join(content_parts)@@ -388,6 +405,48 @@ class StackExchangeSearchEngine(BaseSearchEngine):return results+ def _fetch_top_answers(+ self, question_id: int, max_answers: int = 3+ ) -> List[Dict[str, Any]]:+ """Fetch top answers for a question, sorted by votes."""+ try:+ self._apply_backoff()+ url = f"{self.base_url}/questions/{question_id}/answers"+ params = {+ "site": self.site,+ "order": "desc",+ "sort": "votes",+ "pagesize": max_answers,+ "filter": "withbody",+ }+ response = safe_get(+ url, params=params, headers=self.headers, timeout=30+ )+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ data = response.json()+ self._handle_backoff(data)++ if "error_id" in data:+ logger.warning(+ f"Stack Exchange API error fetching answers for "+ f"{question_id}: {data.get('error_message', 'Unknown')}"+ )+ return []++ quota_remaining = data.get("quota_remaining")+ if quota_remaining is not None and quota_remaining < 10:+ logger.warning(f"Stack Exchange quota low: {quota_remaining}")++ return data.get("items", []) # type: ignore[no-any-return]+ except (RateLimitError, ValueError):+ raise+ except Exception:+ logger.warning(+ f"Failed to fetch answers for question {question_id}"+ )+ return []+def get_question(self, question_id: int) -> Optional[Dict[str, Any]]:"""Get a specific question by ID.diff --git a/tests/search_engines/test_search_engine_gutenberg_deep_coverage.py b/tests/search_engines/test_search_engine_gutenberg_deep_coverage.pyindex 797b59b839..3118059d80 100644--- a/tests/search_engines/test_search_engine_gutenberg_deep_coverage.py+++ b/tests/search_engines/test_search_engine_gutenberg_deep_coverage.py@@ -2,7 +2,8 @@Tests for uncovered code paths in GutenbergSearchEngine.Targets:-- _get_full_content: subjects, bookshelves, translators, content building, download_count+- _get_full_content: subjects, bookshelves, translators, content building, book text+- _fetch_book_text: success, boilerplate stripping, truncation, error handling- get_book: success, rate limit, exception- search_by_topic: topic switching, cleanup on exception"""@@ -29,10 +30,11 @@ def engine():return eng-def _mock_response(status_code=200, json_data=None):+def _mock_response(status_code=200, json_data=None, text=None):resp = Mock()resp.status_code = status_coderesp.json.return_value = json_data or {}+ resp.text = text or ""resp.raise_for_status = Mock()if status_code >= 400:resp.raise_for_status.side_effect = Exception(f"HTTP {status_code}")@@ -45,8 +47,8 @@ def _mock_response(status_code=200, json_data=None):class TestGetFullContent:- def test_builds_content_with_all_fields(self, engine):- """Content string includes authors, subjects, bookshelves, downloads."""+ def test_builds_content_with_book_text(self, engine):+ """Content includes metadata header + actual book text when available."""items = [{"title": "Alice in Wonderland",@@ -57,21 +59,74 @@ class TestGetFullContent:"subjects": ["Fantasy", "Children's literature"],"bookshelves": ["Children's Fiction"],"translators": [{"name": "Someone", "birth_year": 1900}],+ "formats": {+ "text/plain; charset=utf-8": "https://www.gutenberg.org/files/11/11-0.txt"+ },},}]- results = engine._get_full_content(items)+ with patch.object(+ engine, "_fetch_book_text", return_value="Alice was beginning..."+ ) as mock_fetch:+ results = engine._get_full_content(items)+ mock_fetch.assert_called_once_with(+ "https://www.gutenberg.org/files/11/11-0.txt"+ )assert len(results) == 1content = results[0]["content"]assert "Authors: Lewis Carroll" in contentassert "Subjects: Fantasy, Children's literature" in content+ assert "Alice was beginning..." in content+ # Metadata-only fields should NOT appear when text is available+ assert "Bookshelves:" not in content+ assert "Downloads:" not in content+ assert "_raw" not in results[0]++ def test_metadata_fallback_when_no_text(self, engine):+ """Falls back to metadata when book text is unavailable."""+ items = [+ {+ "title": "Alice in Wonderland",+ "authors": ["Lewis Carroll"],+ "download_count": 50000,+ "read_url": "https://gutenberg.org/ebooks/11",+ "_raw": {+ "subjects": ["Fantasy"],+ "bookshelves": ["Children's Fiction"],+ "translators": [],+ },+ }+ ]++ results = engine._get_full_content(items)++ content = results[0]["content"]assert "Bookshelves: Children's Fiction" in contentassert "Downloads: 50000" in contentassert "Read online:" in content- assert results[0]["translators"] is not None- assert "_raw" not in results[0]++ def test_rejects_non_gutenberg_url(self, engine):+ """Skips text URLs not from gutenberg.org."""+ items = [+ {+ "title": "Test",+ "authors": [],+ "_raw": {+ "subjects": [],+ "bookshelves": [],+ "translators": [],+ "formats": {+ "text/plain; charset=utf-8": "https://evil.com/malicious.txt"+ },+ },+ }+ ]++ with patch.object(engine, "_fetch_book_text") as mock_fetch:+ engine._get_full_content(items)+ mock_fetch.assert_not_called()def test_without_raw(self, engine):"""Items without _raw pass through."""@@ -100,6 +155,93 @@ class TestGetFullContent:assert "Bookshelves:" not in content+# ---------------------------------------------------------------------------+# _fetch_book_text+# ---------------------------------------------------------------------------+++class TestFetchBookText:+ @patch(f"{MODULE}.safe_get")+ def test_strips_start_and_end_markers(self, mock_get, engine):+ """Strips Project Gutenberg header and footer boilerplate."""+ raw_text = (+ "The Project Gutenberg EBook of Test\n"+ "*** START OF THE PROJECT GUTENBERG EBOOK TEST ***\n"+ "Actual book content here.\n"+ "*** END OF THE PROJECT GUTENBERG EBOOK TEST ***\n"+ "End of Project Gutenberg..."+ )+ mock_get.return_value = _mock_response(200, text=raw_text)++ result = engine._fetch_book_text(+ "https://www.gutenberg.org/files/1/1-0.txt"+ )++ assert result == "Actual book content here."++ @patch(f"{MODULE}.safe_get")+ def test_handles_variant_markers(self, mock_get, engine):+ """Handles 'THIS' variant of the start/end markers."""+ raw_text = (+ "Header\n"+ "*** START OF THIS PROJECT GUTENBERG EBOOK X ***\n"+ "The real content.\n"+ "*** END OF THIS PROJECT GUTENBERG EBOOK X ***\n"+ )+ mock_get.return_value = _mock_response(200, text=raw_text)++ result = engine._fetch_book_text(+ "https://www.gutenberg.org/files/1/1-0.txt"+ )++ assert result == "The real content."++ @patch(f"{MODULE}.safe_get")+ def test_truncates_to_max_content_chars(self, mock_get, engine):+ """Truncates text to max_content_chars."""+ engine.max_content_chars = 100+ body = "A" * 200+ raw_text = f"*** START OF THE PROJECT GUTENBERG EBOOK T ***\n{body}\n*** END OF THE PROJECT GUTENBERG EBOOK T ***"+ mock_get.return_value = _mock_response(200, text=raw_text)++ result = engine._fetch_book_text(+ "https://www.gutenberg.org/files/1/1-0.txt"+ )++ assert result.startswith("A" * 100)+ assert "[... truncated ...]" in result++ @patch(f"{MODULE}.safe_get")+ def test_empty_response_returns_none(self, mock_get, engine):+ """Returns None for empty response text."""+ mock_get.return_value = _mock_response(200, text="")++ result = engine._fetch_book_text(+ "https://www.gutenberg.org/files/1/1-0.txt"+ )+ assert result is None++ @patch(f"{MODULE}.safe_get")+ def test_http_error_returns_none(self, mock_get, engine):+ """Returns None on HTTP errors."""+ mock_get.return_value = _mock_response(404)++ result = engine._fetch_book_text(+ "https://www.gutenberg.org/files/1/1-0.txt"+ )+ assert result is None++ @patch(f"{MODULE}.safe_get")+ def test_network_error_returns_none(self, mock_get, engine):+ """Returns None on network errors."""+ mock_get.side_effect = ConnectionError("fail")++ result = engine._fetch_book_text(+ "https://www.gutenberg.org/files/1/1-0.txt"+ )+ assert result is None++# ---------------------------------------------------------------------------# get_book# ---------------------------------------------------------------------------diff --git a/tests/search_engines/test_search_engine_openlibrary.py b/tests/search_engines/test_search_engine_openlibrary.pyindex 25ba31865f..49a3e6e62e 100644--- a/tests/search_engines/test_search_engine_openlibrary.py+++ b/tests/search_engines/test_search_engine_openlibrary.py@@ -310,12 +310,15 @@ class TestOpenLibraryFullContent:}]- results = engine._get_full_content(items)+ from unittest.mock import patch++ with patch.object(engine, "_fetch_work_details", return_value=None):+ results = engine._get_full_content(items)assert len(results) == 1assert "Authors: Author One, Author Two" in results[0]["content"]assert "First published: 2020" in results[0]["content"]- assert "Editions: 5" in results[0]["content"]+ assert "Subjects: Fiction, Adventure, Fantasy" in results[0]["content"]assert "Full text available" in results[0]["content"]assert "_raw" not in results[0]diff --git a/tests/search_engines/test_search_engine_openlibrary_deep_coverage.py b/tests/search_engines/test_search_engine_openlibrary_deep_coverage.pyindex 6271941d84..c971f5c1c6 100644--- a/tests/search_engines/test_search_engine_openlibrary_deep_coverage.py+++ b/tests/search_engines/test_search_engine_openlibrary_deep_coverage.py@@ -3,6 +3,7 @@ Tests for uncovered code paths in OpenLibrarySearchEngine.Targets:- _get_full_content: language/subject/publisher normalization, content building, has_fulltext+- _fetch_work_details: success, validation, error handling- get_author: success, rate limit, exception"""@@ -45,9 +46,10 @@ def _mock_response(status_code=200, json_data=None):class TestGetFullContent:def test_builds_content_with_all_fields(self, engine):- """Content string includes authors, year, editions, subjects."""+ """Content string includes authors, year, subjects, description."""items = [{+ "id": "/works/OL27448W","title": "The Lord of the Rings","authors": ["J.R.R. Tolkien"],"first_publish_year": 1954,@@ -61,14 +63,23 @@ class TestGetFullContent:}]- results = engine._get_full_content(items)+ with patch.object(+ engine,+ "_fetch_work_details",+ return_value={+ "description": "An epic fantasy novel.",+ "excerpts": [{"excerpt": "One ring to rule them all."}],+ },+ ):+ results = engine._get_full_content(items)assert len(results) == 1content = results[0]["content"]assert "Authors: J.R.R. Tolkien" in contentassert "First published: 1954" in content- assert "Editions: 200" in contentassert "Fantasy" in content+ assert "An epic fantasy novel." in content+ assert "One ring to rule them all." in contentassert "Full text available" in contentassert results[0]["languages"] == ["eng", "fre"]assert results[0]["publishers"] == ["HarperCollins", "Houghton Mifflin"]@@ -83,7 +94,8 @@ class TestGetFullContent:}]- results = engine._get_full_content(items)+ with patch.object(engine, "_fetch_work_details", return_value=None):+ results = engine._get_full_content(items)assert results[0]["languages"] == ["eng"]def test_subject_string_normalized_to_list(self, engine):@@ -95,7 +107,8 @@ class TestGetFullContent:}]- results = engine._get_full_content(items)+ with patch.object(engine, "_fetch_work_details", return_value=None):+ results = engine._get_full_content(items)assert results[0]["subjects"] == ["Science"]def test_publisher_string_normalized_to_list(self, engine):@@ -107,7 +120,8 @@ class TestGetFullContent:}]- results = engine._get_full_content(items)+ with patch.object(engine, "_fetch_work_details", return_value=None):+ results = engine._get_full_content(items)assert results[0]["publishers"] == ["Penguin"]def test_without_raw(self, engine):@@ -128,9 +142,91 @@ class TestGetFullContent:}]- results = engine._get_full_content(items)+ with patch.object(engine, "_fetch_work_details", return_value=None):+ results = engine._get_full_content(items)assert "Full text" not in results[0].get("content", "")+ def test_description_dict_format(self, engine):+ """Handles description in {value: ...} dict format from Works API."""+ items = [+ {+ "id": "/works/OL1W",+ "title": "Test",+ "_raw": {"language": [], "subject": [], "publisher": []},+ }+ ]++ with patch.object(+ engine,+ "_fetch_work_details",+ return_value={"description": {"value": "A dict description."}},+ ):+ results = engine._get_full_content(items)++ assert "A dict description." in results[0]["content"]++ def test_fallback_to_raw_description(self, engine):+ """Falls back to _raw description when Works API has none."""+ items = [+ {+ "id": "/works/OL1W",+ "title": "Test",+ "_raw": {+ "language": [],+ "subject": [],+ "publisher": [],+ "description": "Raw description.",+ },+ }+ ]++ with patch.object(engine, "_fetch_work_details", return_value={}):+ results = engine._get_full_content(items)++ assert "Raw description." in results[0]["content"]+++# ---------------------------------------------------------------------------+# _fetch_work_details+# ---------------------------------------------------------------------------+++class TestFetchWorkDetails:+ @patch(f"{MODULE}.safe_get")+ def test_success(self, mock_get, engine):+ """Returns work data on success."""+ work_data = {"description": "A great book.", "excerpts": []}+ mock_get.return_value = _mock_response(200, work_data)++ result = engine._fetch_work_details("/works/OL1234W")++ assert result["description"] == "A great book."++ def test_rejects_empty_key(self, engine):+ """Returns None for empty work_key."""+ assert engine._fetch_work_details("") is None++ def test_rejects_invalid_prefix(self, engine):+ """Returns None for work_key not starting with /works/."""+ assert engine._fetch_work_details("/authors/OL123A") is None+ assert engine._fetch_work_details("//evil.com/x") is None++ @patch(f"{MODULE}.safe_get")+ def test_http_error_returns_none(self, mock_get, engine):+ """Returns None on HTTP errors."""+ mock_get.return_value = _mock_response(404)++ result = engine._fetch_work_details("/works/OL999W")+ assert result is None++ @patch(f"{MODULE}.safe_get")+ def test_network_error_returns_none(self, mock_get, engine):+ """Returns None on network errors."""+ mock_get.side_effect = ConnectionError("fail")++ result = engine._fetch_work_details("/works/OL999W")+ assert result is None+# ---------------------------------------------------------------------------# get_authordiff --git a/tests/search_engines/test_search_engine_stackexchange.py b/tests/search_engines/test_search_engine_stackexchange.pyindex d446a73d8c..332c58b48c 100644--- a/tests/search_engines/test_search_engine_stackexchange.py+++ b/tests/search_engines/test_search_engine_stackexchange.py@@ -461,9 +461,8 @@ class TestStackExchangeFullContent:assert ("Question: How to use Python generators?" in results[0]["content"])- assert "Author: Author One" in results[0]["content"]- assert "Score: 50" in results[0]["content"]- assert "Has accepted answer: Yes" in results[0]["content"]+ assert "Tags: python, generators" in results[0]["content"]+ assert "question body with code" in results[0]["content"]assert "_raw" not in results[0]diff --git a/tests/search_engines/test_search_engine_stackexchange_deep_coverage.py b/tests/search_engines/test_search_engine_stackexchange_deep_coverage.pyindex 2de9f303b2..d4d7089f38 100644--- a/tests/search_engines/test_search_engine_stackexchange_deep_coverage.py+++ b/tests/search_engines/test_search_engine_stackexchange_deep_coverage.py@@ -2,7 +2,8 @@Tests for uncovered code paths in StackExchangeSearchEngine.Targets:-- _get_full_content: content building, HTML cleaning, accepted answer, tags+- _get_full_content: content building, HTML cleaning, tags, answer fetching+- _fetch_top_answers: success, error_id, rate limit, exception- get_question: success, rate limit, exception, empty items- get_answers: success, rate limit, exception- search_by_tag: tag switching, cleanup on exception@@ -47,50 +48,56 @@ def _mock_response(status_code=200, json_data=None):class TestGetFullContent:def test_builds_content_from_raw(self, engine):- """Builds content string from raw question data."""+ """Builds content string with question body, tags, and answers."""items = [{"title": "How to sort a list",- "author": "alice",- "score": 42,- "answer_count": 3,- "has_accepted_answer": True,"tags": ["python", "sorting"],"_raw": {- "body": "<p>I want to sort a <b>list</b> in Python.</p>"+ "body": "<p>I want to sort a <b>list</b> in Python.</p>",+ "question_id": 123,},}]- results = engine._get_full_content(items)+ with patch.object(+ engine,+ "_fetch_top_answers",+ return_value=[+ {+ "body": "<p>Use sorted()</p>",+ "score": 10,+ "is_accepted": True,+ }+ ],+ ):+ results = engine._get_full_content(items)assert len(results) == 1content = results[0]["content"]assert "Question: How to sort a list" in content- assert "Author: alice" in content- assert "Score: 42" in content- assert "Answers: 3" in content- assert "Has accepted answer: Yes" in contentassert "Tags: python, sorting" in contentassert "sort a list in Python" in contentassert "<p>" not in content # HTML stripped+ assert "--- Top Answers (1) ---" in content+ assert "[Score: 10, Accepted]" in content+ assert "Use sorted()" in contentassert "_raw" not in results[0]- def test_no_accepted_answer(self, engine):- """Content omits accepted answer line when False."""+ def test_no_question_id_skips_answers(self, engine):+ """Content omits answers when question_id is absent."""items = [{"title": "Q",- "has_accepted_answer": False,"tags": [],"_raw": {- "body": "<p>Body text that is long enough to test.</p>"+ "body": "<p>Body text.</p>",},}]results = engine._get_full_content(items)- assert "accepted answer" not in results[0].get("content", "")+ assert "Top Answers" not in results[0].get("content", "")def test_without_raw(self, engine):"""Items without _raw get no content added."""@@ -101,6 +108,75 @@ class TestGetFullContent:assert "content" not in results[0]+# ---------------------------------------------------------------------------+# _fetch_top_answers+# ---------------------------------------------------------------------------+++class TestFetchTopAnswers:+ @patch(f"{MODULE}.safe_get")+ def test_success(self, mock_get, engine):+ """Returns answer items on success."""+ answers = [+ {"body": "<p>Answer 1</p>", "score": 5, "is_accepted": True},+ {"body": "<p>Answer 2</p>", "score": 3, "is_accepted": False},+ ]+ mock_get.return_value = _mock_response(+ 200, {"items": answers, "quota_remaining": 100}+ )++ result = engine._fetch_top_answers(123, max_answers=2)++ assert len(result) == 2+ assert result[0]["score"] == 5++ @patch(f"{MODULE}.safe_get")+ def test_error_id_returns_empty(self, mock_get, engine):+ """Returns empty list when API returns error_id (e.g. quota exhausted)."""+ mock_get.return_value = _mock_response(+ 200,+ {"items": [], "error_id": 502, "error_message": "Quota Exhausted"},+ )++ result = engine._fetch_top_answers(123)+ assert result == []++ @patch(f"{MODULE}.safe_get")+ def test_rate_limit_propagates(self, mock_get, engine):+ """RateLimitError is re-raised, not swallowed."""+ mock_get.return_value = _mock_response(429)+ engine._raise_if_rate_limit = Mock(side_effect=RateLimitError("429"))++ with pytest.raises(RateLimitError):+ engine._fetch_top_answers(123)++ @patch(f"{MODULE}.safe_get")+ def test_value_error_propagates(self, mock_get, engine):+ """ValueError from safe_get (SSRF, oversize) is re-raised."""+ mock_get.side_effect = ValueError("SSRF blocked")++ with pytest.raises(ValueError):+ engine._fetch_top_answers(123)++ @patch(f"{MODULE}.safe_get")+ def test_network_error_returns_empty(self, mock_get, engine):+ """Network errors return empty list gracefully."""+ mock_get.side_effect = ConnectionError("fail")++ result = engine._fetch_top_answers(123)+ assert result == []++ @patch(f"{MODULE}.safe_get")+ def test_low_quota_warning(self, mock_get, engine):+ """Logs warning when quota is low."""+ mock_get.return_value = _mock_response(+ 200, {"items": [], "quota_remaining": 5}+ )++ result = engine._fetch_top_answers(123)+ assert result == []++# ---------------------------------------------------------------------------# get_question# ---------------------------------------------------------------------------