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 52 high-value tests across 5 modules for security, core logic, and persistence coverage

LearningCircuit8a37e30735d0
diff --git a/tests/benchmarks/test_benchmark_functions_extended.py b/tests/benchmarks/test_benchmark_functions_extended.py
new file mode 100644
index 0000000000..6738172927
--- /dev/null
+++ b/tests/benchmarks/test_benchmark_functions_extended.py
@@ -0,0 +1,211 @@
+"""Extended tests for benchmarks/benchmark_functions.py.
+
+Covers get_available_benchmarks() and compare_configurations().
+"""
+
+import tempfile
+from copy import deepcopy
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.benchmarks.benchmark_functions import (
+ compare_configurations,
+ get_available_benchmarks,
+)
+
+
+# ── get_available_benchmarks ───────────────────────────────────────
+
+
+class TestGetAvailableBenchmarks:
+ """Tests for get_available_benchmarks."""
+
+ def test_returns_list(self):
+ """Return type is a list."""
+ result = get_available_benchmarks()
+ assert isinstance(result, list)
+ assert len(result) > 0
+
+ def test_has_required_fields(self):
+ """Each benchmark dict has id, name, description, recommended_examples."""
+ for b in get_available_benchmarks():
+ assert "id" in b
+ assert "name" in b
+ assert "description" in b
+ assert "recommended_examples" in b
+ assert isinstance(b["recommended_examples"], int)
+
+ def test_includes_all_types(self):
+ """All three benchmark types are present."""
+ ids = {b["id"] for b in get_available_benchmarks()}
+ assert "simpleqa" in ids
+ assert "browsecomp" in ids
+ assert "xbench_deepsearch" in ids
+
+
+# ── compare_configurations ─────────────────────────────────────────
+
+
+class TestCompareConfigurations:
+ """Tests for compare_configurations."""
+
+ def _mock_benchmark_result(self, config_name="test"):
+ return {
+ "metrics": {"accuracy": 0.85, "average_processing_time": 1.5},
+ "total_examples": 20,
+ }
+
+ def test_default_configurations(self):
+ """Default 3 configurations are used when none provided."""
+ with (
+ patch(
+ "local_deep_research.benchmarks.benchmark_functions.run_benchmark"
+ ) as mock_run,
+ patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ),
+ ):
+ mock_run.return_value = self._mock_benchmark_result()
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ result = compare_configurations(
+ num_examples=5, output_dir=tmpdir
+ )
+
+ # 3 default configs → 3 calls
+ assert mock_run.call_count == 3
+ assert result["status"] == "complete"
+ assert result["configurations_tested"] == 3
+
+ def test_custom_configurations(self):
+ """Custom configurations list is used."""
+ custom_configs = [
+ {
+ "name": "Custom A",
+ "search_tool": "brave",
+ "iterations": 2,
+ "questions_per_iteration": 4,
+ },
+ {
+ "name": "Custom B",
+ "search_tool": "duckduckgo",
+ "iterations": 1,
+ "questions_per_iteration": 2,
+ },
+ ]
+
+ with (
+ patch(
+ "local_deep_research.benchmarks.benchmark_functions.run_benchmark"
+ ) as mock_run,
+ patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ),
+ ):
+ mock_run.return_value = self._mock_benchmark_result()
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ result = compare_configurations(
+ configurations=deepcopy(custom_configs),
+ num_examples=5,
+ output_dir=tmpdir,
+ )
+
+ assert mock_run.call_count == 2
+ assert result["configurations_tested"] == 2
+
+ def test_pops_name_from_config(self):
+ """config.pop('name') mutates the caller's dicts (documenting the bug)."""
+ configs = [
+ {
+ "name": "Foo",
+ "search_tool": "searxng",
+ "iterations": 1,
+ "questions_per_iteration": 3,
+ },
+ ]
+
+ with (
+ patch(
+ "local_deep_research.benchmarks.benchmark_functions.run_benchmark"
+ ) as mock_run,
+ patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ),
+ ):
+ mock_run.return_value = self._mock_benchmark_result()
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ compare_configurations(
+ configurations=configs,
+ num_examples=5,
+ output_dir=tmpdir,
+ )
+
+ # The original dict has been mutated: "name" was popped
+ assert "name" not in configs[0]
+
+ def test_generates_report(self):
+ """Comparison report is written via write_file_verified."""
+ with (
+ patch(
+ "local_deep_research.benchmarks.benchmark_functions.run_benchmark"
+ ) as mock_run,
+ patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write,
+ ):
+ mock_run.return_value = self._mock_benchmark_result()
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ result = compare_configurations(
+ num_examples=5, output_dir=tmpdir
+ )
+
+ mock_write.assert_called_once()
+ # Report path is returned
+ assert "report_path" in result
+
+ def test_handles_benchmark_error(self):
+ """Error in run_benchmark for one config propagates (no swallowing)."""
+ configs = [
+ {
+ "name": "Good",
+ "search_tool": "searxng",
+ "iterations": 1,
+ "questions_per_iteration": 3,
+ },
+ {
+ "name": "Bad",
+ "search_tool": "searxng",
+ "iterations": 1,
+ "questions_per_iteration": 3,
+ },
+ ]
+
+ call_count = 0
+
+ def side_effect(**kwargs):
+ nonlocal call_count
+ call_count += 1
+ if call_count == 2:
+ raise RuntimeError("benchmark failed")
+ return self._mock_benchmark_result()
+
+ with (
+ patch(
+ "local_deep_research.benchmarks.benchmark_functions.run_benchmark",
+ side_effect=side_effect,
+ ),
+ patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ),
+ ):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ with pytest.raises(RuntimeError, match="benchmark failed"):
+ compare_configurations(
+ configurations=configs,
+ num_examples=5,
+ output_dir=tmpdir,
+ )
diff --git a/tests/config/test_llm_config_extended.py b/tests/config/test_llm_config_extended.py
new file mode 100644
index 0000000000..4d7ef8e35f
--- /dev/null
+++ b/tests/config/test_llm_config_extended.py
@@ -0,0 +1,478 @@
+"""Extended tests for llm_config provider paths (VLLM, LlamaCpp, Ollama, OpenAI)."""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from langchain_core.language_models import FakeListChatModel
+
+from local_deep_research.config.llm_config import get_llm
+
+
+def _settings_dict(overrides=None):
+ """Base settings dict shared across tests."""
+ base = {
+ "llm.model": "test-model",
+ "llm.temperature": 0.5,
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 4096,
+ "llm.context_window_unrestricted": True,
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 4096,
+ "rate_limiting.llm_enabled": False,
+ }
+ if overrides:
+ base.update(overrides)
+ return base
+
+
+def _mock_get_setting(settings):
+ """Return a side_effect for get_setting_from_snapshot."""
+ return lambda key, default=None, **kw: settings.get(key, default)
+
+
+# ── VLLM provider ──────────────────────────────────────────────────
+
+
+class TestVLLMProvider:
+ """Tests for the VLLM provider path in get_llm."""
+
+ def test_unavailable_returns_fallback(self):
+ """When VLLM deps aren't installed, fallback model is returned."""
+ settings = _settings_dict({"llm.provider": "vllm"})
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch(
+ "local_deep_research.config.llm_config.is_vllm_available",
+ return_value=False,
+ ),
+ ):
+ result = get_llm(provider="vllm")
+ assert isinstance(result, FakeListChatModel)
+
+ def test_available_creates_instance(self):
+ """When VLLM is available, VLLM instance is created."""
+ settings = _settings_dict({"llm.provider": "vllm"})
+
+ mock_vllm_cls = MagicMock()
+ mock_vllm_instance = MagicMock()
+ mock_vllm_cls.return_value = mock_vllm_instance
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch(
+ "local_deep_research.config.llm_config.is_vllm_available",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
+ return_value=mock_vllm_instance,
+ ),
+ patch.dict(
+ "sys.modules",
+ {"langchain_community.llms": MagicMock(VLLM=mock_vllm_cls)},
+ ),
+ ):
+ result = get_llm(provider="vllm")
+ mock_vllm_cls.assert_called_once()
+ assert result is mock_vllm_instance
+
+ def test_exception_returns_fallback(self):
+ """Exception during VLLM creation returns fallback."""
+ settings = _settings_dict({"llm.provider": "vllm"})
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch(
+ "local_deep_research.config.llm_config.is_vllm_available",
+ return_value=True,
+ ),
+ patch.dict(
+ "sys.modules",
+ {
+ "langchain_community.llms": MagicMock(
+ VLLM=MagicMock(side_effect=RuntimeError("GPU error"))
+ )
+ },
+ ),
+ ):
+ result = get_llm(provider="vllm")
+ assert isinstance(result, FakeListChatModel)
+
+
+# ── LlamaCpp provider ──────────────────────────────────────────────
+
+
+class TestLlamaCppProvider:
+ """Tests for the LlamaCpp provider path in get_llm."""
+
+ def test_no_path_raises(self):
+ """Missing model path raises ValueError."""
+ settings = _settings_dict(
+ {
+ "llm.provider": "llamacpp",
+ "llm.llamacpp_model_path": None,
+ }
+ )
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ ):
+ with pytest.raises(ValueError, match="model path not configured"):
+ get_llm(provider="llamacpp")
+
+ def test_invalid_extension_raises(self, tmp_path):
+ """Invalid file extension raises ValueError."""
+ bad_file = tmp_path / "model.txt"
+ bad_file.write_text("not a model")
+
+ settings = _settings_dict(
+ {
+ "llm.provider": "llamacpp",
+ "llm.llamacpp_model_path": str(bad_file),
+ }
+ )
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch(
+ "local_deep_research.security.path_validator.PathValidator.validate_model_path"
+ ) as mock_validate,
+ ):
+ # PathValidator.validate_model_path returns the path as-is
+ mock_validate.return_value = bad_file
+ with pytest.raises(
+ ValueError, match="Invalid model file extension"
+ ):
+ get_llm(provider="llamacpp")
+
+ def test_creates_with_gpu_params(self, tmp_path):
+ """LlamaCpp is created with GPU params from settings."""
+ model_file = tmp_path / "model.gguf"
+ model_file.write_text("fake model data")
+
+ settings = _settings_dict(
+ {
+ "llm.provider": "llamacpp",
+ "llm.llamacpp_model_path": str(model_file),
+ "llm.llamacpp_n_gpu_layers": 8,
+ "llm.llamacpp_n_batch": 256,
+ "llm.llamacpp_f16_kv": False,
+ }
+ )
+
+ mock_llamacpp_cls = MagicMock()
+ mock_llamacpp_instance = MagicMock()
+ mock_llamacpp_cls.return_value = mock_llamacpp_instance
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch(
+ "local_deep_research.security.path_validator.PathValidator.validate_model_path"
+ ) as mock_pv_validate,
+ patch(
+ "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
+ return_value=mock_llamacpp_instance,
+ ),
+ patch.dict(
+ "sys.modules",
+ {
+ "langchain_community.llms": MagicMock(
+ LlamaCpp=mock_llamacpp_cls
+ )
+ },
+ ),
+ ):
+ mock_pv_validate.return_value = model_file
+
+ result = get_llm(provider="llamacpp")
+
+ mock_llamacpp_cls.assert_called_once()
+ call_kwargs = mock_llamacpp_cls.call_args[1]
+ assert call_kwargs["n_gpu_layers"] == 8
+ assert call_kwargs["n_batch"] == 256
+ assert call_kwargs["f16_kv"] is False
+ assert result is mock_llamacpp_instance
+
+ def test_path_validation_called(self, tmp_path):
+ """PathValidator.validate_model_path is called for security."""
+ model_file = tmp_path / "model.gguf"
+ model_file.write_text("fake model")
+
+ settings = _settings_dict(
+ {
+ "llm.provider": "llamacpp",
+ "llm.llamacpp_model_path": str(model_file),
+ }
+ )
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch(
+ "local_deep_research.security.path_validator.PathValidator.validate_model_path"
+ ) as mock_pv_validate,
+ patch(
+ "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
+ return_value=MagicMock(),
+ ),
+ patch.dict(
+ "sys.modules",
+ {"langchain_community.llms": MagicMock()},
+ ),
+ ):
+ mock_pv_validate.return_value = model_file
+ get_llm(provider="llamacpp")
+ mock_pv_validate.assert_called_once_with(str(model_file))
+
+
+# ── Ollama provider ────────────────────────────────────────────────
+
+
+class TestOllamaProvider:
+ """Tests for the Ollama provider path in get_llm."""
+
+ def _ollama_settings(self, overrides=None):
+ s = _settings_dict(
+ {
+ "llm.provider": "ollama",
+ "llm.ollama.url": "http://localhost:11434",
+ "llm.ollama.enable_thinking": True,
+ }
+ )
+ if overrides:
+ s.update(overrides)
+ return s
+
+ def test_model_not_found_returns_fallback(self):
+ """Model not in Ollama model list returns fallback."""
+ settings = self._ollama_settings()
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"models": [{"name": "other-model"}]}
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch(
+ "local_deep_research.config.llm_config.is_ollama_available",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.safe_get",
+ return_value=mock_response,
+ ),
+ ):
+ result = get_llm(provider="ollama", model_name="test-model")
+ assert isinstance(result, FakeListChatModel)
+
+ def test_model_found_creates_client(self):
+ """Model found in list creates ChatOllama."""
+ settings = self._ollama_settings()
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"models": [{"name": "test-model"}]}
+
+ mock_ollama_cls = MagicMock()
+ mock_ollama_instance = MagicMock()
+ mock_ollama_cls.return_value = mock_ollama_instance
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch(
+ "local_deep_research.config.llm_config.is_ollama_available",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.safe_get",
+ return_value=mock_response,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.ChatOllama",
+ mock_ollama_cls,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
+ return_value=mock_ollama_instance,
+ ),
+ ):
+ result = get_llm(provider="ollama", model_name="test-model")
+ mock_ollama_cls.assert_called_once()
+ assert result is mock_ollama_instance
+
+ def test_api_tags_exception_continues(self):
+ """Exception checking model list doesn't crash — continues to create ChatOllama."""
+ settings = self._ollama_settings()
+
+ mock_ollama_cls = MagicMock()
+ mock_ollama_instance = MagicMock()
+ mock_ollama_cls.return_value = mock_ollama_instance
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch(
+ "local_deep_research.config.llm_config.is_ollama_available",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.safe_get",
+ side_effect=ConnectionError("refused"),
+ ),
+ patch(
+ "local_deep_research.config.llm_config.ChatOllama",
+ mock_ollama_cls,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
+ return_value=mock_ollama_instance,
+ ),
+ ):
+ result = get_llm(provider="ollama", model_name="test-model")
+ # Should still try to create ChatOllama despite API error
+ mock_ollama_cls.assert_called_once()
+ assert result is mock_ollama_instance
+
+
+# ── OpenAI provider optional params ────────────────────────────────
+
+
+class TestOpenAIOptionalParams:
+ """Tests for OpenAI provider optional parameters."""
+
+ def _openai_settings(self, overrides=None):
+ s = _settings_dict(
+ {
+ "llm.provider": "openai",
+ "llm.openai.api_key": "sk-test",
+ "llm.openai.api_base": None,
+ "llm.openai.organization": None,
+ "llm.streaming": None,
+ "llm.max_retries": None,
+ "llm.request_timeout": None,
+ }
+ )
+ if overrides:
+ s.update(overrides)
+ return s
+
+ def test_with_api_base(self):
+ """api_base is passed through as openai_api_base."""
+ from langchain_openai import ChatOpenAI
+
+ settings = self._openai_settings(
+ {"llm.openai.api_base": "https://custom.endpoint/v1"}
+ )
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch.object(
+ ChatOpenAI, "__init__", return_value=None
+ ) as mock_init,
+ ):
+ get_llm(provider="openai")
+ call_kwargs = mock_init.call_args.kwargs
+ assert (
+ call_kwargs["openai_api_base"] == "https://custom.endpoint/v1"
+ )
+
+ def test_with_organization(self):
+ """organization is passed through as openai_organization."""
+ from langchain_openai import ChatOpenAI
+
+ settings = self._openai_settings(
+ {"llm.openai.organization": "org-abc123"}
+ )
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=_mock_get_setting(settings),
+ ),
+ patch.object(
+ ChatOpenAI, "__init__", return_value=None
+ ) as mock_init,
+ ):
+ get_llm(provider="openai")
+ call_kwargs = mock_init.call_args.kwargs
+ assert call_kwargs["openai_organization"] == "org-abc123"
diff --git a/tests/metrics/test_token_counter_db.py b/tests/metrics/test_token_counter_db.py
new file mode 100644
index 0000000000..d6b2f40c51
--- /dev/null
+++ b/tests/metrics/test_token_counter_db.py
@@ -0,0 +1,267 @@
+"""Tests for TokenCountingCallback._save_to_db and TokenCounter._merge_metrics."""
+
+import threading
+from unittest.mock import MagicMock, Mock, patch
+
+from local_deep_research.metrics.token_counter import (
+ TokenCounter,
+ TokenCountingCallback,
+)
+
+
+# ── _save_to_db MainThread path ────────────────────────────────────
+
+
+class TestSaveToDbMainThread:
+ """Tests for the MainThread path of _save_to_db (lines 484-588)."""
+
+ def _make_callback(self, **overrides):
+ """Create a callback with sane defaults."""
+ cb = TokenCountingCallback(
+ research_id="r-123",
+ research_context=overrides.pop(
+ "research_context", {"research_query": "test"}
+ ),
+ )
+ cb.current_model = overrides.pop("current_model", "gpt-4")
+ cb.current_provider = overrides.pop("current_provider", "openai")
+ cb.response_time_ms = overrides.pop("response_time_ms", 150)
+ cb.success_status = overrides.pop("success_status", "success")
+ cb.error_type = overrides.pop("error_type", None)
+ cb.calling_file = overrides.pop("calling_file", "test.py")
+ cb.calling_function = overrides.pop("calling_function", "run")
+ cb.call_stack = overrides.pop("call_stack", None)
+ for k, v in overrides.items():
+ setattr(cb, k, v)
+ return cb
+
+ def _mock_main_thread(self):
+ """Return a patch that makes current_thread().name == 'MainThread'."""
+ mock_thread = MagicMock()
+ mock_thread.name = "MainThread"
+ return patch.object(
+ threading, "current_thread", return_value=mock_thread
+ )
+
+ def test_creates_token_usage(self):
+ """TokenUsage record is created and added to session."""
+ cb = self._make_callback()
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ with self._mock_main_thread():
+ with patch("flask.session", {"username": "testuser"}, create=True):
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_gs:
+ mock_gs.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_gs.return_value.__exit__ = Mock(return_value=False)
+
+ cb._save_to_db(100, 50)
+
+ assert mock_session.add.call_count >= 1
+ mock_session.commit.assert_called_once()
+
+ def test_updates_existing_model_usage(self):
+ """Existing ModelUsage record is incremented."""
+ cb = self._make_callback()
+
+ existing_model_usage = MagicMock()
+ existing_model_usage.total_tokens = 1000
+ existing_model_usage.total_calls = 5
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = existing_model_usage
+
+ with self._mock_main_thread():
+ with patch("flask.session", {"username": "testuser"}, create=True):
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_gs:
+ mock_gs.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_gs.return_value.__exit__ = Mock(return_value=False)
+
+ cb._save_to_db(100, 50)
+
+ assert existing_model_usage.total_tokens == 1150
+ assert existing_model_usage.total_calls == 6
+
+ def test_creates_new_model_usage(self):
+ """New ModelUsage record is created when none exists."""
+ cb = self._make_callback()
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ with self._mock_main_thread():
+ with patch("flask.session", {"username": "testuser"}, create=True):
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_gs:
+ mock_gs.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_gs.return_value.__exit__ = Mock(return_value=False)
+
+ cb._save_to_db(200, 100)
+
+ # Two session.add calls: TokenUsage + ModelUsage
+ assert mock_session.add.call_count == 2
+
+ def test_no_username_skips(self):
+ """No username in flask session skips the save."""
+ cb = self._make_callback()
+
+ with self._mock_main_thread():
+ with patch("flask.session", {}, create=True):
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_gs:
+ cb._save_to_db(100, 50)
+ mock_gs.assert_not_called()
+
+ def test_database_error_caught(self):
+ """Database exceptions are caught, not raised."""
+ cb = self._make_callback()
+
+ with self._mock_main_thread():
+ with patch("flask.session", {"username": "testuser"}, create=True):
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=RuntimeError("DB exploded"),
+ ):
+ # Should NOT raise
+ cb._save_to_db(100, 50)
+
+ def test_enhanced_fields_included(self):
+ """response_time_ms and calling_file are stored in TokenUsage."""
+ cb = self._make_callback(
+ response_time_ms=250, calling_file="my_module.py"
+ )
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ added_objects = []
+ mock_session.add.side_effect = lambda obj: added_objects.append(obj)
+
+ with self._mock_main_thread():
+ with patch("flask.session", {"username": "testuser"}, create=True):
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_gs:
+ mock_gs.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_gs.return_value.__exit__ = Mock(return_value=False)
+
+ cb._save_to_db(100, 50)
+
+ token_usage = added_objects[0]
+ assert token_usage.response_time_ms == 250
+ assert token_usage.calling_file == "my_module.py"
+
+
+# ── _save_to_db thread path ───────────────────────────────────────
+
+
+class TestSaveToDbThread:
+ """Tests for the worker-thread path of _save_to_db."""
+
+ def _mock_worker_thread(self):
+ """Return a patch that makes current_thread().name != 'MainThread'."""
+ mock_thread = MagicMock()
+ mock_thread.name = "WorkerThread-1"
+ return patch.object(
+ threading, "current_thread", return_value=mock_thread
+ )
+
+ def test_thread_path_converts_search_engines(self):
+ """search_engines_planned list is JSON-serialized in thread path."""
+ cb = TokenCountingCallback(
+ research_id="r-1",
+ research_context={
+ "username": "testuser",
+ "user_password": "pass",
+ "search_engines_planned": ["google", "brave"],
+ },
+ )
+ cb.current_model = "gpt-4"
+ cb.current_provider = "openai"
+
+ mock_writer = MagicMock()
+
+ with self._mock_worker_thread():
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ cb._save_to_db(100, 50)
+
+ mock_writer.set_user_password.assert_called_once_with(
+ "testuser", "pass"
+ )
+ mock_writer.write_token_metrics.assert_called_once()
+
+ def test_thread_path_no_password_skips(self):
+ """Thread path skips save when no password in research context."""
+ cb = TokenCountingCallback(
+ research_id="r-1",
+ research_context={"username": "testuser"},
+ )
+ cb.current_model = "gpt-4"
+ cb.current_provider = "openai"
+
+ mock_writer = MagicMock()
+
+ with self._mock_worker_thread():
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ cb._save_to_db(100, 50)
+
+ mock_writer.write_token_metrics.assert_not_called()
+
+
+# ── _merge_metrics ────────────────────────────────────────────────
+
+
+class TestMergeMetrics:
+ """Tests for TokenCounter._merge_metrics."""
+
+ def test_empty_sources(self):
+ """Merging two empty metric dicts returns zeros."""
+ tc = TokenCounter()
+ result = tc._merge_metrics({}, {})
+
+ assert result["total_tokens"] == 0
+ assert result["total_researches"] == 0
+ assert result["by_model"] == []
+
+ def test_deduplicates_researches(self):
+ """total_researches uses max() to avoid double-counting."""
+ tc = TokenCounter()
+ encrypted = {
+ "total_tokens": 100,
+ "total_researches": 5,
+ "by_model": [],
+ "recent_researches": [],
+ "token_breakdown": {},
+ }
+ thread = {
+ "total_tokens": 200,
+ "total_researches": 3,
+ "by_model": [],
+ "token_breakdown": {},
+ }
+
+ result = tc._merge_metrics(encrypted, thread)
+
+ assert result["total_tokens"] == 300
+ assert result["total_researches"] == 5 # max(5, 3), not sum
diff --git a/tests/security/file_integrity/test_integrity_manager.py b/tests/security/file_integrity/test_integrity_manager.py
index 04e12c4277..cf965470b4 100644
--- a/tests/security/file_integrity/test_integrity_manager.py
+++ b/tests/security/file_integrity/test_integrity_manager.py
@@ -503,3 +503,334 @@ class TestMaxFailuresLimits:
FileIntegrityManager.MAX_TOTAL_FAILURES
>= FileIntegrityManager.MAX_FAILURES_PER_FILE
)
+
+
+# ---------- helper to build a manager without hitting the real DB ----------
+def _make_manager():
+ """Create a FileIntegrityManager with mocked DB session."""
+ from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+ )
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session"
+ ) as mock_session:
+ mock_ctx = MagicMock()
+ mock_session.return_value.__enter__ = Mock(return_value=mock_ctx)
+ mock_session.return_value.__exit__ = Mock(return_value=False)
+ mock_ctx.query.return_value.count.return_value = 0
+
+ mgr = FileIntegrityManager("testuser", "testpass")
+
+ return mgr
+
+
+class TestDoVerification:
+ """Tests for _do_verification (the core tamper-detection method)."""
+
+ def test_returns_false_when_file_missing(self, tmp_path):
+ """Missing file is detected."""
+ mgr = _make_manager()
+ record = Mock(checksum="abc123")
+ missing = tmp_path / "no_such_file"
+
+ passed, reason = mgr._do_verification(record, missing, MagicMock())
+ assert passed is False
+ assert reason == "file_missing"
+
+ def test_returns_false_when_no_verifier(self, tmp_path):
+ """No registered verifier → failure."""
+ mgr = _make_manager()
+ f = tmp_path / "file.xyz"
+ f.write_text("data")
+ record = Mock(checksum="abc")
+
+ passed, reason = mgr._do_verification(record, f, MagicMock())
+ assert passed is False
+ assert reason == "no_verifier"
+
+ def test_returns_false_on_checksum_mismatch(self, tmp_path):
+ """Tampered file detected via checksum mismatch."""
+ from local_deep_research.security.file_integrity.base_verifier import (
+ BaseFileVerifier,
+ FileType,
+ )
+
+ class StubVerifier(BaseFileVerifier):
+ def should_verify(self, fp):
+ return True
+
+ def get_file_type(self):
+ return FileType.PDF
+
+ def allows_modifications(self):
+ return False
+
+ mgr = _make_manager()
+ v = StubVerifier()
+ v.calculate_checksum = Mock(return_value="new_checksum")
+ mgr.register_verifier(v)
+
+ f = tmp_path / "file.bin"
+ f.write_text("data")
+ record = Mock(checksum="old_checksum")
+
+ passed, reason = mgr._do_verification(record, f, MagicMock())
+ assert passed is False
+ assert reason == "checksum_mismatch"
+
+ def test_returns_true_on_match_and_updates_mtime(self, tmp_path):
+ """Valid file passes and mtime is updated."""
+ from local_deep_research.security.file_integrity.base_verifier import (
+ BaseFileVerifier,
+ FileType,
+ )
+
+ class StubVerifier(BaseFileVerifier):
+ def should_verify(self, fp):
+ return True
+
+ def get_file_type(self):
+ return FileType.PDF
+
+ def allows_modifications(self):
+ return False
+
+ mgr = _make_manager()
+ v = StubVerifier()
+ v.calculate_checksum = Mock(return_value="matching")
+ mgr.register_verifier(v)
+
+ f = tmp_path / "file.bin"
+ f.write_text("data")
+ record = Mock(checksum="matching", file_mtime=0.0)
+
+ passed, reason = mgr._do_verification(record, f, MagicMock())
+ assert passed is True
+ assert reason is None
+ # mtime should have been updated to the file's actual mtime
+ assert record.file_mtime == f.stat().st_mtime
+
+ def test_checksum_calculation_exception(self, tmp_path):
+ """Exception during checksum calculation is handled."""
+ from local_deep_research.security.file_integrity.base_verifier import (
+ BaseFileVerifier,
+ FileType,
+ )
+
+ class StubVerifier(BaseFileVerifier):
+ def should_verify(self, fp):
+ return True
+
+ def get_file_type(self):
+ return FileType.PDF
+
+ def allows_modifications(self):
+ return False
+
+ mgr = _make_manager()
+ v = StubVerifier()
+ v.calculate_checksum = Mock(side_effect=IOError("disk error"))
+ mgr.register_verifier(v)
+
+ f = tmp_path / "file.bin"
+ f.write_text("data")
+ record = Mock(checksum="x")
+
+ passed, reason = mgr._do_verification(record, f, MagicMock())
+ assert passed is False
+ assert "checksum_calculation_failed" in reason
+
+
+class TestRecordFile:
+ """Tests for record_file (baseline creation / update)."""
+
+ def test_creates_new_record(self, tmp_path):
+ """New file baseline is created."""
+ from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+ )
+ from local_deep_research.security.file_integrity.base_verifier import (
+ BaseFileVerifier,
+ FileType,
+ )
+
+ class StubVerifier(BaseFileVerifier):
+ def should_verify(self, fp):
+ return True
+
+ def get_file_type(self):
+ return FileType.PDF
+
+ def allows_modifications(self):
+ return False
+
+ f = tmp_path / "new.bin"
+ f.write_text("hello")
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session"
+ ) as mock_gs:
+ mock_ctx = MagicMock()
+ mock_gs.return_value.__enter__ = Mock(return_value=mock_ctx)
+ mock_gs.return_value.__exit__ = Mock(return_value=False)
+ # Init: cleanup returns 0
+ mock_ctx.query.return_value.count.return_value = 0
+ mgr = FileIntegrityManager("user", "pass")
+
+ v = StubVerifier()
+ v.calculate_checksum = Mock(return_value="abc123")
+ mgr.register_verifier(v)
+
+ # record_file path: no existing record
+ mock_ctx.query.return_value.filter_by.return_value.first.return_value = None
+ mgr.record_file(f)
+
+ # session.add should have been called with a new record
+ mock_ctx.add.assert_called_once()
+ mock_ctx.commit.assert_called()
+
+ def test_updates_existing_record(self, tmp_path):
+ """Existing record is updated."""
+ from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+ )
+ from local_deep_research.security.file_integrity.base_verifier import (
+ BaseFileVerifier,
+ FileType,
+ )
+
+ class StubVerifier(BaseFileVerifier):
+ def should_verify(self, fp):
+ return True
+
+ def get_file_type(self):
+ return FileType.PDF
+
+ def allows_modifications(self):
+ return False
+
+ f = tmp_path / "existing.bin"
+ f.write_text("updated content")
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session"
+ ) as mock_gs:
+ mock_ctx = MagicMock()
+ mock_gs.return_value.__enter__ = Mock(return_value=mock_ctx)
+ mock_gs.return_value.__exit__ = Mock(return_value=False)
+ mock_ctx.query.return_value.count.return_value = 0
+ mgr = FileIntegrityManager("user", "pass")
+
+ v = StubVerifier()
+ v.calculate_checksum = Mock(return_value="newchecksum")
+ mgr.register_verifier(v)
+
+ # Simulate existing record
+ existing = Mock()
+ existing.checksum = "oldchecksum"
+ mock_ctx.query.return_value.filter_by.return_value.first.return_value = existing
+
+ mgr.record_file(f)
+
+ assert existing.checksum == "newchecksum"
+ mock_ctx.commit.assert_called()
+
+ def test_raises_file_not_found(self, tmp_path):
+ """Missing file raises FileNotFoundError."""
+ mgr = _make_manager()
+ with pytest.raises(FileNotFoundError):
+ mgr.record_file(tmp_path / "nope.bin")
+
+ def test_raises_no_verifier(self, tmp_path):
+ """No matching verifier raises ValueError."""
+ mgr = _make_manager()
+ f = tmp_path / "file.xyz"
+ f.write_text("data")
+ with pytest.raises(ValueError, match="No verifier"):
+ mgr.record_file(f)
+
+
+class TestLogFailure:
+ """Tests for _log_failure (audit trail)."""
+
+ def test_creates_failure_record(self, tmp_path):
+ """Failure record is added to session."""
+ from local_deep_research.security.file_integrity.base_verifier import (
+ BaseFileVerifier,
+ FileType,
+ )
+
+ class StubVerifier(BaseFileVerifier):
+ def should_verify(self, fp):
+ return True
+
+ def get_file_type(self):
+ return FileType.PDF
+
+ def allows_modifications(self):
+ return False
+
+ mgr = _make_manager()
+ v = StubVerifier()
+ v.calculate_checksum = Mock(return_value="actual_hash")
+ mgr.register_verifier(v)
+
+ f = tmp_path / "tampered.bin"
+ f.write_text("bad")
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.count.return_value = 0
+ record = Mock(id=1, checksum="expected_hash")
+
+ mgr._log_failure(record, f, "checksum_mismatch", mock_session)
+
+ mock_session.add.assert_called_once()
+ added_obj = mock_session.add.call_args[0][0]
+ assert added_obj.failure_reason == "checksum_mismatch"
+ assert added_obj.expected_checksum == "expected_hash"
+ assert added_obj.actual_checksum == "actual_hash"
+
+
+class TestCleanupOldFailures:
+ """Tests for _cleanup_old_failures (per-file)."""
+
+ def test_deletes_excess_failures(self):
+ """Old failures beyond MAX_FAILURES_PER_FILE are deleted."""
+ mgr = _make_manager()
+ mock_session = MagicMock()
+
+ # Simulate 105 failures (limit is 100)
+ mock_session.query.return_value.filter_by.return_value.count.return_value = 105
+
+ old_failures = [Mock() for _ in range(5)]
+ mock_session.query.return_value.filter_by.return_value.order_by.return_value.limit.return_value.all.return_value = old_failures
+
+ record = Mock(id=1)
+ mgr._cleanup_old_failures(record, mock_session)
+
+ assert mock_session.delete.call_count == 5
+
+
+class TestCleanupAllOldFailures:
+ """Tests for cleanup_all_old_failures (global)."""
+
+ def test_under_limit_returns_zero(self):
+ """No cleanup when under limit."""
+ from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+ )
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session"
+ ) as mock_gs:
+ mock_ctx = MagicMock()
+ mock_gs.return_value.__enter__ = Mock(return_value=mock_ctx)
+ mock_gs.return_value.__exit__ = Mock(return_value=False)
+ mock_ctx.query.return_value.count.return_value = (
+ 50 # well under 10000
+ )
+
+ mgr = FileIntegrityManager("user", "pass")
+ result = mgr.cleanup_all_old_failures()
+ assert result == 0
diff --git a/tests/web_search_engines/test_search_engine_factory.py b/tests/web_search_engines/test_search_engine_factory.py
index 5c36214800..6afc5bf22a 100644
--- a/tests/web_search_engines/test_search_engine_factory.py
+++ b/tests/web_search_engines/test_search_engine_factory.py
@@ -601,3 +601,305 @@ class TestParameterFiltering:
filtered_params["programmatic_mode"] = programmatic_mode
assert filtered_params["programmatic_mode"] is True
+
+
+def _make_engine_class(*param_names):
+ """Create a real class with a controlled __init__ signature.
+
+ The code under test calls inspect.signature(cls.__init__),
+ so we need a real class whose __init__ has the desired parameters.
+ The engine is instantiated with **filtered_params (kwargs style),
+ so the __init__ must accept **kwargs. We use functools.wraps to
+ preserve the signature for inspect while accepting any kwargs.
+ """
+ import inspect as _inspect
+
+ # Build a signature object that the factory code will inspect
+ params = [
+ _inspect.Parameter("self", _inspect.Parameter.POSITIONAL_OR_KEYWORD)
+ ]
+ for name in param_names:
+ params.append(
+ _inspect.Parameter(name, _inspect.Parameter.POSITIONAL_OR_KEYWORD)
+ )
+
+ class _Eng:
+ _call_kwargs = None
+
+ def __init__(self, **kwargs):
+ _Eng._call_kwargs = kwargs
+
+ # Attach the desired signature so inspect.signature(cls.__init__) sees our params
+ _Eng.__init__.__signature__ = _inspect.Signature(params)
+
+ return _Eng
+
+
+class TestCreateEngineInstantiation:
+ """Tests for the real engine instantiation path (lines 194-339)."""
+
+ def _make_engine_config(self, **overrides):
+ """Build a minimal engine config dict."""
+ base = {
+ "module_path": "some.module",
+ "class_name": "SomeEngine",
+ "default_params": {},
+ }
+ base.update(overrides)
+ return base
+
+ def test_calls_get_safe_module_class(self):
+ """get_safe_module_class is called with module_path and class_name."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class()
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class"
+ ) as mock_gsmc,
+ ):
+ mock_reg.get.return_value = None
+ mock_sc.return_value = {"myengine": self._make_engine_config()}
+ mock_gsmc.return_value = EngCls
+
+ create_search_engine("myengine", settings_snapshot={"x": 1})
+
+ mock_gsmc.assert_called_once_with("some.module", "SomeEngine")
+
+ def test_filters_unsupported_params(self):
+ """Parameters not in engine __init__ are filtered out."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results")
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class"
+ ) as mock_gsmc,
+ ):
+ mock_reg.get.return_value = None
+ mock_sc.return_value = {
+ "eng": self._make_engine_config(
+ default_params={"max_results": 5, "bogus_param": "nope"}
+ )
+ }
+ mock_gsmc.return_value = EngCls
+
+ create_search_engine("eng", settings_snapshot={"x": 1})
+
+ assert "max_results" in EngCls._call_kwargs
+ assert "bogus_param" not in EngCls._call_kwargs
+
+ def test_passes_settings_snapshot(self):
+ """settings_snapshot is passed when engine accepts it."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("settings_snapshot")
+ snapshot = {"key": "val"}
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class"
+ ) as mock_gsmc,
+ ):
+ mock_reg.get.return_value = None
+ mock_sc.return_value = {"eng": self._make_engine_config()}
+ mock_gsmc.return_value = EngCls
+
+ create_search_engine("eng", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs["settings_snapshot"] is snapshot
+
+ def test_passes_programmatic_mode(self):
+ """programmatic_mode flag is passed when engine accepts it."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("programmatic_mode")
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class"
+ ) as mock_gsmc,
+ ):
+ mock_reg.get.return_value = None
+ mock_sc.return_value = {"eng": self._make_engine_config()}
+ mock_gsmc.return_value = EngCls
+
+ create_search_engine(
+ "eng", settings_snapshot={"x": 1}, programmatic_mode=True
+ )
+
+ assert EngCls._call_kwargs["programmatic_mode"] is True
+
+ def test_adds_llm_when_requires_llm(self):
+ """LLM is injected when engine config has requires_llm=True."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("llm")
+ mock_llm = Mock()
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class"
+ ) as mock_gsmc,
+ ):
+ mock_reg.get.return_value = None
+ mock_sc.return_value = {
+ "eng": self._make_engine_config(requires_llm=True)
+ }
+ mock_gsmc.return_value = EngCls
+
+ create_search_engine(
+ "eng", llm=mock_llm, settings_snapshot={"x": 1}
+ )
+
+ assert EngCls._call_kwargs["llm"] is mock_llm
+
+ def test_exception_returns_none(self):
+ """Exception during instantiation returns None."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class"
+ ) as mock_gsmc,
+ ):
+ mock_reg.get.return_value = None
+ mock_sc.return_value = {"eng": self._make_engine_config()}
+ mock_gsmc.side_effect = ImportError("module not found")
+
+ result = create_search_engine("eng", settings_snapshot={"x": 1})
+ assert result is None
+
+ def test_unknown_engine_falls_back_to_auto(self):
+ """Unknown engine name falls back to 'auto' config."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class()
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class"
+ ) as mock_gsmc,
+ ):
+ mock_reg.get.return_value = None
+ mock_sc.return_value = {"auto": self._make_engine_config()}
+ mock_gsmc.return_value = EngCls
+
+ result = create_search_engine(
+ "nonexistent", settings_snapshot={"x": 1}
+ )
+ assert result is not None
+
+ def test_no_config_returns_none(self):
+ """Missing engine in config (and no 'auto') returns None."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ ):
+ mock_reg.get.return_value = None
+ mock_sc.return_value = {"other": {}}
+
+ result = create_search_engine(
+ "nonexistent", settings_snapshot={"x": 1}
+ )
+ assert result is None
+
+ def test_default_params_merged(self):
+ """default_params from config are merged with kwargs."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "region")
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config"
+ ) as mock_sc,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class"
+ ) as mock_gsmc,
+ ):
+ mock_reg.get.return_value = None
+ mock_sc.return_value = {
+ "eng": self._make_engine_config(default_params={"region": "us"})
+ }
+ mock_gsmc.return_value = EngCls
+
+ create_search_engine(
+ "eng", settings_snapshot={"x": 1}, max_results=15
+ )
+
+ # default_params region should be present
+ assert EngCls._call_kwargs["region"] == "us"
+ # kwargs max_results should be present
+ assert EngCls._call_kwargs["max_results"] == 15