~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 174 high-value edge case tests across 9 under-tested modules (#2533)
LearningCircuit7321519461b0
diff --git a/tests/citation_handlers/test_citation_handler_edge_cases.py b/tests/citation_handlers/test_citation_handler_edge_cases.pynew file mode 100644index 0000000000..2e9cbb5ca7--- /dev/null+++ b/tests/citation_handlers/test_citation_handler_edge_cases.py@@ -0,0 +1,261 @@+"""High-value edge case tests for citation_handlers module.++Covers gaps not addressed by existing tests:+- _create_documents index assignment and preservation logic+- _format_sources formatting correctness+- StandardCitationHandler prompt construction+- StandardCitationHandler fact-checking toggle+"""++from unittest.mock import MagicMock++from langchain_core.documents import Document++from local_deep_research.citation_handlers.base_citation_handler import (+ BaseCitationHandler,+)+from local_deep_research.citation_handlers.standard_citation_handler import (+ StandardCitationHandler,+)+++class ConcreteCitationHandler(BaseCitationHandler):+ """Concrete implementation for testing base class methods."""++ def analyze_initial(self, query, search_results):+ return {}++ def analyze_followup(self, question, search_results, prev, nr):+ return {}+++class TestCreateDocumentsIndexLogic:+ """Test _create_documents index assignment edge cases."""++ def test_sequential_index_starts_at_one(self):+ """Without nr_of_links offset, indices start at 1."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ results = [+ {"full_content": "content A", "link": "http://a.com", "title": "A"},+ {"full_content": "content B", "link": "http://b.com", "title": "B"},+ ]+ docs = handler._create_documents(results)+ assert docs[0].metadata["index"] == 1+ assert docs[1].metadata["index"] == 2++ def test_nr_of_links_offsets_indices(self):+ """nr_of_links shifts index values."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ results = [+ {"full_content": "content", "link": "http://a.com", "title": "A"},+ ]+ docs = handler._create_documents(results, nr_of_links=10)+ assert docs[0].metadata["index"] == 11++ def test_preserves_existing_index(self):+ """If a result already has an 'index', it is preserved."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ results = [+ {+ "full_content": "content",+ "link": "http://a.com",+ "title": "A",+ "index": "42",+ },+ ]+ docs = handler._create_documents(results)+ assert docs[0].metadata["index"] == 42++ def test_adds_index_to_original_dict(self):+ """_create_documents mutates the original dict to add index."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ results = [+ {"full_content": "content", "link": "http://a.com", "title": "A"},+ ]+ handler._create_documents(results)+ assert "index" in results[0]++ def test_does_not_overwrite_existing_index_in_dict(self):+ """Existing index in dict is not overwritten."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ results = [+ {+ "full_content": "content",+ "link": "http://a.com",+ "title": "A",+ "index": "99",+ },+ ]+ handler._create_documents(results)+ assert results[0]["index"] == "99"++ def test_prefers_full_content_over_snippet(self):+ """full_content is used when both full_content and snippet exist."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ results = [+ {+ "full_content": "full text",+ "snippet": "short text",+ "link": "http://a.com",+ "title": "A",+ },+ ]+ docs = handler._create_documents(results)+ assert docs[0].page_content == "full text"++ def test_falls_back_to_snippet(self):+ """When full_content is missing, snippet is used."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ results = [+ {"snippet": "short text", "link": "http://a.com", "title": "A"},+ ]+ docs = handler._create_documents(results)+ assert docs[0].page_content == "short text"++ def test_empty_list_input(self):+ """Empty list input returns empty list."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ docs = handler._create_documents([])+ assert docs == []++ def test_string_input_returns_empty(self):+ """String input returns empty document list."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ docs = handler._create_documents("some string")+ assert docs == []+++class TestFormatSources:+ """Test _format_sources formatting."""++ def test_formats_with_bracket_numbers(self):+ """Sources are formatted as [N] content."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ docs = [+ Document(+ page_content="Content A",+ metadata={"source": "http://a.com", "title": "A", "index": 1},+ ),+ Document(+ page_content="Content B",+ metadata={"source": "http://b.com", "title": "B", "index": 2},+ ),+ ]+ result = handler._format_sources(docs)+ assert "[1] Content A" in result+ assert "[2] Content B" in result++ def test_sources_separated_by_double_newlines(self):+ """Sources are separated by double newlines."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ docs = [+ Document(+ page_content="A",+ metadata={"source": "", "title": "", "index": 1},+ ),+ Document(+ page_content="B",+ metadata={"source": "", "title": "", "index": 2},+ ),+ ]+ result = handler._format_sources(docs)+ assert "\n\n" in result++ def test_empty_docs_returns_empty(self):+ """Empty document list returns empty string."""+ handler = ConcreteCitationHandler(llm=MagicMock())+ result = handler._format_sources([])+ assert result == ""+++class TestStandardCitationHandlerAnalyzeInitial:+ """Test StandardCitationHandler.analyze_initial."""++ def test_returns_content_and_documents(self):+ """analyze_initial returns dict with 'content' and 'documents' keys."""+ mock_llm = MagicMock()+ mock_llm.invoke.return_value = MagicMock(content="Analysis text")+ handler = StandardCitationHandler(llm=mock_llm)++ results = [+ {+ "full_content": "Source content",+ "link": "http://a.com",+ "title": "A",+ },+ ]+ result = handler.analyze_initial("test query", results)++ assert "content" in result+ assert "documents" in result+ assert len(result["documents"]) == 1++ def test_string_search_results_returns_empty_documents(self):+ """When search_results is a string, documents list is empty."""+ mock_llm = MagicMock()+ mock_llm.invoke.return_value = "text response"+ handler = StandardCitationHandler(llm=mock_llm)++ result = handler.analyze_initial("test query", "string results")+ assert result["documents"] == []++ def test_prompt_includes_query(self):+ """The LLM prompt includes the research query."""+ mock_llm = MagicMock()+ mock_llm.invoke.return_value = MagicMock(content="response")+ handler = StandardCitationHandler(llm=mock_llm)++ handler.analyze_initial("what is quantum computing", [])+ prompt = mock_llm.invoke.call_args[0][0]+ assert "what is quantum computing" in prompt+++class TestStandardCitationHandlerFactChecking:+ """Test fact-checking toggle in analyze_followup."""++ def test_fact_checking_enabled_by_default(self):+ """Fact checking invokes LLM twice when enabled (default)."""+ mock_llm = MagicMock()+ mock_llm.invoke.return_value = MagicMock(content="response")+ handler = StandardCitationHandler(llm=mock_llm)++ results = [+ {"full_content": "content", "link": "http://a.com", "title": "A"},+ ]+ handler.analyze_followup("question", results, "previous knowledge", 0)++ # Should be called twice: once for fact-check, once for analysis+ assert mock_llm.invoke.call_count == 2++ def test_fact_checking_disabled_skips_extra_call(self):+ """When fact_checking disabled, LLM is called only once for main analysis."""+ mock_llm = MagicMock()+ mock_llm.invoke.return_value = MagicMock(content="response")+ handler = StandardCitationHandler(+ llm=mock_llm,+ settings_snapshot={"general.enable_fact_checking": False},+ )++ results = [+ {"full_content": "content", "link": "http://a.com", "title": "A"},+ ]+ handler.analyze_followup("question", results, "previous knowledge", 0)++ # Should be called once: just the main analysis+ assert mock_llm.invoke.call_count == 1++ def test_output_instructions_included_in_followup(self):+ """Custom output instructions are included in the followup prompt."""+ mock_llm = MagicMock()+ mock_llm.invoke.return_value = MagicMock(content="response")+ handler = StandardCitationHandler(+ llm=mock_llm,+ settings_snapshot={+ "general.output_instructions": "Respond in French",+ "general.enable_fact_checking": False,+ },+ )++ handler.analyze_followup("question", [], "prev", 0)+ prompt = mock_llm.invoke.call_args[0][0]+ assert "Respond in French" in promptdiff --git a/tests/domain_classifier/test_classifier_edge_cases.py b/tests/domain_classifier/test_classifier_edge_cases.pynew file mode 100644index 0000000000..f241327761--- /dev/null+++ b/tests/domain_classifier/test_classifier_edge_cases.py@@ -0,0 +1,216 @@+"""High-value edge case tests for the domain_classifier module.++Covers gaps not addressed by existing tests:+- DOMAIN_CATEGORIES structure validation+- DomainClassification model to_dict+- _get_domain_samples with None content_preview+- _build_classification_prompt sample truncation+- classify_all_domains URL parsing and www stripping+"""++from unittest.mock import MagicMock, patch++from local_deep_research.domain_classifier.classifier import (+ DomainClassifier,+ DOMAIN_CATEGORIES,+)+from local_deep_research.domain_classifier.models import DomainClassification+++class TestDomainCategoriesStructure:+ """Validate the DOMAIN_CATEGORIES constant."""++ def test_has_ten_main_categories(self):+ """There should be exactly 10 main categories."""+ assert len(DOMAIN_CATEGORIES) == 10++ def test_no_subcategory_overlap_across_categories(self):+ """No subcategory name appears in more than one main category."""+ all_subcats = []+ for subcats in DOMAIN_CATEGORIES.values():+ all_subcats.extend(subcats)+ # Check for duplicates+ assert len(all_subcats) == len(set(all_subcats))++ def test_other_category_has_unknown(self):+ """The 'Other' category contains 'Unknown' subcategory."""+ assert "Unknown" in DOMAIN_CATEGORIES["Other"]++ def test_all_values_are_lists_of_strings(self):+ """All category values are lists of non-empty strings."""+ for cat, subcats in DOMAIN_CATEGORIES.items():+ assert isinstance(subcats, list), f"{cat} subcategories not a list"+ for s in subcats:+ assert isinstance(s, str) and len(s) > 0+++class TestDomainClassificationModel:+ """Test the DomainClassification SQLAlchemy model."""++ def test_tablename(self):+ """Model uses the expected table name."""+ assert DomainClassification.__tablename__ == "domain_classifications"++ def test_to_dict_has_expected_keys(self):+ """to_dict returns all expected keys."""+ obj = DomainClassification(+ id=1,+ domain="example.com",+ category="Technology",+ subcategory="Software Development",+ confidence=0.9,+ reasoning="test",+ sample_titles='["Title"]',+ sample_count=1,+ )+ d = obj.to_dict()+ expected_keys = {+ "id",+ "domain",+ "category",+ "subcategory",+ "confidence",+ "reasoning",+ "sample_titles",+ "sample_count",+ "created_at",+ "updated_at",+ }+ assert set(d.keys()) == expected_keys++ def test_to_dict_none_timestamps(self):+ """to_dict handles None timestamps gracefully."""+ obj = DomainClassification(+ id=1,+ domain="test.com",+ category="Other",+ )+ obj.created_at = None+ obj.updated_at = None+ d = obj.to_dict()+ assert d["created_at"] is None+ assert d["updated_at"] is None+++class TestGetDomainSamples:+ """Test _get_domain_samples method."""++ @patch(+ "local_deep_research.domain_classifier.classifier.get_user_db_session"+ )+ def test_none_content_preview_returns_none_in_sample(+ self, mock_session_ctx+ ):+ """When content_preview is None, sample preview is None."""+ classifier = DomainClassifier(username="test")++ mock_session = MagicMock()+ mock_resource = MagicMock()+ mock_resource.title = "Test Title"+ mock_resource.url = "http://example.com/page"+ mock_resource.content_preview = None++ mock_session.query.return_value.filter.return_value.limit.return_value.all.return_value = [+ mock_resource+ ]++ samples = classifier._get_domain_samples("example.com", mock_session)+ assert len(samples) == 1+ assert samples[0]["title"] == "Test Title"+ assert samples[0]["preview"] is None++ @patch(+ "local_deep_research.domain_classifier.classifier.get_user_db_session"+ )+ def test_empty_resources_returns_empty_list(self, mock_session_ctx):+ """When no resources match, returns empty list."""+ classifier = DomainClassifier(username="test")+ mock_session = MagicMock()+ mock_session.query.return_value.filter.return_value.limit.return_value.all.return_value = []++ samples = classifier._get_domain_samples("no-match.com", mock_session)+ assert samples == []++ @patch(+ "local_deep_research.domain_classifier.classifier.get_user_db_session"+ )+ def test_none_title_becomes_untitled(self, mock_session_ctx):+ """When resource.title is None, it becomes 'Untitled'."""+ classifier = DomainClassifier(username="test")+ mock_session = MagicMock()+ mock_resource = MagicMock()+ mock_resource.title = None+ mock_resource.url = "http://example.com"+ mock_resource.content_preview = "some preview"+ mock_session.query.return_value.filter.return_value.limit.return_value.all.return_value = [+ mock_resource+ ]++ samples = classifier._get_domain_samples("example.com", mock_session)+ assert samples[0]["title"] == "Untitled"++ @patch(+ "local_deep_research.domain_classifier.classifier.get_user_db_session"+ )+ def test_preview_truncated_to_200_chars(self, mock_session_ctx):+ """content_preview is truncated to 200 characters."""+ classifier = DomainClassifier(username="test")+ mock_session = MagicMock()+ mock_resource = MagicMock()+ mock_resource.title = "Title"+ mock_resource.url = "http://example.com"+ mock_resource.content_preview = "x" * 500+ mock_session.query.return_value.filter.return_value.limit.return_value.all.return_value = [+ mock_resource+ ]++ samples = classifier._get_domain_samples("example.com", mock_session)+ assert len(samples[0]["preview"]) == 200+++class TestBuildClassificationPromptEdgeCases:+ """Test _build_classification_prompt edge cases."""++ def test_samples_without_preview_omit_preview_line(self):+ """Samples with no preview don't include a Preview line."""+ classifier = DomainClassifier(username="test")+ samples = [+ {"title": "Test", "url": "http://example.com", "preview": None}+ ]+ prompt = classifier._build_classification_prompt("example.com", samples)+ assert "Preview:" not in prompt++ def test_only_first_five_samples_included(self):+ """Only the first 5 samples are included in the prompt."""+ classifier = DomainClassifier(username="test")+ samples = [+ {+ "title": f"Title {i}",+ "url": f"http://example.com/{i}",+ "preview": f"preview {i}",+ }+ for i in range(10)+ ]+ prompt = classifier._build_classification_prompt("example.com", samples)+ assert "Title 4" in prompt+ assert (+ "Title 5" not in prompt+ ) # 0-indexed: 5th sample (index 4) is last++ def test_preview_truncated_at_100_chars(self):+ """Sample previews in prompt are truncated to 100 chars."""+ classifier = DomainClassifier(username="test")+ long_preview = "a" * 200+ samples = [+ {"title": "T", "url": "http://ex.com", "preview": long_preview}+ ]+ prompt = classifier._build_classification_prompt("example.com", samples)+ # The prompt should contain the truncated preview followed by "..."+ assert "a" * 100 + "..." in prompt++ def test_all_main_categories_in_prompt(self):+ """All main category names appear in the prompt."""+ classifier = DomainClassifier(username="test")+ prompt = classifier._build_classification_prompt("test.com", [])+ for category in DOMAIN_CATEGORIES.keys():+ assert category in promptdiff --git a/tests/error_handling/test_error_handling_high_value.py b/tests/error_handling/test_error_handling_high_value.pynew file mode 100644index 0000000000..b5803c0bb4--- /dev/null+++ b/tests/error_handling/test_error_handling_high_value.py@@ -0,0 +1,286 @@+"""High-value tests for error_handling and text_processing modules.++Covers gaps not addressed by existing tests:+- ErrorReporter._extract_service_name for all known services+- ErrorReporter severity and recoverability for all categories+- ErrorReportGenerator._make_error_user_friendly pattern matching+- ErrorReportGenerator.generate_quick_error_summary+- ErrorReportGenerator._get_technical_context+- text_cleaner.remove_surrogates fallback path+"""++from unittest.mock import MagicMock++from local_deep_research.error_handling.error_reporter import (+ ErrorReporter,+ ErrorCategory,+)+from local_deep_research.error_handling.report_generator import (+ ErrorReportGenerator,+)+from local_deep_research.text_processing.text_cleaner import remove_surrogates+++class TestExtractServiceName:+ """Test ErrorReporter._extract_service_name."""++ def test_detects_openai(self):+ reporter = ErrorReporter()+ assert (+ reporter._extract_service_name("OpenAI API error 429") == "Openai"+ )++ def test_detects_anthropic(self):+ reporter = ErrorReporter()+ assert (+ reporter._extract_service_name("Anthropic rate limit")+ == "Anthropic"+ )++ def test_detects_ollama(self):+ reporter = ErrorReporter()+ assert (+ reporter._extract_service_name("Ollama connection refused")+ == "Ollama"+ )++ def test_detects_google(self):+ reporter = ErrorReporter()+ assert (+ reporter._extract_service_name("Google API quota exceeded")+ == "Google"+ )++ def test_detects_tavily(self):+ reporter = ErrorReporter()+ assert (+ reporter._extract_service_name("Tavily search failed") == "Tavily"+ )++ def test_detects_brave(self):+ reporter = ErrorReporter()+ assert reporter._extract_service_name("Brave API error") == "Brave"++ def test_returns_default_for_unknown(self):+ reporter = ErrorReporter()+ assert reporter._extract_service_name("Unknown error") == "API Service"++ def test_case_insensitive_detection(self):+ reporter = ErrorReporter()+ assert (+ reporter._extract_service_name("SEARXNG configuration error")+ == "Searxng"+ )+++class TestSeverityAndRecoverability:+ """Test severity and recoverability for all error categories."""++ def test_all_categories_have_severity(self):+ """Every ErrorCategory has a defined severity."""+ reporter = ErrorReporter()+ for cat in ErrorCategory:+ severity = reporter._determine_severity(cat)+ assert severity in ("low", "medium", "high")++ def test_all_categories_have_recoverability(self):+ """Every ErrorCategory has a recoverability value."""+ reporter = ErrorReporter()+ for cat in ErrorCategory:+ recoverable = reporter._is_recoverable(cat)+ assert isinstance(recoverable, bool)++ def test_unknown_error_is_not_recoverable(self):+ reporter = ErrorReporter()+ assert reporter._is_recoverable(ErrorCategory.UNKNOWN_ERROR) is False++ def test_connection_error_is_recoverable(self):+ reporter = ErrorReporter()+ assert reporter._is_recoverable(ErrorCategory.CONNECTION_ERROR) is True++ def test_rate_limit_is_medium_severity(self):+ reporter = ErrorReporter()+ assert (+ reporter._determine_severity(ErrorCategory.RATE_LIMIT_ERROR)+ == "medium"+ )+++class TestUserFriendlyErrorMessages:+ """Test ErrorReportGenerator._make_error_user_friendly."""++ def test_max_workers_replacement(self):+ gen = ErrorReportGenerator()+ result = gen._make_error_user_friendly(+ "max_workers must be greater than 0"+ )+ assert "LLM failed to generate search questions" in result+ assert "Technical error:" in result++ def test_connection_refused_replacement(self):+ gen = ErrorReportGenerator()+ result = gen._make_error_user_friendly("Connection refused [Errno 111]")+ assert "Cannot connect to the LLM service" in result++ def test_github_search_too_long(self):+ gen = ErrorReportGenerator()+ result = gen._make_error_user_friendly(+ "The search is longer than 256 characters"+ )+ assert "too long for GitHub" in result++ def test_model_not_found_ollama(self):+ gen = ErrorReportGenerator()+ result = gen._make_error_user_friendly("Model xyz not found in Ollama")+ assert "isn't available in Ollama" in result++ def test_no_auth_credentials(self):+ gen = ErrorReportGenerator()+ result = gen._make_error_user_friendly(+ "No auth credentials found for API"+ )+ assert "API key is missing" in result++ def test_readonly_database(self):+ gen = ErrorReportGenerator()+ result = gen._make_error_user_friendly(+ "Attempt to write readonly database"+ )+ assert "Permission issue" in result++ def test_unmatched_error_returns_original(self):+ gen = ErrorReportGenerator()+ original = "Some completely unique error that doesn't match any pattern"+ result = gen._make_error_user_friendly(original)+ assert result == original++ def test_no_search_results_replacement(self):+ gen = ErrorReportGenerator()+ result = gen._make_error_user_friendly(+ "No search results found for query"+ )+ assert "No search results were found" in result+++class TestGenerateQuickErrorSummary:+ """Test ErrorReportGenerator.generate_quick_error_summary."""++ def test_returns_dict_with_expected_keys(self):+ gen = ErrorReportGenerator()+ result = gen.generate_quick_error_summary("Connection refused")+ expected_keys = {"title", "category", "severity", "recoverable"}+ assert set(result.keys()) == expected_keys++ def test_connection_error_summary(self):+ gen = ErrorReportGenerator()+ result = gen.generate_quick_error_summary(+ "Connection refused [Errno 111]"+ )+ assert result["category"] == "connection_error"+ assert result["title"] == "Connection Issue"+ assert result["severity"] == "high"+ assert result["recoverable"] is True++ def test_unknown_error_summary(self):+ gen = ErrorReportGenerator()+ result = gen.generate_quick_error_summary(+ "Something totally unknown happened"+ )+ assert result["category"] == "unknown_error"+ assert result["recoverable"] is False+++class TestGetTechnicalContext:+ """Test ErrorReportGenerator._get_technical_context."""++ def test_empty_when_no_partial_results(self):+ gen = ErrorReportGenerator()+ result = gen._get_technical_context({"category": None}, None)+ assert result == ""++ def test_includes_start_time(self):+ gen = ErrorReportGenerator()+ partial = {"start_time": "2024-01-01T00:00:00"}+ result = gen._get_technical_context({}, partial)+ assert "Start Time" in result++ def test_includes_model_config(self):+ gen = ErrorReportGenerator()+ partial = {+ "model_config": {"model_name": "gpt-4", "provider": "openai"}+ }+ result = gen._get_technical_context({}, partial)+ assert "gpt-4" in result+ assert "openai" in result++ def test_includes_search_config(self):+ gen = ErrorReportGenerator()+ partial = {"search_config": {"engine": "duckduckgo", "max_results": 10}}+ result = gen._get_technical_context({}, partial)+ assert "duckduckgo" in result++ def test_connection_category_context(self):+ gen = ErrorReportGenerator()+ mock_cat = MagicMock()+ mock_cat.value = "connection_error"+ result = gen._get_technical_context({"category": mock_cat}, {})+ assert "Network Error" in result+++class TestGenerateErrorReportIntegration:+ """Integration tests for generate_error_report."""++ def test_report_contains_header(self):+ gen = ErrorReportGenerator()+ report = gen.generate_error_report("test error", "test query")+ assert "# ⚠️ Research Failed" in report++ def test_report_contains_help_links(self):+ gen = ErrorReportGenerator()+ report = gen.generate_error_report("test error", "test query")+ assert "Discord" in report+ assert "GitHub Issues" in report++ def test_report_with_partial_results_has_details(self):+ gen = ErrorReportGenerator()+ partial = {+ "current_knowledge": "A" * 100, # > 50 chars+ "findings": [{"content": "Finding 1", "phase": "Phase 1"}],+ }+ report = gen.generate_error_report(+ "test error", "test query", partial_results=partial+ )+ assert "Partial Results" in report+++class TestRemoveSurrogatesFallbackPath:+ """Test text_cleaner.remove_surrogates edge cases."""++ def test_falsy_zero_returns_zero(self):+ """remove_surrogates returns falsy input as-is."""+ result = remove_surrogates(0)+ assert result == 0++ def test_falsy_empty_string_returns_empty(self):+ result = remove_surrogates("")+ assert result == ""++ def test_falsy_none_returns_none(self):+ result = remove_surrogates(None)+ assert result is None++ def test_normal_ascii_unchanged(self):+ result = remove_surrogates("Hello, World!")+ assert result == "Hello, World!"++ def test_emoji_preserved(self):+ """Valid emoji characters are preserved."""+ result = remove_surrogates("Test 🎉 emoji 🚀")+ assert "🎉" in result+ assert "🚀" in result++ def test_mixed_cjk_preserved(self):+ """Chinese/Japanese/Korean characters preserved."""+ result = remove_surrogates("Hello 你好 こんにちは")+ assert "你好" in result+ assert "こんにちは" in resultdiff --git a/tests/followup_research/test_followup_edge_cases.py b/tests/followup_research/test_followup_edge_cases.pynew file mode 100644index 0000000000..c00d19ad31--- /dev/null+++ b/tests/followup_research/test_followup_edge_cases.py@@ -0,0 +1,271 @@+"""High-value edge case tests for followup_research module.++Covers gaps not addressed by existing test_models.py and test_service.py:+- perform_followup fallback context when parent missing+- prepare_research_context field mapping completeness+- FollowUpRequest/Response field types and boundary values+- Service interaction with various parent data shapes+"""++from unittest.mock import patch, MagicMock++from local_deep_research.followup_research.models import (+ FollowUpRequest,+ FollowUpResponse,+)+from local_deep_research.followup_research.service import (+ FollowUpResearchService,+)+++class TestFollowUpRequestEdgeCases:+ """Edge cases for FollowUpRequest dataclass."""++ def test_negative_max_iterations_allowed(self):+ """Dataclass does not validate; negative values pass through."""+ req = FollowUpRequest(+ parent_research_id="123", question="test", max_iterations=-1+ )+ assert req.max_iterations == -1++ def test_zero_questions_per_iteration(self):+ """Zero questions_per_iteration is accepted (no validation)."""+ req = FollowUpRequest(+ parent_research_id="123", question="test", questions_per_iteration=0+ )+ d = req.to_dict()+ assert d["questions_per_iteration"] == 0++ def test_to_dict_returns_all_five_keys(self):+ """Verify to_dict returns exactly the expected keys."""+ req = FollowUpRequest(parent_research_id="p1", question="q1")+ d = req.to_dict()+ expected_keys = {+ "parent_research_id",+ "question",+ "strategy",+ "max_iterations",+ "questions_per_iteration",+ }+ assert set(d.keys()) == expected_keys++ def test_custom_strategy_round_trips(self):+ """Non-default strategy value round-trips through to_dict."""+ req = FollowUpRequest(+ parent_research_id="p1", question="q1", strategy="custom-strat"+ )+ assert req.to_dict()["strategy"] == "custom-strat"+++class TestFollowUpResponseEdgeCases:+ """Edge cases for FollowUpResponse dataclass."""++ def test_to_dict_returns_all_seven_keys(self):+ """Verify to_dict returns exactly the expected keys."""+ resp = FollowUpResponse(+ research_id="r1",+ question="q1",+ answer="a1",+ sources_used=[],+ parent_context_used=False,+ reused_links_count=0,+ new_links_count=0,+ )+ expected_keys = {+ "research_id",+ "question",+ "answer",+ "sources_used",+ "parent_context_used",+ "reused_links_count",+ "new_links_count",+ }+ assert set(resp.to_dict().keys()) == expected_keys++ def test_sources_used_preserves_dict_structure(self):+ """Source dicts are passed through to_dict without modification."""+ sources = [{"url": "http://example.com", "title": "Ex"}]+ resp = FollowUpResponse(+ research_id="r1",+ question="q1",+ answer="a1",+ sources_used=sources,+ parent_context_used=True,+ reused_links_count=1,+ new_links_count=0,+ )+ assert resp.to_dict()["sources_used"] is sources++ def test_large_link_counts(self):+ """Large link counts are stored correctly."""+ resp = FollowUpResponse(+ research_id="r1",+ question="q1",+ answer="a1",+ sources_used=[],+ parent_context_used=True,+ reused_links_count=999999,+ new_links_count=888888,+ )+ d = resp.to_dict()+ assert d["reused_links_count"] == 999999+ assert d["new_links_count"] == 888888+++class TestPerformFollowupEdgeCases:+ """Tests for FollowUpResearchService.perform_followup edge cases."""++ @patch.object(FollowUpResearchService, "prepare_research_context")+ def test_perform_followup_empty_context_uses_fallback(self, mock_prepare):+ """When prepare_research_context returns {}, perform_followup builds fallback context."""+ mock_prepare.return_value = {}+ service = FollowUpResearchService(username="testuser")+ request = FollowUpRequest(+ parent_research_id="missing-id", question="What next?"+ )++ result = service.perform_followup(request)++ # Should still produce valid research params+ assert result["query"] == "What next?"+ assert result["strategy"] == "contextual-followup"+ assert result["research_context"]["parent_research_id"] == "missing-id"+ assert result["research_context"]["past_links"] == []+ assert result["research_context"]["past_findings"] == ""++ @patch.object(FollowUpResearchService, "prepare_research_context")+ def test_perform_followup_preserves_delegate_strategy(self, mock_prepare):+ """The delegate_strategy from the request is passed through."""+ mock_prepare.return_value = {+ "parent_research_id": "p1",+ "past_links": [],+ "past_findings": "",+ "report_content": "",+ "resources": [],+ "all_links_of_system": [],+ "original_query": "orig",+ }+ service = FollowUpResearchService(username="testuser")+ request = FollowUpRequest(+ parent_research_id="p1",+ question="Follow up",+ strategy="evidence-based",+ )++ result = service.perform_followup(request)+ assert result["delegate_strategy"] == "evidence-based"++ @patch.object(FollowUpResearchService, "prepare_research_context")+ def test_perform_followup_passes_iterations_config(self, mock_prepare):+ """max_iterations and questions_per_iteration flow through to params."""+ mock_prepare.return_value = {+ "parent_research_id": "p1",+ "past_links": [],+ "past_findings": "",+ "report_content": "",+ "resources": [],+ "all_links_of_system": [],+ "original_query": "",+ }+ service = FollowUpResearchService(username="testuser")+ request = FollowUpRequest(+ parent_research_id="p1",+ question="q",+ max_iterations=5,+ questions_per_iteration=10,+ )++ result = service.perform_followup(request)+ assert result["max_iterations"] == 5+ assert result["questions_per_iteration"] == 10+++class TestPrepareResearchContextFieldMapping:+ """Verify prepare_research_context maps parent_data fields correctly."""++ @patch.object(FollowUpResearchService, "load_parent_research")+ def test_all_context_keys_present(self, mock_load):+ """Context dict contains all expected keys."""+ mock_load.return_value = {+ "research_id": "r1",+ "query": "original query",+ "report_content": "report text",+ "formatted_findings": "findings text",+ "strategy": "some-strategy",+ "resources": [{"url": "http://example.com"}],+ "all_links_of_system": [{"url": "http://example.com"}],+ }+ service = FollowUpResearchService(username="testuser")+ ctx = service.prepare_research_context("r1")++ expected_keys = {+ "parent_research_id",+ "past_links",+ "past_findings",+ "report_content",+ "resources",+ "all_links_of_system",+ "original_query",+ }+ assert set(ctx.keys()) == expected_keys++ @patch.object(FollowUpResearchService, "load_parent_research")+ def test_missing_optional_fields_default_to_empty(self, mock_load):+ """When parent_data lacks optional keys, defaults are empty strings/lists."""+ mock_load.return_value = {+ "research_id": "r1",+ # Missing: formatted_findings, report_content, resources, all_links_of_system, query+ }+ service = FollowUpResearchService(username="testuser")+ ctx = service.prepare_research_context("r1")++ assert ctx["past_findings"] == ""+ assert ctx["report_content"] == ""+ assert ctx["resources"] == []+ assert ctx["original_query"] == ""+++class TestLoadParentResearchMetaFallback:+ """Tests for load_parent_research meta sources fallback paths."""++ @patch("local_deep_research.followup_research.service.get_user_db_session")+ def test_load_with_meta_sources_key(self, mock_session_ctx):+ """When DB has no sources but research_meta has 'sources' key, it's used."""+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(return_value=False)++ mock_research = MagicMock()+ mock_research.id = "r1"+ mock_research.query = "test query"+ mock_research.report_content = "report"+ mock_research.research_meta = {+ "sources": [{"url": "http://example.com", "title": "Test"}],+ "formatted_findings": "findings",+ "strategy_name": "test-strategy",+ }+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ # Mock ResearchSourcesService+ with patch(+ "local_deep_research.followup_research.service.ResearchSourcesService"+ ) as mock_svc_cls:+ mock_svc = MagicMock()+ mock_svc_cls.return_value = mock_svc+ # First call: no sources in DB+ # After save: return the sources+ mock_svc.get_research_sources.side_effect = [+ [], # First call: empty+ [{"url": "http://example.com", "title": "Test"}], # After save+ ]+ mock_svc.save_research_sources.return_value = 1++ service = FollowUpResearchService(username="testuser")+ result = service.load_parent_research("r1")++ assert result["query"] == "test query"+ assert result["strategy"] == "test-strategy"+ assert len(result["resources"]) == 1+ mock_svc.save_research_sources.assert_called_once()diff --git a/tests/notifications/test_notifications_high_value.py b/tests/notifications/test_notifications_high_value.pynew file mode 100644index 0000000000..2173a4b144--- /dev/null+++ b/tests/notifications/test_notifications_high_value.py@@ -0,0 +1,260 @@+"""High-value tests for the notifications module.++Covers gaps not addressed by existing tests:+- RateLimiter per-user limits, cleanup, and reset+- Queue helper functions with mocked dependencies+- NotificationManager rate limit integration+- Exception hierarchy+"""++from datetime import datetime, timezone, timedelta+from unittest.mock import patch, MagicMock++from local_deep_research.notifications.exceptions import (+ NotificationError,+ ServiceError,+ SendError,+ RateLimitError,+)+from local_deep_research.notifications.manager import (+ RateLimiter,+)+from local_deep_research.notifications.templates import EventType+from local_deep_research.notifications.queue_helpers import (+ send_queue_notification,+ send_queue_failed_notification,+)+++class TestExceptionHierarchy:+ """Test notification exception class hierarchy."""++ def test_service_error_is_notification_error(self):+ """ServiceError inherits from NotificationError."""+ assert issubclass(ServiceError, NotificationError)++ def test_send_error_is_notification_error(self):+ """SendError inherits from NotificationError."""+ assert issubclass(SendError, NotificationError)++ def test_rate_limit_error_is_notification_error(self):+ """RateLimitError inherits from NotificationError."""+ assert issubclass(RateLimitError, NotificationError)++ def test_notification_error_is_exception(self):+ """NotificationError inherits from Exception."""+ assert issubclass(NotificationError, Exception)++ def test_exception_message_preserved(self):+ """Exception message is accessible via str()."""+ err = ServiceError("test message")+ assert str(err) == "test message"+++class TestRateLimiterPerUserLimits:+ """Test RateLimiter per-user rate limit configuration."""++ def test_default_limits_used_when_no_user_config(self):+ """Users without explicit config get default limits."""+ limiter = RateLimiter(max_per_hour=5, max_per_day=20)+ h, d = limiter.get_user_limits("unknown_user")+ assert h == 5+ assert d == 20++ def test_set_user_limits_applies_to_specific_user(self):+ """Per-user limits override defaults for that user."""+ limiter = RateLimiter(max_per_hour=10, max_per_day=50)+ limiter.set_user_limits("user_a", max_per_hour=3, max_per_day=15)++ h, d = limiter.get_user_limits("user_a")+ assert h == 3+ assert d == 15++ # Other user still gets defaults+ h2, d2 = limiter.get_user_limits("user_b")+ assert h2 == 10+ assert d2 == 50++ def test_user_limits_enforced_per_user(self):+ """One user hitting limit doesn't affect another."""+ limiter = RateLimiter(max_per_hour=100, max_per_day=100)+ limiter.set_user_limits("limited_user", max_per_hour=2, max_per_day=100)++ assert limiter.is_allowed("limited_user") is True+ assert limiter.is_allowed("limited_user") is True+ assert limiter.is_allowed("limited_user") is False # Hit hourly limit++ # Other user is unaffected+ assert limiter.is_allowed("other_user") is True++ def test_daily_limit_enforced(self):+ """Daily limit blocks after enough notifications."""+ limiter = RateLimiter(max_per_hour=100, max_per_day=3)++ assert limiter.is_allowed("user1") is True+ assert limiter.is_allowed("user1") is True+ assert limiter.is_allowed("user1") is True+ assert limiter.is_allowed("user1") is False # Hit daily limit+++class TestRateLimiterReset:+ """Test RateLimiter reset functionality."""++ def test_reset_specific_user(self):+ """Resetting a user clears their counts."""+ limiter = RateLimiter(max_per_hour=2, max_per_day=10)+ limiter.is_allowed("user1")+ limiter.is_allowed("user1")+ assert limiter.is_allowed("user1") is False++ limiter.reset("user1")+ assert limiter.is_allowed("user1") is True++ def test_reset_all_users(self):+ """Resetting with None clears all users."""+ limiter = RateLimiter(max_per_hour=1, max_per_day=10)+ limiter.is_allowed("user1")+ limiter.is_allowed("user2")++ limiter.reset()+ assert limiter.is_allowed("user1") is True+ assert limiter.is_allowed("user2") is True++ def test_reset_nonexistent_user_does_not_raise(self):+ """Resetting a user with no history doesn't raise."""+ limiter = RateLimiter()+ limiter.reset("nonexistent") # Should not raise+++class TestRateLimiterCleanup:+ """Test RateLimiter inactive user cleanup."""++ def test_cleanup_removes_inactive_users(self):+ """Users with no activity for >7 days are cleaned up."""+ limiter = RateLimiter(+ max_per_hour=100, max_per_day=100, cleanup_interval_hours=0+ )+ # Force _last_cleanup to be old so cleanup triggers+ limiter._last_cleanup = datetime.now(timezone.utc) - timedelta(hours=25)++ # Add old entries directly+ old_time = datetime.now(timezone.utc) - timedelta(days=8)+ limiter._hourly_counts["old_user"] = MagicMock()+ limiter._hourly_counts["old_user"].__iter__ = MagicMock(+ return_value=iter([old_time])+ )+ limiter._hourly_counts["old_user"].__add__ = MagicMock(+ return_value=[old_time]+ )+ limiter._daily_counts["old_user"] = MagicMock()+ limiter._daily_counts["old_user"].__iter__ = MagicMock(+ return_value=iter([old_time])+ )+ limiter._daily_counts["old_user"].__add__ = MagicMock(+ return_value=[old_time]+ )++ # Trigger cleanup via is_allowed for a different user+ limiter.is_allowed("active_user")++ # old_user should be cleaned up+ assert "old_user" not in limiter._hourly_counts+++class TestQueueHelperFunctions:+ """Test queue notification helper functions."""++ @patch(+ "local_deep_research.notifications.queue_helpers.NotificationManager"+ )+ def test_send_queue_notification_calls_manager(self, mock_manager_cls):+ """send_queue_notification creates manager and calls send_notification."""+ mock_manager = MagicMock()+ mock_manager.send_notification.return_value = True+ mock_manager_cls.return_value = mock_manager++ result = send_queue_notification(+ username="user1",+ research_id="r1",+ query="test query",+ settings_snapshot={"key": "val"},+ position=3,+ )++ assert result is True+ mock_manager.send_notification.assert_called_once()+ call_kwargs = mock_manager.send_notification.call_args+ assert call_kwargs[1]["event_type"] == EventType.RESEARCH_QUEUED+ context = call_kwargs[1]["context"]+ assert context["position"] == 3++ @patch(+ "local_deep_research.notifications.queue_helpers.NotificationManager"+ )+ def test_send_queue_notification_without_position(self, mock_manager_cls):+ """send_queue_notification omits position when not provided."""+ mock_manager = MagicMock()+ mock_manager.send_notification.return_value = True+ mock_manager_cls.return_value = mock_manager++ send_queue_notification(+ username="user1",+ research_id="r1",+ query="test",+ settings_snapshot={},+ )++ context = mock_manager.send_notification.call_args[1]["context"]+ assert "position" not in context++ @patch(+ "local_deep_research.notifications.queue_helpers.NotificationManager"+ )+ def test_send_queue_notification_handles_exception(self, mock_manager_cls):+ """send_queue_notification returns False on exception."""+ mock_manager_cls.side_effect = Exception("init failed")++ result = send_queue_notification(+ username="user1",+ research_id="r1",+ query="test",+ settings_snapshot={},+ )+ assert result is False++ def test_send_queue_failed_notification_no_snapshot_returns_false(self):+ """send_queue_failed_notification returns False when no settings_snapshot."""+ result = send_queue_failed_notification(+ username="user1",+ research_id="r1",+ query="test",+ error_message="error",+ settings_snapshot=None,+ )+ assert result is False++ @patch(+ "local_deep_research.notifications.queue_helpers.NotificationManager"+ )+ def test_send_queue_failed_includes_error_in_context(+ self, mock_manager_cls+ ):+ """send_queue_failed_notification includes error in context."""+ mock_manager = MagicMock()+ mock_manager.send_notification.return_value = True+ mock_manager_cls.return_value = mock_manager++ send_queue_failed_notification(+ username="user1",+ research_id="r1",+ query="test",+ error_message="Something went wrong",+ settings_snapshot={"key": "val"},+ )++ context = mock_manager.send_notification.call_args[1]["context"]+ assert context["error"] == "Something went wrong"+ assert (+ mock_manager.send_notification.call_args[1]["event_type"]+ == EventType.RESEARCH_FAILED+ )diff --git a/tests/research_scheduler/test_scheduler_edge_cases.py b/tests/research_scheduler/test_scheduler_edge_cases.pynew file mode 100644index 0000000000..34bee4953e--- /dev/null+++ b/tests/research_scheduler/test_scheduler_edge_cases.py@@ -0,0 +1,174 @@+"""High-value edge case tests for research_scheduler module.++Covers gaps not addressed by existing tests:+- DocumentSchedulerUtil error handling in get_status+- Route blueprint registration and name+- Singleton pattern for get_document_scheduler+- trigger_manual_run error handling+"""++from unittest.mock import MagicMock, patch+++class TestDocumentSchedulerUtilEdgeCases:+ """Edge cases for DocumentSchedulerUtil."""++ def test_module_importable(self):+ """research_scheduler.document_scheduler module is importable."""+ from local_deep_research.research_scheduler import document_scheduler++ assert document_scheduler is not None++ @patch(+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler"+ )+ def test_get_status_error_returns_error_dict(self, mock_get_scheduler):+ """When scheduler raises, get_status returns error dict."""+ from local_deep_research.research_scheduler.document_scheduler import (+ DocumentSchedulerUtil,+ )++ mock_get_scheduler.side_effect = Exception("Scheduler error")++ util = DocumentSchedulerUtil()+ result = util.get_status("test_user")++ assert isinstance(result, dict)+ assert "error" in result+ assert result["is_running"] is False++ @patch(+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler"+ )+ def test_get_status_error_dict_has_all_keys(self, mock_get_scheduler):+ """Error dict from get_status has all expected keys."""+ from local_deep_research.research_scheduler.document_scheduler import (+ DocumentSchedulerUtil,+ )++ mock_get_scheduler.side_effect = Exception("Scheduler error")++ util = DocumentSchedulerUtil()+ result = util.get_status("test_user")++ expected_keys = {+ "error",+ "is_running",+ "last_run_time",+ "next_run_time",+ "total_processed",+ "currently_processing",+ "processing_ids",+ "settings",+ }+ assert set(result.keys()) == expected_keys++ @patch(+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler"+ )+ def test_get_status_error_dict_types(self, mock_get_scheduler):+ """Error dict values have correct types."""+ from local_deep_research.research_scheduler.document_scheduler import (+ DocumentSchedulerUtil,+ )++ mock_get_scheduler.side_effect = Exception("error")++ util = DocumentSchedulerUtil()+ result = util.get_status("test_user")++ assert isinstance(result["processing_ids"], list)+ assert isinstance(result["settings"], dict)+ assert isinstance(result["total_processed"], int)++ @patch(+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler"+ )+ def test_trigger_manual_run_error_returns_tuple(self, mock_get_scheduler):+ """When trigger fails, returns (False, message) tuple."""+ from local_deep_research.research_scheduler.document_scheduler import (+ DocumentSchedulerUtil,+ )++ mock_get_scheduler.side_effect = Exception("error")++ util = DocumentSchedulerUtil()+ success, message = util.trigger_manual_run("test_user")++ assert success is False+ assert "Failed" in message++ @patch(+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler"+ )+ def test_trigger_manual_run_success(self, mock_get_scheduler):+ """When trigger succeeds, returns (True, message) tuple."""+ from local_deep_research.research_scheduler.document_scheduler import (+ DocumentSchedulerUtil,+ )++ mock_scheduler = MagicMock()+ mock_scheduler.trigger_document_processing.return_value = True+ mock_get_scheduler.return_value = mock_scheduler++ util = DocumentSchedulerUtil()+ success, message = util.trigger_manual_run("test_user")++ assert success is True+ assert "successfully" in message+++class TestSchedulerRouteBlueprint:+ """Test research_scheduler route blueprint."""++ def test_blueprint_importable(self):+ """Scheduler blueprint is importable."""+ from local_deep_research.research_scheduler.routes import scheduler_bp++ assert scheduler_bp is not None++ def test_blueprint_name(self):+ """Blueprint has the expected name."""+ from local_deep_research.research_scheduler.routes import scheduler_bp++ assert scheduler_bp.name == "document_scheduler"++ def test_blueprint_has_url_rules(self):+ """Blueprint has registered URL rules."""+ from local_deep_research.research_scheduler.routes import scheduler_bp++ # Deferred URLs are stored in deferred_functions+ assert len(scheduler_bp.deferred_functions) > 0+++class TestDocumentSchedulerSingleton:+ """Test singleton pattern of get_document_scheduler."""++ @patch(+ "local_deep_research.research_scheduler.document_scheduler.get_news_scheduler"+ )+ def test_singleton_returns_same_instance(self, mock_get_scheduler):+ """get_document_scheduler returns same instance on repeated calls."""+ from local_deep_research.research_scheduler.document_scheduler import (+ get_document_scheduler,+ )+ import local_deep_research.research_scheduler.document_scheduler as mod++ # Reset singleton+ mod._scheduler_util_instance = None++ first = get_document_scheduler()+ second = get_document_scheduler()+ assert first is second++ # Cleanup+ mod._scheduler_util_instance = None++ def test_has_expected_methods(self):+ """DocumentSchedulerUtil has get_status and trigger_manual_run."""+ from local_deep_research.research_scheduler.document_scheduler import (+ DocumentSchedulerUtil,+ )++ assert hasattr(DocumentSchedulerUtil, "get_status")+ assert hasattr(DocumentSchedulerUtil, "trigger_manual_run")diff --git a/tests/storage/test_storage_high_value.py b/tests/storage/test_storage_high_value.pynew file mode 100644index 0000000000..59c7f29016--- /dev/null+++ b/tests/storage/test_storage_high_value.py@@ -0,0 +1,323 @@+"""High-value tests for the storage module.++Covers gaps not addressed by existing tests:+- ABC enforcement (cannot instantiate ReportStorage directly)+- DatabaseReportStorage CRUD with mocked session+- FileReportStorage read/write/delete with tmp_path+- Module __all__ exports+"""++import pytest+from unittest.mock import MagicMock++from local_deep_research.storage.base import ReportStorage+from local_deep_research.storage.database import DatabaseReportStorage+from local_deep_research.storage.file import FileReportStorage+from local_deep_research.storage.database_with_file_backup import (+ DatabaseWithFileBackupStorage,+)+++class TestReportStorageABC:+ """Test the abstract base class enforcement."""++ def test_cannot_instantiate_abstract_base_class(self):+ """ReportStorage cannot be instantiated directly."""+ with pytest.raises(TypeError):+ ReportStorage()++ def test_subclass_without_all_methods_raises(self):+ """Incomplete subclass raises TypeError on instantiation."""++ class PartialStorage(ReportStorage):+ def save_report(self, *args, **kwargs):+ pass++ with pytest.raises(TypeError):+ PartialStorage()++ def test_subclass_with_all_methods_is_instantiable(self):+ """A complete subclass can be instantiated."""++ class CompleteStorage(ReportStorage):+ def save_report(self, *a, **kw):+ return True++ def get_report(self, *a, **kw):+ return None++ def get_report_with_metadata(self, *a, **kw):+ return None++ def delete_report(self, *a, **kw):+ return True++ def report_exists(self, *a, **kw):+ return False++ storage = CompleteStorage()+ assert isinstance(storage, ReportStorage)++ def test_all_concrete_classes_inherit_from_base(self):+ """All concrete storage classes are subclasses of ReportStorage."""+ assert issubclass(DatabaseReportStorage, ReportStorage)+ assert issubclass(FileReportStorage, ReportStorage)+ assert issubclass(DatabaseWithFileBackupStorage, ReportStorage)+++class TestDatabaseReportStorageCRUD:+ """Test DatabaseReportStorage CRUD operations with mocked session."""++ def _make_storage(self):+ session = MagicMock()+ return DatabaseReportStorage(session), session++ def test_save_report_not_found_returns_false(self):+ """save_report returns False when research doesn't exist."""+ storage, session = self._make_storage()+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ result = storage.save_report("nonexistent", "content")+ assert result is False++ def test_save_report_updates_content_and_commits(self):+ """save_report sets report_content and calls commit."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ mock_research.research_meta = None+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ result = storage.save_report("r1", "new content")+ assert result is True+ assert mock_research.report_content == "new content"+ session.commit.assert_called_once()++ def test_save_report_updates_existing_metadata(self):+ """save_report merges metadata into existing research_meta."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ # Use a real dict so .update() works as expected+ mock_research.research_meta = {"existing_key": "val"}+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ storage.save_report("r1", "content", metadata={"new_key": "new_val"})+ assert "new_key" in mock_research.research_meta+ assert mock_research.research_meta["new_key"] == "new_val"+ assert mock_research.research_meta["existing_key"] == "val"++ def test_save_report_sets_metadata_when_none(self):+ """save_report sets research_meta when it was None."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ mock_research.research_meta = None+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ storage.save_report("r1", "content", metadata={"key": "val"})+ assert mock_research.research_meta == {"key": "val"}++ def test_save_report_rollback_on_exception(self):+ """save_report calls rollback when commit raises."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ mock_research.research_meta = None+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )+ session.commit.side_effect = Exception("DB error")++ result = storage.save_report("r1", "content")+ assert result is False+ session.rollback.assert_called_once()++ def test_get_report_returns_none_for_missing(self):+ """get_report returns None when research not found."""+ storage, session = self._make_storage()+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ assert storage.get_report("nonexistent") is None++ def test_get_report_returns_none_for_empty_content(self):+ """get_report returns None when report_content is None."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ mock_research.report_content = None+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ assert storage.get_report("r1") is None++ def test_get_report_returns_content(self):+ """get_report returns the report content string."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ mock_research.report_content = "# Report"+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ assert storage.get_report("r1") == "# Report"++ def test_get_report_with_metadata_returns_expected_keys(self):+ """get_report_with_metadata returns all expected keys."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ mock_research.report_content = "content"+ mock_research.research_meta = {"key": "val"}+ mock_research.query = "test query"+ mock_research.mode = "deep"+ mock_research.created_at = "2024-01-01"+ mock_research.completed_at = "2024-01-02"+ mock_research.duration_seconds = 120+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ result = storage.get_report_with_metadata("r1")+ expected_keys = {+ "content",+ "metadata",+ "query",+ "mode",+ "created_at",+ "completed_at",+ "duration_seconds",+ }+ assert set(result.keys()) == expected_keys++ def test_delete_report_sets_content_to_none(self):+ """delete_report nullifies report_content instead of removing the row."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ mock_research.report_content = "content"+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ result = storage.delete_report("r1")+ assert result is True+ assert mock_research.report_content is None+ session.commit.assert_called_once()++ def test_delete_report_returns_false_for_missing(self):+ """delete_report returns False when research not found."""+ storage, session = self._make_storage()+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )++ assert storage.delete_report("nonexistent") is False++ def test_delete_report_rollback_on_exception(self):+ """delete_report calls rollback on commit failure."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )+ session.commit.side_effect = Exception("DB error")++ result = storage.delete_report("r1")+ assert result is False+ session.rollback.assert_called_once()++ def test_report_exists_true(self):+ """report_exists returns True when report with content exists."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ mock_research.report_content = "content"+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ assert storage.report_exists("r1") is True++ def test_report_exists_false_when_no_content(self):+ """report_exists returns False when report_content is None."""+ storage, session = self._make_storage()+ mock_research = MagicMock()+ mock_research.report_content = None+ session.query.return_value.filter_by.return_value.first.return_value = (+ mock_research+ )++ assert storage.report_exists("r1") is False++ def test_report_exists_false_on_exception(self):+ """report_exists returns False on database exception."""+ storage, session = self._make_storage()+ session.query.side_effect = Exception("DB error")++ assert storage.report_exists("r1") is False+++class TestFileReportStoragePaths:+ """Test FileReportStorage path construction and file operations."""++ def test_report_path_ends_with_md(self, tmp_path):+ """Report files use .md extension."""+ storage = FileReportStorage(base_dir=tmp_path)+ path = storage._get_report_path("test-id")+ assert str(path).endswith("test-id.md")++ def test_metadata_path_ends_with_metadata_json(self, tmp_path):+ """Metadata files use _metadata.json suffix."""+ storage = FileReportStorage(base_dir=tmp_path)+ path = storage._get_metadata_path("test-id")+ assert str(path).endswith("test-id_metadata.json")++ def test_report_exists_checks_md_file_only(self, tmp_path):+ """report_exists only checks for the .md file, not metadata."""+ storage = FileReportStorage(base_dir=tmp_path)++ # Create only metadata file+ meta_path = storage._get_metadata_path("test-id")+ meta_path.write_text("{}")++ assert storage.report_exists("test-id") is False++ def test_get_report_returns_none_for_nonexistent(self, tmp_path):+ """get_report returns None when file doesn't exist."""+ storage = FileReportStorage(base_dir=tmp_path)+ assert storage.get_report("nonexistent") is None++ def test_get_report_with_metadata_returns_none_when_no_report(+ self, tmp_path+ ):+ """get_report_with_metadata returns None when no report file exists."""+ storage = FileReportStorage(base_dir=tmp_path)+ assert storage.get_report_with_metadata("nonexistent") is None++ def test_delete_report_returns_false_for_nonexistent(self, tmp_path):+ """delete_report returns False when no report file exists."""+ storage = FileReportStorage(base_dir=tmp_path)+ assert storage.delete_report("nonexistent") is False++ def test_base_dir_created_if_not_exists(self, tmp_path):+ """FileReportStorage creates base_dir including nested dirs."""+ nested = tmp_path / "deep" / "nested" / "dir"+ FileReportStorage(base_dir=nested)+ assert nested.exists()+++class TestModuleExports:+ """Test the storage module exports."""++ def test_storage_init_exports(self):+ """The storage __init__ module exports expected names."""+ import local_deep_research.storage as storage_module++ # Should be able to import key classes+ assert hasattr(storage_module, "ReportStorage") or hasattr(+ storage_module, "get_report_storage"+ )diff --git a/tests/web/queue/test_queue_high_value.py b/tests/web/queue/test_queue_high_value.pynew file mode 100644index 0000000000..eb3b58fd23--- /dev/null+++ b/tests/web/queue/test_queue_high_value.py@@ -0,0 +1,110 @@+"""High-value tests for web/queue module and storage factory.++Covers gaps not addressed by existing tests:+- Storage factory request context singleton helpers+- Storage factory session validation+- QueueManager basic operations+"""++import pytest+from unittest.mock import MagicMock, patch++from local_deep_research.storage.factory import (+ get_report_storage,+ get_request_report_storage,+ set_request_report_storage,+ clear_request_report_storage,+)+++class TestStorageFactoryRequestContext:+ """Test the request-context storage singleton helpers."""++ def test_initial_state_is_none(self):+ """Before any set, get returns None."""+ clear_request_report_storage()+ assert get_request_report_storage() is None++ def test_set_and_get_round_trip(self):+ """set then get returns the same object."""+ mock_storage = MagicMock()+ set_request_report_storage(mock_storage)+ assert get_request_report_storage() is mock_storage+ clear_request_report_storage()++ def test_clear_removes_storage(self):+ """clear sets the singleton back to None."""+ set_request_report_storage(MagicMock())+ clear_request_report_storage()+ assert get_request_report_storage() is None++ def test_set_overwrites_previous(self):+ """Second set overwrites the first."""+ first = MagicMock()+ second = MagicMock()+ set_request_report_storage(first)+ set_request_report_storage(second)+ assert get_request_report_storage() is second+ clear_request_report_storage()++ def test_raises_when_session_is_none(self):+ """get_report_storage raises ValueError when session is None."""+ with pytest.raises(ValueError, match="Database session is required"):+ get_report_storage(session=None)++ @patch("local_deep_research.storage.factory.DatabaseWithFileBackupStorage")+ @patch("local_deep_research.storage.factory.get_setting_from_snapshot")+ def test_explicit_false_skips_settings_lookup(+ self, mock_get_setting, mock_storage_cls+ ):+ """enable_file_backup=False never calls get_setting_from_snapshot."""+ mock_session = MagicMock()+ get_report_storage(session=mock_session, enable_file_backup=False)+ mock_get_setting.assert_not_called()++ @patch("local_deep_research.storage.factory.DatabaseWithFileBackupStorage")+ @patch("local_deep_research.storage.factory.get_setting_from_snapshot")+ def test_explicit_true_skips_settings_lookup(+ self, mock_get_setting, mock_storage_cls+ ):+ """enable_file_backup=True never calls get_setting_from_snapshot."""+ mock_session = MagicMock()+ get_report_storage(session=mock_session, enable_file_backup=True)+ mock_get_setting.assert_not_called()++ @patch("local_deep_research.storage.factory.DatabaseWithFileBackupStorage")+ def test_factory_propagates_session_to_storage(self, mock_storage_cls):+ """Session is passed through to DatabaseWithFileBackupStorage."""+ mock_session = MagicMock()+ get_report_storage(session=mock_session, enable_file_backup=False)+ mock_storage_cls.assert_called_once_with(+ session=mock_session, enable_file_storage=False+ )+++class TestQueueManagerBasics:+ """Test web/queue/manager.py basic operations."""++ def test_manager_import(self):+ """QueueManager can be imported."""+ from local_deep_research.web.queue.manager import QueueManager++ assert QueueManager is not None++ def test_manager_has_expected_methods(self):+ """QueueManager has expected public methods."""+ from local_deep_research.web.queue.manager import QueueManager++ assert hasattr(QueueManager, "add_to_queue")+ assert hasattr(QueueManager, "remove_from_queue")+ assert hasattr(QueueManager, "get_queue_position")+ assert hasattr(QueueManager, "get_user_queue")++ def test_queue_manager_add_to_queue_signature(self):+ """add_to_queue method exists and is callable."""+ from local_deep_research.web.queue.manager import QueueManager+ import inspect++ sig = inspect.signature(QueueManager.add_to_queue)+ # Should have self plus other params+ assert len(sig.parameters) > 1diff --git a/tests/web/warning_checks/test_warning_checks_high_value.py b/tests/web/warning_checks/test_warning_checks_high_value.pynew file mode 100644index 0000000000..1a16b3d95b--- /dev/null+++ b/tests/web/warning_checks/test_warning_checks_high_value.py@@ -0,0 +1,196 @@+"""High-value edge case tests for web/warning_checks module.++Covers gaps not addressed by existing tests:+- check_model_mismatch with various 70b model name patterns+- check_model_mismatch dismissed state+- check_high_context with exact boundary values+- check_context_below_history with single-record percentile+- check_context_truncation_history with zero/negative counts+"""++from unittest.mock import MagicMock++from local_deep_research.web.warning_checks.hardware import (+ check_high_context,+ check_model_mismatch,+ LOCAL_PROVIDERS,+)+from local_deep_research.web.warning_checks.context import (+ check_context_below_history,+ check_context_truncation_history,+)+++class TestCheckModelMismatchEdgeCases:+ """Edge cases for check_model_mismatch."""++ def test_70b_at_end_of_name(self):+ """Detects 70b at the end of model name."""+ result = check_model_mismatch("ollama", "llama3.1-70b", 16384, False)+ assert result is not None+ assert result["type"] == "model_mismatch"++ def test_70b_in_middle_of_name(self):+ """Detects 70b embedded in model name."""+ result = check_model_mismatch(+ "ollama", "meta-llama-70b-instruct", 16384, False+ )+ assert result is not None++ def test_70B_uppercase(self):+ """Case-insensitive detection of 70B."""+ result = check_model_mismatch("ollama", "Llama-70B-Chat", 16384, False)+ assert result is not None++ def test_no_warning_for_7b_model(self):+ """7b model doesn't match the 70b pattern."""+ result = check_model_mismatch("ollama", "llama3-7b", 16384, False)+ assert result is None++ def test_no_warning_for_170b_model(self):+ """170b still contains '70b' substring, so it would match."""+ result = check_model_mismatch("ollama", "model-170b", 16384, False)+ # "170b" contains "70b" so it matches+ assert result is not None++ def test_dismissed_returns_none(self):+ """Dismissed warning returns None."""+ result = check_model_mismatch("ollama", "llama-70b", 16384, True)+ assert result is None++ def test_none_model_returns_none(self):+ """None model string returns None."""+ result = check_model_mismatch("ollama", None, 16384, False)+ assert result is None++ def test_empty_model_returns_none(self):+ """Empty model string returns None."""+ result = check_model_mismatch("ollama", "", 16384, False)+ assert result is None++ def test_model_name_in_message(self):+ """Warning message includes the model name."""+ result = check_model_mismatch(+ "ollama", "llama3-70b-instruct", 16384, False+ )+ assert "llama3-70b-instruct" in result["message"]++ def test_context_in_message(self):+ """Warning message includes the context size."""+ result = check_model_mismatch("ollama", "llama-70b", 32768, False)+ assert "32,768" in result["message"]++ def test_warning_dict_structure(self):+ """Warning dict has all expected keys."""+ result = check_model_mismatch("ollama", "llama-70b", 16384, False)+ expected_keys = {"type", "icon", "title", "message", "dismissKey"}+ assert set(result.keys()) == expected_keys+++class TestCheckHighContextEdgeCases:+ """Additional edge cases for check_high_context."""++ def test_all_local_providers_trigger_at_16384(self):+ """All LOCAL_PROVIDERS trigger warning at high context."""+ for provider in LOCAL_PROVIDERS:+ result = check_high_context(provider, 16384, False)+ assert result is not None, f"{provider} should trigger warning"++ def test_non_local_provider_never_triggers(self):+ """Non-local providers never trigger, even with very high context."""+ for provider in ["openai", "anthropic", "google", "azure"]:+ result = check_high_context(provider, 1000000, False)+ assert result is None, f"{provider} should not trigger warning"++ def test_context_value_in_message(self):+ """Warning message includes formatted context value."""+ result = check_high_context("ollama", 16384, False)+ assert "16,384" in result["message"]++ def test_provider_in_message(self):+ """Warning message includes provider name."""+ result = check_high_context("vllm", 16384, False)+ assert "vllm" in result["message"]+++class TestCheckContextBelowHistoryEdgeCases:+ """Edge cases for check_context_below_history."""++ def test_exactly_five_identical_records(self):+ """With 5 identical records, percentile equals that value."""+ mock_session = MagicMock()+ mock_session.query.return_value.filter.return_value.order_by.return_value.limit.return_value.all.return_value = (+ [(8192,)] * 5+ )++ # Context below that value should warn+ result = check_context_below_history(mock_session, 4096)+ assert result is not None+ assert result["type"] == "context_below_history"++ def test_at_exactly_min_safe_returns_none(self):+ """Context exactly at min_safe returns None (no warning)."""+ mock_session = MagicMock()+ mock_session.query.return_value.filter.return_value.order_by.return_value.limit.return_value.all.return_value = (+ [(8192,)] * 10+ )++ result = check_context_below_history(mock_session, 8192)+ assert result is None++ def test_warning_message_includes_context_values(self):+ """Warning message includes both current and min safe context."""+ mock_session = MagicMock()+ mock_session.query.return_value.filter.return_value.order_by.return_value.limit.return_value.all.return_value = (+ [(16384,)] * 10+ )++ result = check_context_below_history(mock_session, 4096)+ assert "4,096" in result["message"]+ assert "16,384" in result["message"]+++class TestCheckContextTruncationHistoryEdgeCases:+ """Edge cases for check_context_truncation_history."""++ def test_zero_truncation_count_returns_none(self):+ """Zero truncation count means no warning."""+ mock_session = MagicMock()+ mock_session.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 0++ result = check_context_truncation_history(mock_session, 8192)+ assert result is None++ def test_none_truncation_count_returns_none(self):+ """None truncation count returns None."""+ mock_session = MagicMock()+ mock_session.query.return_value.filter.return_value.filter.return_value.scalar.return_value = None++ result = check_context_truncation_history(mock_session, 8192)+ assert result is None++ def test_single_truncation_message(self):+ """Single truncation shows '1 time(s)' in message."""+ mock_session = MagicMock()+ mock_session.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 1++ result = check_context_truncation_history(mock_session, 8192)+ assert result is not None+ assert "1 time(s)" in result["message"]++ def test_large_truncation_count(self):+ """Large truncation count is reported correctly."""+ mock_session = MagicMock()+ mock_session.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 50++ result = check_context_truncation_history(mock_session, 4096)+ assert "50 time(s)" in result["message"]++ def test_warning_dict_structure(self):+ """Warning dict has all expected keys."""+ mock_session = MagicMock()+ mock_session.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 5++ result = check_context_truncation_history(mock_session, 8192)+ expected_keys = {"type", "icon", "title", "message", "dismissKey"}+ assert set(result.keys()) == expected_keys