~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: expand to 120 tests across 5 files — 2x the original scope (#2887)
LearningCircuitdecb58f588b4
diff --git a/tests/benchmarks/test_graders_extra_coverage.py b/tests/benchmarks/test_graders_extra_coverage.pyindex c9f679de64..a1685261a3 100644--- a/tests/benchmarks/test_graders_extra_coverage.py+++ b/tests/benchmarks/test_graders_extra_coverage.py@@ -6,6 +6,10 @@ Targets:- SimpleQA "no" judgment- Batch _grade_results_inner per-item exception- grade_single_result chat_messages path+- extract_answer_from_response: SimpleQA path, BrowseComp with/without fields+- grade_single_result: exception path (grading error)+- _grade_results_inner: browsecomp dataset, progress callback, with existing output file+- get_evaluation_llm: custom config override, openai_endpoint API key from snapshot"""import json@@ -269,3 +273,273 @@ class TestChatMessagesPath:# Verify HumanMessage was used (invoke called with list)call_args = llm.invoke.call_args[0][0]assert isinstance(call_args, list)+++# ---------------------------------------------------------------------------+# extract_answer_from_response+# ---------------------------------------------------------------------------+++class TestExtractAnswerFromResponse:+ def test_simpleqa_strips_citations(self):+ """SimpleQA: citations [1] [2] removed, whole response returned."""+ from local_deep_research.benchmarks.graders import (+ extract_answer_from_response,+ )++ result = extract_answer_from_response(+ "Paris is the capital [1] of France [2].", "simpleqa"+ )+ assert result["extracted_answer"] == "Paris is the capital of France ."+ assert result["confidence"] == "100"++ def test_browsecomp_extracts_answer_and_confidence(self):+ """BrowseComp: extracts Exact Answer and Confidence."""+ from local_deep_research.benchmarks.graders import (+ extract_answer_from_response,+ )++ result = extract_answer_from_response(+ "Exact Answer: The Moon\nConfidence: 95%", "browsecomp"+ )+ assert result["extracted_answer"] == "The Moon"+ assert result["confidence"] == "95"++ def test_browsecomp_no_match(self):+ """BrowseComp: no matching fields → defaults."""+ from local_deep_research.benchmarks.graders import (+ extract_answer_from_response,+ )++ result = extract_answer_from_response("Random text here", "browsecomp")+ assert result["extracted_answer"] == "None"+ assert result["confidence"] == "100"++ def test_browsecomp_no_confidence(self):+ """BrowseComp: answer found but no confidence → default 100."""+ from local_deep_research.benchmarks.graders import (+ extract_answer_from_response,+ )++ result = extract_answer_from_response(+ "Exact Answer: Jupiter", "browsecomp"+ )+ assert result["extracted_answer"] == "Jupiter"+ assert result["confidence"] == "100"+++# ---------------------------------------------------------------------------+# grade_single_result — exception path+# ---------------------------------------------------------------------------+++class TestGradeSingleResultException:+ def test_llm_exception_returns_error(self):+ """LLM raises exception → returns grading_error dict."""+ from local_deep_research.benchmarks.graders import grade_single_result++ llm = MagicMock()+ llm.invoke.side_effect = RuntimeError("API down")++ with patch(f"{MODULE}.get_evaluation_llm", return_value=llm):+ result = grade_single_result(+ {+ "problem": "Q?",+ "correct_answer": "A",+ "response": "R",+ },+ dataset_type="simpleqa",+ )++ assert "grading_error" in result+ assert result["is_correct"] is False+ assert result["graded_confidence"] == "0"+++# ---------------------------------------------------------------------------+# _grade_results_inner — browsecomp + progress callback + existing output+# ---------------------------------------------------------------------------+++class TestGradeResultsInnerBrowsecomp:+ def test_browsecomp_batch(self):+ """Batch grading with browsecomp dataset type."""+ from local_deep_research.benchmarks.graders import _grade_results_inner++ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".jsonl", delete=False+ ) as f:+ f.write(+ json.dumps(+ {+ "problem": "Q1",+ "correct_answer": "A1",+ "response": "R1",+ }+ )+ + "\n"+ )+ results_file = f.name++ output_file = results_file + ".graded"++ llm = MagicMock()+ result_obj = MagicMock()+ result_obj.content = (+ "extracted_final_answer: A1\n"+ "reasoning: Looks correct\n\n"+ "correct: yes\nconfidence: 90"+ )+ llm.invoke.return_value = result_obj++ try:+ results = _grade_results_inner(+ llm, results_file, output_file, "browsecomp", None+ )++ assert len(results) == 1+ assert results[0]["is_correct"] is True+ assert results[0]["graded_confidence"] == "90"+ finally:+ Path(results_file).unlink(missing_ok=True)+ Path(output_file).unlink(missing_ok=True)++ def test_with_progress_callback(self):+ """Progress callback called for each result."""+ from local_deep_research.benchmarks.graders import _grade_results_inner++ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".jsonl", delete=False+ ) as f:+ f.write(+ json.dumps(+ {+ "problem": "Q1",+ "correct_answer": "A1",+ "response": "R1",+ }+ )+ + "\n"+ )+ results_file = f.name++ output_file = results_file + ".graded"++ llm = MagicMock()+ result_obj = MagicMock()+ result_obj.content = (+ "Extracted Answer: A1\nReasoning: Good\nCorrect: yes"+ )+ llm.invoke.return_value = result_obj++ callback_calls = []++ def progress_cb(idx, total, meta):+ callback_calls.append((idx, total, meta["status"]))++ try:+ _grade_results_inner(+ llm, results_file, output_file, "simpleqa", progress_cb+ )++ # Should be called twice per item: "grading" and "graded"+ assert len(callback_calls) == 2+ assert callback_calls[0][2] == "grading"+ assert callback_calls[1][2] == "graded"+ finally:+ Path(results_file).unlink(missing_ok=True)+ Path(output_file).unlink(missing_ok=True)++ def test_existing_output_file_removed(self):+ """Existing output file gets removed before grading starts."""+ from local_deep_research.benchmarks.graders import _grade_results_inner++ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".jsonl", delete=False+ ) as f:+ f.write(+ json.dumps(+ {+ "problem": "Q",+ "correct_answer": "A",+ "response": "R",+ }+ )+ + "\n"+ )+ results_file = f.name++ output_file = results_file + ".graded"+ # Create pre-existing output file+ Path(output_file).write_text("old data\n")++ llm = MagicMock()+ result_obj = MagicMock()+ result_obj.content = (+ "Extracted Answer: A\nReasoning: Correct\nCorrect: yes"+ )+ llm.invoke.return_value = result_obj++ try:+ _grade_results_inner(+ llm, results_file, output_file, "simpleqa", None+ )+ # Output file should only contain the new result, not "old data"+ content = Path(output_file).read_text()+ assert "old data" not in content+ finally:+ Path(results_file).unlink(missing_ok=True)+ Path(output_file).unlink(missing_ok=True)+++# ---------------------------------------------------------------------------+# get_evaluation_llm+# ---------------------------------------------------------------------------+++class TestGetEvaluationLLM:+ def test_custom_config_override(self):+ """Custom config merges with defaults."""+ from local_deep_research.benchmarks.graders import get_evaluation_llm++ with patch(f"{MODULE}.get_llm") as mock_get_llm:+ mock_get_llm.return_value = MagicMock()+ get_evaluation_llm(custom_config={"model_name": "custom-model"})++ call_kwargs = mock_get_llm.call_args.kwargs+ assert call_kwargs["model_name"] == "custom-model"++ def test_api_key_from_settings_snapshot(self):+ """API key extracted from settings snapshot dict format."""+ from local_deep_research.benchmarks.graders import get_evaluation_llm++ snapshot = {"llm.openai_endpoint.api_key": {"value": "sk-test-key-123"}}++ with patch(f"{MODULE}.get_llm") as mock_get_llm:+ mock_get_llm.return_value = MagicMock()+ get_evaluation_llm(settings_snapshot=snapshot)++ # Should not raise or warn about missing API key+ mock_get_llm.assert_called_once()++ def test_api_key_from_settings_snapshot_plain_string(self):+ """API key as plain string (not dict) from snapshot."""+ from local_deep_research.benchmarks.graders import get_evaluation_llm++ snapshot = {"llm.openai_endpoint.api_key": "sk-plain-key"}++ with patch(f"{MODULE}.get_llm") as mock_get_llm:+ mock_get_llm.return_value = MagicMock()+ get_evaluation_llm(settings_snapshot=snapshot)++ mock_get_llm.assert_called_once()++ def test_no_snapshot_no_api_key(self):+ """No snapshot, no API key → warns but proceeds."""+ from local_deep_research.benchmarks.graders import get_evaluation_llm++ with patch(f"{MODULE}.get_llm") as mock_get_llm:+ mock_get_llm.return_value = MagicMock()+ get_evaluation_llm()++ mock_get_llm.assert_called_once()diff --git a/tests/web/routes/test_research_routes_extra_coverage.py b/tests/web/routes/test_research_routes_extra_coverage.pyindex 640e9359e4..4634e82f3b 100644--- a/tests/web/routes/test_research_routes_extra_coverage.py+++ b/tests/web/routes/test_research_routes_extra_coverage.py@@ -5,10 +5,19 @@ Targets routes/branches NOT covered by test_research_routes_deep_coverage.py:- get_research_report: success, not found, content None, DB exception- export_research_report: unsupported format, not found, empty content, success, export error- get_research_status: error classification (token_limit, llm_error, ollama_error,- connection, unknown, solution metadata)-- save_raw_config: invalid TOML, blocked keys, success-- upload_pdf: success, validation failure, request too large-- get_queue_position: success path+ connection, unknown, solution metadata), with milestone log, no error metadata+- save_raw_config: invalid TOML, blocked keys, success, empty raw_config, write exception+- upload_pdf: success, validation failure, no files, extraction failure, multiple files,+ file count exceeded, exception during processing+- get_queue_position: success, exception+- get_queue_status: success, exception+- get_history: success with duration + doc count + title, no completedAt+- start_research: missing query, missing model, OPENAI_ENDPOINT validation,+ non-JSON body (require_json_body), settings snapshot failure+- page renders: progress, details, results, history, settings+- open_file_location: always 403+- get_upload_limits: returns config+- get_research_details: success, not found"""import io@@ -585,3 +594,525 @@ class TestGetQueuePosition:data = resp.get_json()assert data["status"] == "success"assert data["position"] == 3++ def test_exception(self, client):+ with patch(+ f"{QUEUE_MOD}.QueueManager",+ side_effect=RuntimeError("queue error"),+ ):+ resp = client.get("/api/queue/res-1/position")++ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# get_queue_status+# ---------------------------------------------------------------------------+++class TestGetQueueStatus:+ def test_success(self, client):+ with patch(f"{QUEUE_MOD}.QueueManager") as mock_qm:+ mock_qm.get_user_queue.return_value = [+ {"id": "r1", "position": 1},+ {"id": "r2", "position": 2},+ ]+ resp = client.get("/api/queue/status")++ assert resp.status_code == 200+ data = resp.get_json()+ assert data["status"] == "success"+ assert data["total"] == 2++ def test_exception(self, client):+ with patch(+ f"{QUEUE_MOD}.QueueManager",+ side_effect=RuntimeError("queue error"),+ ):+ resp = client.get("/api/queue/status")++ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# get_research_status — additional branches+# ---------------------------------------------------------------------------+++class TestGetResearchStatusAdditional:+ def test_status_with_milestone_log(self, client):+ """Status with a milestone log → includes log_entry field."""+ research = _make_research(status="in_progress", research_meta={})+ milestone = _make_milestone("Analyzing sources")++ ms = _mock_db_session()+ research_query = MagicMock()+ milestone_query = MagicMock()+ ms.query.side_effect = [research_query, milestone_query]+ research_query.filter_by.return_value.first.return_value = research+ milestone_query.filter_by.return_value.order_by.return_value.first.return_value = milestone++ with patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)):+ resp = client.get("/api/research/res-1/status")++ assert resp.status_code == 200+ data = resp.get_json()+ assert "log_entry" in data+ assert data["log_entry"]["message"] == "Analyzing sources"+ assert data["log_entry"]["type"] == "MILESTONE"++ def test_status_no_error_metadata(self, client):+ """Status without error in metadata → no error_info field."""+ research = _make_research(+ status="in_progress",+ research_meta={"some_key": "val"},+ )+ ms = _mock_db_session()+ research_query = MagicMock()+ milestone_query = MagicMock()+ ms.query.side_effect = [research_query, milestone_query]+ research_query.filter_by.return_value.first.return_value = research+ milestone_query.filter_by.return_value.order_by.return_value.first.return_value = None++ with patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)):+ resp = client.get("/api/research/res-1/status")++ assert resp.status_code == 200+ data = resp.get_json()+ assert "error_info" not in data["metadata"]++ def test_status_not_found(self, client):+ ms = _mock_db_session()+ ms.query.return_value.filter_by.return_value.first.return_value = None++ with patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)):+ resp = client.get("/api/research/res-1/status")++ assert resp.status_code == 404++ def test_status_db_exception(self, client):+ with patch(+ f"{MODULE}.get_user_db_session", side_effect=Exception("db")+ ):+ resp = client.get("/api/research/res-1/status")++ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# save_raw_config — additional+# ---------------------------------------------------------------------------+++class TestSaveRawConfigAdditional:+ def test_empty_raw_config(self, client):+ """Empty raw_config → 400."""+ resp = client.post(+ "/api/save_raw_config",+ json={"raw_config": ""},+ content_type="application/json",+ )+ assert resp.status_code == 400++ def test_write_exception(self, client):+ """Write failure → 500."""+ toml_str = '[search]\ntool = "searxng"\n'++ with (+ patch(f"{MODULE}.get_config_directory", return_value=MagicMock()),+ patch(+ f"{FILE_WRITE_MOD}.write_file_verified",+ side_effect=OSError("disk full"),+ ),+ ):+ resp = client.post(+ "/api/save_raw_config",+ json={"raw_config": toml_str},+ content_type="application/json",+ )++ assert resp.status_code == 500++ def test_nested_blocked_keys(self, client):+ """Nested blocked key in TOML → 403."""+ toml_str = '[outer]\n[outer.inner]\nclass_name = "evil"\n'+ resp = client.post(+ "/api/save_raw_config",+ json={"raw_config": toml_str},+ content_type="application/json",+ )+ assert resp.status_code == 403++ def test_missing_body(self, client):+ """Non-JSON request → handled by require_json_body decorator."""+ resp = client.post(+ "/api/save_raw_config",+ data="not json",+ content_type="text/plain",+ )+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# upload_pdf — additional+# ---------------------------------------------------------------------------+++class TestUploadPdfAdditional:+ def test_extraction_failure(self, client):+ """PDF extraction returns success=False → error recorded."""+ mock_service = MagicMock()+ mock_service.extract_text_and_metadata.return_value = {+ "success": False,+ "error": "Encrypted PDF",+ "filename": "locked.pdf",+ }++ mock_validator = MagicMock()+ mock_validator.MAX_FILE_SIZE = 50 * 1024 * 1024+ mock_validator.MAX_FILES_PER_REQUEST = 100+ mock_validator.validate_file_count.return_value = (True, None)+ mock_validator.validate_upload.return_value = (True, None)++ data = {"files": (io.BytesIO(b"%PDF-1.4"), "locked.pdf")}++ with (+ patch(+ f"{MODULE}.get_pdf_extraction_service",+ return_value=mock_service,+ ),+ patch(f"{MODULE}.FileUploadValidator", mock_validator),+ ):+ resp = client.post(+ "/api/upload/pdf",+ data=data,+ content_type="multipart/form-data",+ )++ assert resp.status_code == 400+ body = resp.get_json()+ assert "Encrypted PDF" in body["errors"][0]++ def test_file_count_exceeded(self, client):+ """Too many files → 400."""+ mock_validator = MagicMock()+ mock_validator.MAX_FILE_SIZE = 50 * 1024 * 1024+ mock_validator.MAX_FILES_PER_REQUEST = 100+ mock_validator.validate_file_count.return_value = (+ False,+ "Too many files",+ )++ data = {"files": (io.BytesIO(b"data"), "file.pdf")}++ with patch(f"{MODULE}.FileUploadValidator", mock_validator):+ resp = client.post(+ "/api/upload/pdf",+ data=data,+ content_type="multipart/form-data",+ )++ assert resp.status_code == 400++ def test_empty_filename(self, client):+ """File with empty filename → 400."""+ data = {"files": (io.BytesIO(b""), "")}++ resp = client.post(+ "/api/upload/pdf",+ data=data,+ content_type="multipart/form-data",+ )++ assert resp.status_code == 400++ def test_exception_during_processing(self, client):+ """Exception during PDF processing → error recorded, continues."""+ mock_service = MagicMock()+ mock_service.extract_text_and_metadata.side_effect = RuntimeError(+ "crash"+ )++ mock_validator = MagicMock()+ mock_validator.MAX_FILE_SIZE = 50 * 1024 * 1024+ mock_validator.MAX_FILES_PER_REQUEST = 100+ mock_validator.validate_file_count.return_value = (True, None)+ mock_validator.validate_upload.return_value = (True, None)++ data = {"files": (io.BytesIO(b"%PDF-1.4"), "test.pdf")}++ with (+ patch(+ f"{MODULE}.get_pdf_extraction_service",+ return_value=mock_service,+ ),+ patch(f"{MODULE}.FileUploadValidator", mock_validator),+ ):+ resp = client.post(+ "/api/upload/pdf",+ data=data,+ content_type="multipart/form-data",+ )++ assert resp.status_code == 400+ body = resp.get_json()+ assert len(body["errors"]) >= 1+++# ---------------------------------------------------------------------------+# get_research_details+# ---------------------------------------------------------------------------+++class TestGetResearchDetails:+ def test_success(self, client):+ research = _make_research(research_meta={"key": "val"})+ ms = _mock_db_session()+ ms.query.return_value.filter.return_value.first.return_value = research++ with patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)):+ resp = client.get("/api/research/res-1")++ assert resp.status_code == 200+ data = resp.get_json()+ assert data["id"] == "res-1"+ assert data["query"] == "test query"++ def test_not_found(self, client):+ ms = _mock_db_session()+ ms.query.return_value.filter.return_value.first.return_value = None++ with patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)):+ resp = client.get("/api/research/no-such")++ assert resp.status_code == 404++ def test_db_exception(self, client):+ with patch(+ f"{MODULE}.get_user_db_session", side_effect=Exception("db")+ ):+ resp = client.get("/api/research/res-1")++ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# get_history+# ---------------------------------------------------------------------------+++class TestGetHistory:+ def test_success_with_title_and_duration(self, client):+ """History returns items with title, duration, doc_count."""+ research = _make_research(+ title="My Research",+ created_at="2025-01-01T00:00:00",+ completed_at="2025-01-01T01:00:00",+ research_meta={"submission": {"model": "gpt4"}},+ )+ ms = _mock_db_session()+ ms.query.return_value.order_by.return_value.all.return_value = [+ research+ ]+ # Document count query+ ms.query.return_value.filter_by.return_value.count.return_value = 5++ with (+ patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)),+ patch(f"{MODULE}.calculate_duration", return_value=3600),+ ):+ resp = client.get("/api/history")++ assert resp.status_code == 200+ data = resp.get_json()+ assert data["status"] == "success"+ assert len(data["items"]) == 1+ assert data["items"][0]["title"] == "My Research"+ assert data["items"][0]["duration_seconds"] == 3600+ assert data["items"][0]["document_count"] == 5++ def test_success_no_completed_at(self, client):+ """History item without completed_at → duration_seconds is None."""+ research = _make_research(completed_at=None, title=None)+ ms = _mock_db_session()+ ms.query.return_value.order_by.return_value.all.return_value = [+ research+ ]+ ms.query.return_value.filter_by.return_value.count.return_value = 0++ with patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)):+ resp = client.get("/api/history")++ assert resp.status_code == 200+ data = resp.get_json()+ assert data["items"][0]["duration_seconds"] is None++ def test_db_exception(self, client):+ with patch(+ f"{MODULE}.get_user_db_session", side_effect=Exception("db")+ ):+ resp = client.get("/api/history")++ assert resp.status_code == 500+++# ---------------------------------------------------------------------------+# Page renders+# ---------------------------------------------------------------------------+++class TestPageRenders:+ def test_progress_page(self, client):+ with patch(f"{MODULE}.render_template_with_defaults", return_value=""):+ resp = client.get("/progress/res-1")+ assert resp.status_code == 200++ def test_details_page(self, client):+ with patch(f"{MODULE}.render_template_with_defaults", return_value=""):+ resp = client.get("/details/res-1")+ assert resp.status_code == 200++ def test_results_page(self, client):+ with patch(f"{MODULE}.render_template_with_defaults", return_value=""):+ resp = client.get("/results/res-1")+ assert resp.status_code == 200++ def test_history_page(self, client):+ with patch(f"{MODULE}.render_template_with_defaults", return_value=""):+ resp = client.get("/history")+ assert resp.status_code == 200++ def test_settings_page(self, client):+ with patch(f"{MODULE}.render_template_with_defaults", return_value=""):+ resp = client.get("/settings")+ assert resp.status_code == 200+++# ---------------------------------------------------------------------------+# open_file_location — always 403+# ---------------------------------------------------------------------------+++class TestOpenFileLocation:+ def test_always_403(self, client):+ resp = client.post("/open_file_location", json={})+ assert resp.status_code == 403+ assert "disabled" in resp.get_json()["message"].lower()+++# ---------------------------------------------------------------------------+# get_upload_limits+# ---------------------------------------------------------------------------+++class TestGetUploadLimits:+ def test_returns_limits(self, client):+ resp = client.get("/api/config/limits")+ assert resp.status_code == 200+ data = resp.get_json()+ assert "max_file_size" in data+ assert "max_files" in data+ assert "allowed_mime_types" in data+++# ---------------------------------------------------------------------------+# redirect_static+# ---------------------------------------------------------------------------+++class TestRedirectStatic:+ def test_redirect(self, client):+ resp = client.get("/redirect-static/css/style.css")+ assert resp.status_code == 302+++# ---------------------------------------------------------------------------+# start_research — validation branches+# ---------------------------------------------------------------------------+++class TestStartResearchValidation:+ def test_missing_query(self, client):+ """No query → 400."""+ mock_sm = MagicMock()+ mock_sm.get_setting.return_value = "OLLAMA"++ ms = _mock_db_session()++ with (+ patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)),+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ return_value=mock_sm,+ ),+ ):+ resp = client.post(+ "/api/start_research",+ json={"query": "", "mode": "quick"},+ content_type="application/json",+ )++ assert resp.status_code == 400++ def test_missing_model(self, client):+ """No model configured → 400."""+ mock_sm = MagicMock()+ mock_sm.get_setting.return_value = None++ ms = _mock_db_session()++ with (+ patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)),+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ return_value=mock_sm,+ ),+ ):+ resp = client.post(+ "/api/start_research",+ json={"query": "test", "mode": "quick"},+ content_type="application/json",+ )++ assert resp.status_code == 400++ def test_openai_endpoint_without_custom_url(self, client):+ """OPENAI_ENDPOINT provider without custom_endpoint → 400."""+ call_count = 0++ def get_setting_side_effect(key, default=None):+ nonlocal call_count+ call_count += 1+ if key == "llm.provider":+ return "OPENAI_ENDPOINT"+ if key == "llm.model":+ return "gpt-4"+ if key == "llm.openai_endpoint.url":+ return None+ return default++ mock_sm = MagicMock()+ mock_sm.get_setting.side_effect = get_setting_side_effect++ ms = _mock_db_session()++ with (+ patch(f"{MODULE}.get_user_db_session", return_value=_ctx(ms)),+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ return_value=mock_sm,+ ),+ ):+ resp = client.post(+ "/api/start_research",+ json={+ "query": "test",+ "mode": "quick",+ "model_provider": "OPENAI_ENDPOINT",+ "model": "gpt-4",+ },+ content_type="application/json",+ )++ assert resp.status_code == 400+ assert "endpoint" in resp.get_json()["message"].lower()diff --git a/tests/web/services/test_research_service_extra_coverage.py b/tests/web/services/test_research_service_extra_coverage.pyindex 3673f07ad3..f76688d8ec 100644--- a/tests/web/services/test_research_service_extra_coverage.py+++ b/tests/web/services/test_research_service_extra_coverage.py@@ -1,15 +1,22 @@"""Extra coverage tests for research_service.py targeting cancel/termination/cleanup.Targets functions NOT covered by test_research_service_deep_coverage.py:-- cancel_research: active, not found, terminal state, non-active non-terminal, db exception+- cancel_research: active, not found, terminal state, non-active non-terminal, db exception, top-level- handle_termination: success, queue processor exception-- cleanup_research_resources: completed status, failed status, socket emit exception-- _generate_report_path: normal query, unicode/special chars+- cleanup_research_resources: completed status, no username, socket emit exception+- _generate_report_path: normal query, unicode/special chars, different queries produce different paths+- _parse_research_metadata: dict, JSON string, invalid JSON, non-string+- get_citation_formatter: various citation modes+- export_report_to_memory: success, unsupported format+- save_research_strategy: create new, update existing, exception+- get_research_strategy: found, not found, exception+- start_research_process: starts thread"""from contextlib import contextmanagerfrom unittest.mock import MagicMock, patch+import pytestfrom loguru import logger# Register MILESTONE log level used by progress_callback@@ -306,3 +313,301 @@ class TestGenerateReportPath:path = _generate_report_path("日本語クエリ $pecial Ch@rs!")assert path.suffix == ".md"assert "research_report_" in path.name++ def test_different_queries_different_hashes(self):+ from local_deep_research.web.services.research_service import (+ _generate_report_path,+ )++ path1 = _generate_report_path("query one")+ path2 = _generate_report_path("query two")+ # Hash portion should differ+ assert path1.name != path2.name+++# ---------------------------------------------------------------------------+# _parse_research_metadata+# ---------------------------------------------------------------------------+++class TestParseResearchMetadata:+ def test_dict_input(self):+ from local_deep_research.web.services.research_service import (+ _parse_research_metadata,+ )++ result = _parse_research_metadata({"key": "val"})+ assert result == {"key": "val"}++ def test_json_string_input(self):+ from local_deep_research.web.services.research_service import (+ _parse_research_metadata,+ )++ result = _parse_research_metadata('{"key": "val"}')+ assert result == {"key": "val"}++ def test_invalid_json_string(self):+ from local_deep_research.web.services.research_service import (+ _parse_research_metadata,+ )++ result = _parse_research_metadata("not json")+ assert result == {}++ def test_none_input(self):+ from local_deep_research.web.services.research_service import (+ _parse_research_metadata,+ )++ result = _parse_research_metadata(None)+ assert result == {}++ def test_int_input(self):+ from local_deep_research.web.services.research_service import (+ _parse_research_metadata,+ )++ result = _parse_research_metadata(42)+ assert result == {}+++# ---------------------------------------------------------------------------+# get_citation_formatter+# ---------------------------------------------------------------------------+++class TestGetCitationFormatter:+ def test_default_mode(self):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="number_hyperlinks",+ ):+ formatter = get_citation_formatter()++ assert formatter is not None++ def test_domain_hyperlinks_mode(self):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="domain_hyperlinks",+ ):+ formatter = get_citation_formatter()++ assert formatter is not None++ def test_no_hyperlinks_mode(self):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="no_hyperlinks",+ ):+ formatter = get_citation_formatter()++ assert formatter is not None++ def test_unknown_mode_falls_back(self):+ from local_deep_research.web.services.research_service import (+ get_citation_formatter,+ )++ with patch(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ return_value="nonexistent_mode",+ ):+ formatter = get_citation_formatter()++ assert formatter is not None+++# ---------------------------------------------------------------------------+# export_report_to_memory+# ---------------------------------------------------------------------------+++class TestExportReportToMemory:+ def test_success(self):+ from local_deep_research.web.services.research_service import (+ export_report_to_memory,+ )++ mock_exporter = MagicMock()+ mock_result = MagicMock()+ mock_result.content = b"PDF bytes"+ mock_result.filename = "report.pdf"+ mock_result.mimetype = "application/pdf"+ mock_exporter.export.return_value = mock_result++ mock_registry = MagicMock()+ mock_registry.get_exporter.return_value = mock_exporter++ with patch(+ "local_deep_research.exporters.ExporterRegistry", mock_registry+ ):+ content, filename, mimetype = export_report_to_memory(+ "# Report", "pdf", title="Test"+ )++ assert content == b"PDF bytes"+ assert filename == "report.pdf"++ def test_unsupported_format_raises(self):+ """Unsupported format raises ValueError."""+ from local_deep_research.exporters import ExporterRegistry++ original = ExporterRegistry.get_exporter++ try:+ ExporterRegistry.get_exporter = staticmethod(lambda fmt: None)+ ExporterRegistry.get_available_formats = staticmethod(+ lambda: ["pdf", "latex"]+ )++ from local_deep_research.web.services.research_service import (+ export_report_to_memory,+ )++ with pytest.raises(ValueError, match="Unsupported"):+ export_report_to_memory("# Report", "docx")+ finally:+ ExporterRegistry.get_exporter = original+++# ---------------------------------------------------------------------------+# save_research_strategy / get_research_strategy+# ---------------------------------------------------------------------------+++class TestSaveResearchStrategy:+ def test_create_new_strategy(self):+ from local_deep_research.web.services.research_service import (+ save_research_strategy,+ )++ ms = MagicMock()+ ms.query.return_value.filter_by.return_value.first.return_value = None++ with patch(f"{MODULE}.get_user_db_session", _fake_session_ctx(ms)):+ save_research_strategy("res-1", "source-based", username="user")++ ms.add.assert_called_once()+ ms.commit.assert_called_once()++ def test_update_existing_strategy(self):+ from local_deep_research.web.services.research_service import (+ save_research_strategy,+ )++ existing = MagicMock()+ ms = MagicMock()+ ms.query.return_value.filter_by.return_value.first.return_value = (+ existing+ )++ with patch(f"{MODULE}.get_user_db_session", _fake_session_ctx(ms)):+ save_research_strategy("res-1", "mcp", username="user")++ assert existing.strategy_name == "mcp"+ ms.commit.assert_called_once()++ def test_exception_swallowed(self):+ from local_deep_research.web.services.research_service import (+ save_research_strategy,+ )++ with patch(+ f"{MODULE}.get_user_db_session",+ side_effect=Exception("db fail"),+ ):+ # Should not raise+ save_research_strategy("res-1", "source-based", username="user")+++class TestGetResearchStrategy:+ def test_found(self):+ from local_deep_research.web.services.research_service import (+ get_research_strategy,+ )++ strategy = MagicMock()+ strategy.strategy_name = "source-based"+ ms = MagicMock()+ ms.query.return_value.filter_by.return_value.first.return_value = (+ strategy+ )++ with patch(f"{MODULE}.get_user_db_session", _fake_session_ctx(ms)):+ result = get_research_strategy("res-1", username="user")++ assert result == "source-based"++ def test_not_found(self):+ from local_deep_research.web.services.research_service import (+ get_research_strategy,+ )++ ms = MagicMock()+ ms.query.return_value.filter_by.return_value.first.return_value = None++ with patch(f"{MODULE}.get_user_db_session", _fake_session_ctx(ms)):+ result = get_research_strategy("res-1", username="user")++ assert result is None++ def test_exception_returns_none(self):+ from local_deep_research.web.services.research_service import (+ get_research_strategy,+ )++ with patch(+ f"{MODULE}.get_user_db_session",+ side_effect=Exception("db fail"),+ ):+ result = get_research_strategy("res-1", username="user")++ assert result is None+++# ---------------------------------------------------------------------------+# start_research_process+# ---------------------------------------------------------------------------+++class TestStartResearchProcess:+ def test_starts_thread(self):+ from local_deep_research.web.services.research_service import (+ start_research_process,+ )++ callback = MagicMock()++ with (+ patch(+ f"{MODULE}.thread_with_app_context",+ side_effect=lambda f: f,+ ),+ patch(f"{MODULE}.thread_context", return_value={}),+ patch("local_deep_research.web.routes.globals.set_active_research"),+ patch("threading.Thread") as mock_thread_cls,+ ):+ mock_thread = MagicMock()+ mock_thread.ident = 12345+ mock_thread_cls.return_value = mock_thread++ result = start_research_process(+ "res-1", "test query", "quick", callback, username="user"+ )++ mock_thread.start.assert_called_once()+ assert result is mock_thread