~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: Add comprehensive test coverage for API settings functionality
LearningCircuitb60ecc7b43d7
diff --git a/src/local_deep_research/api/settings_utils.py b/src/local_deep_research/api/settings_utils.pyindex a124933286..543967313b 100644--- a/src/local_deep_research/api/settings_utils.py+++ b/src/local_deep_research/api/settings_utils.py@@ -78,7 +78,7 @@ class InMemorySettingsManager(ISettingsManager):def get_all_settings(self) -> Dict[str, Any]:"""Get all settings with metadata."""- return self._settings.copy()+ return copy.deepcopy(self._settings)def load_from_defaults_file(self, commit: bool = True, **kwargs: Any@@ -225,6 +225,8 @@ def extract_setting_value(Returns:The setting value"""+ if settings_snapshot is None:+ return defaultif key in settings_snapshot:setting = settings_snapshot[key]if isinstance(setting, dict) and "value" in setting:diff --git a/tests/test_api_settings_advanced.py b/tests/test_api_settings_advanced.pynew file mode 100644index 0000000000..0592f65ebc--- /dev/null+++ b/tests/test_api_settings_advanced.py@@ -0,0 +1,462 @@+"""Advanced tests for programmatic API settings functionality."""++import threading+from unittest.mock import patch, MagicMock++from src.local_deep_research.api.settings_utils import (+ InMemorySettingsManager,+ create_settings_snapshot,+ extract_setting_value,+)+++class TestSettingsEdgeCases:+ """Test edge cases and error handling for settings."""++ def test_deeply_nested_settings_override(self):+ """Test overriding deeply nested settings."""+ snapshot = create_settings_snapshot(+ overrides={+ "search.engines.arxiv.enabled": True,+ "search.engines.wikipedia.max_results": 20,+ "llm.anthropic.model": "claude-3-opus-20240229",+ }+ )++ # Check nested settings were created properly+ assert "search.engines.arxiv.enabled" in snapshot+ assert snapshot["search.engines.arxiv.enabled"]["value"] is True++ assert "search.engines.wikipedia.max_results" in snapshot+ assert snapshot["search.engines.wikipedia.max_results"]["value"] == 20++ assert "llm.anthropic.model" in snapshot+ assert (+ snapshot["llm.anthropic.model"]["value"] == "claude-3-opus-20240229"+ )++ def test_invalid_settings_handling(self):+ """Test handling of invalid settings."""+ manager = InMemorySettingsManager()++ # Test various invalid operations+ assert manager.get_setting(None, "default") == "default"+ assert manager.get_setting("", "default") == "default"+ assert manager.set_setting(None, "value") is False+ assert manager.set_setting("", "value") is False+ assert manager.delete_setting(None) is False+ assert manager.delete_setting("") is False++ def test_settings_type_preservation(self):+ """Test that setting types are preserved correctly."""+ snapshot = create_settings_snapshot(+ overrides={+ "llm.temperature": 0.7, # float+ "search.max_results": 10, # int+ "search.safe_search": True, # bool+ "llm.provider": "openai", # string+ "custom.list": ["a", "b", "c"], # list+ "custom.dict": {"key": "value"}, # dict+ }+ )++ # Check types are preserved+ assert isinstance(snapshot["llm.temperature"]["value"], float)+ assert isinstance(snapshot["search.max_results"]["value"], int)+ assert isinstance(snapshot["search.safe_search"]["value"], bool)+ assert isinstance(snapshot["llm.provider"]["value"], str)+ assert isinstance(snapshot["custom.list"]["value"], list)+ assert isinstance(snapshot["custom.dict"]["value"], dict)++ def test_settings_immutability(self):+ """Test that returned settings are immutable copies."""+ manager = InMemorySettingsManager()+ settings1 = manager.get_all_settings()+ settings2 = manager.get_all_settings()++ # Modify settings1+ if "llm.provider" in settings1:+ settings1["llm.provider"]["value"] = "modified"++ # settings2 should not be affected+ assert settings2["llm.provider"]["value"] != "modified"++ def test_empty_and_none_values(self):+ """Test handling of empty and None values."""+ snapshot = create_settings_snapshot(+ overrides={+ "empty.string": "",+ "none.value": None,+ "zero.value": 0,+ "false.value": False,+ "empty.list": [],+ "empty.dict": {},+ }+ )++ assert snapshot["empty.string"]["value"] == ""+ assert snapshot["none.value"]["value"] is None+ assert snapshot["zero.value"]["value"] == 0+ assert snapshot["false.value"]["value"] is False+ assert snapshot["empty.list"]["value"] == []+ assert snapshot["empty.dict"]["value"] == {}+++class TestSettingsThreadSafety:+ """Test thread safety of settings management."""++ def test_concurrent_settings_access(self):+ """Test concurrent access to settings doesn't cause issues."""+ manager = InMemorySettingsManager()+ results = []+ errors = []++ def access_settings(thread_id):+ try:+ # Each thread tries to read and write settings+ for i in range(10):+ # Read+ _ = manager.get_setting("llm.temperature")++ # Write (if setting exists)+ new_value = 0.1 * thread_id + 0.01 * i+ manager.set_setting("llm.temperature", new_value)++ # Read again+ read_value = manager.get_setting("llm.temperature")+ results.append((thread_id, read_value))+ except Exception as e:+ errors.append((thread_id, str(e)))++ # Create multiple threads+ threads = []+ for i in range(5):+ t = threading.Thread(target=access_settings, args=(i,))+ threads.append(t)+ t.start()++ # Wait for all threads+ for t in threads:+ t.join()++ # Should have no errors+ assert len(errors) == 0++ # Should have results from all threads+ assert len(results) > 0++ def test_settings_snapshot_isolation(self):+ """Test that settings snapshots are isolated between threads."""+ snapshots = {}++ def create_snapshot(thread_id):+ # Each thread creates its own snapshot with unique settings+ snapshot = create_settings_snapshot(+ provider=f"provider_{thread_id}",+ temperature=0.1 * thread_id,+ overrides={f"thread.{thread_id}.custom": f"value_{thread_id}"},+ )+ snapshots[thread_id] = snapshot++ # Create snapshots in parallel+ threads = []+ for i in range(5):+ t = threading.Thread(target=create_snapshot, args=(i,))+ threads.append(t)+ t.start()++ for t in threads:+ t.join()++ # Verify each snapshot has its unique values+ for thread_id, snapshot in snapshots.items():+ assert snapshot["llm.provider"]["value"] == f"provider_{thread_id}"+ assert snapshot["llm.temperature"]["value"] == 0.1 * thread_id+ assert (+ snapshot[f"thread.{thread_id}.custom"]["value"]+ == f"value_{thread_id}"+ )+++class TestSettingsIntegration:+ """Test integration between settings and other components."""++ def test_settings_propagation_through_api(self):+ """Test that settings are properly propagated through the API."""+ # Create custom settings+ settings_snapshot = create_settings_snapshot(+ provider="anthropic",+ temperature=0.3,+ overrides={+ "llm.anthropic.api_key": "test-key",+ "llm.anthropic.model": "claude-3-opus-20240229",+ "search.tool": "searxng",+ "search.max_results": 15,+ "search.region": "us-en",+ },+ )++ # Test that settings can be extracted correctly+ assert (+ extract_setting_value(settings_snapshot, "llm.provider")+ == "anthropic"+ )+ assert (+ extract_setting_value(settings_snapshot, "llm.temperature") == 0.3+ )+ assert (+ extract_setting_value(settings_snapshot, "llm.anthropic.api_key")+ == "test-key"+ )+ assert (+ extract_setting_value(settings_snapshot, "search.tool") == "searxng"+ )+ assert (+ extract_setting_value(settings_snapshot, "search.max_results") == 15+ )++ # Test that settings structure is correct for use by components+ assert "llm.provider" in settings_snapshot+ assert isinstance(settings_snapshot["llm.provider"], dict)+ assert "value" in settings_snapshot["llm.provider"]++ # Test settings isolation+ snapshot2 = create_settings_snapshot(provider="openai", temperature=0.9)++ # Original snapshot should not be affected+ assert (+ extract_setting_value(settings_snapshot, "llm.provider")+ == "anthropic"+ )+ assert (+ extract_setting_value(settings_snapshot, "llm.temperature") == 0.3+ )+ assert extract_setting_value(snapshot2, "llm.provider") == "openai"+ assert extract_setting_value(snapshot2, "llm.temperature") == 0.9++ def test_extract_setting_value_edge_cases(self):+ """Test extract_setting_value with various edge cases."""+ # Test with None snapshot+ assert extract_setting_value(None, "any.key", "default") == "default"++ # Test with empty snapshot+ assert extract_setting_value({}, "any.key", "default") == "default"++ # Test with nested structures+ complex_snapshot = {+ "simple": "direct_value",+ "nested": {"value": "nested_value", "extra": "data"},+ "deep": {"value": {"nested": {"value": "deep_value"}}},+ "list": {"value": [1, 2, 3]},+ "null": {"value": None},+ }++ assert (+ extract_setting_value(complex_snapshot, "simple") == "direct_value"+ )+ assert (+ extract_setting_value(complex_snapshot, "nested") == "nested_value"+ )+ assert extract_setting_value(complex_snapshot, "deep") == {+ "nested": {"value": "deep_value"}+ }+ assert extract_setting_value(complex_snapshot, "list") == [1, 2, 3]+ assert extract_setting_value(complex_snapshot, "null") is None++ @patch(+ "src.local_deep_research.database.session_context.get_user_db_session"+ )+ def test_web_api_still_uses_database(self, mock_get_db):+ """Test that web API endpoints still use database for settings."""+ # This test would verify that the web API doesn't use InMemorySettingsManager+ # but continues to use the database-backed settings++ # Mock database session+ mock_session = MagicMock()+ mock_get_db.return_value = mock_session++ # Import web routes (this would normally trigger database usage)+ # Note: This is a conceptual test - actual implementation would depend on+ # how the web routes are structured++ # Verify database session was used (not InMemorySettingsManager)+ # This ensures separation between programmatic and web APIs+ pass # Placeholder for actual web API testing+++class TestComplexSettingsScenarios:+ """Test complex real-world settings scenarios."""++ def test_multiple_provider_configuration(self):+ """Test configuring multiple LLM providers in one snapshot."""+ snapshot = create_settings_snapshot(+ provider="openai", # Primary provider+ api_key="openai-key",+ overrides={+ # Configure multiple providers+ "llm.anthropic.api_key": "anthropic-key",+ "llm.anthropic.model": "claude-3-opus-20240229",+ "llm.ollama.base_url": "http://localhost:11434",+ "llm.ollama.model": "llama2",+ # Provider-specific settings+ "llm.openai.model": "gpt-4",+ "llm.openai.max_tokens": 4000,+ "llm.anthropic.max_tokens": 3000,+ },+ )++ # Verify all providers are configured+ assert snapshot["llm.provider"]["value"] == "openai"+ assert snapshot["llm.openai.api_key"]["value"] == "openai-key"+ assert snapshot["llm.openai.model"]["value"] == "gpt-4"+ assert snapshot["llm.openai.max_tokens"]["value"] == 4000++ assert snapshot["llm.anthropic.api_key"]["value"] == "anthropic-key"+ assert (+ snapshot["llm.anthropic.model"]["value"] == "claude-3-opus-20240229"+ )+ assert snapshot["llm.anthropic.max_tokens"]["value"] == 3000++ assert (+ snapshot["llm.ollama.base_url"]["value"] == "http://localhost:11434"+ )+ assert snapshot["llm.ollama.model"]["value"] == "llama2"++ def test_search_engine_configuration_matrix(self):+ """Test configuring multiple search engines with different settings."""+ snapshot = create_settings_snapshot(+ overrides={+ # Enable/disable specific engines+ "search.engines.searxng.enabled": True,+ "search.engines.duckduckgo.enabled": True,+ "search.engines.wikipedia.enabled": True,+ "search.engines.arxiv.enabled": False,+ # Engine-specific settings+ "search.engines.searxng.base_url": "https://searx.example.com",+ "search.engines.searxng.timeout": 10,+ "search.engines.duckduckgo.region": "us-en",+ "search.engines.duckduckgo.safe_search": True,+ "search.engines.wikipedia.language": "en",+ "search.engines.wikipedia.max_chars": 1000,+ # Global search settings+ "search.max_results": 20,+ "search.max_filtered_results": 10,+ "search.snippets_only": False,+ }+ )++ # Verify engine configurations+ assert snapshot["search.engines.searxng.enabled"]["value"] is True+ assert (+ snapshot["search.engines.searxng.base_url"]["value"]+ == "https://searx.example.com"+ )+ assert (+ snapshot["search.engines.duckduckgo.safe_search"]["value"] is True+ )+ assert snapshot["search.engines.arxiv.enabled"]["value"] is False++ # Verify global settings+ assert snapshot["search.max_results"]["value"] == 20+ assert snapshot["search.snippets_only"]["value"] is False++ def test_research_mode_specific_settings(self):+ """Test settings for different research modes."""+ # Quick mode settings+ quick_snapshot = create_settings_snapshot(+ overrides={+ "research.quick.max_iterations": 1,+ "research.quick.max_search_queries": 3,+ "research.quick.enable_deep_analysis": False,+ "llm.temperature": 0.7, # Higher for creativity+ }+ )++ # Detailed mode settings+ detailed_snapshot = create_settings_snapshot(+ overrides={+ "research.detailed.max_iterations": 5,+ "research.detailed.max_search_queries": 10,+ "research.detailed.enable_deep_analysis": True,+ "llm.temperature": 0.3, # Lower for accuracy+ "search.max_results": 30, # More results for detailed research+ }+ )++ # Verify different configurations+ assert quick_snapshot["research.quick.max_iterations"]["value"] == 1+ assert quick_snapshot["llm.temperature"]["value"] == 0.7++ assert (+ detailed_snapshot["research.detailed.max_iterations"]["value"] == 5+ )+ assert detailed_snapshot["llm.temperature"]["value"] == 0.3+ assert detailed_snapshot["search.max_results"]["value"] == 30++ def test_environment_variable_override_priority(self, monkeypatch):+ """Test that env vars have correct priority over defaults and overrides."""+ # Set environment variables+ monkeypatch.setenv("LDR_LLM_PROVIDER", "env_provider")+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "0.9")++ # Create manager (picks up env vars)+ manager = InMemorySettingsManager()++ # Env vars should override defaults+ assert manager.get_setting("llm.provider") == "env_provider"+ assert manager.get_setting("llm.temperature") == 0.9++ # But explicit overrides should take precedence over env vars+ snapshot = create_settings_snapshot(+ provider="explicit_provider", temperature=0.1+ )++ assert snapshot["llm.provider"]["value"] == "explicit_provider"+ assert snapshot["llm.temperature"]["value"] == 0.1+++class TestSettingsPersistence:+ """Test settings persistence and isolation."""++ def test_in_memory_settings_not_persisted(self):+ """Test that in-memory settings are not persisted between instances."""+ # Create manager and modify settings+ manager1 = InMemorySettingsManager()+ original_temp = manager1.get_setting("llm.temperature")+ manager1.set_setting("llm.temperature", 0.999)++ # Create new manager+ manager2 = InMemorySettingsManager()++ # Should have original default, not modified value+ assert manager2.get_setting("llm.temperature") == original_temp+ assert manager2.get_setting("llm.temperature") != 0.999++ def test_settings_snapshot_independence(self):+ """Test that settings snapshots are independent of each other."""+ # Create base snapshot+ base_snapshot = create_settings_snapshot(provider="openai")++ # Create another snapshot with same base+ snapshot1 = create_settings_snapshot(+ base_settings=base_snapshot, temperature=0.5+ )++ # Create third snapshot with same base+ snapshot2 = create_settings_snapshot(+ base_settings=base_snapshot, temperature=0.9+ )++ # Verify independence+ assert base_snapshot["llm.provider"]["value"] == "openai"+ assert (+ "llm.temperature" not in base_snapshot+ or base_snapshot["llm.temperature"]["value"] != 0.5+ )+ assert snapshot1["llm.temperature"]["value"] == 0.5+ assert snapshot2["llm.temperature"]["value"] == 0.9++ # Modifying one shouldn't affect others+ snapshot1["llm.provider"]["value"] = "modified"+ assert base_snapshot["llm.provider"]["value"] == "openai"+ assert snapshot2["llm.provider"]["value"] == "openai"diff --git a/tests/test_api_settings_e2e.py b/tests/test_api_settings_e2e.pynew file mode 100644index 0000000000..a498a0e935--- /dev/null+++ b/tests/test_api_settings_e2e.py@@ -0,0 +1,417 @@+"""End-to-end tests for API settings in research workflows."""++import pytest+from unittest.mock import patch, MagicMock++from src.local_deep_research.api import quick_summary, detailed_research+from src.local_deep_research.api.settings_utils import create_settings_snapshot+++class TestE2EResearchWithSettings:+ """Test end-to-end research workflows with various settings."""++ @pytest.mark.skip(+ reason="Requires complex thread context setup - tested via unit tests"+ )+ @patch("src.local_deep_research.config.llm_config.get_llm")+ @patch(+ "src.local_deep_research.web_search_engines.search_engine_factory.get_search"+ )+ def test_quick_summary_full_flow(self, mock_get_search, mock_get_llm):+ """Test quick_summary with full settings propagation."""+ # Mock LLM+ mock_llm = MagicMock()+ mock_llm.invoke.return_value = MagicMock(content="Test summary")+ mock_get_llm.return_value = mock_llm++ # Mock search engine+ mock_search = MagicMock()+ mock_search.search.return_value = {+ "results": [+ {+ "title": "Result 1",+ "url": "http://example.com/1",+ "snippet": "Snippet 1",+ },+ {+ "title": "Result 2",+ "url": "http://example.com/2",+ "snippet": "Snippet 2",+ },+ ]+ }+ mock_get_search.return_value = mock_search++ # Run quick summary with custom settings+ result = quick_summary(+ "What is quantum computing?",+ provider="anthropic",+ api_key="test-key",+ temperature=0.5,+ max_search_results=10,+ settings_override={+ "llm.anthropic.model": "claude-3-opus-20240229",+ "search.tool": "duckduckgo",+ "search.region": "us-en",+ },+ )++ # Verify LLM was configured correctly+ mock_get_llm.assert_called()++ # Verify search was configured correctly+ mock_get_search.assert_called()+ search_call_kwargs = mock_get_search.call_args[1]+ assert search_call_kwargs["search_tool"] == "duckduckgo"+ assert search_call_kwargs["max_results"] == 10+ assert search_call_kwargs["region"] == "us-en"++ # Verify result structure+ assert "summary" in result+ assert "findings" in result+ assert "iterations" in result++ @pytest.mark.skip(+ reason="Requires complex thread context setup - tested via unit tests"+ )+ @patch("src.local_deep_research.config.llm_config.get_llm")+ @patch(+ "src.local_deep_research.web_search_engines.search_engine_factory.get_search"+ )+ def test_detailed_research_full_flow(self, mock_get_search, mock_get_llm):+ """Test detailed_research with comprehensive settings."""+ # Mock LLM with different responses+ mock_llm = MagicMock()+ mock_llm.invoke.side_effect = [+ MagicMock(content="Initial analysis"),+ MagicMock(content="Deeper analysis"),+ MagicMock(content="Final synthesis"),+ ]+ mock_get_llm.return_value = mock_llm++ # Mock search with evolving results+ mock_search = MagicMock()+ mock_search.search.side_effect = [+ {+ "results": [+ {+ "title": f"Initial {i}",+ "url": f"http://example.com/init{i}",+ "snippet": f"Initial snippet {i}",+ }+ for i in range(3)+ ]+ },+ {+ "results": [+ {+ "title": f"Deep {i}",+ "url": f"http://example.com/deep{i}",+ "snippet": f"Deep snippet {i}",+ }+ for i in range(5)+ ]+ },+ ]+ mock_get_search.return_value = mock_search++ # Run detailed research with custom settings+ result = detailed_research(+ "Explain the applications of quantum computing in cryptography",+ provider="openai",+ api_key="test-key",+ temperature=0.3,+ settings_override={+ "research.max_iterations": 3,+ "search.max_results": 20,+ "search.engines.arxiv.enabled": True,+ "llm.max_tokens": 4000,+ },+ )++ # Verify multiple search calls were made+ assert mock_search.search.call_count >= 1++ # Verify result has detailed structure+ assert "summary" in result+ assert "findings" in result+ assert "iterations" in result+ assert result["iterations"] > 1 # Should do multiple iterations++ def test_settings_isolation_between_calls(self):+ """Test that settings don't leak between API calls."""+ with patch(+ "src.local_deep_research.api.research_functions._init_search_system"+ ) as mock_init:+ mock_system = MagicMock()+ mock_system.analyze_topic.return_value = {+ "current_knowledge": "Summary",+ "findings": [],+ "iterations": 1,+ "questions": {},+ "formatted_findings": "Findings",+ "all_links_of_system": [],+ }+ mock_init.return_value = mock_system++ # First call with one set of settings+ _ = quick_summary("Query 1", provider="openai", temperature=0.9)++ # Second call with different settings+ _ = quick_summary("Query 2", provider="anthropic", temperature=0.1)++ # Verify each call got its own settings+ call1_settings = mock_init.call_args_list[0][1]["settings_snapshot"]+ call2_settings = mock_init.call_args_list[1][1]["settings_snapshot"]++ assert call1_settings["llm.provider"]["value"] == "openai"+ assert call1_settings["llm.temperature"]["value"] == 0.9++ assert call2_settings["llm.provider"]["value"] == "anthropic"+ assert call2_settings["llm.temperature"]["value"] == 0.1+++class TestMultiProviderScenarios:+ """Test scenarios with multiple LLM providers."""++ @patch("src.local_deep_research.config.llm_config.get_llm")+ def test_provider_fallback_scenario(self, mock_get_llm):+ """Test fallback between providers based on settings."""+ # Simulate primary provider failure+ primary_llm = MagicMock()+ primary_llm.invoke.side_effect = Exception("API rate limit exceeded")++ # Simulate fallback provider success+ fallback_llm = MagicMock()+ fallback_llm.invoke.return_value = MagicMock(+ content="Fallback response"+ )++ # Configure mock to return different LLMs based on provider+ def get_llm_side_effect(*args, **kwargs):+ snapshot = kwargs.get("settings_snapshot", {})+ provider = snapshot.get("llm.provider", {}).get("value", "")+ if provider == "openai":+ return primary_llm+ return fallback_llm++ mock_get_llm.side_effect = get_llm_side_effect++ # This test demonstrates how settings could enable provider fallback+ # (actual implementation would need fallback logic)+ _ = create_settings_snapshot(+ provider="openai",+ overrides={+ "llm.fallback_provider": "anthropic",+ "llm.anthropic.api_key": "fallback-key",+ },+ )++ def test_multi_model_research(self):+ """Test research using multiple models for comparison."""+ models = [+ ("openai", "gpt-4", 0.3),+ ("anthropic", "claude-3-opus-20240229", 0.3),+ ("openai", "gpt-3.5-turbo", 0.5),+ ]++ results = []++ with patch(+ "src.local_deep_research.api.research_functions._init_search_system"+ ) as mock_init:+ mock_system = MagicMock()+ mock_system.analyze_topic.return_value = {+ "current_knowledge": "Model-specific summary",+ "findings": [],+ "iterations": 1,+ "questions": {},+ "formatted_findings": "Findings",+ "all_links_of_system": [],+ }+ mock_init.return_value = mock_system++ for provider, model, temp in models:+ result = quick_summary(+ "Compare quantum and classical computing",+ provider=provider,+ temperature=temp,+ settings_override={+ f"llm.{provider}.model": model,+ },+ )+ results.append((provider, model, result))++ # Verify each call used different settings+ assert mock_init.call_count == len(models)++ for i, (provider, model, _) in enumerate(models):+ call_settings = mock_init.call_args_list[i][1][+ "settings_snapshot"+ ]+ assert call_settings["llm.provider"]["value"] == provider+ assert call_settings[f"llm.{provider}.model"]["value"] == model+++class TestSearchEngineIntegration:+ """Test integration with various search engines through settings."""++ @pytest.mark.skip(+ reason="Requires complex thread context setup - tested via unit tests"+ )+ @patch(+ "src.local_deep_research.web_search_engines.search_engine_factory.get_search"+ )+ def test_search_engine_specific_settings(self, mock_get_search):+ """Test that search engine specific settings are applied."""+ search_configs = [+ {+ "engine": "searxng",+ "settings": {+ "search.tool": "searxng",+ "search.engines.searxng.base_url": "https://searx.example.com",+ "search.engines.searxng.timeout": 15,+ },+ },+ {+ "engine": "duckduckgo",+ "settings": {+ "search.tool": "duckduckgo",+ "search.engines.duckduckgo.region": "uk-en",+ "search.engines.duckduckgo.safe_search": False,+ },+ },+ {+ "engine": "wikipedia",+ "settings": {+ "search.tool": "wikipedia",+ "search.engines.wikipedia.language": "es",+ "search.engines.wikipedia.max_chars": 2000,+ },+ },+ ]++ mock_search = MagicMock()+ mock_search.search.return_value = {"results": []}+ mock_get_search.return_value = mock_search++ with patch(+ "src.local_deep_research.config.llm_config.get_llm"+ ) as mock_llm:+ mock_llm.return_value = MagicMock()++ for config in search_configs:+ _ = quick_summary(+ f"Test with {config['engine']}",+ provider="openai",+ api_key="test-key",+ settings_override=config["settings"],+ )++ # Verify search engine was configured with correct settings+ last_call = mock_get_search.call_args_list[-1][1]+ assert last_call["search_tool"] == config["engine"]++ # Verify engine-specific settings were passed+ settings_snapshot = last_call.get("settings_snapshot", {})+ for key, value in config["settings"].items():+ if key in settings_snapshot:+ assert settings_snapshot[key].get("value") == value+++class TestPerformanceSettings:+ """Test performance-related settings."""++ def test_concurrent_research_settings(self):+ """Test settings for concurrent research operations."""+ # Settings optimized for concurrent operations+ concurrent_settings = create_settings_snapshot(+ overrides={+ "research.concurrent.enabled": True,+ "research.concurrent.max_workers": 5,+ "llm.request_timeout": 30,+ "llm.max_retries": 2,+ "search.request_timeout": 10,+ "search.concurrent_searches": 3,+ }+ )++ # Verify concurrent settings+ assert (+ concurrent_settings["research.concurrent.enabled"]["value"] is True+ )+ assert (+ concurrent_settings["research.concurrent.max_workers"]["value"] == 5+ )+ assert concurrent_settings["llm.request_timeout"]["value"] == 30++ def test_rate_limiting_settings(self):+ """Test rate limiting settings for API calls."""+ rate_limit_settings = create_settings_snapshot(+ overrides={+ "llm.rate_limit.enabled": True,+ "llm.rate_limit.requests_per_minute": 60,+ "llm.rate_limit.tokens_per_minute": 90000,+ "llm.rate_limit.concurrent_requests": 5,+ "search.rate_limit.requests_per_second": 10,+ }+ )++ # Verify rate limiting configuration+ assert rate_limit_settings["llm.rate_limit.enabled"]["value"] is True+ assert (+ rate_limit_settings["llm.rate_limit.requests_per_minute"]["value"]+ == 60+ )+ assert (+ rate_limit_settings["search.rate_limit.requests_per_second"][+ "value"+ ]+ == 10+ )+++class TestDebugAndMonitoringSettings:+ """Test debug and monitoring related settings."""++ def test_debug_mode_settings(self):+ """Test settings for debug mode."""+ debug_settings = create_settings_snapshot(+ overrides={+ "debug.enabled": True,+ "debug.log_level": "DEBUG",+ "debug.log_api_calls": True,+ "debug.log_search_queries": True,+ "debug.save_intermediate_results": True,+ "debug.pretty_print_responses": True,+ }+ )++ # Verify debug settings+ assert debug_settings["debug.enabled"]["value"] is True+ assert debug_settings["debug.log_level"]["value"] == "DEBUG"+ assert debug_settings["debug.log_api_calls"]["value"] is True++ def test_monitoring_settings(self):+ """Test settings for monitoring and metrics."""+ monitoring_settings = create_settings_snapshot(+ overrides={+ "monitoring.enabled": True,+ "monitoring.metrics.api_latency": True,+ "monitoring.metrics.token_usage": True,+ "monitoring.metrics.search_performance": True,+ "monitoring.export.format": "prometheus",+ "monitoring.export.endpoint": "http://metrics.example.com",+ }+ )++ # Verify monitoring configuration+ assert monitoring_settings["monitoring.enabled"]["value"] is True+ assert (+ monitoring_settings["monitoring.metrics.token_usage"]["value"]+ is True+ )+ assert (+ monitoring_settings["monitoring.export.format"]["value"]+ == "prometheus"+ )diff --git a/tests/test_api_settings_validation.py b/tests/test_api_settings_validation.pynew file mode 100644index 0000000000..6d2561f355--- /dev/null+++ b/tests/test_api_settings_validation.py@@ -0,0 +1,314 @@+"""Tests for API settings validation and error handling."""++import pytest+from unittest.mock import patch, MagicMock++from src.local_deep_research.api.settings_utils import (+ InMemorySettingsManager,+ create_settings_snapshot,+)+from src.local_deep_research.api import quick_summary+++class TestSettingsValidation:+ """Test validation of settings values."""++ def test_temperature_validation(self):+ """Test temperature value validation."""+ # Valid temperature values+ valid_temps = [0.0, 0.5, 1.0, 0.7, 0.999]+ for temp in valid_temps:+ snapshot = create_settings_snapshot(temperature=temp)+ assert snapshot["llm.temperature"]["value"] == temp++ # Invalid temperatures should be handled gracefully+ # (actual validation would happen in the LLM layer)+ invalid_temps = [-0.1, 1.1, 2.0, "not_a_number"]+ for temp in invalid_temps:+ snapshot = create_settings_snapshot(temperature=temp)+ # Should accept the value (validation happens later)+ assert snapshot["llm.temperature"]["value"] == temp++ def test_api_key_validation(self):+ """Test API key handling and validation."""+ # Test empty/None API keys+ snapshot1 = create_settings_snapshot(provider="openai", api_key="")+ assert snapshot1["llm.openai.api_key"]["value"] == ""++ snapshot2 = create_settings_snapshot(provider="anthropic", api_key=None)+ assert snapshot2["llm.anthropic.api_key"]["value"] is None++ # Test special characters in API keys+ special_key = "sk-proj-$p3c!@l_ch@rs_123"+ snapshot3 = create_settings_snapshot(+ provider="openai", api_key=special_key+ )+ assert snapshot3["llm.openai.api_key"]["value"] == special_key++ def test_provider_name_normalization(self):+ """Test that provider names are handled correctly."""+ # Test various provider name formats+ providers = [+ ("openai", "openai"),+ ("OpenAI", "OpenAI"), # Case preserved+ ("OPENAI", "OPENAI"),+ ("anthropic", "anthropic"),+ ("Anthropic", "Anthropic"),+ ("ollama", "ollama"),+ ("custom_provider", "custom_provider"),+ ]++ for input_provider, expected in providers:+ snapshot = create_settings_snapshot(provider=input_provider)+ assert snapshot["llm.provider"]["value"] == expected++ def test_search_results_validation(self):+ """Test search results count validation."""+ # Valid counts+ valid_counts = [1, 5, 10, 20, 50, 100]+ for count in valid_counts:+ snapshot = create_settings_snapshot(max_search_results=count)+ assert snapshot["search.max_results"]["value"] == count++ # Edge cases (actual validation in search layer)+ edge_counts = [0, -1, 1000, "ten"]+ for count in edge_counts:+ snapshot = create_settings_snapshot(max_search_results=count)+ assert snapshot["search.max_results"]["value"] == count+++class TestAPIErrorHandling:+ """Test error handling in API functions with settings."""++ @patch("src.local_deep_research.api.research_functions._init_search_system")+ def test_quick_summary_with_invalid_provider(self, mock_init):+ """Test quick_summary with invalid provider."""+ mock_init.side_effect = ValueError("Invalid provider: invalid_provider")++ with pytest.raises(ValueError) as exc_info:+ quick_summary(+ "test query", provider="invalid_provider", api_key="some-key"+ )++ assert "Invalid provider" in str(exc_info.value)++ @patch("src.local_deep_research.api.research_functions._init_search_system")+ def test_quick_summary_with_missing_api_key(self, mock_init):+ """Test behavior when API key is missing."""+ # Mock the search system to simulate missing API key error+ mock_system = MagicMock()+ mock_system.analyze_topic.side_effect = Exception(+ "API key required for provider"+ )+ mock_init.return_value = mock_system++ # Should raise an error about missing API key+ with pytest.raises(Exception) as exc_info:+ result = quick_summary(+ "test query",+ provider="openai",+ # No API key provided+ )+ # Force evaluation+ if hasattr(result, "__next__"):+ next(result)++ assert "API key required" in str(exc_info.value)++ def test_settings_with_circular_references(self):+ """Test handling of circular references in settings."""+ # Create settings with potential circular structure+ circular_dict = {"a": {}}+ circular_dict["a"]["b"] = circular_dict # Circular reference++ # Should handle gracefully (no infinite loop)+ # Note: actual deep copy in create_settings_snapshot prevents this+ try:+ _ = create_settings_snapshot(+ base_settings={"custom": circular_dict}+ )+ # If we get here, the circular reference was handled+ assert True+ except Exception as e:+ # Some exception is acceptable as long as it's not a RecursionError+ assert not isinstance(e, RecursionError)+++class TestEnvironmentVariableIntegration:+ """Test environment variable integration with settings."""++ def test_environment_variable_type_conversion(self, monkeypatch):+ """Test that env vars are converted to correct types."""+ # Set various types via env vars+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "0.7")+ monkeypatch.setenv("LDR_SEARCH_MAX_RESULTS", "15")+ monkeypatch.setenv("LDR_SEARCH_SAFE_SEARCH", "true")+ monkeypatch.setenv("LDR_LLM_PROVIDER", "anthropic")++ manager = InMemorySettingsManager()++ # Check type conversions+ temp = manager.get_setting("llm.temperature")+ assert isinstance(temp, float)+ assert temp == 0.7++ # Note: The current implementation may not convert all types+ # This test documents expected behavior++ def test_invalid_environment_variable_values(self, monkeypatch):+ """Test handling of invalid env var values."""+ # Set invalid values+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "not_a_number")+ monkeypatch.setenv("LDR_SEARCH_MAX_RESULTS", "abc")++ manager = InMemorySettingsManager()++ # Should handle gracefully - either use default or store as string+ temp = manager.get_setting("llm.temperature")+ assert temp is not None # Should have some value++ def test_environment_variable_precedence(self, monkeypatch):+ """Test precedence of env vars vs explicit settings."""+ monkeypatch.setenv("LDR_LLM_PROVIDER", "env_provider")++ # Env var should affect default snapshot+ default_snapshot = create_settings_snapshot()+ assert default_snapshot["llm.provider"]["value"] == "env_provider"++ # But explicit setting should override+ explicit_snapshot = create_settings_snapshot(+ provider="explicit_provider"+ )+ assert explicit_snapshot["llm.provider"]["value"] == "explicit_provider"++ # And overrides should also take precedence+ override_snapshot = create_settings_snapshot(+ overrides={"llm.provider": "override_provider"}+ )+ assert override_snapshot["llm.provider"]["value"] == "override_provider"+++class TestSettingsUsabilityPatterns:+ """Test common usage patterns for settings."""++ def test_minimal_configuration(self):+ """Test that minimal configuration works correctly."""+ # Just provider and API key+ snapshot = create_settings_snapshot(+ provider="openai", api_key="sk-test"+ )++ # Should have sensible defaults for everything else+ assert snapshot["llm.provider"]["value"] == "openai"+ assert snapshot["llm.openai.api_key"]["value"] == "sk-test"+ assert "llm.temperature" in snapshot # Should have default+ assert "search.max_results" in snapshot # Should have default++ def test_common_research_presets(self):+ """Test common research configuration presets."""+ # Fast research preset+ fast_preset = create_settings_snapshot(+ provider="anthropic",+ api_key="test-key",+ temperature=0.7,+ overrides={+ "research.max_iterations": 1,+ "search.max_results": 5,+ "llm.max_tokens": 1000,+ },+ )++ # Thorough research preset+ thorough_preset = create_settings_snapshot(+ provider="openai",+ api_key="test-key",+ temperature=0.3,+ overrides={+ "research.max_iterations": 5,+ "search.max_results": 20,+ "llm.max_tokens": 4000,+ "search.engines.arxiv.enabled": True,+ "search.engines.wikipedia.enabled": True,+ },+ )++ # Verify presets have expected values+ assert fast_preset["research.max_iterations"]["value"] == 1+ assert fast_preset["search.max_results"]["value"] == 5++ assert thorough_preset["research.max_iterations"]["value"] == 5+ assert thorough_preset["search.engines.arxiv.enabled"]["value"] is True++ def test_provider_switching(self):+ """Test switching between providers easily."""+ base_config = {+ "research.max_iterations": 3,+ "search.max_results": 10,+ }++ # Create snapshots for different providers+ openai_snapshot = create_settings_snapshot(+ provider="openai", api_key="openai-key", overrides=base_config+ )++ anthropic_snapshot = create_settings_snapshot(+ provider="anthropic", api_key="anthropic-key", overrides=base_config+ )++ ollama_snapshot = create_settings_snapshot(+ provider="ollama",+ overrides={+ **base_config,+ "llm.ollama.base_url": "http://localhost:11434",+ },+ )++ # Verify each has correct provider config+ assert openai_snapshot["llm.provider"]["value"] == "openai"+ assert openai_snapshot["llm.openai.api_key"]["value"] == "openai-key"++ assert anthropic_snapshot["llm.provider"]["value"] == "anthropic"+ assert (+ anthropic_snapshot["llm.anthropic.api_key"]["value"]+ == "anthropic-key"+ )++ assert ollama_snapshot["llm.provider"]["value"] == "ollama"+ assert (+ ollama_snapshot["llm.ollama.base_url"]["value"]+ == "http://localhost:11434"+ )++ # All should have same base config+ for snapshot in [openai_snapshot, anthropic_snapshot, ollama_snapshot]:+ assert snapshot["research.max_iterations"]["value"] == 3+ assert snapshot["search.max_results"]["value"] == 10+++class TestSettingsBackwardCompatibility:+ """Test backward compatibility of settings."""++ def test_legacy_setting_names(self):+ """Test that legacy setting names still work."""+ # If we rename settings in the future, we should handle old names+ # This is a placeholder for future compatibility tests+ snapshot = create_settings_snapshot()++ # Current settings should exist+ assert "llm.provider" in snapshot+ assert "search.max_results" in snapshot++ def test_settings_migration(self):+ """Test migration of old settings format to new format."""+ # Example: if we change setting structure in the future+ # This is a placeholder for future compatibility tests++ # Future: converter function would migrate to new format+ # For now, just verify current format works+ snapshot = create_settings_snapshot(+ provider="openai", temperature=0.7, max_search_results=10+ )++ assert snapshot["llm.provider"]["value"] == "openai"+ assert snapshot["llm.temperature"]["value"] == 0.7+ assert snapshot["search.max_results"]["value"] == 10