~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: add 292 tests to improve coverage for 6 low-coverage modules (#2730)
LearningCircuit202c1576b860
diff --git a/tests/content_fetcher/test_fetcher_coverage.py b/tests/content_fetcher/test_fetcher_coverage.pynew file mode 100644index 0000000000..eaad501045--- /dev/null+++ b/tests/content_fetcher/test_fetcher_coverage.py@@ -0,0 +1,760 @@+"""+Comprehensive tests for ContentFetcher to improve coverage of fetcher.py.++Covers: get_url_info, _get_downloader (caching + all branches + ImportError),+fetch (invalid, SSRF, success, PDF, unicode errors, truncation, metadata,+failed download, exceptions, no downloader fallback), fetch_text, and+DEFAULT_MAX_CONTENT_LENGTH usage.+"""++import pytest+from unittest.mock import patch, MagicMock++from local_deep_research.content_fetcher.fetcher import (+ ContentFetcher,+ DEFAULT_MAX_CONTENT_LENGTH,+)+from local_deep_research.content_fetcher.url_classifier import URLType+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_download_result(+ content: bytes, is_success: bool = True, skip_reason=None+):+ """Build a mock DownloadResult."""+ result = MagicMock()+ result.is_success = is_success+ result.content = content+ result.skip_reason = skip_reason+ return result+++# ---------------------------------------------------------------------------+# get_url_info+# ---------------------------------------------------------------------------+++class TestGetUrlInfo:+ def test_arxiv_url(self):+ fetcher = ContentFetcher()+ info = fetcher.get_url_info("https://arxiv.org/abs/2301.12345")+ assert info["url_type"] == "arxiv"+ assert info["source_name"] == "arXiv"+ assert info["extracted_id"] == "2301.12345"++ def test_pubmed_url(self):+ fetcher = ContentFetcher()+ info = fetcher.get_url_info("https://pubmed.ncbi.nlm.nih.gov/12345678/")+ assert info["url_type"] == "pubmed"+ assert info["source_name"] == "PubMed"+ assert info["extracted_id"] == "12345678"++ def test_html_url(self):+ fetcher = ContentFetcher()+ info = fetcher.get_url_info("https://example.com/article")+ assert info["url_type"] == "html"+ assert info["source_name"] == "Web Page"+ assert info["extracted_id"] is None++ def test_invalid_url(self):+ fetcher = ContentFetcher()+ info = fetcher.get_url_info("javascript:alert(1)")+ assert info["url_type"] == "invalid"+ assert info["source_name"] == "Invalid URL"++ def test_doi_url(self):+ fetcher = ContentFetcher()+ info = fetcher.get_url_info("https://doi.org/10.1234/test")+ assert info["url_type"] == "doi"+ assert info["extracted_id"] == "10.1234/test"++ def test_pmc_url(self):+ fetcher = ContentFetcher()+ info = fetcher.get_url_info(+ "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1234567/"+ )+ assert info["url_type"] == "pmc"+ assert info["extracted_id"] == "PMC1234567"++ def test_semantic_scholar_url(self):+ fetcher = ContentFetcher()+ hex40 = "a" * 40+ info = fetcher.get_url_info(+ f"https://www.semanticscholar.org/paper/Title/{hex40}"+ )+ assert info["url_type"] == "semantic_scholar"+ assert info["extracted_id"] == hex40++ def test_biorxiv_url(self):+ fetcher = ContentFetcher()+ info = fetcher.get_url_info(+ "https://www.biorxiv.org/content/10.1101/2023"+ )+ assert info["url_type"] == "biorxiv"++ def test_medrxiv_url(self):+ fetcher = ContentFetcher()+ info = fetcher.get_url_info(+ "https://www.medrxiv.org/content/10.1101/2023"+ )+ assert info["url_type"] == "medrxiv"++ def test_pdf_url(self):+ fetcher = ContentFetcher()+ info = fetcher.get_url_info("https://example.com/paper.pdf")+ assert info["url_type"] == "pdf"+++# ---------------------------------------------------------------------------+# _get_downloader+# ---------------------------------------------------------------------------+++class TestGetDownloader:+ """Test _get_downloader caching and all URLType branches."""++ def test_caching(self):+ """Second call for same type returns cached downloader."""+ fetcher = ContentFetcher()+ mock_dl = MagicMock()+ fetcher._downloaders[URLType.HTML] = mock_dl+ assert fetcher._get_downloader(URLType.HTML) is mock_dl++ def test_downloader_caching_per_type(self):+ """Pre-cached downloader for a specific type is returned directly."""+ fetcher = ContentFetcher()+ mock_dl = MagicMock()+ fetcher._downloaders[URLType.ARXIV] = mock_dl+ assert fetcher._get_downloader(URLType.ARXIV) is mock_dl+ # A different type should NOT return the cached one+ assert fetcher._get_downloader(URLType.INVALID) is None++ @pytest.mark.parametrize(+ "url_type,module_path,class_name",+ [+ (+ URLType.ARXIV,+ "local_deep_research.research_library.downloaders.arxiv",+ "ArxivDownloader",+ ),+ (+ URLType.PUBMED,+ "local_deep_research.research_library.downloaders.pubmed",+ "PubMedDownloader",+ ),+ (+ URLType.PMC,+ "local_deep_research.research_library.downloaders.pubmed",+ "PubMedDownloader",+ ),+ (+ URLType.SEMANTIC_SCHOLAR,+ "local_deep_research.research_library.downloaders.semantic_scholar",+ "SemanticScholarDownloader",+ ),+ (+ URLType.BIORXIV,+ "local_deep_research.research_library.downloaders.biorxiv",+ "BioRxivDownloader",+ ),+ (+ URLType.MEDRXIV,+ "local_deep_research.research_library.downloaders.biorxiv",+ "BioRxivDownloader",+ ),+ (+ URLType.PDF,+ "local_deep_research.research_library.downloaders.direct_pdf",+ "DirectPDFDownloader",+ ),+ (+ URLType.HTML,+ "local_deep_research.research_library.downloaders.html",+ "HTMLDownloader",+ ),+ (+ URLType.DOI,+ "local_deep_research.research_library.downloaders.html",+ "HTMLDownloader",+ ),+ ],+ )+ def test_import_error_returns_none(+ self, url_type, module_path, class_name, monkeypatch+ ):+ """When the downloader module cannot be imported, returns None."""+ import sys++ fetcher = ContentFetcher()+ # Use monkeypatch for safe sys.modules manipulation (auto-restored after test)+ monkeypatch.setitem(sys.modules, module_path, None)+ result = fetcher._get_downloader(url_type)+ assert result is None++ def test_returns_none_for_invalid(self):+ """INVALID type has no branch, returns None."""+ fetcher = ContentFetcher()+ assert fetcher._get_downloader(URLType.INVALID) is None+++# ---------------------------------------------------------------------------+# fetch+# ---------------------------------------------------------------------------+++class TestFetch:+ """Tests for ContentFetcher.fetch()."""++ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def _fetch_with_mocks(+ self,+ url,+ url_type,+ downloader,+ classifier_mock,+ validate_mock,+ **kwargs,+ ):+ """Helper: run fetch() with classifier and validate_url mocked."""+ classifier_mock.classify.return_value = url_type+ classifier_mock.get_source_name.return_value = "Test Source"+ fetcher = ContentFetcher()+ if downloader is not None:+ fetcher._downloaders[url_type] = downloader+ # Also patch _get_downloader to return what's cached or None+ if downloader is None:+ with patch.object(fetcher, "_get_downloader", return_value=None):+ # Also block the HTML fallback import+ with patch(+ "local_deep_research.research_library.downloaders.html.HTMLDownloader",+ create=True,+ side_effect=ImportError("no html"),+ ):+ return fetcher.fetch(url, **kwargs)+ return fetcher.fetch(url, **kwargs)++ # --- Invalid URL ---+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_invalid_url_returns_error(self, classifier_mock):+ classifier_mock.classify.return_value = URLType.INVALID+ classifier_mock.get_source_name.return_value = "Invalid URL"+ fetcher = ContentFetcher()+ result = fetcher.fetch("javascript:alert(1)")+ assert result["status"] == "error"+ assert "Invalid" in result["error"]++ # --- SSRF blocked ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=False,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_ssrf_blocked(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"+ fetcher = ContentFetcher()+ result = fetcher.fetch("http://169.254.169.254/metadata")+ assert result["status"] == "error"+ assert "SSRF" in result["error"]++ # --- Successful UTF-8 fetch ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_success_utf8(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ b"Hello, world!"+ )+ # Remove get_metadata so the hasattr check is False+ del mock_dl.get_metadata++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ result = fetcher.fetch("https://example.com")+ assert result["status"] == "success"+ assert result["content"] == "Hello, world!"++ # --- PDF magic bytes -> text extraction success ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_pdf_content(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.PDF+ classifier_mock.get_source_name.return_value = "PDF"++ pdf_bytes = b"%PDF-1.4 fake pdf content"+ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ pdf_bytes+ )+ del mock_dl.get_metadata++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.PDF] = mock_dl++ with patch(+ "local_deep_research.content_fetcher.fetcher.BaseDownloader",+ create=True,+ ) as base_mock:+ base_mock.extract_text_from_pdf.return_value = "Extracted PDF text"+ # Need to patch the actual import inside fetch+ with patch(+ "local_deep_research.research_library.downloaders.base.BaseDownloader"+ ) as real_base:+ real_base.extract_text_from_pdf.return_value = (+ "Extracted PDF text"+ )+ result = fetcher.fetch("https://example.com/paper.pdf")++ assert result["status"] == "success"+ assert result["content"] == "Extracted PDF text"++ # --- PDF text extraction failure ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_pdf_extraction_failure(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.PDF+ classifier_mock.get_source_name.return_value = "PDF"++ pdf_bytes = b"%PDF-1.4 corrupt"+ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ pdf_bytes+ )++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.PDF] = mock_dl++ with patch(+ "local_deep_research.research_library.downloaders.base.BaseDownloader"+ ) as real_base:+ real_base.extract_text_from_pdf.return_value = None+ result = fetcher.fetch("https://example.com/paper.pdf")++ assert result["status"] == "error"+ assert "Could not extract text from PDF" in result["error"]++ # --- UnicodeDecodeError ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_unicode_decode_error(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ # Content that is NOT pdf and NOT valid UTF-8+ bad_bytes = b"\x80\x81\x82\x83"+ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ bad_bytes+ )++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ result = fetcher.fetch("https://example.com")+ assert result["status"] == "error"+ assert "not valid UTF-8" in result["error"]++ # --- Content truncation ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_content_truncation(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ long_content = b"A" * 200+ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ long_content+ )+ del mock_dl.get_metadata++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ result = fetcher.fetch("https://example.com", max_length=50)+ assert result["status"] == "success"+ assert len(result["content"]) < 200+ assert "[... content truncated ...]" in result["content"]+ # First 50 chars should be preserved+ assert result["content"].startswith("A" * 50)++ # --- Metadata extraction ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_with_metadata(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ b"Content"+ )+ mock_dl.get_metadata.return_value = {+ "title": "Test Title",+ "author": "Author Name",+ "published_date": "2025-01-01",+ }++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ result = fetcher.fetch("https://example.com")+ assert result["status"] == "success"+ assert result["title"] == "Test Title"+ assert result["author"] == "Author Name"+ assert result["published_date"] == "2025-01-01"++ # --- Metadata extraction raises exception (should be silenced) ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_metadata_exception_silenced(+ self, classifier_mock, validate_mock+ ):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ b"Content"+ )+ mock_dl.get_metadata.side_effect = RuntimeError("metadata boom")++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ result = fetcher.fetch("https://example.com")+ assert result["status"] == "success"+ # title should be None because metadata retrieval failed+ assert result["title"] is None++ # --- Download failed (is_success=False) ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_failed_download(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ b"", is_success=False, skip_reason="403 Forbidden"+ )++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ result = fetcher.fetch("https://example.com")+ assert result["status"] == "error"+ assert result["error"] == "403 Forbidden"++ # --- Download failed with no skip_reason ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_failed_download_no_reason(+ self, classifier_mock, validate_mock+ ):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ b"", is_success=False, skip_reason=None+ )++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ result = fetcher.fetch("https://example.com")+ assert result["status"] == "error"+ assert result["error"] == "Download failed"++ # --- Downloader throws exception ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_downloader_exception(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.side_effect = ConnectionError("timeout")++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ result = fetcher.fetch("https://example.com")+ assert result["status"] == "error"+ assert "timeout" in result["error"]++ # --- No downloader and HTML fallback also fails (ImportError) ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_no_downloader_no_html_fallback(+ self, classifier_mock, validate_mock, monkeypatch+ ):+ import sys++ classifier_mock.classify.return_value = URLType.SEMANTIC_SCHOLAR+ classifier_mock.get_source_name.return_value = "Semantic Scholar"++ fetcher = ContentFetcher()+ # _get_downloader returns None, AND the inline HTML fallback import fails+ # Block the HTML downloader module so the fallback import raises ImportError+ monkeypatch.setitem(+ sys.modules,+ "local_deep_research.research_library.downloaders.html",+ None,+ )+ with patch.object(fetcher, "_get_downloader", return_value=None):+ result = fetcher.fetch("https://www.semanticscholar.org/paper/xyz")++ assert result["status"] == "error"+ assert "No suitable downloader" in result["error"]++ # --- No downloader but HTML fallback works ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_html_fallback_success(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.SEMANTIC_SCHOLAR+ classifier_mock.get_source_name.return_value = "Semantic Scholar"++ mock_html_dl = MagicMock()+ mock_html_dl.download_with_result.return_value = _make_download_result(+ b"Fallback content"+ )+ del mock_html_dl.get_metadata++ fetcher = ContentFetcher()+ with patch.object(fetcher, "_get_downloader", return_value=None):+ with patch(+ "local_deep_research.research_library.downloaders.html.HTMLDownloader",+ return_value=mock_html_dl,+ ):+ result = fetcher.fetch(+ "https://www.semanticscholar.org/paper/xyz"+ )++ assert result["status"] == "success"+ assert result["content"] == "Fallback content"++ # --- Default max_length is applied ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_default_max_length_applied(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ # Content larger than DEFAULT_MAX_CONTENT_LENGTH+ huge_content = b"X" * (DEFAULT_MAX_CONTENT_LENGTH + 100)+ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ huge_content+ )+ del mock_dl.get_metadata++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ # Do NOT pass max_length -> should use DEFAULT_MAX_CONTENT_LENGTH+ result = fetcher.fetch("https://example.com")+ assert result["status"] == "success"+ assert "[... content truncated ...]" in result["content"]+ # The content before truncation suffix should be DEFAULT_MAX_CONTENT_LENGTH chars+ assert result["content"].startswith("X" * DEFAULT_MAX_CONTENT_LENGTH)++ # --- prefer_text=False sets PDF content type ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_prefer_text_false(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ b"data"+ )+ del mock_dl.get_metadata++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ fetcher.fetch("https://example.com", prefer_text=False)++ # Verify download_with_result was called with ContentType.PDF+ from local_deep_research.research_library.downloaders.base import (+ ContentType,+ )++ call_args = mock_dl.download_with_result.call_args+ assert call_args[0][1] == ContentType.PDF++ # --- is_success True but content is None/empty ---+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_success_but_empty_content(+ self, classifier_mock, validate_mock+ ):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ result_obj = MagicMock()+ result_obj.is_success = True+ result_obj.content = None+ result_obj.skip_reason = None+ mock_dl.download_with_result.return_value = result_obj++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ result = fetcher.fetch("https://example.com")+ # Falls into the else branch because content is falsy+ assert result["status"] == "error"+ assert result["error"] == "Download failed"+++# ---------------------------------------------------------------------------+# fetch_text+# ---------------------------------------------------------------------------+++class TestFetchText:+ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_text_success(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ b"Text content"+ )+ del mock_dl.get_metadata++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ text = fetcher.fetch_text("https://example.com")+ assert text == "Text content"++ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_text_failure_returns_none(+ self, classifier_mock, validate_mock+ ):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ b"", is_success=False, skip_reason="error"+ )++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ text = fetcher.fetch_text("https://example.com")+ assert text is None++ def test_fetch_text_invalid_url_returns_none(self):+ fetcher = ContentFetcher()+ text = fetcher.fetch_text("javascript:void(0)")+ assert text is None++ @patch(+ "local_deep_research.content_fetcher.fetcher.validate_url",+ return_value=True,+ )+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")+ def test_fetch_text_with_max_length(self, classifier_mock, validate_mock):+ classifier_mock.classify.return_value = URLType.HTML+ classifier_mock.get_source_name.return_value = "Web Page"++ mock_dl = MagicMock()+ mock_dl.download_with_result.return_value = _make_download_result(+ b"A" * 200+ )+ del mock_dl.get_metadata++ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = mock_dl+ text = fetcher.fetch_text("https://example.com", max_length=50)+ assert text is not None+ assert "[... content truncated ...]" in text+++# ---------------------------------------------------------------------------+# __init__+# ---------------------------------------------------------------------------+++class TestInit:+ def test_default_timeout(self):+ fetcher = ContentFetcher()+ assert fetcher.timeout == 30++ def test_custom_timeout(self):+ fetcher = ContentFetcher(timeout=60)+ assert fetcher.timeout == 60++ def test_downloaders_initially_empty(self):+ fetcher = ContentFetcher()+ assert fetcher._downloaders == {}+++# ---------------------------------------------------------------------------+# DEFAULT_MAX_CONTENT_LENGTH constant+# ---------------------------------------------------------------------------+++class TestConstants:+ def test_default_max_content_length_value(self):+ assert DEFAULT_MAX_CONTENT_LENGTH == 500_000diff --git a/tests/news/test_flask_api_deep_coverage.py b/tests/news/test_flask_api_deep_coverage.pynew file mode 100644index 0000000000..6091a84c78--- /dev/null+++ b/tests/news/test_flask_api_deep_coverage.py@@ -0,0 +1,1965 @@+"""+Comprehensive tests for local_deep_research.news.flask_api endpoints.++These tests properly mock auth decorators and the underlying api module+functions to exercise actual endpoint logic, not just status codes.+"""++from unittest.mock import MagicMock, patch++import pytest+from flask import Flask+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _auth_session(client, username="testuser"):+ """Set up a valid authenticated session."""+ with client.session_transaction() as sess:+ sess["username"] = username+++def _auth_patches():+ """Return a dict of common patches needed for auth + db plumbing."""+ return {+ "db_manager": patch(+ "local_deep_research.web.auth.decorators.db_manager"+ ),+ "get_user_id": patch(+ "local_deep_research.news.flask_api.get_user_id",+ return_value="testuser",+ ),+ "get_settings_manager": patch(+ "local_deep_research.news.flask_api.get_settings_manager",+ ),+ }+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def app():+ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret-key"+ app.config["WTF_CSRF_ENABLED"] = False+ app.config["TESTING"] = True++ from local_deep_research.news.flask_api import news_api_bp++ app.register_blueprint(news_api_bp, url_prefix="/news/api")+ return app+++def client(app):+ return app.test_client()+++def authed_client(client):+ """Return client with auth session pre-configured."""+ _auth_session(client)+ return client+++# ---------------------------------------------------------------------------+# 1. GET /feed (get_news_feed)+# ---------------------------------------------------------------------------+++class TestGetNewsFeed:+ """Tests for the /feed endpoint."""++ def test_returns_news_items(self, authed_client):+ patches = _auth_patches()+ mock_result = {+ "news_items": [{"id": "1", "title": "Test News"}],+ "total": 1,+ }+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patches["get_settings_manager"] as mock_sm,+ patch(+ "local_deep_research.news.flask_api.api.get_news_feed",+ return_value=mock_result,+ ) as mock_feed,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sm_instance = MagicMock()+ mock_sm_instance.get_setting.return_value = 20+ mock_sm.return_value = mock_sm_instance++ resp = authed_client.get("/news/api/feed")+ assert resp.status_code == 200+ data = resp.get_json()+ assert len(data["news_items"]) == 1+ assert data["news_items"][0]["title"] == "Test News"++ mock_feed.assert_called_once_with(+ user_id="testuser",+ limit=20,+ use_cache=True,+ focus=None,+ search_strategy=None,+ subscription_id=None,+ )++ def test_with_query_params(self, authed_client):+ patches = _auth_patches()+ mock_result = {"news_items": [], "total": 0}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patches["get_settings_manager"] as mock_sm,+ patch(+ "local_deep_research.news.flask_api.api.get_news_feed",+ return_value=mock_result,+ ) as mock_feed,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sm_instance = MagicMock()+ mock_sm_instance.get_setting.return_value = 20+ mock_sm.return_value = mock_sm_instance++ resp = authed_client.get(+ "/news/api/feed?limit=5&strategy=latest&subscription_id=sub1&focus=tech"+ )+ assert resp.status_code == 200++ mock_feed.assert_called_once_with(+ user_id="testuser",+ limit=5,+ use_cache=True,+ focus="tech",+ search_strategy="latest",+ subscription_id="sub1",+ )++ def test_use_cache_false(self, authed_client):+ patches = _auth_patches()+ mock_result = {"news_items": []}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patches["get_settings_manager"] as mock_sm,+ patch(+ "local_deep_research.news.flask_api.api.get_news_feed",+ return_value=mock_result,+ ) as mock_feed,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sm_instance = MagicMock()+ mock_sm_instance.get_setting.return_value = 20+ mock_sm.return_value = mock_sm_instance++ resp = authed_client.get("/news/api/feed?use_cache=false")+ assert resp.status_code == 200+ mock_feed.assert_called_once()+ assert mock_feed.call_args.kwargs["use_cache"] is False++ def test_api_error_in_result(self, authed_client):+ patches = _auth_patches()+ mock_result = {+ "error": "limit must be between 1 and 100",+ "news_items": [],+ }+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patches["get_settings_manager"] as mock_sm,+ patch(+ "local_deep_research.news.flask_api.api.get_news_feed",+ return_value=mock_result,+ ),+ ):+ mock_db.is_user_connected.return_value = True+ mock_sm_instance = MagicMock()+ mock_sm_instance.get_setting.return_value = 20+ mock_sm.return_value = mock_sm_instance++ resp = authed_client.get("/news/api/feed?limit=-1")+ assert resp.status_code == 400+ data = resp.get_json()+ assert "error" in data++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patches["get_settings_manager"] as mock_sm,+ patch(+ "local_deep_research.news.flask_api.api.get_news_feed",+ side_effect=RuntimeError("boom"),+ ),+ ):+ mock_db.is_user_connected.return_value = True+ mock_sm_instance = MagicMock()+ mock_sm_instance.get_setting.return_value = 20+ mock_sm.return_value = mock_sm_instance++ resp = authed_client.get("/news/api/feed")+ assert resp.status_code == 500+ data = resp.get_json()+ assert "error" in data+ assert data["news_items"] == []++ def test_unauthenticated_is_blocked(self, client):+ """Without session username, login_required prevents access."""+ # The decorator calls _safe_redirect_to_login which needs the auth+ # blueprint. We patch it to return a real Flask response.+ from flask import Response++ with patch(+ "local_deep_research.web.auth.decorators._safe_redirect_to_login",+ return_value=Response("login required", status=302),+ ):+ resp = client.get("/news/api/feed")+ assert resp.status_code == 302+++# ---------------------------------------------------------------------------+# 2. POST /subscribe (create_subscription)+# ---------------------------------------------------------------------------+++class TestCreateSubscription:+ """Tests for the /subscribe endpoint."""++ def test_successful_creation(self, authed_client):+ patches = _auth_patches()+ mock_result = {"id": "sub-123", "status": "active", "query": "AI news"}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.create_subscription",+ return_value=mock_result,+ ) as mock_create,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/subscribe",+ json={"query": "AI news", "subscription_type": "search"},+ )+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["id"] == "sub-123"++ mock_create.assert_called_once()+ call_kwargs = mock_create.call_args.kwargs+ assert call_kwargs["query"] == "AI news"+ assert call_kwargs["user_id"] == "testuser"+ assert call_kwargs["subscription_type"] == "search"++ def test_missing_query_returns_400(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/subscribe",+ json={"subscription_type": "search"},+ )+ assert resp.status_code == 400+ data = resp.get_json()+ assert "query" in data["error"].lower()++ def test_no_json_body_returns_400(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/subscribe",+ data="not json",+ content_type="text/plain",+ )+ assert resp.status_code == 400++ def test_with_all_optional_fields(self, authed_client):+ patches = _auth_patches()+ mock_result = {"id": "sub-456", "status": "active"}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.create_subscription",+ return_value=mock_result,+ ) as mock_create,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/subscribe",+ json={+ "query": "ML papers",+ "subscription_type": "topic",+ "refresh_minutes": 60,+ "model_provider": "OPENAI",+ "model": "gpt-4",+ "search_strategy": "deep",+ "custom_endpoint": "https://example.com",+ "name": "ML Feed",+ "folder_id": "fold-1",+ "is_active": True,+ "search_engine": "google",+ "search_iterations": 3,+ "questions_per_iteration": 5,+ },+ )+ assert resp.status_code == 200+ call_kwargs = mock_create.call_args.kwargs+ assert call_kwargs["model_provider"] == "OPENAI"+ assert call_kwargs["name"] == "ML Feed"+ assert call_kwargs["search_iterations"] == 3++ def test_value_error_returns_400(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.create_subscription",+ side_effect=ValueError("bad value"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/subscribe",+ json={"query": "test"},+ )+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# 3. POST /vote (vote_on_news)+# ---------------------------------------------------------------------------+++class TestVoteOnNews:+ """Tests for the /vote endpoint."""++ def test_upvote(self, authed_client):+ patches = _auth_patches()+ mock_result = {"status": "success", "vote": "up"}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.submit_feedback",+ return_value=mock_result,+ ) as mock_vote,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/vote",+ json={"card_id": "card-1", "vote": "up"},+ )+ assert resp.status_code == 200+ mock_vote.assert_called_once_with(+ card_id="card-1", user_id="testuser", vote="up"+ )++ def test_downvote(self, authed_client):+ patches = _auth_patches()+ mock_result = {"status": "success", "vote": "down"}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.submit_feedback",+ return_value=mock_result,+ ) as mock_vote,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/vote",+ json={"card_id": "card-2", "vote": "down"},+ )+ assert resp.status_code == 200+ mock_vote.assert_called_once_with(+ card_id="card-2", user_id="testuser", vote="down"+ )++ def test_missing_card_id(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/vote",+ json={"vote": "up"},+ )+ assert resp.status_code == 400+ assert "required" in resp.get_json()["error"].lower()++ def test_missing_vote(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/vote",+ json={"card_id": "card-1"},+ )+ assert resp.status_code == 400++ def test_not_found_error(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.submit_feedback",+ side_effect=ValueError("Card not found"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/vote",+ json={"card_id": "bad-id", "vote": "up"},+ )+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# 4. POST /feedback/batch (get_batch_feedback)+# ---------------------------------------------------------------------------+++class TestGetBatchFeedback:+ """Tests for the /feedback/batch endpoint."""++ def test_get_votes_for_cards(self, authed_client):+ patches = _auth_patches()+ mock_result = {"votes": {"c1": "up", "c2": "down"}}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.get_votes_for_cards",+ return_value=mock_result,+ ) as mock_batch,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/batch",+ json={"card_ids": ["c1", "c2"]},+ )+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["votes"]["c1"] == "up"++ mock_batch.assert_called_once_with(+ card_ids=["c1", "c2"], user_id="testuser"+ )++ def test_empty_card_ids_returns_empty(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/batch",+ json={"card_ids": []},+ )+ assert resp.status_code == 200+ assert resp.get_json()["votes"] == {}++ def test_missing_card_ids_returns_empty(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/batch",+ json={},+ )+ assert resp.status_code == 200+ assert resp.get_json()["votes"] == {}++ def test_value_error_not_found(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.get_votes_for_cards",+ side_effect=ValueError("User not found"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/batch",+ json={"card_ids": ["c1"]},+ )+ assert resp.status_code == 404++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.get_votes_for_cards",+ side_effect=RuntimeError("db error"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/batch",+ json={"card_ids": ["c1"]},+ )+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 5. POST /feedback/<card_id> (submit_feedback)+# ---------------------------------------------------------------------------+++class TestSubmitFeedback:+ """Tests for the /feedback/<card_id> endpoint."""++ def test_submit_vote(self, authed_client):+ patches = _auth_patches()+ mock_result = {"status": "recorded"}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.submit_feedback",+ return_value=mock_result,+ ) as mock_fb,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/card-99",+ json={"vote": "up"},+ )+ assert resp.status_code == 200+ mock_fb.assert_called_once_with(+ card_id="card-99", user_id="testuser", vote="up"+ )++ def test_missing_vote_returns_400(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/card-1",+ json={"something": "else"},+ )+ assert resp.status_code == 400+ assert "vote" in resp.get_json()["error"].lower()++ def test_not_found_error(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.submit_feedback",+ side_effect=ValueError("Card not found"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/card-bad",+ json={"vote": "up"},+ )+ assert resp.status_code == 404++ def test_invalid_value_error(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.submit_feedback",+ side_effect=ValueError("Vote must be up or down"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/card-1",+ json={"vote": "invalid"},+ )+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# 6. GET /subscriptions/current (get_current_user_subscriptions)+# ---------------------------------------------------------------------------+++class TestGetCurrentUserSubscriptions:+ """Tests for the /subscriptions/current endpoint."""++ def test_returns_subscriptions(self, authed_client):+ patches = _auth_patches()+ mock_result = {+ "subscriptions": [+ {"id": "s1", "query": "AI"},+ {"id": "s2", "query": "ML"},+ ]+ }+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.get_subscriptions",+ return_value=mock_result,+ ) as mock_subs,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscriptions/current")+ assert resp.status_code == 200+ data = resp.get_json()+ assert len(data["subscriptions"]) == 2+ mock_subs.assert_called_once_with("testuser")++ def test_api_error_returns_500(self, authed_client):+ patches = _auth_patches()+ mock_result = {"error": "Database unavailable"}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.get_subscriptions",+ return_value=mock_result,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscriptions/current")+ assert resp.status_code == 500++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.get_subscriptions",+ side_effect=RuntimeError("crash"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscriptions/current")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 7. GET /subscriptions/<id> (get_subscription)+# ---------------------------------------------------------------------------+++class TestGetSubscription:+ """Tests for the /subscriptions/<id> endpoint."""++ def test_returns_subscription(self, authed_client):+ patches = _auth_patches()+ mock_result = {"id": "s1", "query": "AI news", "status": "active"}+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.get_subscription",+ return_value=mock_result,+ ) as mock_get,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscriptions/s1")+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["id"] == "s1"+ mock_get.assert_called_once_with("s1")++ def test_not_found(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.get_subscription",+ return_value=None,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscriptions/nonexistent")+ assert resp.status_code == 404++ def test_null_id_returns_400(self, authed_client):+ patches = _auth_patches()+ with patches["db_manager"] as mock_db:+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscriptions/null")+ assert resp.status_code == 400++ def test_undefined_id_returns_400(self, authed_client):+ patches = _auth_patches()+ with patches["db_manager"] as mock_db:+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscriptions/undefined")+ assert resp.status_code == 400++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.get_subscription",+ side_effect=RuntimeError("db error"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscriptions/s1")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 8. PUT /subscriptions/<id> (update_subscription)+# ---------------------------------------------------------------------------+++class TestUpdateSubscription:+ """Tests for the PUT /subscriptions/<id> endpoint."""++ def test_successful_update(self, authed_client):+ patches = _auth_patches()+ mock_result = {"id": "s1", "status": "updated"}+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.update_subscription",+ return_value=mock_result,+ ) as mock_update,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.put(+ "/news/api/subscriptions/s1",+ json={"query": "Updated query", "name": "New Name"},+ )+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["status"] == "updated"++ # Verify field mapping: query -> query_or_topic+ call_args = mock_update.call_args+ assert call_args[0][0] == "s1"+ update_data = call_args[0][1]+ assert update_data["query_or_topic"] == "Updated query"+ assert update_data["name"] == "New Name"++ def test_field_mapping(self, authed_client):+ """Verify all field mappings work correctly."""+ patches = _auth_patches()+ mock_result = {"id": "s1", "status": "updated"}+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.update_subscription",+ return_value=mock_result,+ ) as mock_update,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.put(+ "/news/api/subscriptions/s1",+ json={+ "refresh_minutes": 30,+ "is_active": False,+ "search_engine": "bing",+ },+ )+ assert resp.status_code == 200+ update_data = mock_update.call_args[0][1]+ assert update_data["refresh_interval_minutes"] == 30+ assert update_data["is_active"] is False+ assert update_data["search_engine"] == "bing"++ def test_error_in_result_not_found(self, authed_client):+ patches = _auth_patches()+ mock_result = {"error": "Subscription not found"}+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.update_subscription",+ return_value=mock_result,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.put(+ "/news/api/subscriptions/bad-id",+ json={"name": "test"},+ )+ assert resp.status_code == 404++ def test_error_in_result_generic(self, authed_client):+ patches = _auth_patches()+ mock_result = {"error": "Invalid data provided"}+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.update_subscription",+ return_value=mock_result,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.put(+ "/news/api/subscriptions/s1",+ json={"name": "x"},+ )+ assert resp.status_code == 400++ def test_no_json_body_returns_400(self, authed_client):+ patches = _auth_patches()+ with patches["db_manager"] as mock_db:+ mock_db.is_user_connected.return_value = True++ resp = authed_client.put(+ "/news/api/subscriptions/s1",+ data="not json",+ content_type="text/plain",+ )+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# 9. DELETE /subscriptions/<id> (delete_subscription)+# ---------------------------------------------------------------------------+++class TestDeleteSubscription:+ """Tests for the DELETE /subscriptions/<id> endpoint."""++ def test_successful_delete(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.delete_subscription",+ return_value=True,+ ) as mock_del,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.delete("/news/api/subscriptions/s1")+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["status"] == "success"+ assert "s1" in data["message"]+ mock_del.assert_called_once_with("s1")++ def test_not_found(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.delete_subscription",+ return_value=False,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.delete("/news/api/subscriptions/bad-id")+ assert resp.status_code == 404++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.api.delete_subscription",+ side_effect=RuntimeError("db error"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.delete("/news/api/subscriptions/s1")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 10. GET /subscriptions/<id>/history (get_subscription_history)+# ---------------------------------------------------------------------------+++class TestGetSubscriptionHistory:+ """Tests for the /subscriptions/<id>/history endpoint."""++ def test_returns_history(self, authed_client):+ patches = _auth_patches()+ mock_result = {+ "history": [+ {"id": "h1", "date": "2026-01-01"},+ {"id": "h2", "date": "2026-01-02"},+ ]+ }+ with (+ patches["db_manager"] as mock_db,+ patches["get_settings_manager"] as mock_sm,+ patch(+ "local_deep_research.news.flask_api.api.get_subscription_history",+ return_value=mock_result,+ ) as mock_hist,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sm_instance = MagicMock()+ mock_sm_instance.get_setting.return_value = 20+ mock_sm.return_value = mock_sm_instance++ resp = authed_client.get("/news/api/subscriptions/s1/history")+ assert resp.status_code == 200+ data = resp.get_json()+ assert len(data["history"]) == 2+ mock_hist.assert_called_once_with("s1", 20)++ def test_custom_limit(self, authed_client):+ patches = _auth_patches()+ mock_result = {"history": []}+ with (+ patches["db_manager"] as mock_db,+ patches["get_settings_manager"] as mock_sm,+ patch(+ "local_deep_research.news.flask_api.api.get_subscription_history",+ return_value=mock_result,+ ) as mock_hist,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sm_instance = MagicMock()+ mock_sm_instance.get_setting.return_value = 20+ mock_sm.return_value = mock_sm_instance++ resp = authed_client.get(+ "/news/api/subscriptions/s1/history?limit=5"+ )+ assert resp.status_code == 200+ mock_hist.assert_called_once_with("s1", 5)++ def test_error_in_result(self, authed_client):+ patches = _auth_patches()+ mock_result = {"error": "Database error", "history": []}+ with (+ patches["db_manager"] as mock_db,+ patches["get_settings_manager"] as mock_sm,+ patch(+ "local_deep_research.news.flask_api.api.get_subscription_history",+ return_value=mock_result,+ ),+ ):+ mock_db.is_user_connected.return_value = True+ mock_sm_instance = MagicMock()+ mock_sm_instance.get_setting.return_value = 20+ mock_sm.return_value = mock_sm_instance++ resp = authed_client.get("/news/api/subscriptions/s1/history")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 11. POST /preferences (save_preferences)+# ---------------------------------------------------------------------------+++class TestSavePreferences:+ """Tests for the /preferences endpoint."""++ def test_save_preferences(self, authed_client):+ patches = _auth_patches()+ mock_result = {"status": "saved"}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.save_news_preferences",+ return_value=mock_result,+ ) as mock_save,+ ):+ mock_db.is_user_connected.return_value = True++ prefs = {"theme": "dark", "language": "en"}+ resp = authed_client.post(+ "/news/api/preferences",+ json={"preferences": prefs},+ )+ assert resp.status_code == 200+ mock_save.assert_called_once_with("testuser", prefs)++ def test_empty_preferences(self, authed_client):+ patches = _auth_patches()+ mock_result = {"status": "saved"}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.save_news_preferences",+ return_value=mock_result,+ ) as mock_save,+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/preferences",+ json={},+ )+ assert resp.status_code == 200+ mock_save.assert_called_once_with("testuser", {})++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.api.save_news_preferences",+ side_effect=RuntimeError("fail"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/preferences",+ json={"preferences": {"a": 1}},+ )+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 12. GET /categories (get_categories)+# ---------------------------------------------------------------------------+++class TestGetCategories:+ """Tests for the /categories endpoint (no login required)."""++ def test_returns_categories(self, client):+ mock_result = {+ "categories": [+ {"name": "tech", "count": 10},+ {"name": "science", "count": 5},+ ]+ }+ with patch(+ "local_deep_research.news.flask_api.api.get_news_categories",+ return_value=mock_result,+ ) as mock_cats:+ resp = client.get("/news/api/categories")+ assert resp.status_code == 200+ data = resp.get_json()+ assert len(data["categories"]) == 2+ mock_cats.assert_called_once()++ def test_exception_returns_500(self, client):+ with patch(+ "local_deep_research.news.flask_api.api.get_news_categories",+ side_effect=RuntimeError("fail"),+ ):+ resp = client.get("/news/api/categories")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 13. GET /subscription/folders (get_folders)+# ---------------------------------------------------------------------------+++class TestGetFolders:+ """Tests for the /subscription/folders GET endpoint."""++ def test_returns_folders(self, authed_client):+ patches = _auth_patches()+ mock_folder = MagicMock()+ mock_folder.to_dict.return_value = {"id": "f1", "name": "Work"}++ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager") as MockFM,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=MagicMock()+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)+ MockFM.return_value.get_user_folders.return_value = [mock_folder]++ resp = authed_client.get("/news/api/subscription/folders")+ assert resp.status_code == 200+ data = resp.get_json()+ assert len(data) == 1+ assert data[0]["name"] == "Work"++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.get_user_db_session",+ side_effect=RuntimeError("db fail"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscription/folders")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 14. POST /subscription/folders (create_folder)+# ---------------------------------------------------------------------------+++class TestCreateFolder:+ """Tests for the POST /subscription/folders endpoint."""++ def test_create_folder(self, authed_client):+ patches = _auth_patches()+ mock_folder = MagicMock()+ mock_folder.to_dict.return_value = {+ "id": "f-new",+ "name": "Research",+ }+ mock_session = MagicMock()+ mock_query = MagicMock()+ mock_query.filter_by.return_value.first.return_value = None+ mock_session.query.return_value = mock_query++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager") as MockFM,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)+ MockFM.return_value.create_folder.return_value = mock_folder++ resp = authed_client.post(+ "/news/api/subscription/folders",+ json={"name": "Research", "description": "Research topics"},+ )+ assert resp.status_code == 201+ data = resp.get_json()+ assert data["name"] == "Research"++ def test_missing_name_returns_400(self, authed_client):+ patches = _auth_patches()+ with patches["db_manager"] as mock_db:+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/subscription/folders",+ json={"description": "no name"},+ )+ assert resp.status_code == 400++ def test_duplicate_folder_returns_409(self, authed_client):+ patches = _auth_patches()+ mock_session = MagicMock()+ mock_existing = MagicMock()+ mock_query = MagicMock()+ mock_query.filter_by.return_value.first.return_value = mock_existing+ mock_session.query.return_value = mock_query++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager"),+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)++ resp = authed_client.post(+ "/news/api/subscription/folders",+ json={"name": "Existing"},+ )+ assert resp.status_code == 409+++# ---------------------------------------------------------------------------+# 15. PUT /subscription/folders/<id> (update_folder)+# ---------------------------------------------------------------------------+++class TestUpdateFolder:+ """Tests for the PUT /subscription/folders/<id> endpoint."""++ def test_update_folder(self, authed_client):+ patches = _auth_patches()+ mock_folder = MagicMock()+ mock_folder.to_dict.return_value = {"id": "f1", "name": "Updated"}++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager") as MockFM,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=MagicMock()+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)+ MockFM.return_value.update_folder.return_value = mock_folder++ resp = authed_client.put(+ "/news/api/subscription/folders/f1",+ json={"name": "Updated"},+ )+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["name"] == "Updated"++ def test_folder_not_found(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager") as MockFM,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=MagicMock()+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)+ MockFM.return_value.update_folder.return_value = None++ resp = authed_client.put(+ "/news/api/subscription/folders/bad-id",+ json={"name": "X"},+ )+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# 16. DELETE /subscription/folders/<id> (delete_folder)+# ---------------------------------------------------------------------------+++class TestDeleteFolder:+ """Tests for the DELETE /subscription/folders/<id> endpoint."""++ def test_delete_folder(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager") as MockFM,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=MagicMock()+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)+ MockFM.return_value.delete_folder.return_value = True++ resp = authed_client.delete("/news/api/subscription/folders/f1")+ assert resp.status_code == 200+ assert resp.get_json()["status"] == "deleted"++ def test_delete_folder_not_found(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager") as MockFM,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=MagicMock()+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)+ MockFM.return_value.delete_folder.return_value = False++ resp = authed_client.delete("/news/api/subscription/folders/bad-id")+ assert resp.status_code == 404++ def test_delete_folder_with_move_to(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager") as MockFM,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=MagicMock()+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)+ MockFM.return_value.delete_folder.return_value = True++ resp = authed_client.delete(+ "/news/api/subscription/folders/f1?move_to=f2"+ )+ assert resp.status_code == 200+ MockFM.return_value.delete_folder.assert_called_once_with(+ "f1", "f2"+ )+++# ---------------------------------------------------------------------------+# 17. GET /subscription/subscriptions/organized (get_subscriptions_organized)+# ---------------------------------------------------------------------------+++class TestGetSubscriptionsOrganized:+ """Tests for the /subscription/subscriptions/organized endpoint."""++ def test_returns_organized(self, authed_client):+ patches = _auth_patches()+ mock_sub = MagicMock()+ mock_sub.to_dict.return_value = {"id": "s1", "query": "AI"}++ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager") as MockFM,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=MagicMock()+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)+ MockFM.return_value.get_subscriptions_by_folder.return_value = {+ "Work": [mock_sub],+ }++ resp = authed_client.get(+ "/news/api/subscription/subscriptions/organized"+ )+ assert resp.status_code == 200+ data = resp.get_json()+ assert "Work" in data+ assert len(data["Work"]) == 1++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.get_user_db_session",+ side_effect=RuntimeError("db fail"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get(+ "/news/api/subscription/subscriptions/organized"+ )+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 18. GET /subscription/stats (get_subscription_stats)+# ---------------------------------------------------------------------------+++class TestGetSubscriptionStats:+ """Tests for the /subscription/stats endpoint."""++ def test_returns_stats(self, authed_client):+ patches = _auth_patches()+ mock_stats = {"total": 5, "active": 3, "paused": 2}+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.get_user_db_session"+ ) as mock_sess,+ patch("local_deep_research.news.flask_api.FolderManager") as MockFM,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=MagicMock()+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)+ MockFM.return_value.get_subscription_stats.return_value = mock_stats++ resp = authed_client.get("/news/api/subscription/stats")+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["total"] == 5+ assert data["active"] == 3++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patches["get_user_id"],+ patch(+ "local_deep_research.news.flask_api.get_user_db_session",+ side_effect=RuntimeError("db fail"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/subscription/stats")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 19. GET /search-history (get_search_history)+# ---------------------------------------------------------------------------+++class TestGetSearchHistory:+ """Tests for the GET /search-history endpoint."""++ def test_returns_history(self, authed_client):+ patches = _auth_patches()+ mock_item = MagicMock()+ mock_item.to_dict.return_value = {+ "id": 1,+ "query": "test",+ "type": "filter",+ }+ mock_db_session = MagicMock()+ mock_db_session.query.return_value.order_by.return_value.limit.return_value.all.return_value = [+ mock_item+ ]++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value="testuser",+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as mock_sess,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=mock_db_session+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)++ resp = authed_client.get("/news/api/search-history")+ assert resp.status_code == 200+ data = resp.get_json()+ assert len(data["search_history"]) == 1+ assert data["search_history"][0]["query"] == "test"++ def test_unauthenticated_returns_empty(self, authed_client):+ """When current_user returns None, should return empty list."""+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value=None,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/search-history")+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["search_history"] == []++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value="testuser",+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=RuntimeError("db error"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/search-history")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 20. POST /search-history (add_search_history)+# ---------------------------------------------------------------------------+++class TestAddSearchHistory:+ """Tests for the POST /search-history endpoint."""++ def test_add_search(self, authed_client):+ patches = _auth_patches()+ mock_db_session = MagicMock()+ mock_history_instance = MagicMock()+ mock_history_instance.id = 42++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value="testuser",+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as mock_sess,+ patch(+ "local_deep_research.database.models.UserNewsSearchHistory",+ return_value=mock_history_instance,+ ),+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=mock_db_session+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)++ resp = authed_client.post(+ "/news/api/search-history",+ json={+ "query": "test search",+ "type": "filter",+ "resultCount": 10,+ },+ )+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["status"] == "success"+ mock_db_session.add.assert_called_once()+ mock_db_session.commit.assert_called_once()++ def test_missing_query_returns_400(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value="testuser",+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/search-history",+ json={"type": "filter"},+ )+ assert resp.status_code == 400++ def test_no_body_returns_400(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value="testuser",+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/search-history",+ json={},+ )+ assert resp.status_code == 400++ def test_unauthenticated_returns_401(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value=None,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/search-history",+ json={"query": "test"},+ )+ assert resp.status_code == 401+++# ---------------------------------------------------------------------------+# 21. DELETE /search-history (clear_search_history)+# ---------------------------------------------------------------------------+++class TestClearSearchHistory:+ """Tests for the DELETE /search-history endpoint."""++ def test_clear_history(self, authed_client):+ patches = _auth_patches()+ mock_db_session = MagicMock()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value="testuser",+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as mock_sess,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=mock_db_session+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)++ resp = authed_client.delete("/news/api/search-history")+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["status"] == "success"+ mock_db_session.query.return_value.delete.assert_called_once()+ mock_db_session.commit.assert_called_once()++ def test_unauthenticated_returns_success(self, authed_client):+ """When current_user returns None, endpoint returns success (no-op)."""+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value=None,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.delete("/news/api/search-history")+ assert resp.status_code == 200+ assert resp.get_json()["status"] == "success"++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.web.auth.decorators.current_user",+ return_value="testuser",+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=RuntimeError("db error"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.delete("/news/api/search-history")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# 22. POST /check-overdue (check_overdue_subscriptions)+# ---------------------------------------------------------------------------+++class TestCheckOverdueSubscriptions:+ """Tests for the /check-overdue endpoint."""++ def test_no_overdue_subscriptions(self, authed_client):+ patches = _auth_patches()+ mock_db_session = MagicMock()+ mock_db_session.query.return_value.filter.return_value.all.return_value = []++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as mock_sess,+ ):+ mock_db.is_user_connected.return_value = True+ mock_sess.return_value.__enter__ = MagicMock(+ return_value=mock_db_session+ )+ mock_sess.return_value.__exit__ = MagicMock(return_value=False)++ resp = authed_client.post("/news/api/check-overdue")+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["status"] == "success"+ assert data["overdue_found"] == 0+ assert data["started"] == 0++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=RuntimeError("db error"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post("/news/api/check-overdue")+ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# Additional: Scheduler endpoints+# ---------------------------------------------------------------------------+++class TestSchedulerStatus:+ """Tests for the /scheduler/status endpoint."""++ def test_returns_status(self, authed_client):+ patches = _auth_patches()+ mock_scheduler = MagicMock()+ mock_scheduler.is_running = True+ mock_scheduler.config = {"interval": 60}+ mock_scheduler.user_sessions = {"testuser": {"scheduled_jobs": {"j1"}}}+ mock_scheduler.scheduler = None++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",+ return_value=mock_scheduler,+ ),+ patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=False,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/scheduler/status")+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["is_running"] is True+ assert data["scheduler_available"] is True++ def test_exception_returns_500(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",+ side_effect=RuntimeError("fail"),+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.get("/news/api/scheduler/status")+ assert resp.status_code == 500+++class TestSchedulerStartStop:+ """Tests for scheduler start/stop endpoints."""++ def test_start_scheduler(self, authed_client):+ patches = _auth_patches()+ mock_scheduler = MagicMock()+ mock_scheduler.is_running = False+ mock_scheduler.user_sessions = {}++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=True,+ ),+ patch(+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",+ return_value=mock_scheduler,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post("/news/api/scheduler/start")+ assert resp.status_code == 200+ data = resp.get_json()+ assert data["status"] == "success"+ mock_scheduler.start.assert_called_once()++ def test_start_already_running(self, authed_client):+ patches = _auth_patches()+ mock_scheduler = MagicMock()+ mock_scheduler.is_running = True++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=True,+ ),+ patch(+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",+ return_value=mock_scheduler,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post("/news/api/scheduler/start")+ assert resp.status_code == 200+ assert "already running" in resp.get_json()["message"].lower()++ def test_start_blocked_by_setting(self, authed_client):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=False,+ ),+ ):+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post("/news/api/scheduler/start")+ assert resp.status_code == 403++ def test_stop_scheduler(self, authed_client, app):+ patches = _auth_patches()+ mock_scheduler = MagicMock()+ mock_scheduler.is_running = True++ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=True,+ ),+ ):+ mock_db.is_user_connected.return_value = True+ app.news_scheduler = mock_scheduler++ resp = authed_client.post("/news/api/scheduler/stop")+ assert resp.status_code == 200+ mock_scheduler.stop.assert_called_once()++ def test_stop_no_scheduler(self, authed_client, app):+ patches = _auth_patches()+ with (+ patches["db_manager"] as mock_db,+ patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=True,+ ),+ ):+ mock_db.is_user_connected.return_value = True+ # Ensure no news_scheduler attribute+ if hasattr(app, "news_scheduler"):+ delattr(app, "news_scheduler")++ resp = authed_client.post("/news/api/scheduler/stop")+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# Edge case: require_json_body decorator+# ---------------------------------------------------------------------------+++class TestRequireJsonBody:+ """Test that endpoints with @require_json_body reject non-JSON requests."""++ def test_vote_without_json(self, authed_client):+ patches = _auth_patches()+ with patches["db_manager"] as mock_db:+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/vote",+ data="plain text",+ content_type="text/plain",+ )+ assert resp.status_code == 400++ def test_feedback_batch_without_json(self, authed_client):+ patches = _auth_patches()+ with patches["db_manager"] as mock_db:+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/feedback/batch",+ data="plain text",+ content_type="text/plain",+ )+ assert resp.status_code == 400++ def test_preferences_without_json(self, authed_client):+ patches = _auth_patches()+ with patches["db_manager"] as mock_db:+ mock_db.is_user_connected.return_value = True++ resp = authed_client.post(+ "/news/api/preferences",+ data="plain text",+ content_type="text/plain",+ )+ assert resp.status_code == 400diff --git a/tests/research_library/services/test_download_service_coverage.py b/tests/research_library/services/test_download_service_coverage.pynew file mode 100644index 0000000000..15676abe35--- /dev/null+++ b/tests/research_library/services/test_download_service_coverage.py@@ -0,0 +1,259 @@+"""+Tests for DownloadService pure logic methods to improve coverage.++Covers: _normalize_url, _get_url_hash, close, __enter__/__exit__, _setup_directories.+"""++import pytest+from unittest.mock import patch, MagicMock++from local_deep_research.research_library.services.download_service import (+ DownloadService,+)+++def download_service():+ """Create a DownloadService with mocked __init__."""+ with patch.object(DownloadService, "__init__", lambda self, *a, **kw: None):+ service = DownloadService.__new__(DownloadService)+ service.username = "test_user"+ service.password = None+ service._closed = False+ service.downloaders = []+ service.retry_manager = MagicMock()+ service.settings = MagicMock()+ service.library_root = "/tmp/test_library"+ return service+++# ---------------------------------------------------------------------------+# _normalize_url tests+# ---------------------------------------------------------------------------+++class TestNormalizeUrl:+ """Tests for _normalize_url."""++ def test_strips_http_protocol(self, download_service):+ result = download_service._normalize_url("http://example.com/page")+ assert result == "example.com/page"++ def test_strips_https_protocol(self, download_service):+ result = download_service._normalize_url("https://example.com/page")+ assert result == "example.com/page"++ def test_strips_www_prefix(self, download_service):+ result = download_service._normalize_url("https://www.example.com/page")+ assert result == "example.com/page"++ def test_strips_trailing_slashes(self, download_service):+ result = download_service._normalize_url("https://example.com/page///")+ assert result == "example.com/page"++ def test_sorts_query_parameters(self, download_service):+ result = download_service._normalize_url(+ "https://example.com/search?z=1&a=2&m=3"+ )+ assert result == "example.com/search?a=2&m=3&z=1"++ def test_lowercases_url(self, download_service):+ result = download_service._normalize_url("https://Example.COM/Page")+ assert result == "example.com/page"++ def test_url_without_query_string(self, download_service):+ result = download_service._normalize_url(+ "https://example.com/path/to/page"+ )+ assert result == "example.com/path/to/page"++ def test_url_with_empty_query(self, download_service):+ # URL with '?' but nothing after it+ result = download_service._normalize_url("https://example.com/page?")+ assert result == "example.com/page?"++ def test_url_with_multiple_query_params_sorted(self, download_service):+ result = download_service._normalize_url(+ "https://example.com/api?page=2&sort=date&filter=new&lang=en"+ )+ assert result == "example.com/api?filter=new&lang=en&page=2&sort=date"++ def test_complex_url(self, download_service):+ result = download_service._normalize_url(+ "https://www.Example.COM/Papers/PDF/?id=123&ref=home/"+ )+ # trailing slash removed before query split, www stripped, lowercased+ # The URL has query params so base and params are separated+ assert "example.com/" in result+ assert "id=123" in result+ assert "ref=home" in result++ def test_plain_domain_no_path(self, download_service):+ result = download_service._normalize_url("https://example.com")+ assert result == "example.com"++ def test_no_protocol_no_www(self, download_service):+ """URL that already lacks protocol and www is only lowercased."""+ result = download_service._normalize_url("example.com/Page")+ assert result == "example.com/page"+++# ---------------------------------------------------------------------------+# _get_url_hash tests+# ---------------------------------------------------------------------------+++class TestGetUrlHash:+ """Tests for _get_url_hash."""++ def test_returns_hash_of_normalized_url(self, download_service):+ with patch(+ "local_deep_research.research_library.services.download_service.get_url_hash",+ return_value="abc123hash",+ ) as mock_hash:+ result = download_service._get_url_hash(+ "https://www.Example.COM/page"+ )+ # Should call get_url_hash with the normalized form+ mock_hash.assert_called_once_with("example.com/page")+ assert result == "abc123hash"++ def test_equivalent_urls_produce_same_hash(self, download_service):+ """Two URLs differing only by protocol/www/case should produce the same hash."""+ hash1 = download_service._get_url_hash("https://www.example.com/page")+ hash2 = download_service._get_url_hash("http://Example.COM/page")+ assert hash1 == hash2+++# ---------------------------------------------------------------------------+# close tests+# ---------------------------------------------------------------------------+++class TestClose:+ """Tests for close()."""++ def test_closes_all_downloaders(self, download_service):+ d1 = MagicMock()+ d2 = MagicMock()+ download_service.downloaders = [d1, d2]++ download_service.close()++ d1.close.assert_called_once()+ d2.close.assert_called_once()++ def test_clears_references(self, download_service):+ download_service.downloaders = [MagicMock()]+ download_service.retry_manager = MagicMock()+ download_service.settings = MagicMock()++ download_service.close()++ assert download_service.downloaders == []+ assert download_service.retry_manager is None+ assert download_service.settings is None++ def test_sets_closed_flag(self, download_service):+ download_service.close()+ assert download_service._closed is True++ def test_idempotent_calling_twice_is_safe(self, download_service):+ d1 = MagicMock()+ download_service.downloaders = [d1]++ download_service.close()+ download_service.close() # second call should be a no-op++ d1.close.assert_called_once()++ def test_handles_downloader_without_close(self, download_service):+ """Downloaders without a close method are skipped."""+ d_no_close = object() # no close attribute+ d_with_close = MagicMock()+ download_service.downloaders = [d_no_close, d_with_close]++ download_service.close()++ d_with_close.close.assert_called_once()++ def test_handles_downloader_close_exception(self, download_service):+ """Exceptions during downloader.close() are swallowed."""+ d1 = MagicMock()+ d1.close.side_effect = RuntimeError("boom")+ d2 = MagicMock()+ download_service.downloaders = [d1, d2]++ download_service.close() # should not raise++ d1.close.assert_called_once()+ d2.close.assert_called_once()+++# ---------------------------------------------------------------------------+# Context manager tests+# ---------------------------------------------------------------------------+++class TestContextManager:+ """Tests for __enter__ and __exit__."""++ def test_enter_returns_self(self, download_service):+ result = download_service.__enter__()+ assert result is download_service++ def test_exit_calls_close(self, download_service):+ with patch.object(download_service, "close") as mock_close:+ ret = download_service.__exit__(None, None, None)+ mock_close.assert_called_once()+ assert ret is False++ def test_exit_returns_false(self, download_service):+ """__exit__ returns False so exceptions are not suppressed."""+ ret = download_service.__exit__(None, None, None)+ assert ret is False++ def test_with_statement(self, download_service):+ """Using the service in a with-statement calls close on exit."""+ with patch.object(download_service, "close") as mock_close:+ with download_service as svc:+ assert svc is download_service+ mock_close.assert_called_once()+++# ---------------------------------------------------------------------------+# _setup_directories tests+# ---------------------------------------------------------------------------+++class TestSetupDirectories:+ """Tests for _setup_directories."""++ def test_creates_library_root_and_pdfs_dir(+ self, download_service, tmp_path+ ):+ download_service.library_root = str(tmp_path / "my_library")++ download_service._setup_directories()++ assert (tmp_path / "my_library").is_dir()+ assert (tmp_path / "my_library" / "pdfs").is_dir()++ def test_idempotent_existing_dirs(self, download_service, tmp_path):+ download_service.library_root = str(tmp_path / "my_library")++ download_service._setup_directories()+ download_service._setup_directories() # should not raise++ assert (tmp_path / "my_library").is_dir()+ assert (tmp_path / "my_library" / "pdfs").is_dir()++ def test_creates_nested_path(self, download_service, tmp_path):+ download_service.library_root = str(+ tmp_path / "a" / "b" / "c" / "library"+ )++ download_service._setup_directories()++ assert (tmp_path / "a" / "b" / "c" / "library").is_dir()+ assert (tmp_path / "a" / "b" / "c" / "library" / "pdfs").is_dir()diff --git a/tests/security/test_file_integrity_manager_coverage.py b/tests/security/test_file_integrity_manager_coverage.pynew file mode 100644index 0000000000..d8deb0d188--- /dev/null+++ b/tests/security/test_file_integrity_manager_coverage.py@@ -0,0 +1,978 @@+"""+Comprehensive tests for FileIntegrityManager to increase coverage.++Tests all public and internal methods with mocked DB sessions and verifiers.+"""++import pytest+from unittest.mock import patch, MagicMock+from pathlib import Path+from datetime import datetime, UTC+from contextlib import contextmanager+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_mock_session():+ """Create a mock DB session with chainable query interface."""+ session = MagicMock()+ return session+++@contextmanager+def _mock_session_cm(session):+ """Context manager wrapper for mock session."""+ yield session+++def _make_verifier(+ should=True,+ file_type="faiss_index",+ algorithm="sha256",+ checksum="abc123",+ allows_mod=False,+):+ """Create a mock verifier with configurable behavior."""+ v = MagicMock()+ v.should_verify.return_value = should+ v.get_file_type.return_value = file_type+ v.get_algorithm.return_value = algorithm+ v.calculate_checksum.return_value = checksum+ v.allows_modifications.return_value = allows_mod+ return v+++def _make_record(**overrides):+ """Create a mock FileIntegrityRecord with sensible defaults."""+ defaults = dict(+ id=1,+ file_path="/resolved/path",+ file_type="faiss_index",+ checksum="abc123",+ algorithm="sha256",+ file_size=1024,+ file_mtime=1000.0,+ verify_on_load=True,+ allow_modifications=False,+ total_verifications=5,+ last_verified_at=datetime(2025, 1, 1, tzinfo=UTC),+ last_verification_passed=True,+ consecutive_successes=3,+ consecutive_failures=0,+ created_at=datetime(2025, 1, 1, tzinfo=UTC),+ updated_at=None,+ related_entity_type=None,+ related_entity_id=None,+ )+ defaults.update(overrides)+ record = MagicMock()+ for k, v in defaults.items():+ setattr(record, k, v)+ return record+++# Patch path for the session context used inside integrity_manager module+_SESSION_PATCH = (+ "local_deep_research.security.file_integrity.integrity_manager"+ ".get_user_db_session"+)+_HAS_CTX_PATCH = (+ "local_deep_research.security.file_integrity.integrity_manager"+ "._has_session_context"+)+++def integrity_manager():+ """+ Build a FileIntegrityManager with mocked session context.++ Yields (manager, session). Patcher is automatically stopped on teardown.+ """+ session = _make_mock_session()++ with patch(_HAS_CTX_PATCH, True), patch(_SESSION_PATCH) as mock_get_session:+ mock_get_session.return_value = _mock_session_cm(session)+ # cleanup_all_old_failures queries count then returns+ session.query.return_value.count.return_value = 0+ from local_deep_research.security.file_integrity.integrity_manager import (+ FileIntegrityManager,+ )++ mgr = FileIntegrityManager(username="testuser", password="testpass")++ # Re-patch for subsequent calls+ patcher = patch(+ _SESSION_PATCH, side_effect=lambda u, p: _mock_session_cm(session)+ )+ patcher.start()+ mgr._test_session = session+ yield mgr, session+ patcher.stop()+++def _build_manager(session=None):+ """+ Build a FileIntegrityManager with mocked session context.++ Returns (manager, session). Caller MUST call mgr._test_patcher.stop()+ or use the integrity_manager fixture instead.++ NOTE: Prefer the integrity_manager fixture for new tests.+ This helper is kept for TestInit tests that need custom session setup.+ """+ if session is None:+ session = _make_mock_session()++ with patch(_HAS_CTX_PATCH, True), patch(_SESSION_PATCH) as mock_get_session:+ mock_get_session.return_value = _mock_session_cm(session)+ # cleanup_all_old_failures queries count then returns+ session.query.return_value.count.return_value = 0+ from local_deep_research.security.file_integrity.integrity_manager import (+ FileIntegrityManager,+ )++ mgr = FileIntegrityManager(username="testuser", password="testpass")++ # Re-patch for subsequent calls+ patcher = patch(+ _SESSION_PATCH, side_effect=lambda u, p: _mock_session_cm(session)+ )+ patcher.start()+ mgr._test_patcher = patcher+ mgr._test_session = session+ return mgr, session+++# ---------------------------------------------------------------------------+# Tests: __init__+# ---------------------------------------------------------------------------+++class TestInit:+ def test_raises_import_error_when_no_session_context(self):+ with patch(_HAS_CTX_PATCH, False):+ from local_deep_research.security.file_integrity.integrity_manager import (+ FileIntegrityManager,+ )++ with pytest.raises(ImportError, match="requires Flask"):+ FileIntegrityManager(username="user")++ def test_successful_init_sets_attributes(self):+ mgr, _session = _build_manager()+ assert mgr.username == "testuser"+ assert mgr.password == "testpass"+ assert mgr.verifiers == []+ mgr._test_patcher.stop()++ def test_startup_cleanup_logs_when_deleted(self):+ session = _make_mock_session()+ # First call to cleanup_all_old_failures: count returns > MAX+ with (+ patch(_HAS_CTX_PATCH, True),+ patch(_SESSION_PATCH) as mock_get_session,+ ):+ mock_get_session.return_value = _mock_session_cm(session)+ # total_failures > MAX_TOTAL_FAILURES to trigger deletion+ session.query.return_value.count.return_value = 10005+ session.query.return_value.order_by.return_value.limit.return_value.all.return_value = [+ MagicMock() for _ in range(5)+ ]+ from local_deep_research.security.file_integrity.integrity_manager import (+ FileIntegrityManager,+ )++ mgr = FileIntegrityManager(username="user")+ mgr._test_patcher = patch(_SESSION_PATCH) # dummy+ # No assertion needed beyond not raising++ def test_startup_cleanup_handles_exception(self):+ """If startup cleanup raises, __init__ should still succeed."""+ with (+ patch(_HAS_CTX_PATCH, True),+ patch(_SESSION_PATCH) as mock_get_session,+ ):+ mock_get_session.side_effect = RuntimeError("db down")+ from local_deep_research.security.file_integrity.integrity_manager import (+ FileIntegrityManager,+ )++ # Should not raise thanks to try/except in __init__+ mgr = FileIntegrityManager(username="user")+ assert mgr.username == "user"+++# ---------------------------------------------------------------------------+# Tests: _normalize_path+# ---------------------------------------------------------------------------+++class TestNormalizePath:+ def test_returns_resolved_string(self, integrity_manager):+ mgr, _ = integrity_manager+ p = Path("/some/../some/file.txt")+ result = mgr._normalize_path(p)+ assert result == str(p.resolve())+ assert isinstance(result, str)++ def test_relative_path_becomes_absolute(self, integrity_manager):+ mgr, _ = integrity_manager+ p = Path("relative/file.txt")+ result = mgr._normalize_path(p)+ assert Path(result).is_absolute()+++# ---------------------------------------------------------------------------+# Tests: register_verifier+# ---------------------------------------------------------------------------+++class TestRegisterVerifier:+ def test_appends_verifier(self, integrity_manager):+ mgr, _ = integrity_manager+ v1 = _make_verifier()+ v2 = _make_verifier(file_type="pdf")+ mgr.register_verifier(v1)+ mgr.register_verifier(v2)+ assert mgr.verifiers == [v1, v2]+++# ---------------------------------------------------------------------------+# Tests: _get_verifier_for_file+# ---------------------------------------------------------------------------+++class TestGetVerifierForFile:+ def test_returns_matching_verifier(self, integrity_manager):+ mgr, _ = integrity_manager+ v1 = _make_verifier(should=False)+ v2 = _make_verifier(should=True, file_type="pdf")+ mgr.register_verifier(v1)+ mgr.register_verifier(v2)+ result = mgr._get_verifier_for_file(Path("/some/file.pdf"))+ assert result is v2++ def test_returns_first_matching(self, integrity_manager):+ mgr, _ = integrity_manager+ v1 = _make_verifier(should=True, file_type="faiss")+ v2 = _make_verifier(should=True, file_type="pdf")+ mgr.register_verifier(v1)+ mgr.register_verifier(v2)+ result = mgr._get_verifier_for_file(Path("/file"))+ assert result is v1++ def test_returns_none_when_no_match(self, integrity_manager):+ mgr, _ = integrity_manager+ v1 = _make_verifier(should=False)+ mgr.register_verifier(v1)+ result = mgr._get_verifier_for_file(Path("/file"))+ assert result is None++ def test_returns_none_with_no_verifiers(self, integrity_manager):+ mgr, _ = integrity_manager+ result = mgr._get_verifier_for_file(Path("/file"))+ assert result is None+++# ---------------------------------------------------------------------------+# Tests: _needs_verification+# ---------------------------------------------------------------------------+++class TestNeedsVerification:+ def test_file_missing_returns_true(self, integrity_manager):+ mgr, _ = integrity_manager+ record = _make_record()+ path = MagicMock(spec=Path)+ path.exists.return_value = False+ assert mgr._needs_verification(record, path) is True++ def test_never_verified_returns_true(self, integrity_manager):+ mgr, _ = integrity_manager+ record = _make_record(last_verified_at=None)+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ assert mgr._needs_verification(record, path) is True++ def test_no_stored_mtime_returns_true(self, integrity_manager):+ mgr, _ = integrity_manager+ record = _make_record(file_mtime=None)+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.stat.return_value.st_mtime = 1000.0+ assert mgr._needs_verification(record, path) is True++ def test_mtime_changed_returns_true(self, integrity_manager):+ mgr, _ = integrity_manager+ record = _make_record(file_mtime=1000.0)+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.stat.return_value.st_mtime = 2000.0 # clearly different+ assert mgr._needs_verification(record, path) is True++ def test_mtime_unchanged_returns_false(self, integrity_manager):+ mgr, _ = integrity_manager+ record = _make_record(file_mtime=1000.0)+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.stat.return_value.st_mtime = 1000.0+ assert mgr._needs_verification(record, path) is False++ def test_mtime_tiny_float_difference_returns_false(self, integrity_manager):+ """Differences within 0.001 threshold should not trigger verification."""+ mgr, _ = integrity_manager+ record = _make_record(file_mtime=1000.0)+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.stat.return_value.st_mtime = 1000.0005 # within threshold+ assert mgr._needs_verification(record, path) is False+++# ---------------------------------------------------------------------------+# Tests: _do_verification+# ---------------------------------------------------------------------------+++class TestDoVerification:+ def test_file_missing(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record()+ path = MagicMock(spec=Path)+ path.exists.return_value = False+ passed, reason = mgr._do_verification(record, path, session)+ assert passed is False+ assert reason == "file_missing"++ def test_no_verifier(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record()+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ # No verifiers registered+ passed, reason = mgr._do_verification(record, path, session)+ assert passed is False+ assert reason == "no_verifier"++ def test_checksum_match(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(checksum="abc123")+ mgr.register_verifier(v)+ record = _make_record(checksum="abc123")+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.stat.return_value.st_mtime = 1234.0+ passed, reason = mgr._do_verification(record, path, session)+ assert passed is True+ assert reason is None+ # mtime should be updated on record+ assert record.file_mtime == 1234.0++ def test_checksum_mismatch(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(checksum="different_checksum")+ mgr.register_verifier(v)+ record = _make_record(checksum="abc123")+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ passed, reason = mgr._do_verification(record, path, session)+ assert passed is False+ assert reason == "checksum_mismatch"++ def test_checksum_calculation_exception(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier()+ v.calculate_checksum.side_effect = IOError("read error")+ mgr.register_verifier(v)+ record = _make_record()+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ passed, reason = mgr._do_verification(record, path, session)+ assert passed is False+ assert "checksum_calculation_failed" in reason+ assert "read error" in reason+++# ---------------------------------------------------------------------------+# Tests: _update_stats+# ---------------------------------------------------------------------------+++class TestUpdateStats:+ def test_passed(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record(+ total_verifications=5,+ consecutive_successes=2,+ consecutive_failures=1,+ )+ mgr._update_stats(record, True, session)+ assert record.total_verifications == 6+ assert record.consecutive_successes == 3+ assert record.consecutive_failures == 0+ assert record.last_verification_passed is True+ assert record.last_verified_at is not None++ def test_failed(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record(+ total_verifications=10,+ consecutive_successes=5,+ consecutive_failures=0,+ )+ mgr._update_stats(record, False, session)+ assert record.total_verifications == 11+ assert record.consecutive_successes == 0+ assert record.consecutive_failures == 1+ assert record.last_verification_passed is False+++# ---------------------------------------------------------------------------+# Tests: _log_failure+# ---------------------------------------------------------------------------+++class TestLogFailure:+ def test_logs_with_existing_file(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(checksum="actual_cs")+ mgr.register_verifier(v)+ record = _make_record(id=1, checksum="expected_cs")+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.stat.return_value.st_size = 2048+ # Setup session for cleanup queries+ session.query.return_value.filter_by.return_value.count.return_value = 0++ mgr._log_failure(record, path, "checksum_mismatch", session)++ session.add.assert_called_once()+ failure_obj = session.add.call_args[0][0]+ assert failure_obj.expected_checksum == "expected_cs"+ assert failure_obj.actual_checksum == "actual_cs"+ assert failure_obj.file_size == 2048+ assert failure_obj.failure_reason == "checksum_mismatch"++ def test_logs_with_missing_file(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record(id=1, checksum="expected_cs")+ path = MagicMock(spec=Path)+ path.exists.return_value = False+ session.query.return_value.filter_by.return_value.count.return_value = 0++ mgr._log_failure(record, path, "file_missing", session)++ session.add.assert_called_once()+ failure_obj = session.add.call_args[0][0]+ assert failure_obj.actual_checksum is None+ assert failure_obj.file_size is None+ assert failure_obj.failure_reason == "file_missing"++ def test_logs_with_verifier_exception(self, integrity_manager):+ """If verifier.calculate_checksum raises, actual_checksum stays None."""+ mgr, session = integrity_manager+ v = _make_verifier()+ v.calculate_checksum.side_effect = IOError("cannot read")+ mgr.register_verifier(v)+ record = _make_record(id=1)+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ session.query.return_value.filter_by.return_value.count.return_value = 0++ mgr._log_failure(record, path, "error", session)++ failure_obj = session.add.call_args[0][0]+ assert failure_obj.actual_checksum is None++ def test_triggers_global_cleanup_on_id_mod_100(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record(id=200) # 200 % 100 == 0+ path = MagicMock(spec=Path)+ path.exists.return_value = False+ # Per-file cleanup: count under limit+ session.query.return_value.filter_by.return_value.count.return_value = 0+ # Global cleanup: count under threshold+ session.query.return_value.count.return_value = 5000++ mgr._log_failure(record, path, "test", session)++ # count() was called for both per-file and global checks+ assert (+ session.query.return_value.count.called+ or session.query.return_value.filter_by.return_value.count.called+ )+++# ---------------------------------------------------------------------------+# Tests: _cleanup_old_failures+# ---------------------------------------------------------------------------+++class TestCleanupOldFailures:+ def test_no_cleanup_when_under_limit(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record(id=1)+ session.query.return_value.filter_by.return_value.count.return_value = (+ 50+ )+ mgr._cleanup_old_failures(record, session)+ # Should not attempt to delete+ session.delete.assert_not_called()++ def test_cleanup_when_over_limit(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record(id=1)+ session.query.return_value.filter_by.return_value.count.return_value = (+ 110+ )+ old_failures = [MagicMock() for _ in range(10)]+ session.query.return_value.filter_by.return_value.order_by.return_value.limit.return_value.all.return_value = old_failures++ mgr._cleanup_old_failures(record, session)++ assert session.delete.call_count == 10++ def test_cleanup_at_exactly_limit(self, integrity_manager):+ """Exactly at MAX_FAILURES_PER_FILE should not trigger cleanup."""+ mgr, session = integrity_manager+ record = _make_record(id=1)+ session.query.return_value.filter_by.return_value.count.return_value = (+ 100+ )+ mgr._cleanup_old_failures(record, session)+ session.delete.assert_not_called()+++# ---------------------------------------------------------------------------+# Tests: _check_global_cleanup_needed+# ---------------------------------------------------------------------------+++class TestCheckGlobalCleanupNeeded:+ def test_no_cleanup_under_threshold(self, integrity_manager):+ mgr, session = integrity_manager+ # threshold = 10000 * 1.2 = 12000+ session.query.return_value.count.return_value = 11000+ mgr._check_global_cleanup_needed(session)+ session.delete.assert_not_called()++ def test_cleanup_over_threshold(self, integrity_manager):+ mgr, session = integrity_manager+ session.query.return_value.count.return_value = 13000 # > 12000+ old_failures = [MagicMock() for _ in range(3000)] # 13000 - 10000+ session.query.return_value.order_by.return_value.limit.return_value.all.return_value = old_failures+ mgr._check_global_cleanup_needed(session)+ assert session.delete.call_count == 3000++ def test_exactly_at_threshold_no_cleanup(self, integrity_manager):+ mgr, session = integrity_manager+ session.query.return_value.count.return_value = 12000 # == threshold+ mgr._check_global_cleanup_needed(session)+ session.delete.assert_not_called()+++# ---------------------------------------------------------------------------+# Tests: record_file+# ---------------------------------------------------------------------------+++class TestRecordFile:+ def test_new_file(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(+ checksum="newcs", file_type="faiss_index", algorithm="sha256"+ )+ mgr.register_verifier(v)+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.resolve.return_value = Path("/resolved/new_file")+ path.stat.return_value.st_size = 4096+ path.stat.return_value.st_mtime = 2000.0+ # No existing record+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ mgr.record_file(+ path, related_entity_type="rag_index", related_entity_id=42+ )++ session.add.assert_called_once()+ session.commit.assert_called_once()+ session.refresh.assert_called_once()++ def test_existing_file_updates(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(checksum="updatedcs")+ mgr.register_verifier(v)+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.resolve.return_value = Path("/resolved/existing")+ path.stat.return_value.st_size = 8192+ path.stat.return_value.st_mtime = 3000.0+ existing_record = _make_record()+ session.query.return_value.filter_by.return_value.first.return_value = (+ existing_record+ )++ mgr.record_file(path)++ assert existing_record.checksum == "updatedcs"+ assert existing_record.file_size == 8192+ assert existing_record.file_mtime == 3000.0+ session.commit.assert_called_once()+ # session.add should NOT be called for updates+ session.add.assert_not_called()++ def test_file_not_found(self, integrity_manager):+ mgr, _ = integrity_manager+ path = MagicMock(spec=Path)+ path.exists.return_value = False+ with pytest.raises(FileNotFoundError, match="File not found"):+ mgr.record_file(path)++ def test_no_verifier(self, integrity_manager):+ mgr, _ = integrity_manager+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ # No verifiers registered+ with pytest.raises(ValueError, match="No verifier registered"):+ mgr.record_file(path)+++# ---------------------------------------------------------------------------+# Tests: verify_file+# ---------------------------------------------------------------------------+++class TestVerifyFile:+ def test_no_record_creates_one(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(checksum="cs")+ mgr.register_verifier(v)+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.resolve.return_value = Path("/resolved/path")+ path.stat.return_value.st_size = 100+ path.stat.return_value.st_mtime = 500.0+ # First query returns no record, triggering record_file+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ passed, reason = mgr.verify_file(path)++ assert passed is True+ assert reason is None++ def test_no_record_create_fails(self, integrity_manager):+ mgr, session = integrity_manager+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.resolve.return_value = Path("/resolved/path")+ # No record found+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )+ # No verifiers -> record_file will raise ValueError++ passed, reason = mgr.verify_file(path)++ assert passed is False+ assert "Failed to create integrity record" in reason++ def test_skips_if_unchanged(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record(file_mtime=1000.0)+ session.query.return_value.filter_by.return_value.first.return_value = (+ record+ )+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.resolve.return_value = Path("/resolved/path")+ path.stat.return_value.st_mtime = 1000.0 # unchanged++ passed, reason = mgr.verify_file(path)++ assert passed is True+ assert reason is None++ def test_verify_passes(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(checksum="abc123")+ mgr.register_verifier(v)+ record = _make_record(+ checksum="abc123",+ file_mtime=1000.0,+ total_verifications=5,+ consecutive_successes=2,+ consecutive_failures=0,+ )+ session.query.return_value.filter_by.return_value.first.return_value = (+ record+ )+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.resolve.return_value = Path("/resolved/path")+ path.stat.return_value.st_mtime = (+ 2000.0 # changed, triggers verification+ )++ passed, reason = mgr.verify_file(path, force=True)++ assert passed is True+ assert reason is None+ session.commit.assert_called()++ def test_verify_fails(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(checksum="wrong")+ mgr.register_verifier(v)+ record = _make_record(+ id=1,+ checksum="abc123",+ file_mtime=1000.0,+ total_verifications=5,+ consecutive_successes=2,+ consecutive_failures=0,+ )+ session.query.return_value.filter_by.return_value.first.return_value = (+ record+ )+ # Per-file cleanup count+ session.query.return_value.filter_by.return_value.count.return_value = 0+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.resolve.return_value = Path("/resolved/path")+ path.stat.return_value.st_mtime = 2000.0+ path.stat.return_value.st_size = 1024++ passed, reason = mgr.verify_file(path, force=True)++ assert passed is False+ assert reason == "checksum_mismatch"+ session.commit.assert_called()++ def test_force_overrides_skip(self, integrity_manager):+ """force=True should verify even when mtime unchanged."""+ mgr, session = integrity_manager+ v = _make_verifier(checksum="abc123")+ mgr.register_verifier(v)+ record = _make_record(checksum="abc123", file_mtime=1000.0)+ session.query.return_value.filter_by.return_value.first.return_value = (+ record+ )+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.resolve.return_value = Path("/resolved/path")+ path.stat.return_value.st_mtime = 1000.0 # unchanged++ passed, reason = mgr.verify_file(path, force=True)++ assert passed is True+ # Should have called _do_verification (verifier was used)+ v.calculate_checksum.assert_called_once()+++# ---------------------------------------------------------------------------+# Tests: update_checksum+# ---------------------------------------------------------------------------+++class TestUpdateChecksum:+ def test_success(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(checksum="newcs")+ mgr.register_verifier(v)+ record = _make_record()+ session.query.return_value.filter_by.return_value.first.return_value = (+ record+ )+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.stat.return_value.st_size = 5000+ path.stat.return_value.st_mtime = 9000.0++ mgr.update_checksum(path)++ assert record.checksum == "newcs"+ assert record.file_size == 5000+ assert record.file_mtime == 9000.0+ session.commit.assert_called_once()++ def test_file_not_found(self, integrity_manager):+ mgr, _ = integrity_manager+ path = MagicMock(spec=Path)+ path.exists.return_value = False+ with pytest.raises(FileNotFoundError):+ mgr.update_checksum(path)++ def test_no_verifier(self, integrity_manager):+ mgr, _ = integrity_manager+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ with pytest.raises(ValueError, match="No verifier registered"):+ mgr.update_checksum(path)++ def test_no_record(self, integrity_manager):+ mgr, session = integrity_manager+ v = _make_verifier(checksum="cs")+ mgr.register_verifier(v)+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )+ path = MagicMock(spec=Path)+ path.exists.return_value = True+ path.stat.return_value.st_size = 100+ path.stat.return_value.st_mtime = 100.0+ with pytest.raises(ValueError, match="No integrity record exists"):+ mgr.update_checksum(path)+++# ---------------------------------------------------------------------------+# Tests: get_file_stats+# ---------------------------------------------------------------------------+++class TestGetFileStats:+ def test_with_record(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record(+ total_verifications=10,+ last_verified_at=datetime(2025, 6, 1, tzinfo=UTC),+ last_verification_passed=True,+ consecutive_successes=5,+ consecutive_failures=0,+ file_type="faiss_index",+ created_at=datetime(2025, 1, 1, tzinfo=UTC),+ )+ session.query.return_value.filter_by.return_value.first.return_value = (+ record+ )++ result = mgr.get_file_stats(Path("/some/file"))++ assert result is not None+ assert result["total_verifications"] == 10+ assert result["consecutive_successes"] == 5+ assert result["consecutive_failures"] == 0+ assert result["file_type"] == "faiss_index"+ assert result["last_verification_passed"] is True++ def test_without_record(self, integrity_manager):+ mgr, session = integrity_manager+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ result = mgr.get_file_stats(Path("/nonexistent"))++ assert result is None+++# ---------------------------------------------------------------------------+# Tests: get_failure_history+# ---------------------------------------------------------------------------+++class TestGetFailureHistory:+ def test_with_records(self, integrity_manager):+ mgr, session = integrity_manager+ record = _make_record(id=1)+ session.query.return_value.filter_by.return_value.first.return_value = (+ record+ )+ failures = [MagicMock(), MagicMock()]+ session.query.return_value.filter_by.return_value.order_by.return_value.limit.return_value.all.return_value = failures++ result = mgr.get_failure_history(Path("/some/file"), limit=50)++ assert len(result) == 2+ # Each failure should be expunged from session+ assert session.expunge.call_count == 2++ def test_without_record(self, integrity_manager):+ mgr, session = integrity_manager+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ result = mgr.get_failure_history(Path("/no/record"))++ assert result == []++ def test_default_limit(self, integrity_manager):+ """Default limit should be 100."""+ mgr, session = integrity_manager+ record = _make_record(id=1)+ session.query.return_value.filter_by.return_value.first.return_value = (+ record+ )+ session.query.return_value.filter_by.return_value.order_by.return_value.limit.return_value.all.return_value = []++ mgr.get_failure_history(Path("/file"))++ # Verify limit was called via the chain+ session.query.return_value.filter_by.return_value.order_by.return_value.limit.assert_called()+++# ---------------------------------------------------------------------------+# Tests: cleanup_all_old_failures+# ---------------------------------------------------------------------------+++class TestCleanupAllOldFailures:+ def test_under_limit(self, integrity_manager):+ mgr, session = integrity_manager+ session.query.return_value.count.return_value = 5000 # under 10000++ result = mgr.cleanup_all_old_failures()++ assert result == 0+ session.delete.assert_not_called()++ def test_over_limit(self, integrity_manager):+ mgr, session = integrity_manager+ session.query.return_value.count.return_value = 10500+ old_failures = [MagicMock() for _ in range(500)]+ session.query.return_value.order_by.return_value.limit.return_value.all.return_value = old_failures++ result = mgr.cleanup_all_old_failures()++ assert result == 500+ assert session.delete.call_count == 500+ session.commit.assert_called()++ def test_exactly_at_limit(self, integrity_manager):+ mgr, session = integrity_manager+ session.query.return_value.count.return_value = 10000++ result = mgr.cleanup_all_old_failures()++ assert result == 0+++# ---------------------------------------------------------------------------+# Tests: get_total_failure_count+# ---------------------------------------------------------------------------+++class TestGetTotalFailureCount:+ def test_returns_count(self, integrity_manager):+ mgr, session = integrity_manager+ session.query.return_value.count.return_value = 42++ result = mgr.get_total_failure_count()++ assert result == 42++ def test_returns_zero(self, integrity_manager):+ mgr, session = integrity_manager+ session.query.return_value.count.return_value = 0++ result = mgr.get_total_failure_count()++ assert result == 0diff --git a/tests/web/routes/test_settings_routes_coverage.py b/tests/web/routes/test_settings_routes_coverage.pynew file mode 100644index 0000000000..60ea66a6fc--- /dev/null+++ b/tests/web/routes/test_settings_routes_coverage.py@@ -0,0 +1,338 @@+"""+Tests for pure-logic helpers in settings_routes.py.++Targets functions that are easy to unit-test without a Flask app context:+ - is_blocked_setting+ - get_blocked_settings_error+ - validate_setting+ - coerce_setting_for_write+"""++import pytest+from unittest.mock import patch, MagicMock++from local_deep_research.web.routes.settings_routes import (+ is_blocked_setting,+ get_blocked_settings_error,+ validate_setting,+ coerce_setting_for_write,+ BLOCKED_SETTING_PATTERNS,+ DYNAMIC_SETTINGS,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_setting(+ key="test.key",+ ui_element="text",+ min_value=None,+ max_value=None,+ options=None,+):+ """Create a mock Setting object with the attributes validate_setting uses."""+ s = MagicMock()+ s.key = key+ s.ui_element = ui_element+ s.min_value = min_value+ s.max_value = max_value+ s.options = options+ return s+++# =========================================================================+# is_blocked_setting+# =========================================================================+++class TestIsBlockedSetting:+ """Tests for is_blocked_setting(key)."""++ def test_normal_key_not_blocked(self):+ assert is_blocked_setting("llm.model") is False++ def test_normal_key_search_iterations(self):+ assert is_blocked_setting("search.iterations") is False++ def test_module_path_blocked(self):+ assert is_blocked_setting("custom.module_path") is True++ def test_class_name_blocked(self):+ assert is_blocked_setting("handler.class_name") is True++ def test_module_blocked(self):+ assert is_blocked_setting("custom_module.path") is True++ def test_class_blocked(self):+ assert is_blocked_setting("handler_class") is True++ def test_case_insensitive_upper(self):+ assert is_blocked_setting("MODULE_PATH") is True++ def test_case_insensitive_mixed(self):+ assert is_blocked_setting("My_Class_Name") is True++ def test_partial_match_nested_key(self):+ assert is_blocked_setting("search.custom_engine.module_path") is True++ def test_empty_string_not_blocked(self):+ assert is_blocked_setting("") is False++ def test_all_patterns_are_checked(self):+ """Every entry in BLOCKED_SETTING_PATTERNS should trigger blocking."""+ for pattern in BLOCKED_SETTING_PATTERNS:+ assert is_blocked_setting(f"prefix.{pattern}.suffix") is True+++# =========================================================================+# get_blocked_settings_error+# =========================================================================+++class TestGetBlockedSettingsError:+ """Tests for get_blocked_settings_error(blocked_keys)."""++ def test_single_blocked_key(self):+ result = get_blocked_settings_error(["some.module_path"])+ assert result["status"] == "error"+ assert "Security violation" in result["message"]+ assert len(result["errors"]) == 1+ assert result["errors"][0]["key"] == "some.module_path"++ def test_multiple_blocked_keys(self):+ keys = ["a.module_path", "b.class_name"]+ result = get_blocked_settings_error(keys)+ assert len(result["errors"]) == 2+ returned_keys = [e["key"] for e in result["errors"]]+ assert returned_keys == keys++ def test_empty_list(self):+ result = get_blocked_settings_error([])+ assert result["status"] == "error"+ assert result["errors"] == []++ def test_error_structure(self):+ result = get_blocked_settings_error(["x"])+ err = result["errors"][0]+ assert "key" in err+ assert "name" in err+ assert "error" in err+ # name mirrors key+ assert err["name"] == err["key"]+ assert "cannot be modified" in err["error"]+++# =========================================================================+# validate_setting+# =========================================================================+++class TestValidateSetting:+ """Tests for validate_setting(setting, value).++ get_typed_setting_value is patched so we control the converted value+ without depending on real type-coercion logic.+ """++ _PATCH_TARGET = (+ "local_deep_research.web.routes.settings_routes.get_typed_setting_value"+ )++ # -- checkbox --------------------------------------------------------++ def test_checkbox_with_bool_passes(self):+ setting = _make_setting(ui_element="checkbox")+ with patch(self._PATCH_TARGET, return_value=True):+ valid, err = validate_setting(setting, "true")+ assert valid is True+ assert err is None++ def test_checkbox_with_false_passes(self):+ setting = _make_setting(ui_element="checkbox")+ with patch(self._PATCH_TARGET, return_value=False):+ valid, err = validate_setting(setting, "false")+ assert valid is True+ assert err is None++ def test_checkbox_non_boolean_fails(self):+ setting = _make_setting(ui_element="checkbox")+ # Simulate get_typed_setting_value returning a non-bool+ with patch(self._PATCH_TARGET, return_value="not_a_bool"):+ valid, err = validate_setting(setting, "not_a_bool")+ assert valid is False+ assert "boolean" in err.lower()++ # -- number / slider / range -----------------------------------------++ @pytest.mark.parametrize("ui", ["number", "slider", "range"])+ def test_number_within_range_passes(self, ui):+ setting = _make_setting(ui_element=ui, min_value=0, max_value=100)+ with patch(self._PATCH_TARGET, return_value=50):+ valid, err = validate_setting(setting, 50)+ assert valid is True+ assert err is None++ @pytest.mark.parametrize("ui", ["number", "slider", "range"])+ def test_number_below_min_fails(self, ui):+ setting = _make_setting(ui_element=ui, min_value=10, max_value=100)+ with patch(self._PATCH_TARGET, return_value=5):+ valid, err = validate_setting(setting, 5)+ assert valid is False+ assert "at least" in err++ @pytest.mark.parametrize("ui", ["number", "slider", "range"])+ def test_number_above_max_fails(self, ui):+ setting = _make_setting(ui_element=ui, min_value=0, max_value=100)+ with patch(self._PATCH_TARGET, return_value=200):+ valid, err = validate_setting(setting, 200)+ assert valid is False+ assert "at most" in err++ def test_number_no_min_max_passes(self):+ setting = _make_setting(ui_element="number")+ with patch(self._PATCH_TARGET, return_value=999):+ valid, err = validate_setting(setting, 999)+ assert valid is True++ def test_number_non_numeric_fails(self):+ setting = _make_setting(ui_element="number", min_value=0, max_value=10)+ with patch(self._PATCH_TARGET, return_value="abc"):+ valid, err = validate_setting(setting, "abc")+ assert valid is False+ assert "number" in err.lower()++ def test_number_at_exact_min(self):+ setting = _make_setting(ui_element="number", min_value=0, max_value=100)+ with patch(self._PATCH_TARGET, return_value=0):+ valid, err = validate_setting(setting, 0)+ assert valid is True++ def test_number_at_exact_max(self):+ setting = _make_setting(ui_element="number", min_value=0, max_value=100)+ with patch(self._PATCH_TARGET, return_value=100):+ valid, err = validate_setting(setting, 100)+ assert valid is True++ def test_number_float_value(self):+ setting = _make_setting(+ ui_element="number", min_value=0.0, max_value=1.0+ )+ with patch(self._PATCH_TARGET, return_value=0.5):+ valid, err = validate_setting(setting, 0.5)+ assert valid is True++ # -- select ----------------------------------------------------------++ def test_select_valid_option_passes(self):+ setting = _make_setting(+ ui_element="select",+ options=["opt_a", "opt_b", "opt_c"],+ )+ with patch(self._PATCH_TARGET, return_value="opt_b"):+ valid, err = validate_setting(setting, "opt_b")+ assert valid is True++ def test_select_dict_options_valid(self):+ setting = _make_setting(+ ui_element="select",+ options=[+ {"value": "v1", "label": "Label 1"},+ {"value": "v2", "label": "Label 2"},+ ],+ )+ with patch(self._PATCH_TARGET, return_value="v1"):+ valid, err = validate_setting(setting, "v1")+ assert valid is True++ def test_select_invalid_option_fails(self):+ setting = _make_setting(+ ui_element="select",+ options=["opt_a", "opt_b"],+ )+ with patch(self._PATCH_TARGET, return_value="opt_z"):+ valid, err = validate_setting(setting, "opt_z")+ assert valid is False+ assert "must be one of" in err.lower()++ def test_select_dynamic_setting_skips_validation(self):+ """Dynamic settings (e.g. llm.model) skip options validation."""+ for dyn_key in DYNAMIC_SETTINGS:+ setting = _make_setting(+ key=dyn_key,+ ui_element="select",+ options=["only_this"],+ )+ with patch(self._PATCH_TARGET, return_value="anything_else"):+ valid, err = validate_setting(setting, "anything_else")+ assert valid is True, (+ f"Dynamic setting {dyn_key} should skip validation"+ )++ def test_select_no_options_passes(self):+ """If options is None/empty, validation passes regardless."""+ setting = _make_setting(ui_element="select", options=None)+ with patch(self._PATCH_TARGET, return_value="whatever"):+ valid, err = validate_setting(setting, "whatever")+ assert valid is True++ # -- text / other ui elements ----------------------------------------++ def test_text_element_always_passes(self):+ setting = _make_setting(ui_element="text")+ with patch(self._PATCH_TARGET, return_value="any string"):+ valid, err = validate_setting(setting, "any string")+ assert valid is True+ assert err is None++ # -- get_typed_setting_value call arguments ---------------------------++ def test_calls_get_typed_setting_value_correctly(self):+ setting = _make_setting(key="my.key", ui_element="text")+ with patch(self._PATCH_TARGET, return_value="v") as mock_fn:+ validate_setting(setting, "raw_val")+ mock_fn.assert_called_once_with(+ key="my.key",+ value="raw_val",+ ui_element="text",+ default=None,+ check_env=False,+ )+++# =========================================================================+# coerce_setting_for_write+# =========================================================================+++class TestCoerceSettingForWrite:+ """Tests for coerce_setting_for_write(key, value, ui_element)."""++ _PATCH_TARGET = (+ "local_deep_research.web.routes.settings_routes.get_typed_setting_value"+ )++ def test_delegates_to_get_typed_setting_value(self):+ with patch(self._PATCH_TARGET, return_value=42) as mock_fn:+ result = coerce_setting_for_write("k", "42", "number")+ assert result == 42+ mock_fn.assert_called_once_with(+ key="k",+ value="42",+ ui_element="number",+ default=None,+ check_env=False,+ )++ def test_returns_coerced_value(self):+ with patch(self._PATCH_TARGET, return_value=True):+ assert coerce_setting_for_write("k", "true", "checkbox") is True++ def test_passes_check_env_false(self):+ """check_env must be False on the write path."""+ with patch(self._PATCH_TARGET, return_value="v") as mock_fn:+ coerce_setting_for_write("any.key", "v", "text")+ _, kwargs = mock_fn.call_args+ assert kwargs["check_env"] is Falsediff --git a/tests/web/services/test_research_service_coverage.py b/tests/web/services/test_research_service_coverage.pynew file mode 100644index 0000000000..db72baa116--- /dev/null+++ b/tests/web/services/test_research_service_coverage.py@@ -0,0 +1,512 @@+"""+Tests for research_service.py targeting uncovered lines and easy-to-unit-test+helper functions: _parse_research_metadata, _generate_report_path,+get_citation_formatter, export_report_to_memory, save_research_strategy,+and get_research_strategy.+"""++import json+from contextlib import contextmanager+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.web.services.research_service import (+ _generate_report_path,+ _parse_research_metadata,+)+++# ---------------------------------------------------------------------------+# _parse_research_metadata+# ---------------------------------------------------------------------------+++class TestParseResearchMetadata:+ """Tests for _parse_research_metadata (lines 48-58)."""++ def test_dict_input_returns_copy(self):+ original = {"key": "value", "nested": [1, 2]}+ result = _parse_research_metadata(original)+ assert result == original+ # Must be a copy, not the same object+ assert result is not original++ def test_empty_dict_returns_empty_dict(self):+ result = _parse_research_metadata({})+ assert result == {}++ def test_valid_json_string(self):+ data = {"foo": "bar", "num": 42}+ result = _parse_research_metadata(json.dumps(data))+ assert result == data++ def test_empty_json_object_string(self):+ result = _parse_research_metadata("{}")+ assert result == {}++ def test_invalid_json_string_returns_empty_dict(self):+ result = _parse_research_metadata("not-valid-json{{{")+ assert result == {}++ def test_empty_string_returns_empty_dict(self):+ result = _parse_research_metadata("")+ assert result == {}++ def test_none_returns_empty_dict(self):+ result = _parse_research_metadata(None)+ assert result == {}++ def test_int_returns_empty_dict(self):+ result = _parse_research_metadata(42)+ assert result == {}++ def test_list_returns_empty_dict(self):+ # list is not dict and not str+ result = _parse_research_metadata([1, 2, 3])+ assert result == {}++ def test_bool_returns_empty_dict(self):+ result = _parse_research_metadata(True)+ assert result == {}+++# ---------------------------------------------------------------------------+# _generate_report_path+# ---------------------------------------------------------------------------+++class TestGenerateReportPath:+ """Tests for _generate_report_path (lines 261-279)."""++ def test_returns_path_object(self):+ result = _generate_report_path("test query")+ assert isinstance(result, Path)++ def test_filename_starts_with_prefix(self):+ result = _generate_report_path("test query")+ assert result.name.startswith("research_report_")++ def test_filename_ends_with_md(self):+ result = _generate_report_path("test query")+ assert result.suffix == ".md"++ def test_different_queries_produce_different_hashes(self):+ path1 = _generate_report_path("query one")+ path2 = _generate_report_path("query two")+ # Extract hash portion (between "research_report_" and the timestamp)+ hash1 = path1.stem.split("_")[2]+ hash2 = path2.stem.split("_")[2]+ assert hash1 != hash2++ def test_same_query_produces_same_hash(self):+ path1 = _generate_report_path("identical")+ path2 = _generate_report_path("identical")+ hash1 = path1.stem.split("_")[2]+ hash2 = path2.stem.split("_")[2]+ assert hash1 == hash2++ def test_unicode_query(self):+ result = _generate_report_path("recherche scientifique en francais")+ assert isinstance(result, Path)+ assert result.name.startswith("research_report_")++ def test_unicode_query_with_cjk(self):+ result = _generate_report_path("deep learning")+ assert isinstance(result, Path)+ assert result.suffix == ".md"++ def test_hash_length_is_10(self):+ result = _generate_report_path("some query")+ # Filename pattern: research_report_{hash}_{timestamp}.md+ hash_part = result.stem.split("_")[2]+ assert len(hash_part) == 10+++# ---------------------------------------------------------------------------+# get_citation_formatter+# ---------------------------------------------------------------------------+++class TestGetCitationFormatter:+ """Tests for get_citation_formatter (lines 61-77)."""++ @patch(+ "local_deep_research.web.services.research_service.CitationFormatter"+ )+ @patch("local_deep_research.web.services.research_service.CitationMode")+ def test_number_hyperlinks(self, mock_mode_cls, mock_formatter_cls):+ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="number_hyperlinks",+ ):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ get_citation_formatter()+ mock_formatter_cls.assert_called_once_with(+ mode=mock_mode_cls.NUMBER_HYPERLINKS+ )++ @patch(+ "local_deep_research.web.services.research_service.CitationFormatter"+ )+ @patch("local_deep_research.web.services.research_service.CitationMode")+ def test_domain_hyperlinks(self, mock_mode_cls, mock_formatter_cls):+ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="domain_hyperlinks",+ ):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ get_citation_formatter()+ mock_formatter_cls.assert_called_once_with(+ mode=mock_mode_cls.DOMAIN_HYPERLINKS+ )++ @patch(+ "local_deep_research.web.services.research_service.CitationFormatter"+ )+ @patch("local_deep_research.web.services.research_service.CitationMode")+ def test_domain_id_hyperlinks(self, mock_mode_cls, mock_formatter_cls):+ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="domain_id_hyperlinks",+ ):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ get_citation_formatter()+ mock_formatter_cls.assert_called_once_with(+ mode=mock_mode_cls.DOMAIN_ID_HYPERLINKS+ )++ @patch(+ "local_deep_research.web.services.research_service.CitationFormatter"+ )+ @patch("local_deep_research.web.services.research_service.CitationMode")+ def test_domain_id_always_hyperlinks(+ self, mock_mode_cls, mock_formatter_cls+ ):+ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="domain_id_always_hyperlinks",+ ):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ get_citation_formatter()+ mock_formatter_cls.assert_called_once_with(+ mode=mock_mode_cls.DOMAIN_ID_ALWAYS_HYPERLINKS+ )++ @patch(+ "local_deep_research.web.services.research_service.CitationFormatter"+ )+ @patch("local_deep_research.web.services.research_service.CitationMode")+ def test_no_hyperlinks(self, mock_mode_cls, mock_formatter_cls):+ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="no_hyperlinks",+ ):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ get_citation_formatter()+ mock_formatter_cls.assert_called_once_with(+ mode=mock_mode_cls.NO_HYPERLINKS+ )++ @patch(+ "local_deep_research.web.services.research_service.CitationFormatter"+ )+ @patch("local_deep_research.web.services.research_service.CitationMode")+ def test_unknown_format_falls_back_to_number_hyperlinks(+ self, mock_mode_cls, mock_formatter_cls+ ):+ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="totally_unknown_format",+ ):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ get_citation_formatter()+ # Unknown format should fall back to NUMBER_HYPERLINKS via dict.get default+ mock_formatter_cls.assert_called_once_with(+ mode=mock_mode_cls.NUMBER_HYPERLINKS+ )+++# ---------------------------------------------------------------------------+# export_report_to_memory+# ---------------------------------------------------------------------------+++class TestExportReportToMemory:+ """Tests for export_report_to_memory (lines 80-125)."""++ @patch("local_deep_research.web.services.research_service.logger")+ def test_success(self, mock_logger):+ mock_exporter = MagicMock()+ mock_result = SimpleNamespace(+ content=b"pdf-bytes",+ filename="report.pdf",+ mimetype="application/pdf",+ )+ mock_exporter.export.return_value = mock_result++ mock_registry = MagicMock()+ mock_registry.get_exporter.return_value = mock_exporter++ mock_options_cls = MagicMock()++ with patch.dict(+ "sys.modules",+ {},+ ):+ # Patch the lazy import inside export_report_to_memory+ with (+ patch(+ "local_deep_research.exporters.ExporterRegistry",+ mock_registry,+ ),+ patch(+ "local_deep_research.exporters.ExportOptions",+ mock_options_cls,+ ),+ ):+ from local_deep_research.web.services.research_service import (+ export_report_to_memory,+ )++ content, filename, mimetype = export_report_to_memory(+ "# Report", "pdf", title="My Report"+ )++ assert content == b"pdf-bytes"+ assert filename == "report.pdf"+ assert mimetype == "application/pdf"+ mock_registry.get_exporter.assert_called_once_with("pdf")+ mock_exporter.export.assert_called_once()++ @patch("local_deep_research.web.services.research_service.logger")+ def test_unsupported_format_raises_value_error(self, mock_logger):+ mock_registry = MagicMock()+ mock_registry.get_exporter.return_value = None+ mock_registry.get_available_formats.return_value = ["pdf", "odt"]++ mock_options_cls = MagicMock()++ with (+ patch(+ "local_deep_research.exporters.ExporterRegistry",+ mock_registry,+ ),+ patch(+ "local_deep_research.exporters.ExportOptions",+ mock_options_cls,+ ),+ ):+ from local_deep_research.web.services.research_service import (+ export_report_to_memory,+ )++ with pytest.raises(ValueError, match="Unsupported export format"):+ export_report_to_memory("# Report", "xyz")++ @patch("local_deep_research.web.services.research_service.logger")+ def test_format_is_lowercased(self, mock_logger):+ mock_exporter = MagicMock()+ mock_result = SimpleNamespace(+ content=b"data", filename="f.pdf", mimetype="application/pdf"+ )+ mock_exporter.export.return_value = mock_result++ mock_registry = MagicMock()+ mock_registry.get_exporter.return_value = mock_exporter++ mock_options_cls = MagicMock()++ with (+ patch(+ "local_deep_research.exporters.ExporterRegistry",+ mock_registry,+ ),+ patch(+ "local_deep_research.exporters.ExportOptions",+ mock_options_cls,+ ),+ ):+ from local_deep_research.web.services.research_service import (+ export_report_to_memory,+ )++ export_report_to_memory("# Report", "PDF")++ # Should have called get_exporter with lowercased format+ mock_registry.get_exporter.assert_called_once_with("pdf")+++# ---------------------------------------------------------------------------+# save_research_strategy / get_research_strategy+# ---------------------------------------------------------------------------+++class TestSaveResearchStrategy:+ """Tests for save_research_strategy (lines 128-171)."""++ @patch(+ "local_deep_research.web.services.research_service.get_user_db_session"+ )+ @patch("local_deep_research.web.services.research_service.ResearchStrategy")+ def test_creates_new_strategy(self, mock_strategy_cls, mock_get_session):+ session = MagicMock()+ # query(...).filter_by(...).first() returns None => new record+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ @contextmanager+ def session_ctx(username):+ yield session++ mock_get_session.side_effect = session_ctx++ from local_deep_research.web.services.research_service import (+ save_research_strategy,+ )++ save_research_strategy(1, "detailed", username="alice")++ mock_strategy_cls.assert_called_once_with(+ research_id=1, strategy_name="detailed"+ )+ session.add.assert_called_once_with(mock_strategy_cls.return_value)+ session.commit.assert_called_once()++ @patch(+ "local_deep_research.web.services.research_service.get_user_db_session"+ )+ @patch("local_deep_research.web.services.research_service.ResearchStrategy")+ def test_updates_existing_strategy(+ self, mock_strategy_cls, mock_get_session+ ):+ session = MagicMock()+ existing = MagicMock()+ existing.strategy_name = "old_strategy"+ session.query.return_value.filter_by.return_value.first.return_value = (+ existing+ )++ @contextmanager+ def session_ctx(username):+ yield session++ mock_get_session.side_effect = session_ctx++ from local_deep_research.web.services.research_service import (+ save_research_strategy,+ )++ save_research_strategy(1, "new_strategy", username="bob")++ assert existing.strategy_name == "new_strategy"+ session.add.assert_not_called()+ session.commit.assert_called_once()++ @patch(+ "local_deep_research.web.services.research_service.get_user_db_session"+ )+ @patch("local_deep_research.web.services.research_service.logger")+ def test_handles_exception_gracefully(self, mock_logger, mock_get_session):+ mock_get_session.side_effect = RuntimeError("DB connection failed")++ from local_deep_research.web.services.research_service import (+ save_research_strategy,+ )++ # Should not raise+ save_research_strategy(1, "detailed")++ mock_logger.exception.assert_called_once_with(+ "Error saving research strategy"+ )+++class TestGetResearchStrategy:+ """Tests for get_research_strategy (lines 173-195)."""++ @patch(+ "local_deep_research.web.services.research_service.get_user_db_session"+ )+ def test_returns_strategy_name_when_found(self, mock_get_session):+ session = MagicMock()+ strategy_obj = MagicMock()+ strategy_obj.strategy_name = "comprehensive"+ session.query.return_value.filter_by.return_value.first.return_value = (+ strategy_obj+ )++ @contextmanager+ def session_ctx(username):+ yield session++ mock_get_session.side_effect = session_ctx++ from local_deep_research.web.services.research_service import (+ get_research_strategy,+ )++ result = get_research_strategy(42, username="alice")+ assert result == "comprehensive"++ @patch(+ "local_deep_research.web.services.research_service.get_user_db_session"+ )+ def test_returns_none_when_not_found(self, mock_get_session):+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ @contextmanager+ def session_ctx(username):+ yield session++ mock_get_session.side_effect = session_ctx++ from local_deep_research.web.services.research_service import (+ get_research_strategy,+ )++ result = get_research_strategy(42, username="bob")+ assert result is None++ @patch(+ "local_deep_research.web.services.research_service.get_user_db_session"+ )+ @patch("local_deep_research.web.services.research_service.logger")+ def test_handles_exception_returns_none(+ self, mock_logger, mock_get_session+ ):+ mock_get_session.side_effect = RuntimeError("DB error")++ from local_deep_research.web.services.research_service import (+ get_research_strategy,+ )++ result = get_research_strategy(99)+ assert result is None+ mock_logger.exception.assert_called_once_with(+ "Error getting research strategy"+ )