Skip to content

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

test: add 86 coverage gap tests across 6 critical modules (#2957)

LearningCircuit40cdf3710555
diff --git a/tests/metrics/test_token_counter_provider_coverage.py b/tests/metrics/test_token_counter_provider_coverage.py
new file mode 100644
index 0000000000..09118c686e
--- /dev/null
+++ b/tests/metrics/test_token_counter_provider_coverage.py
@@ -0,0 +1,330 @@
+"""Provider-level coverage tests for token_counter.py.
+
+Targets specific uncovered lines:
+- on_llm_start: model extraction fallbacks (kwargs direct, serialized kwargs model_name)
+- on_llm_start: provider extraction for unrecognized _type with provider kwarg
+- on_llm_end: token extraction from llm_output 'usage' key (alternative to 'token_usage')
+- on_llm_end: Ollama context overflow with zero original_prompt_estimate guard
+- _save_to_db: background thread success path with full token_data dict verification
+"""
+
+import threading
+from unittest.mock import MagicMock, patch
+
+from langchain_core.outputs import LLMResult
+
+from local_deep_research.metrics.token_counter import TokenCountingCallback
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_callback(research_context=None, research_id="rid-test", **overrides):
+ """Build a TokenCountingCallback with controllable state."""
+ ctx = research_context if research_context is not None else {}
+ cb = TokenCountingCallback(research_id=research_id, research_context=ctx)
+ for k, v in overrides.items():
+ setattr(cb, k, v)
+ return cb
+
+
+def _make_llm_result(llm_output=None, generations=None):
+ """Build a minimal mock LLMResult."""
+ result = MagicMock(spec=LLMResult)
+ result.llm_output = llm_output
+ result.generations = generations or []
+ return result
+
+
+def _make_generation(usage_metadata=None, response_metadata=None):
+ """Build a mock generation with a message carrying metadata."""
+ gen = MagicMock()
+ msg = MagicMock()
+ msg.usage_metadata = usage_metadata
+ msg.response_metadata = (
+ response_metadata if response_metadata is not None else {}
+ )
+ gen.message = msg
+ return gen
+
+
+def _setup_model_counts(cb, model_name="test-model", provider="openai"):
+ """Register model in cb.counts so on_llm_end can update them."""
+ cb.current_model = model_name
+ cb.current_provider = provider
+ cb.counts["by_model"][model_name] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": provider,
+ }
+
+
+def _patch_worker_thread():
+ t = MagicMock()
+ t.name = "WorkerThread-1"
+ return patch.object(threading, "current_thread", return_value=t)
+
+
+# ---------------------------------------------------------------------------
+# 1. on_llm_start – model extraction fallback: kwargs["model"] when
+# invocation_params has no model key (line 163)
+# ---------------------------------------------------------------------------
+
+
+class TestModelFromKwargsModel:
+ """Model extracted from kwargs['model'] when invocation_params is empty."""
+
+ def test_model_from_kwargs_model_key(self):
+ """kwargs['model'] is used when invocation_params has no model."""
+ cb = _make_callback()
+ cb.on_llm_start(
+ {},
+ ["hello"],
+ invocation_params={},
+ model="gemma-2-27b",
+ )
+ assert cb.current_model == "gemma-2-27b"
+
+ def test_model_from_kwargs_model_name_key(self):
+ """kwargs['model_name'] is used when invocation_params and kwargs['model'] are absent."""
+ cb = _make_callback()
+ cb.on_llm_start({}, ["hello"], model_name="codellama-34b")
+ assert cb.current_model == "codellama-34b"
+
+
+# ---------------------------------------------------------------------------
+# 2. on_llm_start – model from serialized["kwargs"]["model_name"]
+# (line 167-169, specifically the model_name branch)
+# ---------------------------------------------------------------------------
+
+
+class TestModelFromSerializedKwargsModelName:
+ """Model extracted from serialized['kwargs']['model_name'] when 'model' absent."""
+
+ def test_serialized_kwargs_model_name(self):
+ """serialized['kwargs']['model_name'] provides the model when 'model' key missing."""
+ cb = _make_callback()
+ cb.on_llm_start(
+ {"kwargs": {"model_name": "deepseek-coder"}},
+ ["prompt"],
+ )
+ assert cb.current_model == "deepseek-coder"
+
+
+# ---------------------------------------------------------------------------
+# 3. on_llm_start – provider from kwargs when _type is unrecognized
+# (line 210-211: else branch inside the if "_type" in serialized block)
+# ---------------------------------------------------------------------------
+
+
+class TestProviderFromKwargsWithUnrecognizedType:
+ """When _type exists but is not ChatOllama/ChatOpenAI/ChatAnthropic,
+ provider falls back to kwargs.get('provider', 'unknown')."""
+
+ def test_unrecognized_type_with_provider_kwarg(self):
+ """Unrecognized _type uses provider kwarg."""
+ cb = _make_callback()
+ cb.on_llm_start(
+ {"_type": "ChatGoogleGenAI", "kwargs": {"model": "gemini-pro"}},
+ ["prompt"],
+ provider="google",
+ )
+ assert cb.current_provider == "google"
+
+ def test_unrecognized_type_without_provider_kwarg(self):
+ """Unrecognized _type without provider kwarg defaults to 'unknown'."""
+ cb = _make_callback()
+ cb.on_llm_start(
+ {"_type": "ChatGoogleGenAI", "kwargs": {"model": "gemini-pro"}},
+ ["prompt"],
+ )
+ assert cb.current_provider == "unknown"
+
+
+# ---------------------------------------------------------------------------
+# 4. on_llm_end – token extraction from llm_output 'usage' key
+# (line 240-241: the or branch: response.llm_output.get("usage", {}))
+# ---------------------------------------------------------------------------
+
+
+class TestTokenExtractionFromUsageKey:
+ """Tokens extracted from llm_output['usage'] when 'token_usage' absent."""
+
+ def test_usage_key_provides_tokens(self):
+ """llm_output['usage'] provides prompt_tokens/completion_tokens."""
+ cb = _make_callback()
+ _setup_model_counts(cb, "gpt-4o", "openai")
+
+ result = _make_llm_result(
+ llm_output={
+ "usage": {
+ "prompt_tokens": 45,
+ "completion_tokens": 30,
+ "total_tokens": 75,
+ }
+ },
+ )
+ cb.on_llm_end(result)
+
+ assert cb.counts["total_prompt_tokens"] == 45
+ assert cb.counts["total_completion_tokens"] == 30
+ assert cb.counts["total_tokens"] == 75
+
+
+# ---------------------------------------------------------------------------
+# 5. on_llm_end – Ollama context overflow: original_prompt_estimate == 0
+# guards against division-by-zero (line 312-314)
+# ---------------------------------------------------------------------------
+
+
+class TestContextOverflowZeroPromptEstimate:
+ """When original_prompt_estimate is 0 the truncation_ratio is 0, not a ZeroDivisionError."""
+
+ def test_zero_prompt_estimate_no_division_error(self):
+ """truncation_ratio stays 0 when original_prompt_estimate is 0."""
+ cb = _make_callback(research_context={"context_limit": 100})
+ _setup_model_counts(cb, "llama3", "ollama")
+ # context_limit is set during on_llm_start; set it directly here
+ cb.context_limit = 100
+ cb.original_prompt_estimate = 0
+
+ gen = _make_generation(
+ usage_metadata=None,
+ response_metadata={
+ "prompt_eval_count": 96, # >= 95 (95% of 100)
+ "eval_count": 20,
+ },
+ )
+ result = _make_llm_result(generations=[[gen]])
+ cb.on_llm_end(result)
+
+ assert cb.context_truncated is True
+ # original_prompt_estimate (0) <= prompt_eval_count (96), so
+ # the inner if branch is not entered; tokens_truncated stays 0
+ assert cb.tokens_truncated == 0
+ assert cb.truncation_ratio == 0.0
+
+ def test_context_overflow_calculates_truncation(self):
+ """When prompt estimate > actual, truncation fields are populated."""
+ cb = _make_callback(research_context={"context_limit": 1000})
+ _setup_model_counts(cb, "llama3", "ollama")
+ # context_limit is set during on_llm_start; set it directly here
+ cb.context_limit = 1000
+ cb.original_prompt_estimate = 1200
+
+ gen = _make_generation(
+ usage_metadata=None,
+ response_metadata={
+ "prompt_eval_count": 960, # >= 950 (95% of 1000)
+ "eval_count": 50,
+ },
+ )
+ result = _make_llm_result(generations=[[gen]])
+ cb.on_llm_end(result)
+
+ assert cb.context_truncated is True
+ assert cb.tokens_truncated == 240 # 1200 - 960
+ expected_ratio = 240 / 1200
+ assert abs(cb.truncation_ratio - expected_ratio) < 1e-9
+
+
+# ---------------------------------------------------------------------------
+# 6. _save_to_db – background thread success path
+# (lines 408-482): verifies metrics_writer is called with correct data
+# ---------------------------------------------------------------------------
+
+
+class TestSaveToDbBackgroundThread:
+ """_save_to_db in a background thread writes via metrics_writer."""
+
+ def test_metrics_writer_called_with_token_data(self):
+ """metrics_writer.write_token_metrics receives correct token_data dict."""
+ cb = _make_callback(
+ research_context={
+ "username": "alice",
+ "user_password": "secret",
+ "research_query": "quantum computing",
+ "research_mode": "detailed",
+ "research_phase": "search",
+ "search_iteration": 2,
+ "search_engines_planned": ["google", "bing"],
+ "search_engine_selected": "google",
+ },
+ research_id="rid-42",
+ )
+ cb.current_model = "gpt-4o"
+ cb.current_provider = "openai"
+ cb.response_time_ms = 350
+ cb.success_status = "success"
+ cb.error_type = None
+ cb.calling_file = "runner.py"
+ cb.calling_function = "execute"
+ cb.call_stack = "runner.py:execute:10"
+
+ with _patch_worker_thread():
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer"
+ ) as mock_writer:
+ cb._save_to_db(prompt_tokens=100, completion_tokens=50)
+
+ mock_writer.set_user_password.assert_called_once_with(
+ "alice", "secret"
+ )
+ mock_writer.write_token_metrics.assert_called_once()
+
+ call_args = mock_writer.write_token_metrics.call_args
+ assert call_args[0][0] == "alice"
+ assert call_args[0][1] == "rid-42"
+
+ token_data = call_args[0][2]
+ assert token_data["model_name"] == "gpt-4o"
+ assert token_data["provider"] == "openai"
+ assert token_data["prompt_tokens"] == 100
+ assert token_data["completion_tokens"] == 50
+ assert token_data["research_query"] == "quantum computing"
+ assert token_data["research_mode"] == "detailed"
+ assert token_data["research_phase"] == "search"
+ assert token_data["search_iteration"] == 2
+ # search_engines_planned list should be JSON-serialized
+ assert (
+ token_data["search_engines_planned"] == '["google", "bing"]'
+ )
+ assert token_data["search_engine_selected"] == "google"
+ assert token_data["response_time_ms"] == 350
+ assert token_data["calling_file"] == "runner.py"
+
+ def test_no_username_logs_warning_and_returns(self):
+ """Missing username in research_context causes early return."""
+ cb = _make_callback(
+ research_context={"user_password": "secret"},
+ research_id="rid-99",
+ )
+ cb.current_model = "gpt-4"
+ cb.current_provider = "openai"
+
+ with _patch_worker_thread():
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer"
+ ) as mock_writer:
+ cb._save_to_db(prompt_tokens=10, completion_tokens=5)
+ mock_writer.write_token_metrics.assert_not_called()
+
+ def test_no_password_logs_warning_and_returns(self):
+ """Missing password in research_context causes early return after username check."""
+ cb = _make_callback(
+ research_context={"username": "bob"},
+ research_id="rid-88",
+ )
+ cb.current_model = "gpt-4"
+ cb.current_provider = "openai"
+
+ with _patch_worker_thread():
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer"
+ ) as mock_writer:
+ cb._save_to_db(prompt_tokens=10, completion_tokens=5)
+ mock_writer.write_token_metrics.assert_not_called()
diff --git a/tests/news/test_flask_api_coverage_gaps.py b/tests/news/test_flask_api_coverage_gaps.py
new file mode 100644
index 0000000000..0887df9e3d
--- /dev/null
+++ b/tests/news/test_flask_api_coverage_gaps.py
@@ -0,0 +1,462 @@
+"""
+Tests covering uncovered lines in news/flask_api.py.
+
+Targets:
+- scheduler_control_required decorator 403 path with session username logging
+- _is_job_owned_by_user() fallback via scheduler.user_sessions
+- run_subscription_now() subscription lookup, config extraction, response paths
+- check_subscriptions_now() overdue query + threading
+- trigger_cleanup() APScheduler job scheduling
+- update_subscription_folder() dynamic field update + next_refresh recalculation
+- get_search_history() / clear_search_history() unauthenticated return paths
+- add_search_history() data validation
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+from flask import Flask, jsonify
+
+
+def app():
+ """Create a Flask app with the news blueprint registered."""
+ app = Flask(__name__)
+ app.config["SECRET_KEY"] = "test-secret-key"
+ app.config["WTF_CSRF_ENABLED"] = False
+ app.config["TESTING"] = True
+
+ from local_deep_research.news.flask_api import news_api_bp
+
+ app.register_blueprint(news_api_bp, url_prefix="/news/api")
+ return app
+
+
+def client(app):
+ """Create a test client."""
+ return app.test_client()
+
+
+def _auth_session(client, username="testuser"):
+ """Inject a valid session so login_required passes."""
+ with client.session_transaction() as sess:
+ sess["username"] = username
+
+
+class TestSchedulerControlRequiredLogging:
+ """Cover the 403 branch that reads session username and remote_addr."""
+
+ def test_403_body_includes_session_username_in_log(self, app):
+ """When blocked, the decorator reads session['username'] for logging."""
+ from local_deep_research.news.flask_api import (
+ scheduler_control_required,
+ )
+
+ with app.test_request_context():
+ # Put a username in the Flask session so the decorator can read it
+ from flask import session as flask_session
+
+ flask_session["username"] = "alice"
+
+ with patch(
+ "local_deep_research.news.flask_api.get_env_setting",
+ return_value=False,
+ ):
+
+ @scheduler_control_required
+ def dummy():
+ return jsonify({"ok": True}), 200
+
+ response, status = dummy()
+ assert status == 403
+ data = response.get_json()
+ assert "disabled" in data["error"].lower()
+
+
+class TestIsJobOwnedByUser:
+ """Cover _is_job_owned_by_user fallback through scheduler.user_sessions."""
+
+ def test_primary_match_via_job_args(self):
+ """Job is owned when job.args[0] matches the username."""
+ from local_deep_research.news.flask_api import _is_job_owned_by_user
+
+ job = MagicMock()
+ job.args = ("alice", 42)
+ scheduler = MagicMock(spec=[]) # no user_sessions attribute
+
+ assert _is_job_owned_by_user(job, "alice", scheduler) is True
+
+ def test_fallback_match_via_user_sessions(self):
+ """Job is owned when its id appears in scheduler.user_sessions."""
+ from local_deep_research.news.flask_api import _is_job_owned_by_user
+
+ job = MagicMock()
+ job.args = ("other_user",) # primary check fails
+ job.id = "job_123"
+
+ scheduler = MagicMock()
+ scheduler.user_sessions = {
+ "alice": {"scheduled_jobs": {"job_123", "job_456"}},
+ }
+
+ assert _is_job_owned_by_user(job, "alice", scheduler) is True
+
+ def test_no_match_returns_false(self):
+ """Returns False when neither primary nor fallback matches."""
+ from local_deep_research.news.flask_api import _is_job_owned_by_user
+
+ job = MagicMock()
+ job.args = ("other_user",)
+ job.id = "job_999"
+
+ scheduler = MagicMock()
+ scheduler.user_sessions = {
+ "alice": {"scheduled_jobs": {"job_123"}},
+ }
+
+ assert _is_job_owned_by_user(job, "alice", scheduler) is False
+
+
+class TestRunSubscriptionNow:
+ """Cover run_subscription_now route: subscription lookup, config, responses."""
+
+ def _setup_auth(self, client):
+ _auth_session(client)
+
+ def test_subscription_not_found_returns_404(self, client):
+ """Returns 404 when the subscription id is not in the list."""
+ self._setup_auth(client)
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.api.get_subscriptions",
+ return_value={"subscriptions": []},
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+ resp = client.post("/news/api/subscriptions/nonexistent/run")
+ assert resp.status_code == 404
+ assert "not found" in resp.get_json()["error"].lower()
+
+ def test_successful_run_returns_research_id(self, client, app):
+ """Successful run returns status=success and a research_id."""
+ self._setup_auth(client)
+
+ mock_response = MagicMock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "status": "success",
+ "research_id": "res_42",
+ }
+
+ mock_ctx_mgr = MagicMock()
+ mock_ctx_mgr.__enter__ = MagicMock(return_value=MagicMock())
+ mock_ctx_mgr.__exit__ = MagicMock(return_value=False)
+
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.api.get_subscriptions",
+ return_value={
+ "subscriptions": [
+ {
+ "id": "sub_1",
+ "query": "AI news YYYY-MM-DD",
+ "model_provider": "OPENAI",
+ "model": "gpt-4",
+ "search_strategy": "news_aggregation",
+ "name": "AI Digest",
+ "custom_endpoint": None,
+ }
+ ]
+ },
+ ),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ return_value=mock_ctx_mgr,
+ ),
+ patch(
+ "local_deep_research.news.flask_api.safe_post",
+ return_value=mock_response,
+ ),
+ patch(
+ "local_deep_research.news.core.utils.get_local_date_string",
+ return_value="2026-03-20",
+ ),
+ patch(
+ "local_deep_research.settings.manager.SettingsManager",
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ resp = client.post("/news/api/subscriptions/sub_1/run")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["status"] == "success"
+ assert data["research_id"] == "res_42"
+
+ def test_failed_response_returns_error(self, client):
+ """Non-ok response from research API returns the status code."""
+ self._setup_auth(client)
+
+ mock_response = MagicMock()
+ mock_response.ok = False
+ mock_response.status_code = 503
+
+ mock_ctx_mgr = MagicMock()
+ mock_ctx_mgr.__enter__ = MagicMock(return_value=MagicMock())
+ mock_ctx_mgr.__exit__ = MagicMock(return_value=False)
+
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.api.get_subscriptions",
+ return_value={
+ "subscriptions": [
+ {
+ "id": "sub_1",
+ "query": "test",
+ "name": None,
+ }
+ ]
+ },
+ ),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ return_value=mock_ctx_mgr,
+ ),
+ patch(
+ "local_deep_research.news.flask_api.safe_post",
+ return_value=mock_response,
+ ),
+ patch(
+ "local_deep_research.news.core.utils.get_local_date_string",
+ return_value="2026-03-20",
+ ),
+ patch(
+ "local_deep_research.settings.manager.SettingsManager",
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ resp = client.post("/news/api/subscriptions/sub_1/run")
+ assert resp.status_code == 503
+ assert "error" in resp.get_json()
+
+
+class TestCheckSubscriptionsNow:
+ """Cover check_subscriptions_now: DB query for overdue subs + threading."""
+
+ def test_scheduler_not_initialized_returns_503(self, client, app):
+ """Returns 503 when news_scheduler is missing from current_app."""
+ _auth_session(client)
+
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.get_env_setting",
+ return_value=True,
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+ # Ensure current_app has no news_scheduler
+ if hasattr(app, "news_scheduler"):
+ delattr(app, "news_scheduler")
+
+ resp = client.post("/news/api/scheduler/check-now")
+ assert resp.status_code == 503
+
+ def test_scheduler_not_running_returns_503(self, client, app):
+ """Returns 503 when scheduler exists but is_running is False."""
+ _auth_session(client)
+ app.news_scheduler = MagicMock()
+ app.news_scheduler.is_running = False
+
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.get_env_setting",
+ return_value=True,
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ resp = client.post("/news/api/scheduler/check-now")
+ assert resp.status_code == 503
+
+ # Clean up
+ delattr(app, "news_scheduler")
+
+
+class TestTriggerCleanup:
+ """Cover trigger_cleanup: scheduler.add_job scheduling."""
+
+ def test_cleanup_not_running_returns_400(self, client):
+ """Returns 400 when scheduler is not running."""
+ _auth_session(client)
+ mock_scheduler = MagicMock()
+ mock_scheduler.is_running = False
+
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.get_env_setting",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.news.flask_api.get_news_scheduler",
+ return_value=mock_scheduler,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",
+ return_value=mock_scheduler,
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ resp = client.post("/news/api/scheduler/cleanup-now")
+ assert resp.status_code == 400
+ assert "not running" in resp.get_json()["error"].lower()
+
+ def test_cleanup_triggered_returns_success(self, client):
+ """Returns triggered status when scheduler is running."""
+ _auth_session(client)
+ mock_scheduler = MagicMock()
+ mock_scheduler.is_running = True
+ mock_scheduler.scheduler = MagicMock()
+
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.get_env_setting",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",
+ return_value=mock_scheduler,
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ resp = client.post("/news/api/scheduler/cleanup-now")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["status"] == "triggered"
+ # Verify add_job was called
+ mock_scheduler.scheduler.add_job.assert_called_once()
+
+
+class TestSearchHistoryUnauthenticated:
+ """Cover unauthenticated return paths in search history endpoints."""
+
+ def test_get_search_history_unauthenticated_returns_empty(self, client):
+ """GET /search-history returns empty list when current_user is None."""
+ _auth_session(client)
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.current_user",
+ return_value=None,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.web.auth.decorators.current_user",
+ return_value=None,
+ create=True,
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ resp = client.get("/news/api/search-history")
+ assert resp.status_code == 200
+ assert resp.get_json()["search_history"] == []
+
+ def test_clear_search_history_unauthenticated_returns_success(self, client):
+ """DELETE /search-history returns success when current_user is None."""
+ _auth_session(client)
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.current_user",
+ return_value=None,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.web.auth.decorators.current_user",
+ return_value=None,
+ create=True,
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ resp = client.delete("/news/api/search-history")
+ assert resp.status_code == 200
+ assert resp.get_json()["status"] == "success"
+
+ def test_add_search_history_missing_query_returns_400(self, client):
+ """POST /search-history returns 400 when query field is missing."""
+ _auth_session(client)
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.web.auth.decorators.current_user",
+ return_value="testuser",
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ resp = client.post(
+ "/news/api/search-history",
+ json={"type": "filter"},
+ content_type="application/json",
+ )
+ assert resp.status_code == 400
+ assert "query" in resp.get_json()["error"].lower()
+
+ def test_add_search_history_unauthenticated_returns_401(self, client):
+ """POST /search-history returns 401 when current_user is None."""
+ _auth_session(client)
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.current_user",
+ return_value=None,
+ create=True,
+ ),
+ patch(
+ "local_deep_research.web.auth.decorators.current_user",
+ return_value=None,
+ create=True,
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+
+ resp = client.post(
+ "/news/api/search-history",
+ json={"query": "test"},
+ content_type="application/json",
+ )
+ assert resp.status_code == 401
diff --git a/tests/research_library/routes/test_rag_routes_background_coverage.py b/tests/research_library/routes/test_rag_routes_background_coverage.py
new file mode 100644
index 0000000000..0bc011f5c2
--- /dev/null
+++ b/tests/research_library/routes/test_rag_routes_background_coverage.py
@@ -0,0 +1,626 @@
+"""
+Coverage tests for background / helper functions in rag_routes.py.
+
+Targets lines in:
+- _get_rag_service_for_thread (use_defaults=True, bool normalize_vectors)
+- _auto_index_documents_worker (mixed success/skip/failure counting)
+- _background_index_worker (embedding metadata storage, filename fallback,
+ unknown status branch, mid-loop cancellation)
+- _update_task_status (progress_current-only update, failed status
+ without completed_at)
+- _is_task_cancelled (None task returns falsy)
+- trigger_auto_index (settings check exception)
+"""
+
+from contextlib import contextmanager
+from unittest.mock import Mock, patch
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+MODULE = "local_deep_research.research_library.routes.rag_routes"
+_DB_CTX = "local_deep_research.database.session_context"
+_EMB_MGR = (
+ "local_deep_research.web_search_engines.engines"
+ ".local_embedding_manager.LocalEmbeddingManager"
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _build_mock_query(all_result=None, first_result=None, count_result=0):
+ """Build a chainable mock query."""
+ q = Mock()
+ q.all.return_value = all_result or []
+ q.first.return_value = first_result
+ q.count.return_value = count_result
+ q.filter_by.return_value = q
+ q.filter.return_value = q
+ q.order_by.return_value = q
+ q.outerjoin.return_value = q
+ q.join.return_value = q
+ q.limit.return_value = q
+ q.offset.return_value = q
+ q.delete.return_value = 0
+ q.update.return_value = 0
+ return q
+
+
+def _make_db_session():
+ """Create a standard mock db session."""
+ s = Mock()
+ s.query = Mock(return_value=_build_mock_query())
+ s.commit = Mock()
+ s.add = Mock()
+ s.flush = Mock()
+ s.expire_all = Mock()
+ return s
+
+
+def _make_settings_mock(overrides=None):
+ """Create a mock settings manager."""
+ defaults = {
+ "local_search_embedding_model": "all-MiniLM-L6-v2",
+ "local_search_embedding_provider": "sentence_transformers",
+ "local_search_chunk_size": 1000,
+ "local_search_chunk_overlap": 200,
+ "local_search_splitter_type": "recursive",
+ "local_search_text_separators": '["\n\n", "\n", ". ", " ", ""]',
+ "local_search_distance_metric": "cosine",
+ "local_search_normalize_vectors": True,
+ "local_search_index_type": "flat",
+ "research_library.auto_index_enabled": True,
+ }
+ if overrides:
+ defaults.update(overrides)
+ mock_sm = Mock()
+ mock_sm.get_setting.side_effect = lambda k, d=None: defaults.get(k, d)
+ mock_sm.get_bool_setting.side_effect = lambda k, d=None: defaults.get(k, d)
+ mock_sm.get_settings_snapshot.return_value = {}
+ return mock_sm
+
+
+def _make_rag_service_mock():
+ """Create a mock LibraryRAGService that works as context manager."""
+ svc = Mock()
+ svc.__enter__ = Mock(return_value=svc)
+ svc.__exit__ = Mock(return_value=False)
+ svc.embedding_model = "all-MiniLM-L6-v2"
+ svc.embedding_provider = "sentence_transformers"
+ svc.chunk_size = 1000
+ svc.chunk_overlap = 200
+ svc.splitter_type = "recursive"
+ svc.text_separators = ["\n\n", "\n"]
+ svc.distance_metric = "cosine"
+ svc.normalize_vectors = True
+ svc.index_type = "flat"
+ return svc
+
+
+@contextmanager
+def _fake_db_session(db_session):
+ """Context manager that yields a mock db session."""
+ yield db_session
+
+
+# ---------------------------------------------------------------------------
+# _get_rag_service_for_thread
+# ---------------------------------------------------------------------------
+
+
+class TestGetRagServiceForThreadBackground:
+ """Additional coverage for _get_rag_service_for_thread."""
+
+ def test_use_defaults_true_ignores_collection_settings(self):
+ """When use_defaults=True, collection settings are ignored even if present."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _get_rag_service_for_thread,
+ )
+
+ mock_sm = _make_settings_mock()
+ mock_coll = Mock()
+ mock_coll.embedding_model = "custom-model"
+ mock_coll.embedding_model_type = Mock(value="ollama")
+ mock_coll.chunk_size = 999
+ mock_coll.chunk_overlap = 50
+ mock_coll.splitter_type = "character"
+ mock_coll.text_separators = ["\n"]
+ mock_coll.distance_metric = "l2"
+ mock_coll.normalize_vectors = False
+ mock_coll.index_type = "hnsw"
+
+ db_session = _make_db_session()
+ q = _build_mock_query(first_result=mock_coll)
+ db_session.query = Mock(return_value=q)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ mock_service = Mock()
+
+ with (
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{MODULE}.SettingsManager", return_value=mock_sm),
+ patch(
+ f"{MODULE}.LibraryRAGService", return_value=mock_service
+ ) as mock_rag_cls,
+ patch(f"{_EMB_MGR}") as mock_emb,
+ ):
+ mock_emb.return_value = Mock()
+ _get_rag_service_for_thread(
+ "coll-1", "testuser", "pass123", use_defaults=True
+ )
+
+ # Should use defaults, not the collection's custom-model
+ call_kwargs = mock_rag_cls.call_args.kwargs
+ assert call_kwargs["embedding_model"] == "all-MiniLM-L6-v2"
+ assert call_kwargs["embedding_provider"] == "sentence_transformers"
+ assert call_kwargs["chunk_size"] == 1000
+
+ def test_normalize_vectors_as_integer_coerced_to_bool(self):
+ """normalize_vectors stored as non-string truthy value is coerced via bool()."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _get_rag_service_for_thread,
+ )
+
+ mock_sm = _make_settings_mock()
+ mock_coll = Mock()
+ mock_coll.embedding_model = "test-model"
+ mock_coll.embedding_model_type = Mock(value="ollama")
+ mock_coll.chunk_size = 500
+ mock_coll.chunk_overlap = 100
+ mock_coll.splitter_type = "recursive"
+ mock_coll.text_separators = ["\n\n"]
+ mock_coll.distance_metric = "cosine"
+ mock_coll.normalize_vectors = 1 # integer, not str or None
+ mock_coll.index_type = "flat"
+
+ db_session = _make_db_session()
+ q = _build_mock_query(first_result=mock_coll)
+ db_session.query = Mock(return_value=q)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ mock_service = Mock()
+
+ with (
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{MODULE}.SettingsManager", return_value=mock_sm),
+ patch(
+ f"{MODULE}.LibraryRAGService", return_value=mock_service
+ ) as mock_rag_cls,
+ patch(f"{_EMB_MGR}") as mock_emb,
+ ):
+ mock_emb.return_value = Mock()
+ _get_rag_service_for_thread("coll-1", "testuser", "pass123")
+
+ call_kwargs = mock_rag_cls.call_args.kwargs
+ assert call_kwargs["normalize_vectors"] is True
+
+
+# ---------------------------------------------------------------------------
+# _auto_index_documents_worker
+# ---------------------------------------------------------------------------
+
+
+class TestAutoIndexDocumentsWorkerBackground:
+ """Additional coverage for _auto_index_documents_worker."""
+
+ def test_mixed_results_counts_successes_only(self):
+ """Worker counts successes while handling skips and per-doc failures."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _auto_index_documents_worker,
+ )
+
+ mock_service = Mock()
+ mock_service.__enter__ = Mock(return_value=mock_service)
+ mock_service.__exit__ = Mock(return_value=False)
+ mock_service.index_document.side_effect = [
+ {"status": "success"},
+ {"status": "skipped"},
+ RuntimeError("doc3 failed"),
+ {"status": "success"},
+ ]
+
+ with patch(
+ f"{MODULE}._get_rag_service_for_thread", return_value=mock_service
+ ):
+ # Should not raise despite the exception on doc3
+ _auto_index_documents_worker(
+ ["d1", "d2", "d3", "d4"], "coll-1", "user", "pass"
+ )
+
+ # All four documents were attempted
+ assert mock_service.index_document.call_count == 4
+
+
+# ---------------------------------------------------------------------------
+# _background_index_worker
+# ---------------------------------------------------------------------------
+
+
+class TestBackgroundIndexWorkerBackground:
+ """Additional coverage for _background_index_worker."""
+
+ def test_stores_embedding_metadata_when_collection_has_no_model(self):
+ """When collection.embedding_model is None, metadata is stored from rag_service."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _background_index_worker,
+ )
+
+ mock_svc = _make_rag_service_mock()
+
+ mock_coll = Mock()
+ mock_coll.embedding_model = None # triggers metadata storage
+
+ db_session = _make_db_session()
+ query_counter = {"n": 0}
+
+ def query_side_effect(*models):
+ query_counter["n"] += 1
+ q = _build_mock_query()
+ if query_counter["n"] == 1:
+ q.first.return_value = mock_coll
+ else:
+ q.all.return_value = [] # no docs
+ return q
+
+ db_session.query = Mock(side_effect=query_side_effect)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ statuses = []
+
+ def track_status(username, db_password, task_id, **kwargs):
+ statuses.append(kwargs)
+
+ with (
+ patch(
+ f"{MODULE}._get_rag_service_for_thread", return_value=mock_svc
+ ),
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{MODULE}._update_task_status", side_effect=track_status),
+ ):
+ _background_index_worker(
+ "task-1", "coll-1", "user", "pass", force_reindex=False
+ )
+
+ # Embedding metadata should have been stored on the collection
+ assert mock_coll.embedding_model == "all-MiniLM-L6-v2"
+ assert mock_coll.chunk_size == 1000
+ assert mock_coll.chunk_overlap == 200
+ db_session.commit.assert_called()
+
+ def test_filename_fallback_to_title(self):
+ """When doc.filename is None, title is used for progress messages."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _background_index_worker,
+ )
+
+ mock_svc = _make_rag_service_mock()
+ mock_svc.index_document.return_value = {"status": "success"}
+
+ mock_coll = Mock()
+ mock_coll.embedding_model = "model"
+
+ doc = Mock()
+ doc.filename = None
+ doc.title = "My Document Title"
+ doc.id = "doc-1"
+ link = Mock()
+
+ db_session = _make_db_session()
+ query_counter = {"n": 0}
+
+ def query_side_effect(*models):
+ query_counter["n"] += 1
+ q = _build_mock_query()
+ if query_counter["n"] == 1:
+ q.first.return_value = mock_coll
+ else:
+ q.all.return_value = [(link, doc)]
+ return q
+
+ db_session.query = Mock(side_effect=query_side_effect)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ statuses = []
+
+ def track_status(username, db_password, task_id, **kwargs):
+ statuses.append(kwargs)
+
+ with (
+ patch(
+ f"{MODULE}._get_rag_service_for_thread", return_value=mock_svc
+ ),
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{MODULE}._update_task_status", side_effect=track_status),
+ patch(f"{MODULE}._is_task_cancelled", return_value=False),
+ ):
+ _background_index_worker(
+ "task-1", "coll-1", "user", "pass", force_reindex=False
+ )
+
+ # Progress message should contain the title (not "Unknown")
+ progress_msgs = [s.get("progress_message", "") for s in statuses]
+ assert any("My Document Title" in msg for msg in progress_msgs)
+
+ def test_unknown_index_status_counts_as_failed(self):
+ """When index_document returns an unrecognized status, it counts as failed."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _background_index_worker,
+ )
+
+ mock_svc = _make_rag_service_mock()
+ mock_svc.index_document.return_value = {"status": "error"}
+
+ mock_coll = Mock()
+ mock_coll.embedding_model = "model"
+
+ doc = Mock()
+ doc.filename = "test.txt"
+ doc.title = None
+ doc.id = "doc-1"
+ link = Mock()
+
+ db_session = _make_db_session()
+ query_counter = {"n": 0}
+
+ def query_side_effect(*models):
+ query_counter["n"] += 1
+ q = _build_mock_query()
+ if query_counter["n"] == 1:
+ q.first.return_value = mock_coll
+ else:
+ q.all.return_value = [(link, doc)]
+ return q
+
+ db_session.query = Mock(side_effect=query_side_effect)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ statuses = []
+
+ def track_status(username, db_password, task_id, **kwargs):
+ statuses.append(kwargs)
+
+ with (
+ patch(
+ f"{MODULE}._get_rag_service_for_thread", return_value=mock_svc
+ ),
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{MODULE}._update_task_status", side_effect=track_status),
+ patch(f"{MODULE}._is_task_cancelled", return_value=False),
+ ):
+ _background_index_worker(
+ "task-1", "coll-1", "user", "pass", force_reindex=False
+ )
+
+ # Final completed message should show 1 failed, 0 indexed
+ final_msg = next(
+ (
+ s.get("progress_message", "")
+ for s in reversed(statuses)
+ if s.get("status") == "completed"
+ ),
+ "",
+ )
+ assert "1 failed" in final_msg
+ assert "0 indexed" in final_msg
+
+ def test_cancellation_after_first_document(self):
+ """Worker stops after indexing first document when cancelled before second."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _background_index_worker,
+ )
+
+ mock_svc = _make_rag_service_mock()
+ mock_svc.index_document.return_value = {"status": "success"}
+
+ mock_coll = Mock()
+ mock_coll.embedding_model = "model"
+
+ doc1 = Mock()
+ doc1.filename = "a.txt"
+ doc1.title = None
+ doc1.id = "d1"
+ doc2 = Mock()
+ doc2.filename = "b.txt"
+ doc2.title = None
+ doc2.id = "d2"
+ link1 = Mock()
+ link2 = Mock()
+
+ db_session = _make_db_session()
+ query_counter = {"n": 0}
+
+ def query_side_effect(*models):
+ query_counter["n"] += 1
+ q = _build_mock_query()
+ if query_counter["n"] == 1:
+ q.first.return_value = mock_coll
+ else:
+ q.all.return_value = [(link1, doc1), (link2, doc2)]
+ return q
+
+ db_session.query = Mock(side_effect=query_side_effect)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ statuses = []
+
+ def track_status(username, db_password, task_id, **kwargs):
+ statuses.append(kwargs)
+
+ # Cancel after the first document (False on first check, True on second)
+ cancel_calls = {"n": 0}
+
+ def cancel_side_effect(*a, **kw):
+ cancel_calls["n"] += 1
+ return cancel_calls["n"] > 1
+
+ with (
+ patch(
+ f"{MODULE}._get_rag_service_for_thread", return_value=mock_svc
+ ),
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{MODULE}._update_task_status", side_effect=track_status),
+ patch(
+ f"{MODULE}._is_task_cancelled", side_effect=cancel_side_effect
+ ),
+ ):
+ _background_index_worker(
+ "task-1", "coll-1", "user", "pass", force_reindex=False
+ )
+
+ # First document should have been indexed
+ assert mock_svc.index_document.call_count == 1
+ # Task should be marked cancelled
+ assert any(s.get("status") == "cancelled" for s in statuses)
+ cancel_msg = next(
+ s.get("progress_message", "")
+ for s in statuses
+ if s.get("status") == "cancelled"
+ )
+ assert "1/2" in cancel_msg
+
+
+# ---------------------------------------------------------------------------
+# _update_task_status
+# ---------------------------------------------------------------------------
+
+
+class TestUpdateTaskStatusBackground:
+ """Additional coverage for _update_task_status."""
+
+ def test_progress_current_only_without_status_change(self):
+ """Updating only progress_current does not set completed_at."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _update_task_status,
+ )
+
+ mock_task = Mock()
+ mock_task.status = "processing"
+ mock_task.completed_at = None
+
+ db_session = _make_db_session()
+ q = _build_mock_query(first_result=mock_task)
+ db_session.query = Mock(return_value=q)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ with patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session):
+ _update_task_status("user", "pass", "task-1", progress_current=5)
+
+ assert mock_task.progress_current == 5
+ # status and completed_at should not have been touched
+ assert mock_task.status == "processing"
+ assert mock_task.completed_at is None
+ db_session.commit.assert_called_once()
+
+ def test_failed_status_does_not_set_completed_at(self):
+ """Setting status to 'failed' does not set completed_at."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _update_task_status,
+ )
+
+ mock_task = Mock()
+ mock_task.status = "processing"
+ mock_task.completed_at = None
+
+ db_session = _make_db_session()
+ q = _build_mock_query(first_result=mock_task)
+ db_session.query = Mock(return_value=q)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ with patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session):
+ _update_task_status(
+ "user",
+ "pass",
+ "task-1",
+ status="failed",
+ error_message="something broke",
+ )
+
+ assert mock_task.status == "failed"
+ assert mock_task.error_message == "something broke"
+ # completed_at should remain None for failed status
+ assert mock_task.completed_at is None
+
+
+# ---------------------------------------------------------------------------
+# _is_task_cancelled
+# ---------------------------------------------------------------------------
+
+
+class TestIsTaskCancelledBackground:
+ """Additional coverage for _is_task_cancelled."""
+
+ def test_none_task_returns_falsy(self):
+ """When no task is found, the result is falsy."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _is_task_cancelled,
+ )
+
+ db_session = _make_db_session()
+ q = _build_mock_query(first_result=None)
+ db_session.query = Mock(return_value=q)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ with patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session):
+ result = _is_task_cancelled("user", "pass", "no-such-task")
+
+ # None and (None and ...) is falsy
+ assert not result
+
+
+# ---------------------------------------------------------------------------
+# trigger_auto_index
+# ---------------------------------------------------------------------------
+
+
+class TestTriggerAutoIndexBackground:
+ """Additional coverage for trigger_auto_index."""
+
+ def test_settings_check_exception_returns_early(self):
+ """When settings check raises, function returns without spawning thread."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ trigger_auto_index,
+ )
+
+ with (
+ patch(
+ f"{_DB_CTX}.get_user_db_session",
+ side_effect=RuntimeError("db unavailable"),
+ ),
+ patch(f"{MODULE}._get_auto_index_executor") as mock_executor,
+ ):
+ trigger_auto_index(["doc-1"], "coll-1", "user", "pass")
+
+ # Executor should never be called when settings check fails
+ mock_executor.assert_not_called()
diff --git a/tests/web/routes/test_settings_routes_corrupted_coverage.py b/tests/web/routes/test_settings_routes_corrupted_coverage.py
new file mode 100644
index 0000000000..4d29af72eb
--- /dev/null
+++ b/tests/web/routes/test_settings_routes_corrupted_coverage.py
@@ -0,0 +1,563 @@
+"""Tests targeting uncovered lines in settings_routes.py.
+
+Covered areas:
+- save_all_settings: corrupted value detection ([, ], {}, "[object Object]"),
+ report key -> empty dict, search.tool/app.theme defaults, new setting creation
+ with automatic UI element detection (checkbox, number, textarea), and creation
+ failure path
+- fix_corrupted_settings: duplicate key detection and removal, per-key default
+ value assignment (search.*, app.*, report.*), report unknown key fallback to
+ empty dict, empty dict corruption detection
+- save_settings: individual setting exception handling with failed_count
+- api_update_setting: new setting creation path when setting does not exist
+- api_get_data_location: platform detection (Windows/macOS/Linux)
+"""
+
+from contextlib import contextmanager
+from unittest.mock import MagicMock, Mock, patch
+
+from flask import Flask, jsonify
+
+from local_deep_research.web.auth.routes import auth_bp
+from local_deep_research.web.routes.settings_routes import settings_bp
+
+MODULE = "local_deep_research.web.routes.settings_routes"
+SETTINGS_PREFIX = "/settings"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_setting(
+ key="test.key",
+ value="val",
+ ui_element="text",
+ name="Test Key",
+ description="desc",
+ category="general",
+ setting_type="app",
+ editable=True,
+ visible=True,
+ options=None,
+ min_value=None,
+ max_value=None,
+ step=None,
+ updated_at=None,
+):
+ """Build a mock Setting ORM object."""
+ s = MagicMock()
+ s.key = key
+ s.value = value
+ s.ui_element = ui_element
+ s.name = name
+ s.description = description
+ s.category = category
+ s.type = setting_type
+ s.editable = editable
+ s.visible = visible
+ s.options = options
+ s.min_value = min_value
+ s.max_value = max_value
+ s.step = step
+ s.updated_at = updated_at
+ return s
+
+
+def _create_test_app():
+ """Create a minimal Flask app with only the settings blueprint."""
+ app = Flask(__name__)
+ app.config["SECRET_KEY"] = "test-secret"
+ app.config["WTF_CSRF_ENABLED"] = False
+ app.register_blueprint(auth_bp)
+ app.register_blueprint(settings_bp)
+
+ @app.errorhandler(500)
+ def _handle_500(error):
+ return jsonify({"error": "Internal server error"}), 500
+
+ return app
+
+
+@contextmanager
+def _authenticated_client(app):
+ """Provide an authenticated test client with mocked auth and settings_limit."""
+ mock_db = Mock()
+ mock_db.connections = {"testuser": True}
+ mock_db.has_encryption = False
+
+ @contextmanager
+ def _fake_session(*args, **kwargs):
+ yield MagicMock()
+
+ patches = [
+ patch("local_deep_research.web.auth.decorators.db_manager", mock_db),
+ patch(f"{MODULE}.get_user_db_session", side_effect=_fake_session),
+ patch(f"{MODULE}.settings_limit", lambda f: f),
+ ]
+
+ started = []
+ try:
+ for p in patches:
+ started.append(p.start())
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["session_id"] = "test-session-id"
+ yield client
+ finally:
+ for p in patches:
+ p.stop()
+
+
+# ---------------------------------------------------------------------------
+# Tests
+# ---------------------------------------------------------------------------
+
+
+class TestSaveAllSettingsCorruptedValues:
+ """save_all_settings: corrupted value detection and replacement."""
+
+ @patch(f"{MODULE}.set_setting", return_value=True)
+ @patch(
+ f"{MODULE}.coerce_setting_for_write",
+ side_effect=lambda key, value, ui_element: value,
+ )
+ @patch(f"{MODULE}.validate_setting", return_value=(True, None))
+ def test_bracket_open_detected_as_corrupted_for_search_tool(
+ self, mock_v, mock_c, mock_s
+ ):
+ """Value '[' is detected as corrupted; search.tool gets default 'auto'."""
+ setting = _make_setting(
+ key="search.tool", value="auto", ui_element="text", editable=True
+ )
+ setting.type = "search"
+
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.side_effect = [
+ [setting],
+ [setting],
+ ]
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+ resp = client.post(
+ f"{SETTINGS_PREFIX}/save_all_settings",
+ json={"search.tool": "["},
+ )
+ assert resp.status_code == 200
+ # The coerced value should have been replaced with "auto"
+ call_args = mock_c.call_args
+ assert (
+ call_args[1]["value"] == "auto" or call_args[0][0] == "search.tool"
+ )
+
+ @patch(f"{MODULE}.set_setting", return_value=True)
+ @patch(
+ f"{MODULE}.coerce_setting_for_write",
+ side_effect=lambda key, value, ui_element: value,
+ )
+ @patch(f"{MODULE}.validate_setting", return_value=(True, None))
+ def test_empty_braces_detected_as_corrupted_for_app_theme(
+ self, mock_v, mock_c, mock_s
+ ):
+ """Value '{}' is detected as corrupted; app.theme gets default 'dark'."""
+ setting = _make_setting(
+ key="app.theme", value="dark", ui_element="text", editable=True
+ )
+ setting.type = "app"
+
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.side_effect = [
+ [setting],
+ [setting],
+ ]
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+ resp = client.post(
+ f"{SETTINGS_PREFIX}/save_all_settings",
+ json={"app.theme": "{}"},
+ )
+ assert resp.status_code == 200
+ # coerce_setting_for_write should receive "dark" (the default)
+ _, kwargs = mock_c.call_args
+ assert kwargs["value"] == "dark"
+
+ @patch(f"{MODULE}.set_setting", return_value=True)
+ @patch(
+ f"{MODULE}.coerce_setting_for_write",
+ side_effect=lambda key, value, ui_element: value,
+ )
+ @patch(f"{MODULE}.validate_setting", return_value=(True, None))
+ def test_corrupted_report_key_gets_empty_dict(self, mock_v, mock_c, mock_s):
+ """report.* keys with corrupted values get replaced with empty dict."""
+ setting = _make_setting(
+ key="report.structure",
+ value={},
+ ui_element="textarea",
+ editable=True,
+ )
+ setting.type = "report"
+
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.side_effect = [
+ [setting],
+ [setting],
+ ]
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+ resp = client.post(
+ f"{SETTINGS_PREFIX}/save_all_settings",
+ json={"report.structure": "[]"},
+ )
+ assert resp.status_code == 200
+ _, kwargs = mock_c.call_args
+ assert kwargs["value"] == {}
+
+
+class TestSaveAllSettingsNewSettingCreationFailure:
+ """save_all_settings: new setting creation failure returns validation error."""
+
+ @patch(f"{MODULE}.create_or_update_setting", return_value=None)
+ def test_new_setting_creation_failure_gives_error(self, mock_create):
+ """When create_or_update_setting returns None, a validation error is recorded."""
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ # First call: no existing settings; second call: return list for response
+ mock_session.query.return_value.all.side_effect = [[], []]
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+ resp = client.post(
+ f"{SETTINGS_PREFIX}/save_all_settings",
+ json={"app.new_flag": "some_value"},
+ )
+ assert resp.status_code == 400
+ data = resp.get_json()
+ assert data["status"] == "error"
+ assert any(e["key"] == "app.new_flag" for e in data["errors"])
+
+ @patch(f"{MODULE}.create_or_update_setting")
+ def test_new_list_setting_gets_textarea(self, mock_create):
+ """A new setting with a list value gets ui_element 'textarea'."""
+ mock_new = _make_setting(key="app.items", value=[1, 2])
+ mock_new.type = "app"
+ mock_create.return_value = mock_new
+
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.side_effect = [[], []]
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+ resp = client.post(
+ f"{SETTINGS_PREFIX}/save_all_settings",
+ json={"app.items": [1, 2]},
+ )
+ assert resp.status_code == 200
+ call_args = mock_create.call_args[0][0]
+ assert call_args["ui_element"] == "textarea"
+
+
+class TestFixCorruptedSettingsDuplicatesAndDefaults:
+ """fix_corrupted_settings: duplicate removal and per-key default values."""
+
+ def test_duplicates_removed_and_corrupted_values_fixed(self):
+ """Duplicate keys are removed; corrupted values get per-key defaults."""
+ from datetime import datetime, UTC
+
+ now = datetime.now(UTC)
+
+ # Build two settings with the same key (duplicates)
+ dupe1 = _make_setting(
+ key="search.max_results", value=10, updated_at=now
+ )
+ dupe2 = _make_setting(key="search.max_results", value=5, updated_at=now)
+
+ # Build settings with various corrupted values
+ corrupted_search_region = _make_setting(
+ key="search.region", value="null"
+ )
+ corrupted_search_tool = _make_setting(
+ key="search.tool", value="[object Object]"
+ )
+ corrupted_app_theme = _make_setting(key="app.theme", value="{}")
+ corrupted_app_port = _make_setting(key="app.port", value=None)
+ corrupted_report_unknown = _make_setting(
+ key="report.custom_layout", value="undefined"
+ )
+ corrupted_empty_dict = _make_setting(
+ key="search.questions_per_iteration", value={}
+ )
+ clean_setting = _make_setting(key="llm.model", value="gpt-4")
+
+ all_settings = [
+ corrupted_search_region,
+ corrupted_search_tool,
+ corrupted_app_theme,
+ corrupted_app_port,
+ corrupted_report_unknown,
+ corrupted_empty_dict,
+ clean_setting,
+ ]
+
+ # Mock duplicate key query result
+ mock_dupe_key = MagicMock()
+ mock_dupe_key.__getitem__ = Mock(return_value="search.max_results")
+
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+
+ # Chain query mocks for duplicate detection
+ mock_group_query = MagicMock()
+ mock_group_query.group_by.return_value.having.return_value.all.return_value = [
+ mock_dupe_key
+ ]
+
+ # Chain for fetching duplicate settings by key
+ mock_filter_query = MagicMock()
+ mock_filter_query.filter.return_value.order_by.return_value.all.return_value = [
+ dupe1,
+ dupe2,
+ ]
+
+ # All settings query for corruption check
+ mock_all_query = MagicMock()
+ mock_all_query.all.return_value = all_settings
+
+ # Wire up the three query() calls
+ mock_session.query.side_effect = [
+ mock_group_query, # duplicate key detection
+ mock_filter_query, # fetch duplicates for removal
+ mock_all_query, # all settings for corruption check
+ ]
+
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+
+ resp = client.post(
+ f"{SETTINGS_PREFIX}/fix_corrupted_settings",
+ )
+
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["status"] == "success"
+ # Duplicate should have been deleted
+ mock_session.delete.assert_called_once_with(dupe2)
+ # Corrupted values should be fixed with defaults
+ assert corrupted_search_region.value == "us"
+ assert corrupted_search_tool.value == "auto"
+ assert corrupted_app_theme.value == "dark"
+ assert corrupted_app_port.value == 5000
+ # search.questions_per_iteration (empty dict -> corrupted)
+ assert corrupted_empty_dict.value == 3
+ # report.custom_layout has no known default -> fallback to empty dict
+ assert corrupted_report_unknown.value == {}
+
+ def test_fix_corrupted_settings_exception_returns_500(self):
+ """When an exception occurs, rollback and return 500."""
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ mock_session.query.side_effect = RuntimeError("db failure")
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+
+ resp = client.post(
+ f"{SETTINGS_PREFIX}/fix_corrupted_settings",
+ )
+
+ assert resp.status_code == 500
+ data = resp.get_json()
+ assert data["status"] == "error"
+ mock_session.rollback.assert_called_once()
+
+
+class TestSaveSettingsExceptionInLoop:
+ """save_settings (POST fallback): exception inside the per-setting loop."""
+
+ def test_setting_exception_increments_failed_count(self):
+ """When a single setting raises, failed_count increments and flash warns."""
+ setting = _make_setting(
+ key="llm.temperature", value=0.7, ui_element="number", editable=True
+ )
+
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.return_value = [setting]
+
+ mock_sm = MagicMock()
+ mock_sm.set_setting.side_effect = RuntimeError("save error")
+
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+
+ with patch(f"{MODULE}.SettingsManager", return_value=mock_sm):
+ with patch(
+ f"{MODULE}.coerce_setting_for_write",
+ side_effect=RuntimeError("coerce error"),
+ ):
+ resp = client.post(
+ f"{SETTINGS_PREFIX}/save_settings",
+ data={"llm.temperature": "0.5"},
+ )
+
+ # save_settings redirects on completion
+ assert resp.status_code == 302
+
+
+class TestApiUpdateSettingCreatesNew:
+ """api_update_setting: when the setting does not exist, create a new one."""
+
+ def test_create_new_setting_via_put(self):
+ """PUT to a non-existent key creates a new setting and returns 201."""
+ mock_new = _make_setting(key="custom.new_param", value="hello")
+ mock_new.type = MagicMock()
+ mock_new.type.value = "app"
+
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ # Setting does not exist
+ mock_session.query.return_value.filter.return_value.first.return_value = None
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+
+ with patch(
+ f"{MODULE}.create_or_update_setting",
+ return_value=mock_new,
+ ):
+ resp = client.put(
+ f"{SETTINGS_PREFIX}/api/custom.new_param",
+ json={"value": "hello", "type": "app"},
+ )
+
+ assert resp.status_code == 201
+ data = resp.get_json()
+ assert "created successfully" in data["message"]
+ assert data["setting"]["key"] == "custom.new_param"
+
+ def test_create_new_setting_failure_returns_500(self):
+ """PUT to a non-existent key returns 500 when creation fails."""
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter.return_value.first.return_value = None
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+
+ with patch(
+ f"{MODULE}.create_or_update_setting",
+ return_value=None,
+ ):
+ resp = client.put(
+ f"{SETTINGS_PREFIX}/api/custom.new_param",
+ json={"value": "hello"},
+ )
+
+ assert resp.status_code == 500
+ data = resp.get_json()
+ assert "Failed to create" in data["error"]
+
+
+class TestApiGetDataLocationPlatform:
+ """api_get_data_location: platform detection branches."""
+
+ def _call_data_location(self, platform_system_return):
+ """Helper that calls the data-location endpoint with mocked platform."""
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ with patch(f"{MODULE}.get_user_db_session") as mock_ctx:
+ mock_session = MagicMock()
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+
+ mock_sm = MagicMock()
+ mock_sm.get_setting.return_value = None
+
+ with (
+ patch(f"{MODULE}.get_data_directory", return_value="/data"),
+ patch(
+ f"{MODULE}.get_encrypted_database_path",
+ return_value="/data/db",
+ ),
+ patch(f"{MODULE}.SettingsManager", return_value=mock_sm),
+ patch(f"{MODULE}.platform") as mock_platform,
+ patch(f"{MODULE}.db_manager") as mock_db_mgr,
+ ):
+ mock_platform.system.return_value = platform_system_return
+ mock_db_mgr.has_encryption = False
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ mock_db_mgr,
+ ):
+ # Re-set session since we re-patched db_manager
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["session_id"] = "test-session-id"
+
+ resp = client.get(
+ f"{SETTINGS_PREFIX}/api/data-location",
+ )
+
+ return resp
+
+ def test_linux_platform(self):
+ resp = self._call_data_location("Linux")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["platform"] == "Linux"
+ assert "Linux" in data["platform_info"]
+
+ def test_darwin_mapped_to_macos(self):
+ resp = self._call_data_location("Darwin")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["platform"] == "macOS"
+
+ def test_windows_platform(self):
+ resp = self._call_data_location("Windows")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["platform"] == "Windows"
diff --git a/tests/web/services/test_research_service_coverage_gaps.py b/tests/web/services/test_research_service_coverage_gaps.py
new file mode 100644
index 0000000000..9c6f734e34
--- /dev/null
+++ b/tests/web/services/test_research_service_coverage_gaps.py
@@ -0,0 +1,761 @@
+"""
+Tests for coverage gaps in research_service.py.
+
+Targets specific uncovered lines:
+- run_research_process early termination (307-313)
+- SettingsContext inner class (358-380)
+- progress_callback termination check (428-434)
+- LLM config error handling with ValueError raise (605-630)
+- Search engine config error handling with ValueError raise (646-670)
+- Search error classification (703-727)
+- cleanup_research_resources test-mode delay path (1693-1699)
+- handle_termination exception path (1797-1800)
+- cancel_research database exception path (1860-1864)
+- cancel_research outer exception path (1867-1871)
+"""
+
+from contextlib import contextmanager
+from unittest.mock import MagicMock, patch
+
+from loguru import logger
+
+# Register MILESTONE log level used by progress_callback
+try:
+ logger.level("MILESTONE")
+except ValueError:
+ logger.level("MILESTONE", no=26)
+
+# Module path constants
+MODULE = "local_deep_research.web.services.research_service"
+GLOBALS_MOD = "local_deep_research.web.routes.globals"
+THREAD_SETTINGS_MOD = "local_deep_research.config.thread_settings"
+SETTINGS_LOGGER_MOD = "local_deep_research.settings.logger"
+QUEUE_PROC_MOD = "local_deep_research.web.queue.processor_v2"
+ENV_REGISTRY_MOD = "local_deep_research.settings.env_registry"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _fake_session_ctx(session=None):
+ """Return a context manager factory that yields a mock session."""
+ if session is None:
+ session = MagicMock()
+
+ @contextmanager
+ def ctx(username=None):
+ yield session
+
+ return ctx
+
+
+def _make_mock_research(status=None, research_meta=None):
+ """Build a minimal ResearchHistory mock."""
+ r = MagicMock()
+ r.status = status
+ r.research_meta = research_meta
+ r.created_at = "2024-01-01T00:00:00"
+ r.report_content = None
+ return r
+
+
+def _get_raw_run_research_process():
+ """Get the unwrapped (no decorators) run_research_process function."""
+ from local_deep_research.web.services.research_service import (
+ run_research_process,
+ )
+
+ return run_research_process.__wrapped__.__wrapped__
+
+
+def _base_run_patches(mock_session=None):
+ """Return a dict of patches needed for run_research_process tests."""
+ if mock_session is None:
+ mock_session = MagicMock()
+ mock_research = _make_mock_research(research_meta={})
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research
+
+ return {
+ f"{MODULE}.get_user_db_session": _fake_session_ctx(mock_session),
+ f"{MODULE}.handle_termination": MagicMock(),
+ f"{MODULE}.cleanup_research_resources": MagicMock(),
+ f"{MODULE}.set_search_context": MagicMock(),
+ f"{MODULE}.SocketIOService": MagicMock(),
+ f"{MODULE}.calculate_duration": MagicMock(return_value=5),
+ f"{MODULE}.ErrorReportGenerator": MagicMock(
+ return_value=MagicMock(
+ generate_error_report=MagicMock(return_value="error report")
+ )
+ ),
+ f"{GLOBALS_MOD}.is_termination_requested": MagicMock(
+ return_value=False
+ ),
+ f"{GLOBALS_MOD}.is_research_active": MagicMock(return_value=False),
+ f"{GLOBALS_MOD}.update_progress_and_check_active": MagicMock(
+ return_value=(5, True)
+ ),
+ f"{SETTINGS_LOGGER_MOD}.log_settings": MagicMock(),
+ f"{THREAD_SETTINGS_MOD}.set_settings_context": MagicMock(),
+ f"{QUEUE_PROC_MOD}.queue_processor": MagicMock(),
+ }
+
+
+# ---------------------------------------------------------------------------
+# 1. run_research_process early termination (lines 307-313)
+# ---------------------------------------------------------------------------
+
+
+class TestRunResearchEarlyTermination:
+ """When termination is requested before the research even starts,
+ the function should clean up and return immediately."""
+
+ def test_returns_immediately_when_terminated_before_start(self):
+ """If is_termination_requested returns True on entry, the function
+ calls cleanup_research_resources and returns without running research."""
+ func = _get_raw_run_research_process()
+ mock_cleanup = MagicMock()
+
+ patches = _base_run_patches()
+ # Override: termination already requested
+ patches[f"{GLOBALS_MOD}.is_termination_requested"] = MagicMock(
+ return_value=True
+ )
+ patches[f"{MODULE}.cleanup_research_resources"] = mock_cleanup
+
+ # AdvancedSearchSystem should never be instantiated
+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock()
+
+ stack = []
+ for target, mock_obj in patches.items():
+ p = patch(target, mock_obj)
+ stack.append(p)
+ p.start()
+ try:
+ func(1, "test query", "quick", username="testuser")
+ finally:
+ for p in stack:
+ p.stop()
+
+ # cleanup_research_resources must have been called
+ mock_cleanup.assert_called_once_with(1, "testuser")
+ # AdvancedSearchSystem should not have been created
+ patches[f"{MODULE}.AdvancedSearchSystem"].assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# 2. SettingsContext inner class (lines 358-380)
+# ---------------------------------------------------------------------------
+
+
+class TestSettingsContextInnerClass:
+ """The SettingsContext inner class in run_research_process extracts
+ values from a settings snapshot and provides get_setting()."""
+
+ def test_settings_context_extracts_dict_values(self):
+ """When snapshot items are full setting objects with 'value' keys,
+ SettingsContext should extract just the value."""
+ func = _get_raw_run_research_process()
+
+ captured_contexts = []
+ original_set = MagicMock()
+
+ def capture_settings_context(ctx):
+ captured_contexts.append(ctx)
+ original_set(ctx)
+
+ mock_system = MagicMock()
+ mock_system.analyze_topic.return_value = {
+ "findings": "test",
+ "formatted_findings": "test result",
+ }
+
+ patches = _base_run_patches()
+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(
+ return_value=mock_system
+ )
+ patches[f"{THREAD_SETTINGS_MOD}.set_settings_context"] = (
+ capture_settings_context
+ )
+
+ snapshot = {
+ "llm.model": {"value": "gpt-4", "type": "string"},
+ "search.max_results": {"value": 10, "type": "int"},
+ "plain_key": "just_a_value",
+ }
+
+ stack = []
+ for target, mock_obj in patches.items():
+ p = patch(target, mock_obj)
+ stack.append(p)
+ p.start()
+ try:
+ func(
+ 1,
+ "test",
+ "quick",
+ username="user1",
+ settings_snapshot=snapshot,
+ )
+ finally:
+ for p in stack:
+ p.stop()
+
+ assert len(captured_contexts) == 1
+ ctx = captured_contexts[0]
+ # Full setting objects should have their values extracted
+ assert ctx.get_setting("llm.model") == "gpt-4"
+ assert ctx.get_setting("search.max_results") == 10
+ # Plain values should be kept as-is
+ assert ctx.get_setting("plain_key") == "just_a_value"
+
+ def test_settings_context_returns_default_for_missing_key(self):
+ """get_setting returns default when key is not in snapshot."""
+ func = _get_raw_run_research_process()
+
+ captured_contexts = []
+
+ def capture(ctx):
+ captured_contexts.append(ctx)
+
+ mock_system = MagicMock()
+ mock_system.analyze_topic.return_value = {
+ "findings": "test",
+ "formatted_findings": "result",
+ }
+
+ patches = _base_run_patches()
+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(
+ return_value=mock_system
+ )
+ patches[f"{THREAD_SETTINGS_MOD}.set_settings_context"] = capture
+
+ stack = []
+ for target, mock_obj in patches.items():
+ p = patch(target, mock_obj)
+ stack.append(p)
+ p.start()
+ try:
+ func(
+ 1,
+ "test",
+ "quick",
+ username="user1",
+ settings_snapshot={},
+ )
+ finally:
+ for p in stack:
+ p.stop()
+
+ ctx = captured_contexts[0]
+ assert ctx.get_setting("nonexistent.key", "fallback") == "fallback"
+ assert ctx.get_setting("nonexistent.key") is None
+
+
+# ---------------------------------------------------------------------------
+# 3. progress_callback termination check (lines 428-434)
+# ---------------------------------------------------------------------------
+
+
+class TestProgressCallbackTerminationCheck:
+ """progress_callback checks is_termination_requested on every call and
+ raises ResearchTerminatedException if termination was requested."""
+
+ def test_progress_callback_raises_on_termination(self):
+ """When termination is requested mid-research, progress_callback
+ should call handle_termination and raise ResearchTerminatedException."""
+ from local_deep_research.exceptions import (
+ ResearchTerminatedException,
+ )
+
+ func = _get_raw_run_research_process()
+
+ call_count = [0]
+ mock_handle = MagicMock()
+
+ def termination_check(rid):
+ call_count[0] += 1
+ # Return True on second call (first call is the early-exit check,
+ # second call is from inside progress_callback)
+ return call_count[0] >= 2
+
+ mock_system = MagicMock()
+ # analyze_topic will trigger progress_callback which triggers termination
+ mock_system.analyze_topic.side_effect = ResearchTerminatedException(
+ "terminated"
+ )
+
+ patches = _base_run_patches()
+ patches[f"{GLOBALS_MOD}.is_termination_requested"] = termination_check
+ patches[f"{MODULE}.handle_termination"] = mock_handle
+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(
+ return_value=mock_system
+ )
+
+ stack = []
+ for target, mock_obj in patches.items():
+ p = patch(target, mock_obj)
+ stack.append(p)
+ p.start()
+ try:
+ # The function catches ResearchTerminatedException internally
+ func(1, "test", "quick", username="user1", settings_snapshot={})
+ finally:
+ for p in stack:
+ p.stop()
+
+ # The function should not propagate ResearchTerminatedException
+ # (it is caught in the except ResearchTerminatedException block)
+
+
+# ---------------------------------------------------------------------------
+# 4. LLM config error handling (lines 605-630)
+# ---------------------------------------------------------------------------
+
+
+class TestLLMConfigErrorRaisesValueError:
+ """When get_llm raises an error containing config-related keywords,
+ the code re-raises as ValueError('LLM Configuration Error: ...')."""
+
+ def _run_with_llm_error(self, error_msg, model="gpt-4", provider="openai"):
+ """Run research with get_llm raising an exception containing error_msg."""
+ func = _get_raw_run_research_process()
+ mock_qp = MagicMock()
+
+ patches = _base_run_patches()
+ patches[f"{MODULE}.get_llm"] = MagicMock(
+ side_effect=Exception(error_msg)
+ )
+ patches[f"{QUEUE_PROC_MOD}.queue_processor"] = mock_qp
+
+ stack = []
+ for target, mock_obj in patches.items():
+ p = patch(target, mock_obj)
+ stack.append(p)
+ p.start()
+ try:
+ func(
+ 1,
+ "test",
+ "quick",
+ username="user1",
+ model=model,
+ model_provider=provider,
+ settings_snapshot={},
+ )
+ finally:
+ for p in stack:
+ p.stop()
+
+ return mock_qp
+
+ def test_llamacpp_keyword_triggers_config_error(self):
+ """'llamacpp' in error message triggers ValueError with config prefix."""
+ mock_qp = self._run_with_llm_error("llamacpp model failed to load")
+ # Error is caught by outer handler and queued
+ mock_qp.queue_error_update.assert_called_once()
+ call_kwargs = mock_qp.queue_error_update.call_args
+ assert "LLM Configuration Error" in str(call_kwargs)
+
+ def test_model_path_keyword_triggers_config_error(self):
+ """'model path' in error message triggers ValueError with config prefix."""
+ mock_qp = self._run_with_llm_error("model path /foo/bar does not exist")
+ mock_qp.queue_error_update.assert_called_once()
+ assert "LLM Configuration Error" in str(
+ mock_qp.queue_error_update.call_args
+ )
+
+ def test_gguf_keyword_triggers_config_error(self):
+ """'.gguf' in error message triggers ValueError with config prefix."""
+ mock_qp = self._run_with_llm_error("please provide a valid .gguf file")
+ mock_qp.queue_error_update.assert_called_once()
+ assert "LLM Configuration Error" in str(
+ mock_qp.queue_error_update.call_args
+ )
+
+ def test_non_config_llm_error_re_raises_directly(self):
+ """Errors without config keywords are re-raised as-is (not wrapped)."""
+ mock_qp = self._run_with_llm_error(
+ "unexpected null pointer in inference"
+ )
+ mock_qp.queue_error_update.assert_called_once()
+ # Should NOT contain "LLM Configuration Error" prefix
+ error_str = str(mock_qp.queue_error_update.call_args)
+ assert "LLM Configuration Error" not in error_str
+
+
+# ---------------------------------------------------------------------------
+# 5. Search engine config error handling (lines 646-670)
+# ---------------------------------------------------------------------------
+
+
+class TestSearchEngineConfigError:
+ """When get_search raises with config keywords, the code re-raises as
+ ValueError('Search Engine Configuration Error ...')."""
+
+ def _run_with_search_error(self, error_msg, search_engine="searxng"):
+ func = _get_raw_run_research_process()
+ mock_qp = MagicMock()
+
+ patches = _base_run_patches()
+ patches[f"{MODULE}.get_search"] = MagicMock(
+ side_effect=Exception(error_msg)
+ )
+ patches[f"{QUEUE_PROC_MOD}.queue_processor"] = mock_qp
+
+ stack = []
+ for target, mock_obj in patches.items():
+ p = patch(target, mock_obj)
+ stack.append(p)
+ p.start()
+ try:
+ func(
+ 1,
+ "test",
+ "quick",
+ username="user1",
+ search_engine=search_engine,
+ settings_snapshot={},
+ )
+ finally:
+ for p in stack:
+ p.stop()
+
+ return mock_qp
+
+ def test_searxng_keyword_triggers_config_error(self):
+ """'searxng' in error message triggers Search Engine Configuration Error."""
+ mock_qp = self._run_with_search_error("SearXNG instance unreachable")
+ mock_qp.queue_error_update.assert_called_once()
+ assert "Search Engine Configuration Error" in str(
+ mock_qp.queue_error_update.call_args
+ )
+
+ def test_api_key_keyword_triggers_config_error(self):
+ """'api_key' in error message triggers Search Engine Configuration Error."""
+ mock_qp = self._run_with_search_error(
+ "Missing api_key for search provider"
+ )
+ mock_qp.queue_error_update.assert_called_once()
+ assert "Search Engine Configuration Error" in str(
+ mock_qp.queue_error_update.call_args
+ )
+
+ def test_connection_keyword_triggers_config_error(self):
+ """'connection' in error message triggers Search Engine Configuration Error."""
+ mock_qp = self._run_with_search_error(
+ "Connection refused by search backend"
+ )
+ mock_qp.queue_error_update.assert_called_once()
+ assert "Search Engine Configuration Error" in str(
+ mock_qp.queue_error_update.call_args
+ )
+
+ def test_non_config_search_error_re_raises(self):
+ """Errors without config keywords are re-raised as-is."""
+ mock_qp = self._run_with_search_error("some random internal crash")
+ mock_qp.queue_error_update.assert_called_once()
+ error_str = str(mock_qp.queue_error_update.call_args)
+ assert "Search Engine Configuration Error" not in error_str
+
+
+# ---------------------------------------------------------------------------
+# 6. Search error classification (lines 703-727)
+# ---------------------------------------------------------------------------
+
+
+class TestSearchErrorClassification:
+ """system.analyze_topic() failures are classified by HTTP status code
+ or connection error pattern and re-raised with improved messages."""
+
+ def _run_with_analyze_error(self, error_msg):
+ func = _get_raw_run_research_process()
+ mock_qp = MagicMock()
+
+ mock_system = MagicMock()
+ mock_system.analyze_topic.side_effect = Exception(error_msg)
+
+ patches = _base_run_patches()
+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(
+ return_value=mock_system
+ )
+ patches[f"{QUEUE_PROC_MOD}.queue_processor"] = mock_qp
+
+ stack = []
+ for target, mock_obj in patches.items():
+ p = patch(target, mock_obj)
+ stack.append(p)
+ p.start()
+ try:
+ func(
+ 1,
+ "test",
+ "quick",
+ username="user1",
+ settings_snapshot={},
+ )
+ finally:
+ for p in stack:
+ p.stop()
+
+ return mock_qp
+
+ def test_503_classified_as_ollama_unavailable(self):
+ """HTTP 503 is classified as ollama_unavailable by the inner handler
+ (lines 709-711), then the outer handler (lines 1469-1473) rewrites it
+ to a user-friendly message with a solution hint."""
+ mock_qp = self._run_with_analyze_error(
+ "Request failed with status code: 503"
+ )
+ mock_qp.queue_error_update.assert_called_once()
+ call_kwargs = mock_qp.queue_error_update.call_args[1]
+ # Outer handler replaces the error type marker with user-friendly text
+ assert (
+ "Ollama AI service is unavailable" in call_kwargs["error_message"]
+ )
+ assert "solution" in call_kwargs["metadata"]
+ assert "ollama serve" in call_kwargs["metadata"]["solution"]
+
+ def test_404_classified_as_model_not_found(self):
+ """HTTP 404 is classified as model_not_found by the inner handler
+ (lines 712-714), then rewritten by outer handler (lines 1474-1478)."""
+ mock_qp = self._run_with_analyze_error(
+ "Request failed with status code: 404"
+ )
+ mock_qp.queue_error_update.assert_called_once()
+ call_kwargs = mock_qp.queue_error_update.call_args[1]
+ assert "model not found" in call_kwargs["error_message"].lower()
+ assert "solution" in call_kwargs["metadata"]
+ assert "ollama pull" in call_kwargs["metadata"]["solution"]
+
+ def test_other_status_code_classified_as_api_error(self):
+ """Other HTTP status codes are classified as api_error by lines 715-719,
+ then matched by 'Error type: api_error' in the outer handler (line 1484)."""
+ mock_qp = self._run_with_analyze_error(
+ "Request failed with status code: 429"
+ )
+ mock_qp.queue_error_update.assert_called_once()
+ call_kwargs = mock_qp.queue_error_update.call_args[1]
+ assert "solution" in call_kwargs["metadata"]
+ assert "API" in call_kwargs["metadata"]["solution"]
+
+ def test_connection_error_classified_correctly(self):
+ """Connection errors (case-insensitive) are classified as connection_error
+ by lines 720-722, then rewritten by outer handler (lines 1479-1483)."""
+ mock_qp = self._run_with_analyze_error(
+ "Connection refused to localhost:11434"
+ )
+ mock_qp.queue_error_update.assert_called_once()
+ call_kwargs = mock_qp.queue_error_update.call_args[1]
+ assert "Connection error" in call_kwargs["error_message"]
+ assert "solution" in call_kwargs["metadata"]
+
+ def test_unknown_error_preserves_original_message(self):
+ """Errors without known patterns keep error_type=unknown in the re-raised
+ exception, and the outer handler does not match any rewrite pattern."""
+ mock_qp = self._run_with_analyze_error(
+ "something completely unexpected happened"
+ )
+ mock_qp.queue_error_update.assert_called_once()
+ call_kwargs = mock_qp.queue_error_update.call_args[1]
+ # No solution context is added for unknown errors
+ assert "solution" not in call_kwargs["metadata"]
+
+
+# ---------------------------------------------------------------------------
+# 7. cleanup_research_resources test-mode delay (lines 1693-1699)
+# ---------------------------------------------------------------------------
+
+
+class TestCleanupResearchResourcesTestMode:
+ """When is_test_mode() returns True, cleanup adds a 5-second delay."""
+
+ @patch(f"{MODULE}.SocketIOService")
+ @patch(f"{GLOBALS_MOD}.cleanup_research")
+ @patch(f"{QUEUE_PROC_MOD}.queue_processor")
+ @patch(f"{ENV_REGISTRY_MOD}.is_test_mode", return_value=True)
+ def test_test_mode_sleeps_before_cleanup(
+ self, mock_test_mode, mock_qp, mock_cleanup, mock_socket
+ ):
+ """In test mode, time.sleep(5) is called before continuing cleanup."""
+ from local_deep_research.web.services.research_service import (
+ cleanup_research_resources,
+ )
+
+ with patch(f"{MODULE}.time.sleep") as mock_sleep:
+ cleanup_research_resources(42, username="user1")
+
+ mock_sleep.assert_called_once_with(5)
+ mock_test_mode.assert_called_once()
+
+ @patch(f"{MODULE}.SocketIOService")
+ @patch(f"{GLOBALS_MOD}.cleanup_research")
+ @patch(f"{QUEUE_PROC_MOD}.queue_processor")
+ @patch(f"{ENV_REGISTRY_MOD}.is_test_mode", return_value=False)
+ def test_non_test_mode_does_not_sleep(
+ self, mock_test_mode, mock_qp, mock_cleanup, mock_socket
+ ):
+ """Outside test mode, no delay is added."""
+ from local_deep_research.web.services.research_service import (
+ cleanup_research_resources,
+ )
+
+ with patch(f"{MODULE}.time.sleep") as mock_sleep:
+ cleanup_research_resources(42, username="user1")
+
+ mock_sleep.assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# 8. handle_termination exception path (lines 1797-1800)
+# ---------------------------------------------------------------------------
+
+
+class TestHandleTerminationExceptionPath:
+ """When queue_processor.queue_error_update raises, handle_termination
+ catches the exception and still proceeds to cleanup."""
+
+ @patch(f"{MODULE}.cleanup_research_resources")
+ def test_queue_error_exception_is_caught_and_cleanup_still_runs(
+ self, mock_cleanup
+ ):
+ """If queue_error_update raises, the exception is caught and
+ cleanup_research_resources is still called."""
+ from local_deep_research.web.services.research_service import (
+ handle_termination,
+ )
+
+ mock_qp = MagicMock()
+ mock_qp.queue_error_update.side_effect = RuntimeError(
+ "queue processor down"
+ )
+
+ with patch(f"{QUEUE_PROC_MOD}.queue_processor", mock_qp):
+ # Should not raise
+ handle_termination(99, username="user1")
+
+ # cleanup_research_resources must still be called despite the error
+ mock_cleanup.assert_called_once_with(99, "user1")
+
+ @patch(f"{MODULE}.cleanup_research_resources")
+ def test_successful_termination_queues_suspended_status(self, mock_cleanup):
+ """On success, handle_termination queues a SUSPENDED status update."""
+ from local_deep_research.constants import ResearchStatus
+ from local_deep_research.web.services.research_service import (
+ handle_termination,
+ )
+
+ mock_qp = MagicMock()
+
+ with patch(f"{QUEUE_PROC_MOD}.queue_processor", mock_qp):
+ handle_termination(55, username="user1")
+
+ mock_qp.queue_error_update.assert_called_once()
+ call_kwargs = mock_qp.queue_error_update.call_args[1]
+ assert call_kwargs["status"] == ResearchStatus.SUSPENDED
+ assert call_kwargs["username"] == "user1"
+ assert call_kwargs["research_id"] == 55
+ mock_cleanup.assert_called_once_with(55, "user1")
+
+
+# ---------------------------------------------------------------------------
+# 9. cancel_research database exception path (lines 1860-1864)
+# ---------------------------------------------------------------------------
+
+
+class TestCancelResearchDbException:
+ """When the database query in the inactive-research branch of
+ cancel_research raises, the function returns False."""
+
+ def test_db_exception_returns_false(self):
+ """Database errors in the non-active path return False."""
+ from local_deep_research.web.services.research_service import (
+ cancel_research,
+ )
+
+ with patch(f"{GLOBALS_MOD}.set_termination_flag"):
+ with patch(f"{GLOBALS_MOD}.is_research_active", return_value=False):
+ with patch(
+ f"{MODULE}.get_user_db_session",
+ side_effect=RuntimeError("db connection lost"),
+ ):
+ result = cancel_research(123, username="user1")
+
+ assert result is False
+
+ def test_db_not_found_returns_false(self):
+ """When research is not found in database, returns False."""
+ from local_deep_research.web.services.research_service import (
+ cancel_research,
+ )
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ with patch(f"{GLOBALS_MOD}.set_termination_flag"):
+ with patch(f"{GLOBALS_MOD}.is_research_active", return_value=False):
+ with patch(
+ f"{MODULE}.get_user_db_session",
+ _fake_session_ctx(mock_session),
+ ):
+ result = cancel_research(123, username="user1")
+
+ assert result is False
+
+
+# ---------------------------------------------------------------------------
+# 10. cancel_research outer exception path (lines 1867-1871)
+# ---------------------------------------------------------------------------
+
+
+class TestCancelResearchOuterException:
+ """When an unexpected exception occurs in cancel_research's outer try
+ block (e.g., set_termination_flag itself raises), the function catches
+ the exception and returns False."""
+
+ def test_set_termination_flag_raises_returns_false(self):
+ """If set_termination_flag raises, cancel_research returns False."""
+ from local_deep_research.web.services.research_service import (
+ cancel_research,
+ )
+
+ with patch(
+ f"{GLOBALS_MOD}.set_termination_flag",
+ side_effect=RuntimeError("unexpected failure"),
+ ):
+ result = cancel_research(456, username="user1")
+
+ assert result is False
+
+ def test_is_research_active_raises_returns_false(self):
+ """If is_research_active raises, cancel_research returns False."""
+ from local_deep_research.web.services.research_service import (
+ cancel_research,
+ )
+
+ with patch(f"{GLOBALS_MOD}.set_termination_flag"):
+ with patch(
+ f"{GLOBALS_MOD}.is_research_active",
+ side_effect=RuntimeError("state corrupted"),
+ ):
+ result = cancel_research(789, username="user1")
+
+ assert result is False
+
+ def test_active_research_calls_handle_termination_and_returns_true(self):
+ """When research IS active, cancel_research calls handle_termination
+ and returns True."""
+ from local_deep_research.web.services.research_service import (
+ cancel_research,
+ )
+
+ mock_handle = MagicMock()
+
+ with patch(f"{GLOBALS_MOD}.set_termination_flag"):
+ with patch(f"{GLOBALS_MOD}.is_research_active", return_value=True):
+ with patch(f"{MODULE}.handle_termination", mock_handle):
+ result = cancel_research(10, username="user1")
+
+ assert result is True
+ mock_handle.assert_called_once_with(10, "user1")
diff --git a/tests/web_search_engines/test_search_engine_factory_branch_coverage.py b/tests/web_search_engines/test_search_engine_factory_branch_coverage.py
new file mode 100644
index 0000000000..cbd29d1a1c
--- /dev/null
+++ b/tests/web_search_engines/test_search_engine_factory_branch_coverage.py
@@ -0,0 +1,486 @@
+"""
+Branch-coverage tests for search_engine_factory.py and llm_config.py.
+
+Targets specific uncovered branch paths not exercised by existing test suites:
+
+search_engine_factory.py:
+ - Display label fallback: space_idx <= 0 (no icon prefix) skips base_name extraction
+ - LLM pass-through when engine accepts 'llm' but requires_llm is False
+ - LLM relevance filter: per-engine plain bool, auto-detect scientific with
+ global skip_relevance_filter=False (no override), and generic engine
+ - _create_full_search_wrapper: SerpAPI api_key + language + safesearch mapping
+ - _create_full_search_wrapper: Brave safesearch mapping (True -> "moderate",
+ False -> "off")
+
+llm_config.py:
+ - Registered custom LLM: callable factory TypeError re-wrap
+ - Registered custom LLM: non-callable, non-BaseChatModel invalid type error
+ - wrap_llm_without_think_tags: context_limit injection for registered provider
+"""
+
+import inspect as _inspect
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+# ---------------------------------------------------------------------------
+# Helpers (search_engine_factory tests)
+# ---------------------------------------------------------------------------
+
+_FACTORY_MOD = "local_deep_research.web_search_engines.search_engine_factory"
+_LLM_MOD = "local_deep_research.config.llm_config"
+
+
+def _make_engine_class(*param_names, class_attrs=None):
+ """Build a class with a controlled __init__ signature for factory tests."""
+ params = [
+ _inspect.Parameter("self", _inspect.Parameter.POSITIONAL_OR_KEYWORD)
+ ]
+ for name in param_names:
+ params.append(
+ _inspect.Parameter(
+ name, _inspect.Parameter.POSITIONAL_OR_KEYWORD, default=None
+ )
+ )
+
+ class _Eng:
+ _call_kwargs = None
+
+ def __init__(self, **kwargs):
+ _Eng._call_kwargs = kwargs
+ for k, v in kwargs.items():
+ setattr(self, k, v)
+
+ _Eng.__init__.__signature__ = _inspect.Signature(params)
+ if class_attrs:
+ for k, v in class_attrs.items():
+ setattr(_Eng, k, v)
+ return _Eng
+
+
+def _engine_config(**overrides):
+ base = {
+ "module_path": "some.module",
+ "class_name": "SomeEngine",
+ "default_params": {},
+ }
+ base.update(overrides)
+ return base
+
+
+def _patches(registry_return=None, config_return=None, class_return=None):
+ import contextlib
+
+ @contextlib.contextmanager
+ def _ctx():
+ with (
+ patch(f"{_FACTORY_MOD}.retriever_registry") as mock_reg,
+ patch(f"{_FACTORY_MOD}.search_config") as mock_sc,
+ patch(f"{_FACTORY_MOD}.get_safe_module_class") as mock_gsmc,
+ ):
+ mock_reg.get.return_value = registry_return
+ if config_return is not None:
+ mock_sc.return_value = config_return
+ if class_return is not None:
+ mock_gsmc.return_value = class_return
+ yield mock_reg, mock_sc, mock_gsmc
+
+ return _ctx()
+
+
+# ---------------------------------------------------------------------------
+# search_engine_factory: display label fallback -- no icon prefix
+# ---------------------------------------------------------------------------
+
+
+class TestDisplayLabelNoIconPrefix:
+ """When the display label has no icon (space_idx <= 0), the base_name
+ extraction is skipped and the engine falls through to the 'auto' fallback.
+ Covers the else branch at line 107 of search_engine_factory.py."""
+
+ def test_label_without_icon_prefix_falls_back_to_auto(self):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+ # Label has parenthesised category but no icon prefix:
+ # rsplit(" (", 1) produces ["NoIcon", "Cat)"],
+ # space_idx on "NoIcon" is -1 -> base_name extraction is skipped.
+ config = {"auto": _engine_config()}
+
+ with _patches(config_return=config, class_return=EngCls):
+ result = create_search_engine(
+ "NoIcon (Category)", settings_snapshot={"x": 1}
+ )
+
+ # Should have fallen through to 'auto' and succeeded
+ assert result is not None
+
+
+# ---------------------------------------------------------------------------
+# search_engine_factory: LLM pass-through when not required but accepted
+# ---------------------------------------------------------------------------
+
+
+class TestLlmPassThroughNotRequired:
+ """When requires_llm is False but the engine __init__ accepts 'llm'
+ and an LLM is provided, the LLM should be injected. This covers the
+ elif branch at lines 228-237."""
+
+ def test_llm_injected_when_accepted_and_provided(self):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("llm", "max_results")
+ mock_llm = Mock()
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot={"x": 1}
+ )
+
+ assert EngCls._call_kwargs["llm"] is mock_llm
+
+
+# ---------------------------------------------------------------------------
+# search_engine_factory: LLM relevance filter -- global skip False
+# ---------------------------------------------------------------------------
+
+
+class TestRelevanceFilterGlobalSkipFalse:
+ """When a scientific engine auto-enables the filter and the global
+ skip_relevance_filter is present but False, the filter should remain
+ enabled. Covers the skip_filter=False branch at line 313."""
+
+ def test_scientific_engine_filter_stays_when_skip_false(self):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class(
+ "llm",
+ "max_results",
+ class_attrs={"is_scientific": True},
+ )
+ mock_llm = Mock()
+ snapshot = {
+ "search.skip_relevance_filter": {"value": False},
+ }
+
+ with _patches(
+ config_return={"eng": _engine_config(requires_llm=True)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot=snapshot
+ )
+
+ assert result is not None
+ assert getattr(result, "enable_llm_relevance_filter", False) is True
+
+
+# ---------------------------------------------------------------------------
+# _create_full_search_wrapper: SerpAPI special case
+# ---------------------------------------------------------------------------
+
+
+class _FakeSerpApiWrapper:
+ """Fake wrapper that accepts SerpAPI-specific params."""
+
+ def __init__(
+ self,
+ serpapi_api_key=None,
+ language=None,
+ safesearch=None,
+ llm=None,
+ web_search=None,
+ ):
+ self.serpapi_api_key = serpapi_api_key
+ self.language = language
+ self.safesearch = safesearch
+ self.llm = llm
+ self.web_search = web_search
+
+
+class TestFullSearchWrapperSerpApi:
+ """Covers the SerpAPI special-case branch (lines 418-452) in
+ _create_full_search_wrapper, including API key extraction, language
+ mapping, and safesearch mapping."""
+
+ def test_serpapi_api_key_and_params_mapped(self):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ _create_full_search_wrapper,
+ )
+
+ base_engine = Mock()
+ mock_llm = Mock()
+ settings_snapshot = {
+ "search.engine.web.serpapi.full_search_module": {
+ "value": "some.module"
+ },
+ "search.engine.web.serpapi.full_search_class": {
+ "value": "SerpApiSearch"
+ },
+ "search.engine.web.serpapi.api_key": {"value": "serpapi-key-789"},
+ }
+ params = {
+ "language": "French",
+ "safe_search": True,
+ }
+
+ with patch(
+ f"{_FACTORY_MOD}.get_safe_module_class",
+ return_value=_FakeSerpApiWrapper,
+ ):
+ result = _create_full_search_wrapper(
+ "serpapi",
+ base_engine,
+ mock_llm,
+ params,
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert isinstance(result, _FakeSerpApiWrapper)
+ assert result.serpapi_api_key == "serpapi-key-789"
+ assert result.language == "French"
+ assert result.safesearch == "active"
+ assert result.llm is mock_llm
+ assert result.web_search is base_engine
+
+ def test_serpapi_safesearch_off_when_false(self):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ _create_full_search_wrapper,
+ )
+
+ base_engine = Mock()
+ settings_snapshot = {
+ "search.engine.web.serpapi.full_search_module": {
+ "value": "some.module"
+ },
+ "search.engine.web.serpapi.full_search_class": {
+ "value": "SerpApiSearch"
+ },
+ "search.engine.web.serpapi.api_key": "serpapi-plain-key",
+ }
+ params = {"safe_search": False}
+
+ with patch(
+ f"{_FACTORY_MOD}.get_safe_module_class",
+ return_value=_FakeSerpApiWrapper,
+ ):
+ result = _create_full_search_wrapper(
+ "serpapi",
+ base_engine,
+ Mock(),
+ params,
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert result.safesearch == "off"
+
+
+# ---------------------------------------------------------------------------
+# _create_full_search_wrapper: Brave special case
+# ---------------------------------------------------------------------------
+
+
+class _FakeBraveWrapper:
+ """Fake wrapper that accepts Brave-specific params."""
+
+ def __init__(
+ self,
+ api_key=None,
+ language=None,
+ safesearch=None,
+ llm=None,
+ web_search=None,
+ ):
+ self.api_key = api_key
+ self.language = language
+ self.safesearch = safesearch
+ self.llm = llm
+ self.web_search = web_search
+
+
+class TestFullSearchWrapperBrave:
+ """Covers the Brave special-case branch (lines 454-487) in
+ _create_full_search_wrapper, including safesearch mapping
+ (True -> 'moderate', False -> 'off')."""
+
+ def test_brave_safesearch_moderate_when_true(self):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ _create_full_search_wrapper,
+ )
+
+ settings_snapshot = {
+ "search.engine.web.brave.full_search_module": {
+ "value": "some.module"
+ },
+ "search.engine.web.brave.full_search_class": {
+ "value": "BraveSearch"
+ },
+ "search.engine.web.brave.api_key": {"value": "brave-key-abc"},
+ }
+ params = {"language": "German", "safe_search": True}
+
+ with patch(
+ f"{_FACTORY_MOD}.get_safe_module_class",
+ return_value=_FakeBraveWrapper,
+ ):
+ result = _create_full_search_wrapper(
+ "brave",
+ Mock(),
+ Mock(),
+ params,
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert isinstance(result, _FakeBraveWrapper)
+ assert result.api_key == "brave-key-abc"
+ assert result.language == "German"
+ assert result.safesearch == "moderate"
+
+ def test_brave_safesearch_off_when_false(self):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ _create_full_search_wrapper,
+ )
+
+ settings_snapshot = {
+ "search.engine.web.brave.full_search_module": {
+ "value": "some.module"
+ },
+ "search.engine.web.brave.full_search_class": {
+ "value": "BraveSearch"
+ },
+ "search.engine.web.brave.api_key": "brave-plain-key",
+ }
+ params = {"safe_search": False}
+
+ with patch(
+ f"{_FACTORY_MOD}.get_safe_module_class",
+ return_value=_FakeBraveWrapper,
+ ):
+ result = _create_full_search_wrapper(
+ "brave",
+ Mock(),
+ Mock(),
+ params,
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert result.safesearch == "off"
+
+
+# ---------------------------------------------------------------------------
+# llm_config: context_limit injection via wrap_llm_without_think_tags
+# for a registered custom provider (not a built-in like ollama/openai)
+# ---------------------------------------------------------------------------
+
+
+class TestWrapLlmContextLimitRegisteredProvider:
+ """Covers the context_limit injection in wrap_llm_without_think_tags
+ (lines 883-892) when the provider is a custom registered provider that
+ goes through the registered-LLM path in get_llm (which returns before
+ the get_llm code that sets context_limit)."""
+
+ def test_context_limit_injected_for_custom_provider(self):
+ """wrap_llm injects context_limit for a non-built-in provider when
+ research_context has no existing context_limit."""
+ llm = MagicMock()
+ research_ctx = {}
+
+ def fake_setting(key, default=None, settings_snapshot=None):
+ if key == "rate_limiting.llm_enabled":
+ return False
+ if key == "llm.context_window_unrestricted":
+ return False
+ if key == "llm.context_window_size":
+ return 50000
+ return default
+
+ with patch(
+ f"{_LLM_MOD}.get_setting_from_snapshot",
+ side_effect=fake_setting,
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrap_llm_without_think_tags(
+ llm,
+ provider="my_custom_provider",
+ research_context=research_ctx,
+ )
+
+ assert research_ctx["context_limit"] == 50000
+
+ def test_context_limit_not_injected_when_none(self):
+ """When _get_context_window_for_provider returns None (unrestricted
+ cloud), context_limit is NOT added to research_context."""
+ llm = MagicMock()
+ research_ctx = {}
+
+ def fake_setting(key, default=None, settings_snapshot=None):
+ if key == "rate_limiting.llm_enabled":
+ return False
+ if key == "llm.context_window_unrestricted":
+ return True
+ return default
+
+ with patch(
+ f"{_LLM_MOD}.get_setting_from_snapshot",
+ side_effect=fake_setting,
+ ):
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ wrap_llm_without_think_tags(
+ llm,
+ provider="anthropic",
+ research_context=research_ctx,
+ )
+
+ assert "context_limit" not in research_ctx
+
+
+# ---------------------------------------------------------------------------
+# llm_config: Anthropic provider missing API key
+# ---------------------------------------------------------------------------
+
+
+class TestGetLlmAnthropicMissingKey:
+ """Covers the ValueError branch when Anthropic API key is missing
+ (lines 418-421 in llm_config.py)."""
+
+ def test_anthropic_no_api_key_raises(self):
+ settings = {
+ "llm.model": "claude-3-haiku",
+ "llm.temperature": 0.7,
+ "llm.provider": "anthropic",
+ "llm.anthropic.api_key": None,
+ "llm.supports_max_tokens": False,
+ "llm.context_window_unrestricted": True,
+ "rate_limiting.llm_enabled": False,
+ }
+
+ with (
+ patch(f"{_LLM_MOD}.is_llm_registered", return_value=False),
+ patch(
+ f"{_LLM_MOD}.get_setting_from_snapshot",
+ side_effect=lambda key,
+ default=None,
+ settings_snapshot=None: settings.get(key, default),
+ ),
+ ):
+ from local_deep_research.config.llm_config import get_llm
+
+ with pytest.raises(
+ ValueError, match="Anthropic API key not configured"
+ ):
+ get_llm(provider="anthropic", settings_snapshot=settings)