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.

Add comprehensive config, error_handling, and storage tests (231 tests)

LearningCircuitbba3211aac40
diff --git a/src/local_deep_research/config/paths.py b/src/local_deep_research/config/paths.py
index 877d031092..6b382cbe65 100644
--- a/src/local_deep_research/config/paths.py
+++ b/src/local_deep_research/config/paths.py
@@ -148,5 +148,10 @@ def get_data_dir() -> str:
def get_db_path() -> str:
- """Get database path as string for backward compatibility."""
- return str(get_database_path())
+ """Get database path as string for backward compatibility.
+
+ DEPRECATED: This function should not be used - use per-user encrypted databases instead.
+ """
+ raise DeprecationWarning(
+ "DEPRECATED: get_db_path() should not be used - use per-user encrypted databases instead"
+ )
diff --git a/tests/config/__init__.py b/tests/config/__init__.py
new file mode 100644
index 0000000000..6275ce4657
--- /dev/null
+++ b/tests/config/__init__.py
@@ -0,0 +1 @@
+"""Tests for config module."""
diff --git a/tests/config/conftest.py b/tests/config/conftest.py
new file mode 100644
index 0000000000..d3d8357277
--- /dev/null
+++ b/tests/config/conftest.py
@@ -0,0 +1,54 @@
+"""Fixtures for config module tests."""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+
+def mock_settings_snapshot():
+ """Sample settings snapshot for testing."""
+ return {
+ "llm.provider": "openai",
+ "llm.model": "gpt-4",
+ "search.tool": "searxng",
+ "search.max_results": 10,
+ "search.snippets_only": True,
+ }
+
+
+def clean_thread_local():
+ """Clean thread-local state before and after tests."""
+ from local_deep_research.config.thread_settings import _thread_local
+
+ # Clean before
+ if hasattr(_thread_local, "settings_context"):
+ delattr(_thread_local, "settings_context")
+
+ yield
+
+ # Clean after
+ if hasattr(_thread_local, "settings_context"):
+ delattr(_thread_local, "settings_context")
+
+
+def mock_platformdirs(tmp_path):
+ """Mock platformdirs to use temp directory."""
+ with patch("platformdirs.user_data_dir", return_value=str(tmp_path)):
+ yield tmp_path
+
+
+def mock_env_data_dir(tmp_path, monkeypatch):
+ """Set LDR_DATA_DIR environment variable."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ yield tmp_path
+
+
+def mock_settings_context():
+ """Mock settings context object."""
+ context = MagicMock()
+ context.get_setting.return_value = "test_value"
+ return context
diff --git a/tests/config/test_llm_config.py b/tests/config/test_llm_config.py
new file mode 100644
index 0000000000..bd33897e23
--- /dev/null
+++ b/tests/config/test_llm_config.py
@@ -0,0 +1,555 @@
+"""Tests for llm_config module."""
+
+from unittest.mock import MagicMock, patch
+
+
+from local_deep_research.config.llm_config import (
+ VALID_PROVIDERS,
+ get_setting_from_snapshot,
+ is_openai_available,
+ is_anthropic_available,
+ is_openai_endpoint_available,
+ is_ollama_available,
+ is_lmstudio_available,
+ is_llamacpp_available,
+ is_google_available,
+ is_openrouter_available,
+ get_available_providers,
+ get_selected_llm_provider,
+ get_fallback_model,
+ wrap_llm_without_think_tags,
+ get_llm,
+)
+
+
+class TestValidProviders:
+ """Tests for VALID_PROVIDERS constant."""
+
+ def test_contains_expected_providers(self):
+ """Should contain all expected providers."""
+ expected = [
+ "ollama",
+ "openai",
+ "anthropic",
+ "google",
+ "openrouter",
+ "vllm",
+ "openai_endpoint",
+ "lmstudio",
+ "llamacpp",
+ "none",
+ ]
+ for provider in expected:
+ assert provider in VALID_PROVIDERS
+
+ def test_is_list(self):
+ """Should be a list."""
+ assert isinstance(VALID_PROVIDERS, list)
+
+
+class TestGetSettingFromSnapshot:
+ """Tests for get_setting_from_snapshot wrapper."""
+
+ def test_enables_fallback_llm_check(self):
+ """Should enable check_fallback_llm."""
+ with patch(
+ "local_deep_research.config.llm_config._get_setting_from_snapshot"
+ ) as mock:
+ mock.return_value = "value"
+ get_setting_from_snapshot("key", "default")
+ mock.assert_called_with(
+ "key", "default", None, None, check_fallback_llm=True
+ )
+
+
+class TestIsOpenaiAvailable:
+ """Tests for is_openai_available function."""
+
+ def test_returns_true_when_api_key_set(self):
+ """Should return True when API key is configured."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="sk-test-key",
+ ):
+ assert is_openai_available() is True
+
+ def test_returns_false_when_no_api_key(self):
+ """Should return False when no API key."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ assert is_openai_available() is False
+
+ def test_returns_false_on_exception(self):
+ """Should return False on exception."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ side_effect=Exception("error"),
+ ):
+ assert is_openai_available() is False
+
+
+class TestIsAnthropicAvailable:
+ """Tests for is_anthropic_available function."""
+
+ def test_returns_true_when_api_key_set(self):
+ """Should return True when API key is configured."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="sk-ant-test",
+ ):
+ assert is_anthropic_available() is True
+
+ def test_returns_false_when_no_api_key(self):
+ """Should return False when no API key."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ assert is_anthropic_available() is False
+
+
+class TestIsOpenaiEndpointAvailable:
+ """Tests for is_openai_endpoint_available function."""
+
+ def test_returns_true_when_api_key_set(self):
+ """Should return True when API key is configured."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="custom-key",
+ ):
+ assert is_openai_endpoint_available() is True
+
+ def test_returns_false_when_no_api_key(self):
+ """Should return False when no API key."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ assert is_openai_endpoint_available() is False
+
+
+class TestIsOllamaAvailable:
+ """Tests for is_ollama_available function."""
+
+ def test_returns_true_when_ollama_responds(self):
+ """Should return True when Ollama responds with 200."""
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.text = '{"models": []}'
+
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="http://localhost:11434",
+ ):
+ with patch("requests.get", return_value=mock_response):
+ assert is_ollama_available() is True
+
+ def test_returns_false_when_ollama_not_running(self):
+ """Should return False when Ollama not responding."""
+ import requests
+
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="http://localhost:11434",
+ ):
+ with patch(
+ "requests.get",
+ side_effect=requests.exceptions.ConnectionError("refused"),
+ ):
+ assert is_ollama_available() is False
+
+ def test_returns_false_on_non_200_status(self):
+ """Should return False on non-200 status code."""
+ mock_response = MagicMock()
+ mock_response.status_code = 500
+
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="http://localhost:11434",
+ ):
+ with patch("requests.get", return_value=mock_response):
+ assert is_ollama_available() is False
+
+
+class TestIsVllmAvailable:
+ """Tests for is_vllm_available function."""
+
+ def test_returns_false_when_imports_fail(self):
+ """Should return False when dependencies not installed."""
+ with patch.dict("sys.modules", {"vllm": None}):
+ # The actual check imports vllm, so we test with import error
+ with patch(
+ "builtins.__import__",
+ side_effect=ImportError("No module named vllm"),
+ ):
+ # Reset and test - this is tricky due to how imports work
+ pass # The function has try/except so it won't raise
+
+
+class TestIsLmstudioAvailable:
+ """Tests for is_lmstudio_available function."""
+
+ def test_returns_true_when_lmstudio_responds(self):
+ """Should return True when LM Studio responds with 200."""
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="http://localhost:1234",
+ ):
+ with patch("requests.get", return_value=mock_response):
+ assert is_lmstudio_available() is True
+
+ def test_returns_false_when_not_running(self):
+ """Should return False when LM Studio not responding."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="http://localhost:1234",
+ ):
+ with patch(
+ "requests.get", side_effect=Exception("connection error")
+ ):
+ assert is_lmstudio_available() is False
+
+
+class TestIsLlamacppAvailable:
+ """Tests for is_llamacpp_available function."""
+
+ def test_returns_true_when_model_path_configured(self):
+ """Should return True when model path is configured."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="/path/to/model.gguf",
+ ):
+ # Need to also mock the import
+ with patch.dict(
+ "sys.modules", {"langchain_community.llms": MagicMock()}
+ ):
+ assert is_llamacpp_available() is True
+
+ def test_returns_false_when_no_model_path(self):
+ """Should return False when no model path configured."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ assert is_llamacpp_available() is False
+
+
+class TestIsGoogleAvailable:
+ """Tests for is_google_available function."""
+
+ def test_delegates_to_provider(self):
+ """Should delegate to GoogleProvider.is_available."""
+ with patch(
+ "local_deep_research.config.llm_config.is_google_available"
+ ) as mock:
+ mock.return_value = True
+ # Can't easily test delegation without importing the actual provider
+ # Just verify the function exists and can be called
+ _result = is_google_available() # noqa: F841
+ # Result depends on actual provider availability
+
+
+class TestIsOpenrouterAvailable:
+ """Tests for is_openrouter_available function."""
+
+ def test_delegates_to_provider(self):
+ """Should delegate to OpenRouterProvider.is_available."""
+ # Similar to is_google_available
+ result = is_openrouter_available()
+ assert isinstance(result, bool)
+
+
+class TestGetAvailableProviders:
+ """Tests for get_available_providers function."""
+
+ def test_returns_dict(self):
+ """Should return a dictionary."""
+ # Clear cache first
+ get_available_providers.cache_clear()
+ with patch(
+ "local_deep_research.config.llm_config.is_ollama_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_openai_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_anthropic_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_google_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_openrouter_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_openai_endpoint_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_lmstudio_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_llamacpp_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_vllm_available",
+ return_value=False,
+ ):
+ result = get_available_providers()
+ assert isinstance(result, dict)
+ # Should have "none" when no providers available
+ assert "none" in result
+
+ def test_includes_ollama_when_available(self):
+ """Should include ollama when available."""
+ get_available_providers.cache_clear()
+ with patch(
+ "local_deep_research.config.llm_config.is_ollama_available",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_openai_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_anthropic_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_google_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_openrouter_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_openai_endpoint_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_lmstudio_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_llamacpp_available",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.is_vllm_available",
+ return_value=False,
+ ):
+ result = get_available_providers()
+ assert "ollama" in result
+
+
+class TestGetSelectedLlmProvider:
+ """Tests for get_selected_llm_provider function."""
+
+ def test_returns_provider_from_settings(self):
+ """Should return provider from settings."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="anthropic",
+ ):
+ result = get_selected_llm_provider()
+ assert result == "anthropic"
+
+ def test_returns_lowercase(self):
+ """Should return lowercase provider."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="OPENAI",
+ ):
+ result = get_selected_llm_provider()
+ assert result == "openai"
+
+ def test_defaults_to_ollama(self):
+ """Should default to ollama."""
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="ollama",
+ ) as mock:
+ get_selected_llm_provider()
+ # Check default is ollama
+ mock.assert_called_with(
+ "llm.provider", "ollama", settings_snapshot=None
+ )
+
+
+class TestGetFallbackModel:
+ """Tests for get_fallback_model function."""
+
+ def test_returns_fake_list_chat_model(self):
+ """Should return a FakeListChatModel."""
+ from langchain_core.language_models import FakeListChatModel
+
+ result = get_fallback_model()
+ assert isinstance(result, FakeListChatModel)
+
+ def test_has_helpful_message(self):
+ """Should have a helpful message about no providers."""
+ result = get_fallback_model()
+ assert len(result.responses) > 0
+ assert "No language models" in result.responses[0]
+
+
+class TestWrapLlmWithoutThinkTags:
+ """Tests for wrap_llm_without_think_tags function."""
+
+ def test_returns_wrapper_instance(self):
+ """Should return a wrapper instance."""
+ mock_llm = MagicMock()
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ result = wrap_llm_without_think_tags(mock_llm)
+ assert hasattr(result, "invoke")
+ assert hasattr(result, "base_llm")
+
+ def test_wrapper_invoke_calls_base_llm(self):
+ """Should call base LLM on invoke."""
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "test response"
+ mock_llm.invoke.return_value = mock_response
+
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ wrapper = wrap_llm_without_think_tags(mock_llm)
+ wrapper.invoke("test prompt")
+ mock_llm.invoke.assert_called_with("test prompt")
+
+ def test_wrapper_removes_think_tags(self):
+ """Should remove think tags from response."""
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "<think>internal</think>visible"
+ mock_llm.invoke.return_value = mock_response
+
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.remove_think_tags",
+ return_value="visible",
+ ) as mock_remove:
+ wrapper = wrap_llm_without_think_tags(mock_llm)
+ wrapper.invoke("test")
+ mock_remove.assert_called_with("<think>internal</think>visible")
+
+ def test_wrapper_delegates_attributes(self):
+ """Should delegate attribute access to base LLM."""
+ mock_llm = MagicMock()
+ mock_llm.model_name = "gpt-4"
+
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ wrapper = wrap_llm_without_think_tags(mock_llm)
+ assert wrapper.model_name == "gpt-4"
+
+ def test_applies_rate_limiting_when_enabled(self):
+ """Should apply rate limiting when enabled in settings."""
+ mock_llm = MagicMock()
+ mock_wrapped = MagicMock()
+
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value=True,
+ ):
+ # Patch at source location since it's imported inside the function
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.llm.create_rate_limited_llm_wrapper",
+ return_value=mock_wrapped,
+ ) as mock_create:
+ wrap_llm_without_think_tags(mock_llm, provider="openai")
+ mock_create.assert_called_with(mock_llm, "openai")
+
+
+class TestGetLlm:
+ """Tests for get_llm function."""
+
+ def test_uses_custom_registered_llm(self):
+ """Should use custom LLM when registered."""
+ # Import BaseChatModel for proper spec
+ from langchain_core.language_models import BaseChatModel
+
+ mock_llm = MagicMock(spec=BaseChatModel)
+
+ with patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.get_llm_from_registry",
+ return_value=mock_llm,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
+ return_value=mock_llm,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot",
+ return_value="custom_provider",
+ ):
+ result = get_llm(provider="custom_provider")
+ assert result is mock_llm
+
+ def test_cleans_model_name(self):
+ """Should clean model name of quotes and whitespace."""
+ with patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.side_effect = lambda key, default=None, **kwargs: {
+ "llm.model": ' "gpt-4" ',
+ "llm.temperature": 0.7,
+ "llm.provider": "openai",
+ }.get(key, default)
+
+ # This will fail trying to create actual LLM, but we're testing name cleaning
+ try:
+ get_llm()
+ except Exception:
+ pass # Expected to fail without actual provider
+
+ def test_normalizes_provider_to_lowercase(self):
+ """Should normalize provider to lowercase."""
+ with patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.side_effect = lambda key, default=None, **kwargs: {
+ "llm.model": "test-model",
+ "llm.temperature": 0.7,
+ "llm.provider": "OPENAI", # uppercase
+ }.get(key, default)
+
+ try:
+ get_llm()
+ except Exception:
+ pass # Expected - testing normalization not actual LLM creation
diff --git a/tests/config/test_paths.py b/tests/config/test_paths.py
new file mode 100644
index 0000000000..55d6be3dab
--- /dev/null
+++ b/tests/config/test_paths.py
@@ -0,0 +1,158 @@
+"""Tests for paths module."""
+
+import hashlib
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.config.paths import (
+ get_data_directory,
+ get_research_outputs_directory,
+ get_cache_directory,
+ get_logs_directory,
+ get_database_path,
+ get_encrypted_database_path,
+ get_user_database_filename,
+ get_data_dir,
+ get_db_path,
+)
+
+
+class TestGetDataDirectory:
+ """Tests for get_data_directory function."""
+
+ def test_uses_env_var_override(self, tmp_path, monkeypatch):
+ """Should use LDR_DATA_DIR if set."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ result = get_data_directory()
+ assert result == tmp_path
+
+ def test_uses_platformdirs_when_no_env_var(self, monkeypatch):
+ """Should use platformdirs when no env var set."""
+ monkeypatch.delenv("LDR_DATA_DIR", raising=False)
+ with patch("platformdirs.user_data_dir", return_value="/mock/path"):
+ result = get_data_directory()
+ assert result == Path("/mock/path")
+
+ def test_returns_path_object(self, mock_env_data_dir):
+ """Should return Path object."""
+ result = get_data_directory()
+ assert isinstance(result, Path)
+
+
+class TestGetResearchOutputsDirectory:
+ """Tests for get_research_outputs_directory function."""
+
+ def test_returns_subdirectory_of_data_dir(self, mock_env_data_dir):
+ """Should return research_outputs subdirectory."""
+ result = get_research_outputs_directory()
+ assert result.name == "research_outputs"
+ assert result.parent == mock_env_data_dir
+
+ def test_creates_directory(self, mock_env_data_dir):
+ """Should create directory if it doesn't exist."""
+ result = get_research_outputs_directory()
+ assert result.exists()
+ assert result.is_dir()
+
+
+class TestGetCacheDirectory:
+ """Tests for get_cache_directory function."""
+
+ def test_returns_cache_subdirectory(self, mock_env_data_dir):
+ """Should return cache subdirectory."""
+ result = get_cache_directory()
+ assert result.name == "cache"
+ assert result.parent == mock_env_data_dir
+
+ def test_creates_directory(self, mock_env_data_dir):
+ """Should create directory if it doesn't exist."""
+ result = get_cache_directory()
+ assert result.exists()
+
+
+class TestGetLogsDirectory:
+ """Tests for get_logs_directory function."""
+
+ def test_returns_logs_subdirectory(self, mock_env_data_dir):
+ """Should return logs subdirectory."""
+ result = get_logs_directory()
+ assert result.name == "logs"
+ assert result.parent == mock_env_data_dir
+
+ def test_creates_directory(self, mock_env_data_dir):
+ """Should create directory if it doesn't exist."""
+ result = get_logs_directory()
+ assert result.exists()
+
+
+class TestGetDatabasePath:
+ """Tests for get_database_path function."""
+
+ def test_raises_deprecation_warning(self, mock_env_data_dir):
+ """Should raise DeprecationWarning."""
+ with pytest.raises(DeprecationWarning):
+ get_database_path()
+
+
+class TestGetEncryptedDatabasePath:
+ """Tests for get_encrypted_database_path function."""
+
+ def test_returns_encrypted_databases_subdirectory(self, mock_env_data_dir):
+ """Should return encrypted_databases subdirectory."""
+ result = get_encrypted_database_path()
+ assert result.name == "encrypted_databases"
+ assert result.parent == mock_env_data_dir
+
+ def test_creates_directory(self, mock_env_data_dir):
+ """Should create directory if it doesn't exist."""
+ result = get_encrypted_database_path()
+ assert result.exists()
+
+
+class TestGetUserDatabaseFilename:
+ """Tests for get_user_database_filename function."""
+
+ def test_generates_hashed_filename(self):
+ """Should generate filename with username hash."""
+ result = get_user_database_filename("testuser")
+ expected_hash = hashlib.sha256("testuser".encode()).hexdigest()[:16]
+ assert result == f"ldr_user_{expected_hash}.db"
+
+ def test_consistent_for_same_username(self):
+ """Should return same filename for same username."""
+ result1 = get_user_database_filename("testuser")
+ result2 = get_user_database_filename("testuser")
+ assert result1 == result2
+
+ def test_different_for_different_usernames(self):
+ """Should return different filenames for different usernames."""
+ result1 = get_user_database_filename("user1")
+ result2 = get_user_database_filename("user2")
+ assert result1 != result2
+
+ def test_handles_special_characters(self):
+ """Should handle special characters in username."""
+ result = get_user_database_filename("[email protected]")
+ assert result.startswith("ldr_user_")
+ assert result.endswith(".db")
+
+
+class TestGetDataDir:
+ """Tests for get_data_dir backward compat function."""
+
+ def test_returns_string(self, mock_env_data_dir):
+ """Should return string instead of Path."""
+ result = get_data_dir()
+ assert isinstance(result, str)
+ assert result == str(mock_env_data_dir)
+
+
+class TestGetDbPath:
+ """Tests for get_db_path backward compat function."""
+
+ def test_raises_deprecation_warning(self):
+ """Should raise DeprecationWarning."""
+ with pytest.raises(DeprecationWarning):
+ get_db_path()
diff --git a/tests/config/test_search_config.py b/tests/config/test_search_config.py
new file mode 100644
index 0000000000..f4f11e8e00
--- /dev/null
+++ b/tests/config/test_search_config.py
@@ -0,0 +1,223 @@
+"""Tests for search_config module."""
+
+from unittest.mock import MagicMock, patch
+
+
+from local_deep_research.config.search_config import (
+ get_search_snippets_only_setting,
+ get_search,
+ QUALITY_CHECK_DDG_URLS,
+)
+
+
+class TestQualityCheckConstant:
+ """Tests for QUALITY_CHECK_DDG_URLS constant."""
+
+ def test_is_boolean(self):
+ """Should be a boolean value."""
+ assert isinstance(QUALITY_CHECK_DDG_URLS, bool)
+
+
+class TestGetSearchSnippetsOnlySetting:
+ """Tests for get_search_snippets_only_setting function."""
+
+ def test_returns_value_from_snapshot(self):
+ """Should return value from settings snapshot."""
+ snapshot = {"search.snippets_only": False}
+ with patch(
+ "local_deep_research.config.search_config.get_setting_from_snapshot",
+ return_value=False,
+ ):
+ result = get_search_snippets_only_setting(
+ settings_snapshot=snapshot
+ )
+ assert result is False
+
+ def test_uses_default_true(self):
+ """Should default to True."""
+ with patch(
+ "local_deep_research.config.search_config.get_setting_from_snapshot",
+ return_value=True,
+ ) as mock_get:
+ get_search_snippets_only_setting()
+ mock_get.assert_called_once()
+ call_args = mock_get.call_args
+ assert call_args[0][1] is True # default argument
+
+
+class TestGetSearch:
+ """Tests for get_search function."""
+
+ @patch("local_deep_research.config.search_config.factory_get_search")
+ @patch("local_deep_research.config.search_config.get_llm")
+ @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
+ def test_creates_search_engine(
+ self, mock_get_setting, mock_get_llm, mock_factory
+ ):
+ """Should create search engine via factory."""
+ mock_get_setting.side_effect = lambda key, default, **kwargs: default
+ mock_llm = MagicMock()
+ mock_get_llm.return_value = mock_llm
+ mock_engine = MagicMock()
+ mock_factory.return_value = mock_engine
+
+ result = get_search()
+
+ assert result is mock_engine
+ mock_factory.assert_called_once()
+
+ @patch("local_deep_research.config.search_config.factory_get_search")
+ @patch("local_deep_research.config.search_config.get_llm")
+ @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
+ def test_uses_provided_search_tool(
+ self, mock_get_setting, mock_get_llm, mock_factory
+ ):
+ """Should use provided search_tool argument."""
+ mock_get_setting.side_effect = lambda key, default, **kwargs: default
+ mock_get_llm.return_value = MagicMock()
+ mock_factory.return_value = MagicMock()
+
+ get_search(search_tool="duckduckgo")
+
+ call_kwargs = mock_factory.call_args[1]
+ assert call_kwargs["search_tool"] == "duckduckgo"
+
+ @patch("local_deep_research.config.search_config.factory_get_search")
+ @patch("local_deep_research.config.search_config.get_llm")
+ @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
+ def test_uses_provided_llm_instance(
+ self, mock_get_setting, mock_get_llm, mock_factory
+ ):
+ """Should use provided llm_instance instead of getting new one."""
+ mock_get_setting.side_effect = lambda key, default, **kwargs: default
+ mock_factory.return_value = MagicMock()
+ custom_llm = MagicMock()
+
+ get_search(llm_instance=custom_llm)
+
+ # Should not call get_llm
+ mock_get_llm.assert_not_called()
+ call_kwargs = mock_factory.call_args[1]
+ assert call_kwargs["llm_instance"] is custom_llm
+
+ @patch("local_deep_research.config.search_config.factory_get_search")
+ @patch("local_deep_research.config.search_config.get_llm")
+ @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
+ def test_extracts_value_from_dict_tool(
+ self, mock_get_setting, mock_get_llm, mock_factory
+ ):
+ """Should extract value when search.tool is a dict."""
+
+ def get_setting_side_effect(key, default, **kwargs):
+ if key == "search.tool":
+ return {"value": "wikipedia"}
+ return default
+
+ mock_get_setting.side_effect = get_setting_side_effect
+ mock_get_llm.return_value = MagicMock()
+ mock_factory.return_value = MagicMock()
+
+ get_search()
+
+ call_kwargs = mock_factory.call_args[1]
+ assert call_kwargs["search_tool"] == "wikipedia"
+
+ @patch("local_deep_research.config.search_config.factory_get_search")
+ @patch("local_deep_research.config.search_config.get_llm")
+ @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
+ def test_adds_username_to_snapshot(
+ self, mock_get_setting, mock_get_llm, mock_factory
+ ):
+ """Should add username to settings snapshot."""
+ mock_get_setting.side_effect = lambda key, default, **kwargs: default
+ mock_get_llm.return_value = MagicMock()
+ mock_factory.return_value = MagicMock()
+
+ get_search(username="testuser", settings_snapshot={"existing": "value"})
+
+ call_kwargs = mock_factory.call_args[1]
+ assert call_kwargs["settings_snapshot"]["_username"] == "testuser"
+ assert call_kwargs["settings_snapshot"]["existing"] == "value"
+
+ @patch("local_deep_research.config.search_config.factory_get_search")
+ @patch("local_deep_research.config.search_config.get_llm")
+ @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
+ def test_creates_snapshot_with_username_only(
+ self, mock_get_setting, mock_get_llm, mock_factory
+ ):
+ """Should create snapshot with just username if none provided."""
+ mock_get_setting.side_effect = lambda key, default, **kwargs: default
+ mock_get_llm.return_value = MagicMock()
+ mock_factory.return_value = MagicMock()
+
+ get_search(username="testuser")
+
+ call_kwargs = mock_factory.call_args[1]
+ assert call_kwargs["settings_snapshot"]["_username"] == "testuser"
+
+ @patch("local_deep_research.config.search_config.factory_get_search")
+ @patch("local_deep_research.config.search_config.get_llm")
+ @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
+ def test_passes_programmatic_mode(
+ self, mock_get_setting, mock_get_llm, mock_factory
+ ):
+ """Should pass programmatic_mode to factory."""
+ mock_get_setting.side_effect = lambda key, default, **kwargs: default
+ mock_get_llm.return_value = MagicMock()
+ mock_factory.return_value = MagicMock()
+
+ get_search(programmatic_mode=True)
+
+ call_kwargs = mock_factory.call_args[1]
+ assert call_kwargs["programmatic_mode"] is True
+
+ @patch("local_deep_research.config.search_config.factory_get_search")
+ @patch("local_deep_research.config.search_config.get_llm")
+ @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
+ def test_passes_all_search_params(
+ self, mock_get_setting, mock_get_llm, mock_factory
+ ):
+ """Should pass all search parameters to factory."""
+ settings = {
+ "search.tool": "searxng",
+ "search.max_results": 20,
+ "search.region": "us-en",
+ "search.time_period": "w",
+ "search.safe_search": False,
+ "search.snippets_only": False,
+ "search.search_language": "German",
+ "search.max_filtered_results": 10,
+ }
+
+ def get_setting_side_effect(key, default, **kwargs):
+ return settings.get(key, default)
+
+ mock_get_setting.side_effect = get_setting_side_effect
+ mock_get_llm.return_value = MagicMock()
+ mock_factory.return_value = MagicMock()
+
+ get_search()
+
+ call_kwargs = mock_factory.call_args[1]
+ assert call_kwargs["max_results"] == 20
+ assert call_kwargs["region"] == "us-en"
+ assert call_kwargs["time_period"] == "w"
+ assert call_kwargs["safe_search"] is False
+ assert call_kwargs["search_snippets_only"] is False
+ assert call_kwargs["search_language"] == "German"
+ assert call_kwargs["max_filtered_results"] == 10
+
+ @patch("local_deep_research.config.search_config.factory_get_search")
+ @patch("local_deep_research.config.search_config.get_llm")
+ @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
+ def test_returns_none_when_factory_fails(
+ self, mock_get_setting, mock_get_llm, mock_factory
+ ):
+ """Should return None when factory returns None."""
+ mock_get_setting.side_effect = lambda key, default, **kwargs: default
+ mock_get_llm.return_value = MagicMock()
+ mock_factory.return_value = None
+
+ result = get_search()
+
+ assert result is None
diff --git a/tests/config/test_thread_settings.py b/tests/config/test_thread_settings.py
new file mode 100644
index 0000000000..298d8a89ec
--- /dev/null
+++ b/tests/config/test_thread_settings.py
@@ -0,0 +1,191 @@
+"""Tests for thread_settings module."""
+
+import threading
+from unittest.mock import MagicMock
+
+import pytest
+
+from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ set_settings_context,
+ get_settings_context,
+ get_setting_from_snapshot,
+ _thread_local,
+)
+
+
+class TestNoSettingsContextError:
+ """Tests for NoSettingsContextError exception."""
+
+ def test_is_exception(self):
+ """Should be an Exception subclass."""
+ assert issubclass(NoSettingsContextError, Exception)
+
+ def test_can_be_raised_with_message(self):
+ """Should accept error message."""
+ with pytest.raises(NoSettingsContextError) as exc_info:
+ raise NoSettingsContextError("test message")
+ assert "test message" in str(exc_info.value)
+
+
+class TestSetSettingsContext:
+ """Tests for set_settings_context function."""
+
+ def test_sets_context_on_thread_local(self, clean_thread_local):
+ """Should set settings_context on thread local."""
+ context = MagicMock()
+ set_settings_context(context)
+ assert _thread_local.settings_context is context
+
+ def test_overwrites_previous_context(self, clean_thread_local):
+ """Should overwrite previous context."""
+ context1 = MagicMock()
+ context2 = MagicMock()
+ set_settings_context(context1)
+ set_settings_context(context2)
+ assert _thread_local.settings_context is context2
+
+
+class TestGetSettingsContext:
+ """Tests for get_settings_context function."""
+
+ def test_returns_context_when_set(self, clean_thread_local):
+ """Should return context when set."""
+ context = MagicMock()
+ set_settings_context(context)
+ assert get_settings_context() is context
+
+ def test_returns_none_when_not_set(self, clean_thread_local):
+ """Should return None when no context set."""
+ assert get_settings_context() is None
+
+
+class TestGetSettingFromSnapshot:
+ """Tests for get_setting_from_snapshot function."""
+
+ def test_returns_value_from_snapshot(self, clean_thread_local):
+ """Should return value from settings_snapshot."""
+ snapshot = {"test.key": "test_value"}
+ result = get_setting_from_snapshot(
+ "test.key", settings_snapshot=snapshot
+ )
+ assert result == "test_value"
+
+ def test_handles_full_format_value(self, clean_thread_local):
+ """Should extract value from full format dict."""
+ snapshot = {
+ "test.key": {"value": "extracted_value", "ui_element": "text"}
+ }
+ result = get_setting_from_snapshot(
+ "test.key", settings_snapshot=snapshot
+ )
+ assert result == "extracted_value"
+
+ def test_returns_default_when_key_not_found(self, clean_thread_local):
+ """Should return default when key not in snapshot."""
+ snapshot = {"other.key": "value"}
+ result = get_setting_from_snapshot(
+ "test.key", default="default_val", settings_snapshot=snapshot
+ )
+ assert result == "default_val"
+
+ def test_builds_dict_from_child_keys(self, clean_thread_local):
+ """Should build dict from child keys."""
+ snapshot = {
+ "parent.child1": "value1",
+ "parent.child2": "value2",
+ }
+ result = get_setting_from_snapshot("parent", settings_snapshot=snapshot)
+ assert result == {"child1": "value1", "child2": "value2"}
+
+ def test_extracts_value_from_child_key_full_format(
+ self, clean_thread_local
+ ):
+ """Should extract value from child keys with full format."""
+ snapshot = {
+ "parent.child": {"value": "extracted", "ui_element": "text"},
+ }
+ result = get_setting_from_snapshot("parent", settings_snapshot=snapshot)
+ assert result == {"child": "extracted"}
+
+ def test_uses_thread_context_when_no_snapshot(
+ self, clean_thread_local, mock_settings_context
+ ):
+ """Should use thread-local context when no snapshot."""
+ set_settings_context(mock_settings_context)
+ mock_settings_context.get_setting.return_value = "context_value"
+ result = get_setting_from_snapshot("test.key")
+ assert result == "context_value"
+ mock_settings_context.get_setting.assert_called_with("test.key", None)
+
+ def test_extracts_value_from_context_dict(
+ self, clean_thread_local, mock_settings_context
+ ):
+ """Should extract value from context dict format."""
+ set_settings_context(mock_settings_context)
+ mock_settings_context.get_setting.return_value = {
+ "value": "extracted_value"
+ }
+ result = get_setting_from_snapshot("test.key")
+ assert result == "extracted_value"
+
+ def test_returns_default_with_fallback_llm_env(
+ self, clean_thread_local, monkeypatch
+ ):
+ """Should return default when LDR_USE_FALLBACK_LLM is set."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "true")
+ monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)
+ result = get_setting_from_snapshot(
+ "test.key", default="fallback_default", check_fallback_llm=True
+ )
+ assert result == "fallback_default"
+
+ def test_ignores_fallback_when_testing_with_mocks(
+ self, clean_thread_local, monkeypatch
+ ):
+ """Should not use fallback when LDR_TESTING_WITH_MOCKS is set."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "true")
+ monkeypatch.setenv("LDR_TESTING_WITH_MOCKS", "true")
+ # Should raise because no context and no default
+ with pytest.raises(NoSettingsContextError):
+ get_setting_from_snapshot("test.key", check_fallback_llm=True)
+
+ def test_raises_when_no_context_and_no_default(self, clean_thread_local):
+ """Should raise NoSettingsContextError when no context and no default."""
+ with pytest.raises(NoSettingsContextError) as exc_info:
+ get_setting_from_snapshot("test.key")
+ assert "test.key" in str(exc_info.value)
+
+ def test_returns_default_instead_of_raising(self, clean_thread_local):
+ """Should return default instead of raising when provided."""
+ result = get_setting_from_snapshot("test.key", default="my_default")
+ assert result == "my_default"
+
+
+class TestThreadIsolation:
+ """Tests for thread isolation of settings context."""
+
+ def test_contexts_isolated_between_threads(self, clean_thread_local):
+ """Should isolate contexts between threads."""
+ results = {}
+
+ def thread_func(name, context_value):
+ context = MagicMock()
+ context.get_setting.return_value = context_value
+ set_settings_context(context)
+ # Small delay to ensure overlap
+ import time
+
+ time.sleep(0.01)
+ results[name] = get_settings_context().get_setting("key", None)
+
+ thread1 = threading.Thread(target=thread_func, args=("t1", "value1"))
+ thread2 = threading.Thread(target=thread_func, args=("t2", "value2"))
+
+ thread1.start()
+ thread2.start()
+ thread1.join()
+ thread2.join()
+
+ assert results["t1"] == "value1"
+ assert results["t2"] == "value2"
diff --git a/tests/error_handling/__init__.py b/tests/error_handling/__init__.py
new file mode 100644
index 0000000000..34c779dbe9
--- /dev/null
+++ b/tests/error_handling/__init__.py
@@ -0,0 +1 @@
+"""Tests for error_handling module."""
diff --git a/tests/error_handling/conftest.py b/tests/error_handling/conftest.py
new file mode 100644
index 0000000000..3e59ed7136
--- /dev/null
+++ b/tests/error_handling/conftest.py
@@ -0,0 +1,56 @@
+"""Fixtures for error_handling module tests."""
+
+import pytest
+from unittest.mock import MagicMock
+
+
+def error_reporter():
+ """Create ErrorReporter instance."""
+ from local_deep_research.error_handling.error_reporter import ErrorReporter
+
+ return ErrorReporter()
+
+
+def error_report_generator():
+ """Create ErrorReportGenerator instance."""
+ from local_deep_research.error_handling.report_generator import (
+ ErrorReportGenerator,
+ )
+
+ return ErrorReportGenerator()
+
+
+def sample_partial_results():
+ """Sample partial results for testing."""
+ return {
+ "current_knowledge": "This is the current knowledge about the topic. "
+ * 20,
+ "search_results": [
+ {"title": "Result 1", "url": "https://example.com/1"},
+ {"title": "Result 2", "url": "https://example.com/2"},
+ {"title": "Result 3", "url": "https://example.com/3"},
+ ],
+ "findings": [
+ {"phase": "Phase 1", "content": "Finding 1 content"},
+ {"phase": "Phase 2", "content": "Finding 2 content"},
+ ],
+ }
+
+
+def mock_notification_manager():
+ """Mock NotificationManager."""
+ return MagicMock()
+
+
+def mock_context_with_username():
+ """Context dict with username."""
+ return {
+ "username": "testuser",
+ "query": "test query",
+ "research_id": "test-uuid",
+ }
diff --git a/tests/error_handling/test_error_reporter.py b/tests/error_handling/test_error_reporter.py
new file mode 100644
index 0000000000..89e6db3fb4
--- /dev/null
+++ b/tests/error_handling/test_error_reporter.py
@@ -0,0 +1,351 @@
+"""Tests for error_reporter module."""
+
+from unittest.mock import MagicMock, patch
+
+
+from local_deep_research.error_handling.error_reporter import (
+ ErrorCategory,
+)
+
+
+class TestErrorCategory:
+ """Tests for ErrorCategory enum."""
+
+ def test_has_all_expected_categories(self):
+ """Should have all expected error categories."""
+ expected = [
+ "CONNECTION_ERROR",
+ "MODEL_ERROR",
+ "SEARCH_ERROR",
+ "SYNTHESIS_ERROR",
+ "FILE_ERROR",
+ "RATE_LIMIT_ERROR",
+ "UNKNOWN_ERROR",
+ ]
+ for category in expected:
+ assert hasattr(ErrorCategory, category)
+
+ def test_values_are_strings(self):
+ """Should have string values."""
+ for category in ErrorCategory:
+ assert isinstance(category.value, str)
+
+
+class TestErrorReporterInit:
+ """Tests for ErrorReporter initialization."""
+
+ def test_initializes_error_patterns(self, error_reporter):
+ """Should initialize with error patterns."""
+ assert hasattr(error_reporter, "error_patterns")
+ assert isinstance(error_reporter.error_patterns, dict)
+
+ def test_has_patterns_for_all_categories(self, error_reporter):
+ """Should have patterns for all categories except UNKNOWN."""
+ for category in ErrorCategory:
+ if category != ErrorCategory.UNKNOWN_ERROR:
+ assert category in error_reporter.error_patterns
+
+
+class TestCategorizeError:
+ """Tests for categorize_error method."""
+
+ def test_categorizes_connection_error(self, error_reporter):
+ """Should categorize connection errors."""
+ error_messages = [
+ "POST predict EOF",
+ "Connection refused",
+ "timeout waiting for response",
+ "[Errno 111] Connection refused",
+ ]
+ for msg in error_messages:
+ result = error_reporter.categorize_error(msg)
+ assert result == ErrorCategory.CONNECTION_ERROR
+
+ def test_categorizes_model_error(self, error_reporter):
+ """Should categorize model errors."""
+ error_messages = [
+ "Model not found in Ollama",
+ "Invalid model specified",
+ "API key invalid",
+ "401 API key error",
+ ]
+ for msg in error_messages:
+ result = error_reporter.categorize_error(msg)
+ assert result == ErrorCategory.MODEL_ERROR
+
+ def test_categorizes_rate_limit_error(self, error_reporter):
+ """Should categorize rate limit errors."""
+ error_messages = [
+ "429 resource exhausted",
+ "rate limit exceeded",
+ "quota exceeded",
+ "LLM rate limit reached",
+ ]
+ for msg in error_messages:
+ result = error_reporter.categorize_error(msg)
+ assert result == ErrorCategory.RATE_LIMIT_ERROR
+
+ def test_categorizes_search_error(self, error_reporter):
+ """Should categorize search errors."""
+ error_messages = [
+ "Search failed",
+ "No search results found",
+ "The search is longer than 256 characters",
+ "GitHub API error occurred",
+ ]
+ for msg in error_messages:
+ result = error_reporter.categorize_error(msg)
+ assert result == ErrorCategory.SEARCH_ERROR
+
+ def test_categorizes_synthesis_error(self, error_reporter):
+ """Should categorize synthesis errors."""
+ error_messages = [
+ "Error during synthesis process",
+ "Failed to generate the report",
+ "detailed report stuck at 99%",
+ "report taking too long to complete",
+ ]
+ for msg in error_messages:
+ result = error_reporter.categorize_error(msg)
+ assert result == ErrorCategory.SYNTHESIS_ERROR, (
+ f"'{msg}' should be SYNTHESIS_ERROR"
+ )
+
+ def test_categorizes_file_error(self, error_reporter):
+ """Should categorize file errors."""
+ error_messages = [
+ "Permission denied",
+ "Cannot write to file",
+ "Disk is full",
+ "No module named local_deep_research",
+ ]
+ for msg in error_messages:
+ result = error_reporter.categorize_error(msg)
+ assert result == ErrorCategory.FILE_ERROR, (
+ f"'{msg}' should be FILE_ERROR"
+ )
+
+ def test_returns_unknown_for_unmatched(self, error_reporter):
+ """Should return UNKNOWN_ERROR for unmatched errors."""
+ result = error_reporter.categorize_error("Some random error message")
+ assert result == ErrorCategory.UNKNOWN_ERROR
+
+ def test_case_insensitive_matching(self, error_reporter):
+ """Should match patterns case-insensitively."""
+ result = error_reporter.categorize_error("CONNECTION REFUSED")
+ assert result == ErrorCategory.CONNECTION_ERROR
+
+
+class TestGetUserFriendlyTitle:
+ """Tests for get_user_friendly_title method."""
+
+ def test_returns_title_for_each_category(self, error_reporter):
+ """Should return a title for each category."""
+ for category in ErrorCategory:
+ result = error_reporter.get_user_friendly_title(category)
+ assert isinstance(result, str)
+ assert len(result) > 0
+
+ def test_returns_specific_titles(self, error_reporter):
+ """Should return specific expected titles."""
+ assert (
+ error_reporter.get_user_friendly_title(
+ ErrorCategory.CONNECTION_ERROR
+ )
+ == "Connection Issue"
+ )
+ assert (
+ error_reporter.get_user_friendly_title(ErrorCategory.MODEL_ERROR)
+ == "LLM Service Error"
+ )
+ assert (
+ error_reporter.get_user_friendly_title(
+ ErrorCategory.RATE_LIMIT_ERROR
+ )
+ == "API Rate Limit Exceeded"
+ )
+
+
+class TestGetSuggestedActions:
+ """Tests for get_suggested_actions method."""
+
+ def test_returns_list_for_each_category(self, error_reporter):
+ """Should return a list for each category."""
+ for category in ErrorCategory:
+ result = error_reporter.get_suggested_actions(category)
+ assert isinstance(result, list)
+ assert len(result) > 0
+
+ def test_suggestions_are_strings(self, error_reporter):
+ """Should return list of strings."""
+ for category in ErrorCategory:
+ suggestions = error_reporter.get_suggested_actions(category)
+ for suggestion in suggestions:
+ assert isinstance(suggestion, str)
+
+
+class TestAnalyzeError:
+ """Tests for analyze_error method."""
+
+ def test_returns_dict_with_expected_keys(self, error_reporter):
+ """Should return dict with expected keys."""
+ result = error_reporter.analyze_error("Connection refused")
+ expected_keys = [
+ "category",
+ "title",
+ "original_error",
+ "suggestions",
+ "severity",
+ "recoverable",
+ ]
+ for key in expected_keys:
+ assert key in result
+
+ def test_includes_context_when_provided(self, error_reporter):
+ """Should include context when provided."""
+ context = {"query": "test query", "findings": ["finding1"]}
+ result = error_reporter.analyze_error("Connection refused", context)
+ assert "context" in result
+ assert result["context"] == context
+
+ def test_detects_partial_results(
+ self, error_reporter, sample_partial_results
+ ):
+ """Should detect partial results in context."""
+ result = error_reporter.analyze_error(
+ "Error occurred", sample_partial_results
+ )
+ assert result["has_partial_results"] is True
+
+ def test_no_partial_results_when_empty(self, error_reporter):
+ """Should not have partial results when context is empty."""
+ result = error_reporter.analyze_error("Error occurred", {})
+ assert result.get("has_partial_results", False) is False
+
+
+class TestExtractServiceName:
+ """Tests for _extract_service_name method."""
+
+ def test_extracts_openai(self, error_reporter):
+ """Should extract OpenAI service name."""
+ result = error_reporter._extract_service_name(
+ "OpenAI API returned error"
+ )
+ assert result == "Openai"
+
+ def test_extracts_anthropic(self, error_reporter):
+ """Should extract Anthropic service name."""
+ result = error_reporter._extract_service_name("Anthropic rate limit")
+ assert result == "Anthropic"
+
+ def test_extracts_ollama(self, error_reporter):
+ """Should extract Ollama service name."""
+ result = error_reporter._extract_service_name(
+ "Ollama connection failed"
+ )
+ assert result == "Ollama"
+
+ def test_returns_default_for_unknown(self, error_reporter):
+ """Should return default for unknown service."""
+ result = error_reporter._extract_service_name("Unknown error")
+ assert result == "API Service"
+
+
+class TestDetermineSeverity:
+ """Tests for _determine_severity method."""
+
+ def test_connection_error_is_high(self, error_reporter):
+ """Should return high for connection errors."""
+ result = error_reporter._determine_severity(
+ ErrorCategory.CONNECTION_ERROR
+ )
+ assert result == "high"
+
+ def test_model_error_is_high(self, error_reporter):
+ """Should return high for model errors."""
+ result = error_reporter._determine_severity(ErrorCategory.MODEL_ERROR)
+ assert result == "high"
+
+ def test_synthesis_error_is_low(self, error_reporter):
+ """Should return low for synthesis errors."""
+ result = error_reporter._determine_severity(
+ ErrorCategory.SYNTHESIS_ERROR
+ )
+ assert result == "low"
+
+ def test_rate_limit_is_medium(self, error_reporter):
+ """Should return medium for rate limit errors."""
+ result = error_reporter._determine_severity(
+ ErrorCategory.RATE_LIMIT_ERROR
+ )
+ assert result == "medium"
+
+
+class TestIsRecoverable:
+ """Tests for _is_recoverable method."""
+
+ def test_unknown_error_not_recoverable(self, error_reporter):
+ """Should return False for unknown errors."""
+ result = error_reporter._is_recoverable(ErrorCategory.UNKNOWN_ERROR)
+ assert result is False
+
+ def test_connection_error_recoverable(self, error_reporter):
+ """Should return True for connection errors."""
+ result = error_reporter._is_recoverable(ErrorCategory.CONNECTION_ERROR)
+ assert result is True
+
+ def test_rate_limit_recoverable(self, error_reporter):
+ """Should return True for rate limit errors."""
+ result = error_reporter._is_recoverable(ErrorCategory.RATE_LIMIT_ERROR)
+ assert result is True
+
+
+class TestSendErrorNotifications:
+ """Tests for _send_error_notifications method."""
+
+ def test_skips_when_no_username(self, error_reporter):
+ """Should skip notification when no username in context."""
+ # Should not raise, just skip
+ error_reporter._send_error_notifications(
+ ErrorCategory.MODEL_ERROR, "API key invalid", {}
+ )
+
+ def test_skips_non_notifiable_categories(self, error_reporter):
+ """Should skip notification for non-notifiable categories."""
+ context = {"username": "testuser"}
+ # Should not raise, just skip
+ error_reporter._send_error_notifications(
+ ErrorCategory.SEARCH_ERROR, "Search failed", context
+ )
+
+ def test_sends_auth_notification_for_auth_errors(
+ self, error_reporter, mock_context_with_username
+ ):
+ """Should send auth notification for auth errors."""
+ # Patch at source locations since these are imported inside the method
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_session:
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = MagicMock(return_value=MagicMock())
+ mock_cm.__exit__ = MagicMock(return_value=None)
+ mock_session.return_value = mock_cm
+
+ with patch(
+ "local_deep_research.settings.SettingsManager"
+ ) as mock_settings:
+ mock_settings.return_value.get_settings_snapshot.return_value = {}
+
+ with patch(
+ "local_deep_research.notifications.manager.NotificationManager"
+ ) as mock_nm:
+ mock_nm_instance = MagicMock()
+ mock_nm.return_value = mock_nm_instance
+
+ error_reporter._send_error_notifications(
+ ErrorCategory.MODEL_ERROR,
+ "401 API key error",
+ mock_context_with_username,
+ )
+
+ mock_nm_instance.send_notification.assert_called_once()
diff --git a/tests/error_handling/test_report_generator.py b/tests/error_handling/test_report_generator.py
new file mode 100644
index 0000000000..1e57b6444a
--- /dev/null
+++ b/tests/error_handling/test_report_generator.py
@@ -0,0 +1,407 @@
+"""Tests for report_generator module."""
+
+from unittest.mock import MagicMock
+
+
+from local_deep_research.error_handling.report_generator import (
+ ErrorReportGenerator,
+)
+from local_deep_research.error_handling.error_reporter import ErrorCategory
+
+
+class TestErrorReportGeneratorInit:
+ """Tests for ErrorReportGenerator initialization."""
+
+ def test_initializes_error_reporter(self, error_report_generator):
+ """Should initialize with ErrorReporter."""
+ assert hasattr(error_report_generator, "error_reporter")
+ assert error_report_generator.error_reporter is not None
+
+ def test_accepts_optional_llm(self):
+ """Should accept optional LLM (kept for compatibility)."""
+ mock_llm = MagicMock()
+ generator = ErrorReportGenerator(llm=mock_llm)
+ # LLM is not used, just accepted
+ assert generator is not None
+
+
+class TestGenerateErrorReport:
+ """Tests for generate_error_report method."""
+
+ def test_returns_markdown_string(self, error_report_generator):
+ """Should return markdown string."""
+ result = error_report_generator.generate_error_report(
+ "Connection refused", "test query"
+ )
+ assert isinstance(result, str)
+ assert "#" in result # Has markdown headers
+
+ def test_includes_error_type(self, error_report_generator):
+ """Should include error type in report."""
+ result = error_report_generator.generate_error_report(
+ "Connection refused", "test query"
+ )
+ assert "Error Type:" in result
+
+ def test_includes_what_happened(self, error_report_generator):
+ """Should include what happened section."""
+ result = error_report_generator.generate_error_report(
+ "Connection refused", "test query"
+ )
+ assert "What happened:" in result
+
+ def test_includes_help_links(self, error_report_generator):
+ """Should include help links."""
+ result = error_report_generator.generate_error_report(
+ "Connection refused", "test query"
+ )
+ assert "Get Help" in result
+ assert "Wiki" in result
+ assert "Discord" in result
+ assert "GitHub Issues" in result
+
+ def test_includes_partial_results_when_available(
+ self, error_report_generator, sample_partial_results
+ ):
+ """Should include partial results when available."""
+ result = error_report_generator.generate_error_report(
+ "Connection refused",
+ "test query",
+ partial_results=sample_partial_results,
+ )
+ assert "Partial Results" in result
+
+ def test_handles_no_partial_results(self, error_report_generator):
+ """Should handle no partial results gracefully."""
+ result = error_report_generator.generate_error_report(
+ "Connection refused", "test query", partial_results=None
+ )
+ assert isinstance(result, str)
+ # Should not include partial results section
+ assert "Partial Results" not in result
+
+ def test_includes_research_id_when_provided(self, error_report_generator):
+ """Should accept research_id parameter."""
+ result = error_report_generator.generate_error_report(
+ "Error", "query", research_id="test-uuid"
+ )
+ assert isinstance(result, str)
+
+ def test_includes_search_iterations_when_provided(
+ self, error_report_generator
+ ):
+ """Should accept search_iterations parameter."""
+ result = error_report_generator.generate_error_report(
+ "Error", "query", search_iterations=5
+ )
+ assert isinstance(result, str)
+
+ def test_fallback_on_exception(self, error_report_generator):
+ """Should return fallback report on exception."""
+ # Mock error_reporter to raise exception
+ error_report_generator.error_reporter.analyze_error = MagicMock(
+ side_effect=Exception("test error")
+ )
+ result = error_report_generator.generate_error_report("Error", "query")
+ assert "Research Failed" in result
+ assert "Error report generation failed" in result
+
+
+class TestFormatPartialResults:
+ """Tests for _format_partial_results method."""
+
+ def test_returns_empty_for_none(self, error_report_generator):
+ """Should return empty string for None."""
+ result = error_report_generator._format_partial_results(None)
+ assert result == ""
+
+ def test_returns_empty_for_empty_dict(self, error_report_generator):
+ """Should return empty string for empty dict."""
+ result = error_report_generator._format_partial_results({})
+ assert result == ""
+
+ def test_formats_current_knowledge(self, error_report_generator):
+ """Should format current_knowledge section."""
+ partial = {"current_knowledge": "This is knowledge content " * 10}
+ result = error_report_generator._format_partial_results(partial)
+ assert "Research Summary" in result
+
+ def test_truncates_long_knowledge(self, error_report_generator):
+ """Should truncate knowledge over 1000 chars."""
+ long_content = "x" * 1500
+ partial = {"current_knowledge": long_content}
+ result = error_report_generator._format_partial_results(partial)
+ assert "..." in result
+
+ def test_skips_short_knowledge(self, error_report_generator):
+ """Should skip knowledge under 50 chars."""
+ partial = {"current_knowledge": "short"}
+ result = error_report_generator._format_partial_results(partial)
+ assert "Research Summary" not in result
+
+ def test_formats_search_results(self, error_report_generator):
+ """Should format search_results section."""
+ partial = {
+ "search_results": [
+ {"title": "Result 1", "url": "https://example.com/1"},
+ {"title": "Result 2", "url": "https://example.com/2"},
+ ]
+ }
+ result = error_report_generator._format_partial_results(partial)
+ assert "Search Results Found" in result
+ assert "Result 1" in result
+ assert "https://example.com/1" in result
+
+ def test_limits_search_results_to_five(self, error_report_generator):
+ """Should show only top 5 search results."""
+ partial = {
+ "search_results": [
+ {"title": f"Result {i}", "url": f"https://example.com/{i}"}
+ for i in range(10)
+ ]
+ }
+ result = error_report_generator._format_partial_results(partial)
+ # Results are 0-indexed, so 5 results means indices 0-4
+ assert "Result 4" in result
+ assert "Result 5" not in result
+
+ def test_formats_findings(self, error_report_generator):
+ """Should format findings section."""
+ partial = {
+ "findings": [
+ {"phase": "Phase 1", "content": "Finding content 1"},
+ {"phase": "Phase 2", "content": "Finding content 2"},
+ ]
+ }
+ result = error_report_generator._format_partial_results(partial)
+ assert "Research Findings" in result
+ assert "Phase 1" in result
+
+ def test_skips_error_findings(self, error_report_generator):
+ """Should skip findings that start with Error:."""
+ partial = {
+ "findings": [
+ {"phase": "Phase 1", "content": "Error: Something went wrong"},
+ {"phase": "Phase 2", "content": "Valid finding"},
+ ]
+ }
+ result = error_report_generator._format_partial_results(partial)
+ assert "Valid finding" in result
+ # Error finding should be skipped
+
+ def test_limits_findings_to_three(self, error_report_generator):
+ """Should show only top 3 findings."""
+ partial = {
+ "findings": [
+ {"phase": f"Phase {i}", "content": f"Finding {i}"}
+ for i in range(5)
+ ]
+ }
+ result = error_report_generator._format_partial_results(partial)
+ assert "Phase 2" in result
+ assert "Phase 4" not in result
+
+ def test_truncates_long_finding_content(self, error_report_generator):
+ """Should truncate finding content over 500 chars."""
+ partial = {"findings": [{"phase": "Phase 1", "content": "x" * 600}]}
+ result = error_report_generator._format_partial_results(partial)
+ assert "..." in result
+
+ def test_includes_note_when_results_exist(self, error_report_generator):
+ """Should include note about successful collection."""
+ partial = {
+ "search_results": [
+ {"title": "Result", "url": "https://example.com"}
+ ]
+ }
+ result = error_report_generator._format_partial_results(partial)
+ assert "successfully collected" in result
+
+
+class TestGenerateQuickErrorSummary:
+ """Tests for generate_quick_error_summary method."""
+
+ def test_returns_dict(self, error_report_generator):
+ """Should return dictionary."""
+ result = error_report_generator.generate_quick_error_summary(
+ "Connection refused"
+ )
+ assert isinstance(result, dict)
+
+ def test_has_expected_keys(self, error_report_generator):
+ """Should have expected keys."""
+ result = error_report_generator.generate_quick_error_summary(
+ "Connection refused"
+ )
+ expected_keys = ["title", "category", "severity", "recoverable"]
+ for key in expected_keys:
+ assert key in result
+
+ def test_category_is_string_value(self, error_report_generator):
+ """Should return category as string value."""
+ result = error_report_generator.generate_quick_error_summary(
+ "Connection refused"
+ )
+ assert isinstance(result["category"], str)
+
+ def test_recoverable_is_boolean(self, error_report_generator):
+ """Should return recoverable as boolean."""
+ result = error_report_generator.generate_quick_error_summary(
+ "Connection refused"
+ )
+ assert isinstance(result["recoverable"], bool)
+
+
+class TestMakeErrorUserFriendly:
+ """Tests for _make_error_user_friendly method."""
+
+ def test_replaces_max_workers_error(self, error_report_generator):
+ """Should replace max_workers error with friendly message."""
+ result = error_report_generator._make_error_user_friendly(
+ "max_workers must be greater than 0"
+ )
+ assert "LLM failed to generate" in result
+ assert "Try this:" in result
+
+ def test_replaces_ollama_eof_error(self, error_report_generator):
+ """Should replace Ollama EOF error with friendly message."""
+ result = error_report_generator._make_error_user_friendly(
+ "POST predict encountered EOF"
+ )
+ assert "Lost connection to Ollama" in result
+
+ def test_replaces_connection_refused(self, error_report_generator):
+ """Should replace connection refused with friendly message."""
+ result = error_report_generator._make_error_user_friendly(
+ "Connection refused"
+ )
+ assert "Cannot connect to the LLM service" in result
+
+ def test_replaces_search_too_long(self, error_report_generator):
+ """Should replace search too long error."""
+ result = error_report_generator._make_error_user_friendly(
+ "The search is longer than 256 characters"
+ )
+ assert "search query is too long" in result
+
+ def test_replaces_model_not_found(self, error_report_generator):
+ """Should replace model not found error."""
+ result = error_report_generator._make_error_user_friendly(
+ "Model gemma not found in Ollama"
+ )
+ assert "model isn't available in Ollama" in result
+
+ def test_replaces_api_key_error(self, error_report_generator):
+ """Should replace API key errors."""
+ result = error_report_generator._make_error_user_friendly(
+ "No auth credentials found"
+ )
+ assert "API key is missing" in result
+
+ def test_replaces_readonly_database(self, error_report_generator):
+ """Should replace readonly database error."""
+ result = error_report_generator._make_error_user_friendly(
+ "Attempt to write readonly database"
+ )
+ assert "Permission issue" in result
+
+ def test_replaces_docker_networking(self, error_report_generator):
+ """Should replace Docker networking errors."""
+ # Pattern requires "host.*localhost.*Docker" or similar
+ result = error_report_generator._make_error_user_friendly(
+ "Cannot connect to host at localhost via Docker"
+ )
+ # Should match docker pattern and suggest using host.docker.internal
+ assert "Docker" in result or "host.docker.internal" in result
+
+ def test_returns_original_for_unknown(self, error_report_generator):
+ """Should return original message for unknown errors."""
+ original = "Some random error that has no pattern"
+ result = error_report_generator._make_error_user_friendly(original)
+ assert result == original
+
+ def test_includes_technical_error_in_replacement(
+ self, error_report_generator
+ ):
+ """Should include technical error in replaced message."""
+ result = error_report_generator._make_error_user_friendly(
+ "max_workers must be greater than 0"
+ )
+ assert "Technical error:" in result
+ assert "max_workers" in result
+
+ def test_case_insensitive_matching(self, error_report_generator):
+ """Should match patterns case-insensitively."""
+ result = error_report_generator._make_error_user_friendly(
+ "CONNECTION REFUSED"
+ )
+ assert "Cannot connect" in result
+
+
+class TestGetTechnicalContext:
+ """Tests for _get_technical_context method."""
+
+ def test_returns_empty_for_no_context(self, error_report_generator):
+ """Should return empty string for no context."""
+ error_analysis = {"category": ErrorCategory.CONNECTION_ERROR}
+ result = error_report_generator._get_technical_context(
+ error_analysis, None
+ )
+ # May still have category-based context
+ assert isinstance(result, str)
+
+ def test_includes_timing_info(self, error_report_generator):
+ """Should include timing info when available."""
+ error_analysis = {"category": ErrorCategory.CONNECTION_ERROR}
+ partial = {
+ "start_time": "2024-01-01T10:00:00",
+ "last_activity": "2024-01-01T10:05:00",
+ }
+ result = error_report_generator._get_technical_context(
+ error_analysis, partial
+ )
+ assert "Start Time:" in result
+
+ def test_includes_model_info(self, error_report_generator):
+ """Should include model info when available."""
+ error_analysis = {"category": ErrorCategory.MODEL_ERROR}
+ partial = {
+ "model_config": {"model_name": "gpt-4", "provider": "openai"}
+ }
+ result = error_report_generator._get_technical_context(
+ error_analysis, partial
+ )
+ assert "Model:" in result
+
+ def test_includes_search_info(self, error_report_generator):
+ """Should include search info when available."""
+ error_analysis = {"category": ErrorCategory.SEARCH_ERROR}
+ partial = {"search_config": {"engine": "duckduckgo", "max_results": 10}}
+ result = error_report_generator._get_technical_context(
+ error_analysis, partial
+ )
+ assert "Search Engine:" in result
+
+ def test_includes_error_codes(self, error_report_generator):
+ """Should include error codes when available."""
+ error_analysis = {"category": ErrorCategory.CONNECTION_ERROR}
+ partial = {"status_code": 503, "error_code": "SERVICE_UNAVAILABLE"}
+ result = error_report_generator._get_technical_context(
+ error_analysis, partial
+ )
+ assert "Status Code:" in result
+ assert "Error Code:" in result
+
+ def test_adds_category_specific_context(self, error_report_generator):
+ """Should add category-specific context."""
+ error_analysis = {"category": ErrorCategory.CONNECTION_ERROR}
+ result = error_report_generator._get_technical_context(
+ error_analysis, {}
+ )
+ assert "Network Error:" in result
+
+ error_analysis = {"category": ErrorCategory.MODEL_ERROR}
+ result = error_report_generator._get_technical_context(
+ error_analysis, {}
+ )
+ assert "Model Error:" in result
diff --git a/tests/storage/__init__.py b/tests/storage/__init__.py
new file mode 100644
index 0000000000..9785e360b3
--- /dev/null
+++ b/tests/storage/__init__.py
@@ -0,0 +1 @@
+"""Tests for storage module."""
diff --git a/tests/storage/conftest.py b/tests/storage/conftest.py
new file mode 100644
index 0000000000..dd8753e29e
--- /dev/null
+++ b/tests/storage/conftest.py
@@ -0,0 +1,54 @@
+"""Fixtures for storage module tests."""
+
+import pytest
+from unittest.mock import MagicMock
+
+
+def mock_session():
+ """Mock SQLAlchemy session."""
+ session = MagicMock()
+ return session
+
+
+def mock_research_history():
+ """Mock ResearchHistory model instance."""
+ record = MagicMock()
+ record.id = "test-uuid-123"
+ record.report_content = "# Test Report\n\nThis is a test report."
+ record.research_meta = {"key": "value"}
+ record.query = "test query"
+ record.mode = "detailed"
+ record.created_at = "2024-01-01T10:00:00"
+ record.completed_at = "2024-01-01T10:30:00"
+ record.duration_seconds = 1800
+ return record
+
+
+def sample_report_content():
+ """Sample report content for testing."""
+ return """# Research Report
+
+## Summary
+This is a test research report.
+
+## Findings
+1. Finding one
+2. Finding two
+
+## Conclusion
+Test conclusion.
+"""
+
+
+def sample_metadata():
+ """Sample metadata for testing."""
+ return {
+ "query": "test query",
+ "mode": "detailed",
+ "sources_count": 5,
+ "timestamp": "2024-01-01T10:00:00",
+ }
diff --git a/tests/storage/test_composite_storage.py b/tests/storage/test_composite_storage.py
new file mode 100644
index 0000000000..e0a07906a5
--- /dev/null
+++ b/tests/storage/test_composite_storage.py
@@ -0,0 +1,222 @@
+"""Tests for composite database with file backup storage."""
+
+from unittest.mock import MagicMock, patch
+
+
+from local_deep_research.storage.database_with_file_backup import (
+ DatabaseWithFileBackupStorage,
+)
+
+
+class TestDatabaseWithFileBackupStorageInit:
+ """Tests for DatabaseWithFileBackupStorage initialization."""
+
+ def test_creates_db_storage(self, mock_session):
+ """Should create database storage."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ assert storage.db_storage is not None
+
+ def test_file_storage_disabled_by_default(self, mock_session):
+ """Should not create file storage by default."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ assert storage.file_storage is None
+ assert storage.enable_file_storage is False
+
+ def test_creates_file_storage_when_enabled(self, mock_session):
+ """Should create file storage when enabled."""
+ with patch(
+ "local_deep_research.storage.database_with_file_backup.FileReportStorage"
+ ):
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ assert storage.enable_file_storage is True
+
+
+class TestSaveReport:
+ """Tests for save_report method."""
+
+ def test_saves_to_database(self, mock_session, sample_report_content):
+ """Should save to database."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = True
+
+ result = storage.save_report("test-uuid", sample_report_content)
+
+ assert result is True
+ storage.db_storage.save_report.assert_called_once()
+
+ def test_returns_false_when_db_fails(
+ self, mock_session, sample_report_content
+ ):
+ """Should return False when database save fails."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = False
+
+ result = storage.save_report("test-uuid", sample_report_content)
+
+ assert result is False
+
+ def test_saves_to_file_when_enabled(
+ self, mock_session, sample_report_content
+ ):
+ """Should save to file when file storage enabled."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = True
+ storage.file_storage = MagicMock()
+ storage.file_storage.save_report.return_value = True
+
+ result = storage.save_report("test-uuid", sample_report_content)
+
+ assert result is True
+ storage.file_storage.save_report.assert_called_once()
+
+ def test_succeeds_even_if_file_fails(
+ self, mock_session, sample_report_content
+ ):
+ """Should succeed even if file save fails."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = True
+ storage.file_storage = MagicMock()
+ storage.file_storage.save_report.return_value = False
+
+ result = storage.save_report("test-uuid", sample_report_content)
+
+ assert result is True # Still success because DB succeeded
+
+ def test_handles_file_exception(self, mock_session, sample_report_content):
+ """Should handle file storage exception gracefully."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = True
+ storage.file_storage = MagicMock()
+ storage.file_storage.save_report.side_effect = Exception("file error")
+
+ result = storage.save_report("test-uuid", sample_report_content)
+
+ assert result is True # Still success because DB succeeded
+
+
+class TestGetReport:
+ """Tests for get_report method."""
+
+ def test_gets_from_database(self, mock_session, sample_report_content):
+ """Should get from database."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.get_report.return_value = sample_report_content
+
+ result = storage.get_report("test-uuid")
+
+ assert result == sample_report_content
+ storage.db_storage.get_report.assert_called_once()
+
+ def test_never_reads_from_file(self, mock_session, sample_report_content):
+ """Should never read from file, only database."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.get_report.return_value = sample_report_content
+ storage.file_storage = MagicMock()
+
+ storage.get_report("test-uuid")
+
+ storage.file_storage.get_report.assert_not_called()
+
+
+class TestDeleteReport:
+ """Tests for delete_report method."""
+
+ def test_deletes_from_database(self, mock_session):
+ """Should delete from database."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.delete_report.return_value = True
+
+ result = storage.delete_report("test-uuid")
+
+ assert result is True
+ storage.db_storage.delete_report.assert_called_once()
+
+ def test_deletes_from_file_when_enabled(self, mock_session):
+ """Should delete from file when file storage enabled."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.delete_report.return_value = True
+ storage.file_storage = MagicMock()
+
+ storage.delete_report("test-uuid")
+
+ storage.file_storage.delete_report.assert_called_once()
+
+ def test_skips_file_delete_when_db_fails(self, mock_session):
+ """Should skip file delete when database delete fails."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.delete_report.return_value = False
+ storage.file_storage = MagicMock()
+
+ storage.delete_report("test-uuid")
+
+ storage.file_storage.delete_report.assert_not_called()
+
+ def test_handles_file_delete_exception(self, mock_session):
+ """Should handle file delete exception gracefully."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.delete_report.return_value = True
+ storage.file_storage = MagicMock()
+ storage.file_storage.delete_report.side_effect = Exception(
+ "delete error"
+ )
+
+ result = storage.delete_report("test-uuid")
+
+ assert result is True # Still returns db result
+
+
+class TestGetReportWithMetadata:
+ """Tests for get_report_with_metadata method."""
+
+ def test_gets_from_database(self, mock_session):
+ """Should get from database."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ expected = {"content": "test", "metadata": {}}
+ storage.db_storage.get_report_with_metadata.return_value = expected
+
+ result = storage.get_report_with_metadata("test-uuid")
+
+ assert result == expected
+
+
+class TestReportExists:
+ """Tests for report_exists method."""
+
+ def test_checks_database(self, mock_session):
+ """Should check database."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.report_exists.return_value = True
+
+ result = storage.report_exists("test-uuid")
+
+ assert result is True
+ storage.db_storage.report_exists.assert_called_once()
diff --git a/tests/storage/test_database_storage.py b/tests/storage/test_database_storage.py
new file mode 100644
index 0000000000..815fc42f19
--- /dev/null
+++ b/tests/storage/test_database_storage.py
@@ -0,0 +1,268 @@
+"""Tests for database storage implementation."""
+
+from local_deep_research.storage.database import DatabaseReportStorage
+
+
+class TestDatabaseReportStorageInit:
+ """Tests for DatabaseReportStorage initialization."""
+
+ def test_stores_session(self, mock_session):
+ """Should store provided session."""
+ storage = DatabaseReportStorage(mock_session)
+ assert storage.session is mock_session
+
+
+class TestSaveReport:
+ """Tests for save_report method."""
+
+ def test_saves_content_to_existing_record(
+ self, mock_session, mock_research_history, sample_report_content
+ ):
+ """Should save content to existing research record."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.save_report("test-uuid", sample_report_content)
+
+ assert result is True
+ assert mock_research_history.report_content == sample_report_content
+ mock_session.commit.assert_called_once()
+
+ def test_updates_metadata_when_provided(
+ self,
+ mock_session,
+ mock_research_history,
+ sample_report_content,
+ sample_metadata,
+ ):
+ """Should update metadata when provided."""
+ mock_research_history.research_meta = {"existing": "value"}
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ storage.save_report(
+ "test-uuid", sample_report_content, metadata=sample_metadata
+ )
+
+ # Should merge metadata
+ assert "existing" in mock_research_history.research_meta
+ assert "query" in mock_research_history.research_meta
+
+ def test_sets_metadata_when_none_exists(
+ self,
+ mock_session,
+ mock_research_history,
+ sample_report_content,
+ sample_metadata,
+ ):
+ """Should set metadata when none exists."""
+ mock_research_history.research_meta = None
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ storage.save_report(
+ "test-uuid", sample_report_content, metadata=sample_metadata
+ )
+
+ assert mock_research_history.research_meta == sample_metadata
+
+ def test_returns_false_when_record_not_found(
+ self, mock_session, sample_report_content
+ ):
+ """Should return False when research record not found."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.save_report("nonexistent", sample_report_content)
+
+ assert result is False
+
+ def test_returns_false_on_error(
+ self, mock_session, mock_research_history, sample_report_content
+ ):
+ """Should return False on error and rollback."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+ mock_session.commit.side_effect = Exception("commit error")
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.save_report("test-uuid", sample_report_content)
+
+ assert result is False
+ mock_session.rollback.assert_called_once()
+
+
+class TestGetReport:
+ """Tests for get_report method."""
+
+ def test_returns_content_when_exists(
+ self, mock_session, mock_research_history
+ ):
+ """Should return report content when exists."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.get_report("test-uuid")
+
+ assert result == mock_research_history.report_content
+
+ def test_returns_none_when_not_found(self, mock_session):
+ """Should return None when record not found."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.get_report("nonexistent")
+
+ assert result is None
+
+ def test_returns_none_when_content_is_none(
+ self, mock_session, mock_research_history
+ ):
+ """Should return None when report_content is None."""
+ mock_research_history.report_content = None
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.get_report("test-uuid")
+
+ assert result is None
+
+ def test_returns_none_on_error(self, mock_session):
+ """Should return None on error."""
+ mock_session.query.side_effect = Exception("query error")
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.get_report("test-uuid")
+
+ assert result is None
+
+
+class TestGetReportWithMetadata:
+ """Tests for get_report_with_metadata method."""
+
+ def test_returns_full_record(self, mock_session, mock_research_history):
+ """Should return full record with metadata."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.get_report_with_metadata("test-uuid")
+
+ assert result["content"] == mock_research_history.report_content
+ assert result["metadata"] == mock_research_history.research_meta
+ assert result["query"] == mock_research_history.query
+ assert result["mode"] == mock_research_history.mode
+ assert "created_at" in result
+ assert "completed_at" in result
+ assert "duration_seconds" in result
+
+ def test_returns_empty_metadata_when_none(
+ self, mock_session, mock_research_history
+ ):
+ """Should return empty dict when research_meta is None."""
+ mock_research_history.research_meta = None
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.get_report_with_metadata("test-uuid")
+
+ assert result["metadata"] == {}
+
+ def test_returns_none_when_not_found(self, mock_session):
+ """Should return None when not found."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.get_report_with_metadata("nonexistent")
+
+ assert result is None
+
+ def test_returns_none_when_no_content(
+ self, mock_session, mock_research_history
+ ):
+ """Should return None when report_content is None."""
+ mock_research_history.report_content = None
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.get_report_with_metadata("test-uuid")
+
+ assert result is None
+
+
+class TestDeleteReport:
+ """Tests for delete_report method."""
+
+ def test_sets_content_to_none(self, mock_session, mock_research_history):
+ """Should set report_content to None."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.delete_report("test-uuid")
+
+ assert result is True
+ assert mock_research_history.report_content is None
+ mock_session.commit.assert_called_once()
+
+ def test_returns_false_when_not_found(self, mock_session):
+ """Should return False when not found."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.delete_report("nonexistent")
+
+ assert result is False
+
+ def test_returns_false_on_error(self, mock_session, mock_research_history):
+ """Should return False on error and rollback."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+ mock_session.commit.side_effect = Exception("commit error")
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.delete_report("test-uuid")
+
+ assert result is False
+ mock_session.rollback.assert_called_once()
+
+
+class TestReportExists:
+ """Tests for report_exists method."""
+
+ def test_returns_true_when_content_exists(
+ self, mock_session, mock_research_history
+ ):
+ """Should return True when report content exists."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.report_exists("test-uuid")
+
+ assert result is True
+
+ def test_returns_false_when_not_found(self, mock_session):
+ """Should return False when not found."""
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.report_exists("nonexistent")
+
+ assert result is False
+
+ def test_returns_false_when_content_is_none(
+ self, mock_session, mock_research_history
+ ):
+ """Should return False when report_content is None."""
+ mock_research_history.report_content = None
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research_history
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.report_exists("test-uuid")
+
+ assert result is False
+
+ def test_returns_false_on_error(self, mock_session):
+ """Should return False on error."""
+ mock_session.query.side_effect = Exception("query error")
+
+ storage = DatabaseReportStorage(mock_session)
+ result = storage.report_exists("test-uuid")
+
+ assert result is False
diff --git a/tests/storage/test_factory.py b/tests/storage/test_factory.py
new file mode 100644
index 0000000000..2159d5eaa8
--- /dev/null
+++ b/tests/storage/test_factory.py
@@ -0,0 +1,134 @@
+"""Tests for storage factory."""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.storage.factory import (
+ get_report_storage,
+ get_request_report_storage,
+ set_request_report_storage,
+ clear_request_report_storage,
+)
+from local_deep_research.storage.database_with_file_backup import (
+ DatabaseWithFileBackupStorage,
+)
+from local_deep_research.config.thread_settings import NoSettingsContextError
+
+
+class TestGetReportStorage:
+ """Tests for get_report_storage factory function."""
+
+ def test_raises_when_session_is_none(self):
+ """Should raise ValueError when session is None."""
+ with pytest.raises(ValueError, match="Database session is required"):
+ get_report_storage(session=None)
+
+ def test_returns_database_with_file_backup_storage(self, mock_session):
+ """Should return DatabaseWithFileBackupStorage instance."""
+ with patch(
+ "local_deep_research.storage.factory.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.return_value = False
+ storage = get_report_storage(session=mock_session)
+
+ assert isinstance(storage, DatabaseWithFileBackupStorage)
+
+ def test_uses_provided_enable_file_backup_true(self, mock_session):
+ """Should use enable_file_backup=True when explicitly provided."""
+ storage = get_report_storage(
+ session=mock_session, enable_file_backup=True
+ )
+
+ assert storage.enable_file_storage is True
+
+ def test_uses_provided_enable_file_backup_false(self, mock_session):
+ """Should use enable_file_backup=False when explicitly provided."""
+ storage = get_report_storage(
+ session=mock_session, enable_file_backup=False
+ )
+
+ assert storage.enable_file_storage is False
+
+ def test_reads_setting_when_enable_file_backup_is_none(self, mock_session):
+ """Should read from settings when enable_file_backup not provided."""
+ with patch(
+ "local_deep_research.storage.factory.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.return_value = True
+ storage = get_report_storage(session=mock_session)
+
+ mock_get.assert_called_once_with(
+ "report.enable_file_backup",
+ settings_snapshot=None,
+ )
+ assert storage.enable_file_storage is True
+
+ def test_passes_settings_snapshot_to_get_setting(self, mock_session):
+ """Should pass settings_snapshot to get_setting_from_snapshot."""
+ snapshot = {"report": {"enable_file_backup": True}}
+
+ with patch(
+ "local_deep_research.storage.factory.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.return_value = True
+ get_report_storage(session=mock_session, settings_snapshot=snapshot)
+
+ mock_get.assert_called_once_with(
+ "report.enable_file_backup",
+ settings_snapshot=snapshot,
+ )
+
+ def test_defaults_to_false_when_no_settings_context(self, mock_session):
+ """Should default to False when NoSettingsContextError raised."""
+ with patch(
+ "local_deep_research.storage.factory.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.side_effect = NoSettingsContextError("No context")
+ storage = get_report_storage(session=mock_session)
+
+ assert storage.enable_file_storage is False
+
+
+class TestRequestStorageHelpers:
+ """Tests for request context storage helpers."""
+
+ def test_get_returns_none_initially(self):
+ """Should return None when no storage set."""
+ clear_request_report_storage() # Ensure clean state
+ result = get_request_report_storage()
+ assert result is None
+
+ def test_set_and_get(self, mock_session):
+ """Should store and retrieve storage instance."""
+ storage = MagicMock()
+
+ try:
+ set_request_report_storage(storage)
+ result = get_request_report_storage()
+ assert result is storage
+ finally:
+ clear_request_report_storage()
+
+ def test_clear_removes_storage(self, mock_session):
+ """Should remove storage instance."""
+ storage = MagicMock()
+
+ set_request_report_storage(storage)
+ clear_request_report_storage()
+ result = get_request_report_storage()
+
+ assert result is None
+
+ def test_set_overwrites_previous(self, mock_session):
+ """Should overwrite previous storage instance."""
+ storage1 = MagicMock()
+ storage2 = MagicMock()
+
+ try:
+ set_request_report_storage(storage1)
+ set_request_report_storage(storage2)
+ result = get_request_report_storage()
+ assert result is storage2
+ finally:
+ clear_request_report_storage()
diff --git a/tests/storage/test_file_storage.py b/tests/storage/test_file_storage.py
new file mode 100644
index 0000000000..aa4ddeabb9
--- /dev/null
+++ b/tests/storage/test_file_storage.py
@@ -0,0 +1,283 @@
+"""Tests for file storage implementation."""
+
+import json
+from pathlib import Path
+from unittest.mock import patch
+
+
+from local_deep_research.storage.file import FileReportStorage
+
+
+class TestFileReportStorageInit:
+ """Tests for FileReportStorage initialization."""
+
+ def test_uses_default_directory_when_none(self, tmp_path):
+ """Should use default research outputs directory when none provided."""
+ with patch(
+ "local_deep_research.storage.file.get_research_outputs_directory",
+ return_value=tmp_path,
+ ):
+ storage = FileReportStorage()
+ assert storage.base_dir == tmp_path
+
+ def test_uses_provided_directory(self, tmp_path):
+ """Should use provided directory."""
+ custom_dir = tmp_path / "custom"
+ storage = FileReportStorage(base_dir=custom_dir)
+ assert storage.base_dir == custom_dir
+
+ def test_creates_directory_if_not_exists(self, tmp_path):
+ """Should create directory if it doesn't exist."""
+ new_dir = tmp_path / "new_reports"
+ storage = FileReportStorage(base_dir=new_dir)
+ assert storage.base_dir.exists()
+
+
+class TestGetReportPath:
+ """Tests for _get_report_path method."""
+
+ def test_returns_md_file_path(self, tmp_path):
+ """Should return path with .md extension."""
+ storage = FileReportStorage(base_dir=tmp_path)
+ path = storage._get_report_path("test-uuid")
+ assert path == tmp_path / "test-uuid.md"
+
+ def test_returns_path_object(self, tmp_path):
+ """Should return Path object."""
+ storage = FileReportStorage(base_dir=tmp_path)
+ path = storage._get_report_path("test-uuid")
+ assert isinstance(path, Path)
+
+
+class TestGetMetadataPath:
+ """Tests for _get_metadata_path method."""
+
+ def test_returns_metadata_json_path(self, tmp_path):
+ """Should return path with _metadata.json suffix."""
+ storage = FileReportStorage(base_dir=tmp_path)
+ path = storage._get_metadata_path("test-uuid")
+ assert path == tmp_path / "test-uuid_metadata.json"
+
+
+class TestSaveReport:
+ """Tests for save_report method."""
+
+ def test_saves_report_content(self, tmp_path, sample_report_content):
+ """Should save report content to file."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ # Patch at source location since it's imported inside the method
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ) as mock_write:
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ ):
+ result = storage.save_report("test-uuid", sample_report_content)
+
+ assert result is True
+ mock_write.assert_called_once()
+
+ def test_saves_metadata_when_provided(
+ self, tmp_path, sample_report_content, sample_metadata
+ ):
+ """Should save metadata when provided."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ):
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ ) as mock_json:
+ storage.save_report(
+ "test-uuid", sample_report_content, metadata=sample_metadata
+ )
+
+ mock_json.assert_called_once()
+
+ def test_skips_metadata_when_not_provided(
+ self, tmp_path, sample_report_content
+ ):
+ """Should skip metadata save when not provided."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+ ):
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ ) as mock_json:
+ storage.save_report("test-uuid", sample_report_content)
+
+ mock_json.assert_not_called()
+
+ def test_returns_false_on_error(self, tmp_path, sample_report_content):
+ """Should return False on error."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ with patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified",
+ side_effect=Exception("write error"),
+ ):
+ result = storage.save_report("test-uuid", sample_report_content)
+
+ assert result is False
+
+
+class TestGetReport:
+ """Tests for get_report method."""
+
+ def test_returns_content_when_file_exists(
+ self, tmp_path, sample_report_content
+ ):
+ """Should return content when file exists."""
+ storage = FileReportStorage(base_dir=tmp_path)
+ report_path = tmp_path / "test-uuid.md"
+ report_path.write_text(sample_report_content, encoding="utf-8")
+
+ result = storage.get_report("test-uuid")
+
+ assert result == sample_report_content
+
+ def test_returns_none_when_file_not_exists(self, tmp_path):
+ """Should return None when file doesn't exist."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ result = storage.get_report("nonexistent-uuid")
+
+ assert result is None
+
+ def test_returns_none_on_error(self, tmp_path):
+ """Should return None on read error."""
+ storage = FileReportStorage(base_dir=tmp_path)
+ report_path = tmp_path / "test-uuid.md"
+ report_path.write_text("content", encoding="utf-8")
+
+ with patch("builtins.open", side_effect=Exception("read error")):
+ result = storage.get_report("test-uuid")
+
+ assert result is None
+
+
+class TestGetReportWithMetadata:
+ """Tests for get_report_with_metadata method."""
+
+ def test_returns_content_and_metadata(
+ self, tmp_path, sample_report_content, sample_metadata
+ ):
+ """Should return both content and metadata."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ # Create files
+ report_path = tmp_path / "test-uuid.md"
+ report_path.write_text(sample_report_content, encoding="utf-8")
+
+ metadata_path = tmp_path / "test-uuid_metadata.json"
+ metadata_path.write_text(json.dumps(sample_metadata), encoding="utf-8")
+
+ result = storage.get_report_with_metadata("test-uuid")
+
+ assert result["content"] == sample_report_content
+ assert result["metadata"] == sample_metadata
+
+ def test_returns_empty_metadata_when_missing(
+ self, tmp_path, sample_report_content
+ ):
+ """Should return empty metadata when file missing."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ report_path = tmp_path / "test-uuid.md"
+ report_path.write_text(sample_report_content, encoding="utf-8")
+
+ result = storage.get_report_with_metadata("test-uuid")
+
+ assert result["content"] == sample_report_content
+ assert result["metadata"] == {}
+
+ def test_returns_none_when_report_missing(self, tmp_path):
+ """Should return None when report doesn't exist."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ result = storage.get_report_with_metadata("nonexistent")
+
+ assert result is None
+
+
+class TestDeleteReport:
+ """Tests for delete_report method."""
+
+ def test_deletes_report_file(self, tmp_path, sample_report_content):
+ """Should delete report file."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ report_path = tmp_path / "test-uuid.md"
+ report_path.write_text(sample_report_content, encoding="utf-8")
+
+ result = storage.delete_report("test-uuid")
+
+ assert result is True
+ assert not report_path.exists()
+
+ def test_deletes_metadata_file(
+ self, tmp_path, sample_report_content, sample_metadata
+ ):
+ """Should delete metadata file."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ report_path = tmp_path / "test-uuid.md"
+ report_path.write_text(sample_report_content, encoding="utf-8")
+
+ metadata_path = tmp_path / "test-uuid_metadata.json"
+ metadata_path.write_text(json.dumps(sample_metadata), encoding="utf-8")
+
+ storage.delete_report("test-uuid")
+
+ assert not metadata_path.exists()
+
+ def test_returns_false_when_files_not_exist(self, tmp_path):
+ """Should return False when no files to delete."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ result = storage.delete_report("nonexistent")
+
+ assert result is False
+
+ def test_returns_false_on_error(self, tmp_path, sample_report_content):
+ """Should return False on delete error."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ report_path = tmp_path / "test-uuid.md"
+ report_path.write_text(sample_report_content, encoding="utf-8")
+
+ with patch.object(
+ Path, "unlink", side_effect=Exception("delete error")
+ ):
+ result = storage.delete_report("test-uuid")
+
+ assert result is False
+
+
+class TestReportExists:
+ """Tests for report_exists method."""
+
+ def test_returns_true_when_file_exists(
+ self, tmp_path, sample_report_content
+ ):
+ """Should return True when file exists."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ report_path = tmp_path / "test-uuid.md"
+ report_path.write_text(sample_report_content, encoding="utf-8")
+
+ result = storage.report_exists("test-uuid")
+
+ assert result is True
+
+ def test_returns_false_when_file_not_exists(self, tmp_path):
+ """Should return False when file doesn't exist."""
+ storage = FileReportStorage(base_dir=tmp_path)
+
+ result = storage.report_exists("nonexistent")
+
+ assert result is False