~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: comprehensive tests for search_system_factory (#2428)
LearningCircuitf9b65d82a331
diff --git a/tests/core/test_search_system_factory.py b/tests/core/test_search_system_factory.pyindex 988d92bb36..1b2e5e2dbf 100644--- a/tests/core/test_search_system_factory.py+++ b/tests/core/test_search_system_factory.py@@ -2,557 +2,1109 @@Tests for search_system_factory.pyTests cover:-- _get_setting helper function-- create_strategy factory function-- Strategy name normalization+- _get_setting helper function (all edge cases)+- create_strategy factory function (all strategy types)+- Strategy name normalization (case-insensitive, alternative forms)+- kwargs pass-through and settings_snapshot forwarding+- Focused-iteration special behaviors (zero-to-None, flexible generator)+- Iterative-refinement recursive create_strategy call+- Unknown strategy fallback with warning"""-from unittest.mock import Mock, patch+from unittest.mock import MagicMock, Mock, patch++import pytest+from langchain_core.language_models import BaseChatModel++from local_deep_research.search_system_factory import (+ _get_setting,+ create_strategy,+)+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def mock_model():+ """Return a MagicMock with BaseChatModel spec."""+ return MagicMock(spec=BaseChatModel)+++def mock_search():+ """Return a plain MagicMock for the search engine."""+ return MagicMock()+++# ===========================================================================+# _get_setting tests+# ===========================================================================class TestGetSetting:"""Tests for _get_setting helper function."""- def test_get_setting_returns_default_for_empty_snapshot(self):- """Test _get_setting returns default for empty snapshot."""- from local_deep_research.search_system_factory import _get_setting+ def test_returns_default_when_snapshot_is_none(self):+ assert _get_setting(None, "any.key", "default_val") == "default_val"- result = _get_setting(None, "test.key", "default")- assert result == "default"+ def test_returns_default_when_snapshot_is_empty_dict(self):+ # Empty dict is falsy; the guard `if not settings_snapshot` catches it.+ assert _get_setting({}, "missing.key", 42) == 42- def test_get_setting_returns_default_for_missing_key(self):- """Test _get_setting returns default for missing key."""- from local_deep_research.search_system_factory import _get_setting+ def test_returns_default_when_key_not_in_snapshot(self):+ snapshot = {"other.key": "other_val"}+ assert _get_setting(snapshot, "missing.key", "fallback") == "fallback"- result = _get_setting({"other.key": "value"}, "test.key", "default")- assert result == "default"+ def test_returns_raw_value_when_value_is_not_dict(self):+ snapshot = {"my.key": "plain_string"}+ assert _get_setting(snapshot, "my.key", "default") == "plain_string"- def test_get_setting_returns_value_directly(self):- """Test _get_setting returns value directly if not dict."""- from local_deep_research.search_system_factory import _get_setting+ def test_returns_integer_value_directly(self):+ snapshot = {"iterations": 7}+ assert _get_setting(snapshot, "iterations", 10) == 7- result = _get_setting(- {"test.key": "direct_value"}, "test.key", "default"- )- assert result == "direct_value"+ def test_returns_boolean_value_directly(self):+ snapshot = {"enabled": True}+ assert _get_setting(snapshot, "enabled", False) is True- def test_get_setting_extracts_value_from_dict(self):- """Test _get_setting extracts value from dict structure."""- from local_deep_research.search_system_factory import _get_setting+ def test_extracts_value_from_dict_with_value_key(self):+ snapshot = {"my.key": {"value": "nested_result", "type": "string"}}+ assert _get_setting(snapshot, "my.key", "default") == "nested_result"- snapshot = {"test.key": {"value": "nested_value", "extra": "ignored"}}- result = _get_setting(snapshot, "test.key", "default")- assert result == "nested_value"+ def test_returns_dict_itself_when_no_value_key(self):+ inner = {"type": "string", "description": "no value key here"}+ snapshot = {"my.key": inner}+ assert _get_setting(snapshot, "my.key", "default") == inner- def test_get_setting_handles_integer_value(self):- """Test _get_setting handles integer values."""- from local_deep_research.search_system_factory import _get_setting+ def test_extracts_none_from_value_key(self):+ """Even if value['value'] is None, it should be returned (not default)."""+ snapshot = {"my.key": {"value": None}}+ assert _get_setting(snapshot, "my.key", "default") is None- result = _get_setting({"iterations": 5}, "iterations", 10)- assert result == 5+ def test_extracts_zero_from_value_key(self):+ """Zero is a valid value and should not be replaced by default."""+ snapshot = {"limit": {"value": 0}}+ assert _get_setting(snapshot, "limit", 10) == 0- def test_get_setting_handles_boolean_value(self):- """Test _get_setting handles boolean values."""- from local_deep_research.search_system_factory import _get_setting+ def test_returns_list_value_directly(self):+ snapshot = {"tags": ["a", "b", "c"]}+ assert _get_setting(snapshot, "tags", []) == ["a", "b", "c"]- result = _get_setting({"enabled": True}, "enabled", False)- assert result is True+# ===========================================================================+# create_strategy tests – individual strategies+# ===========================================================================-class TestCreateStrategySourceBased:- """Tests for create_strategy with source-based strategy."""+# Helpers: common patch paths+_STRAT_BASE = "local_deep_research.advanced_search_system.strategies"- def test_create_source_based_strategy(self):- """Test creating source-based strategy."""- mock_model = Mock()- mock_search = Mock()- with patch(- "local_deep_research.advanced_search_system.strategies.source_based_strategy.SourceBasedSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy-- from local_deep_research.search_system_factory import (- create_strategy,+class TestCreateStrategySourceBased:+ """Tests for source-based strategy and its name variants."""++ PATCH_PATH = (+ f"{_STRAT_BASE}.source_based_strategy.SourceBasedSearchStrategy"+ )++ @pytest.mark.parametrize(+ "name",+ ["source-based", "source_based", "source_based_search"],+ )+ def test_all_name_variants_create_source_based(+ self, name, mock_model, mock_search+ ):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search)+ cls.assert_called_once()+ assert result == cls.return_value- result = create_strategy(+ def test_kwargs_passed_through(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ create_strategy(strategy_name="source-based",model=mock_model,search=mock_search,+ include_text_content=False,+ use_cross_engine_filter=False,+ use_atomic_facts=True,+ search_original_query=False,)+ kw = cls.call_args[1]+ assert kw["include_text_content"] is False+ assert kw["use_cross_engine_filter"] is False+ assert kw["use_atomic_facts"] is True+ assert kw["search_original_query"] is False++ def test_settings_snapshot_forwarded(self, mock_model, mock_search):+ snapshot = {"some.setting": 123}+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="source-based",+ model=mock_model,+ search=mock_search,+ settings_snapshot=snapshot,+ )+ kw = cls.call_args[1]+ assert kw["settings_snapshot"] is snapshot- mock_strategy_class.assert_called_once()- assert result == mock_strategy- def test_create_source_based_with_underscore(self):- """Test creating source_based strategy (underscore variant)."""- mock_model = Mock()- mock_search = Mock()+class TestCreateStrategyFocusedIteration:+ """Tests for focused-iteration strategy and its special behaviors."""- with patch(- "local_deep_research.advanced_search_system.strategies.source_based_strategy.SourceBasedSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+ PATCH_PATH = (+ f"{_STRAT_BASE}.focused_iteration_strategy.FocusedIterationStrategy"+ )- from local_deep_research.search_system_factory import (- create_strategy,+ @pytest.mark.parametrize("name", ["focused-iteration", "focused_iteration"])+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_value++ def test_knowledge_limit_zero_converts_to_none(+ self, mock_model, mock_search+ ):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="focused-iteration",+ model=mock_model,+ search=mock_search,+ knowledge_summary_limit=0,+ )+ kw = cls.call_args[1]+ assert kw["knowledge_summary_limit"] is None++ def test_snippet_truncate_zero_converts_to_none(+ self, mock_model, mock_search+ ):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="focused-iteration",+ model=mock_model,+ search=mock_search,+ knowledge_snippet_truncate=0,+ )+ kw = cls.call_args[1]+ assert kw["knowledge_snippet_truncate"] is None++ def test_prompt_knowledge_truncate_zero_converts_to_none(+ self, mock_model, mock_search+ ):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="focused-iteration",+ model=mock_model,+ search=mock_search,+ prompt_knowledge_truncate=0,+ )+ kw = cls.call_args[1]+ assert kw["prompt_knowledge_truncate"] is None++ def test_previous_searches_limit_zero_converts_to_none(+ self, mock_model, mock_search+ ):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="focused-iteration",+ model=mock_model,+ search=mock_search,+ previous_searches_limit=0,)+ kw = cls.call_args[1]+ assert kw["previous_searches_limit"] is None+ def test_nonzero_limits_stay_unchanged(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="source_based",+ strategy_name="focused-iteration",model=mock_model,search=mock_search,+ knowledge_summary_limit=5,+ knowledge_snippet_truncate=200,)+ kw = cls.call_args[1]+ assert kw["knowledge_summary_limit"] == 5+ assert kw["knowledge_snippet_truncate"] == 200++ def test_flexible_question_generator_overrides(+ self, mock_model, mock_search+ ):+ flex_gen_path = "local_deep_research.advanced_search_system.questions.flexible_browsecomp_question.FlexibleBrowseCompQuestionGenerator"+ with patch(self.PATCH_PATH) as cls, patch(flex_gen_path) as flex_cls:+ strategy_instance = Mock()+ cls.return_value = strategy_instance+ flex_cls.return_value = Mock()- mock_strategy_class.assert_called_once()+ create_strategy(+ strategy_name="focused-iteration",+ model=mock_model,+ search=mock_search,+ question_generator="flexible",+ )- def test_create_source_based_passes_parameters(self):- """Test source-based strategy receives correct parameters."""- mock_model = Mock()- mock_search = Mock()+ flex_cls.assert_called_once()+ # The generator is assigned to the strategy's question_generator+ assert strategy_instance.question_generator == flex_cls.return_value- with patch(- "local_deep_research.advanced_search_system.strategies.source_based_strategy.SourceBasedSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+ def test_non_flexible_generator_does_not_override(+ self, mock_model, mock_search+ ):+ flex_gen_path = "local_deep_research.advanced_search_system.questions.flexible_browsecomp_question.FlexibleBrowseCompQuestionGenerator"+ with patch(self.PATCH_PATH) as cls, patch(flex_gen_path) as flex_cls:+ strategy_instance = Mock()+ cls.return_value = strategy_instance- from local_deep_research.search_system_factory import (- create_strategy,+ create_strategy(+ strategy_name="focused-iteration",+ model=mock_model,+ search=mock_search,+ question_generator="browsecomp",)+ flex_cls.assert_not_called()++ def test_settings_snapshot_read_for_focused_iteration(+ self, mock_model, mock_search+ ):+ settings = {+ "focused_iteration.adaptive_questions": 1,+ "focused_iteration.knowledge_summary_limit": 20,+ "focused_iteration.snippet_truncate": 300,+ }+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="source-based",+ strategy_name="focused-iteration",model=mock_model,search=mock_search,- include_text_content=False,- use_cross_engine_filter=False,+ settings_snapshot=settings,)+ kw = cls.call_args[1]+ assert kw["enable_adaptive_questions"] is True+ assert kw["knowledge_summary_limit"] == 20+ assert kw["knowledge_snippet_truncate"] == 300- call_kwargs = mock_strategy_class.call_args[1]- assert call_kwargs["include_text_content"] is False- assert call_kwargs["use_cross_engine_filter"] is False-+ def test_kwargs_override_settings_snapshot(self, mock_model, mock_search):+ settings = {+ "focused_iteration.knowledge_summary_limit": 20,+ }+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="focused-iteration",+ model=mock_model,+ search=mock_search,+ settings_snapshot=settings,+ knowledge_summary_limit=99,+ )+ kw = cls.call_args[1]+ assert kw["knowledge_summary_limit"] == 99-class TestCreateStrategyStandard:- """Tests for create_strategy with standard strategy."""- def test_create_standard_strategy(self):- """Test creating standard strategy."""- mock_model = Mock()- mock_search = Mock()+class TestCreateStrategyFocusedIterationStandard:+ """Tests for focused-iteration-standard (with standard citation handler)."""- with patch(- "local_deep_research.advanced_search_system.strategies.standard_strategy.StandardSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+ PATCH_PATH = (+ f"{_STRAT_BASE}.focused_iteration_strategy.FocusedIterationStrategy"+ )+ CITATION_PATH = "local_deep_research.citation_handler.CitationHandler"- from local_deep_research.search_system_factory import (- create_strategy,+ @pytest.mark.parametrize(+ "name",+ ["focused-iteration-standard", "focused_iteration_standard"],+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls, patch(self.CITATION_PATH):+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search)-+ cls.assert_called_once()+ assert result == cls.return_value++ def test_citation_handler_created_with_standard_type(+ self, mock_model, mock_search+ ):+ with (+ patch(self.PATCH_PATH) as cls,+ patch(self.CITATION_PATH) as cite_cls,+ ):+ cls.return_value = Mock()create_strategy(- strategy_name="standard",+ strategy_name="focused-iteration-standard",model=mock_model,search=mock_search,)+ cite_cls.assert_called_once()+ cite_kw = cite_cls.call_args+ assert cite_kw[1]["handler_type"] == "standard"+++class TestCreateStrategyIterativeReasoning:+ """Tests for iterative-reasoning strategy."""++ PATCH_PATH = (+ f"{_STRAT_BASE}.iterative_reasoning_strategy.IterativeReasoningStrategy"+ )++ @pytest.mark.parametrize(+ "name",+ [+ "iterative-reasoning",+ "iterative_reasoning",+ "iterative_reasoning_depth",+ ],+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_value- mock_strategy_class.assert_called_once()+class TestCreateStrategyNews:+ """Tests for news strategy."""-class TestCreateStrategyIterdrag:- """Tests for create_strategy with iterdrag strategy."""+ PATCH_PATH = f"{_STRAT_BASE}.news_strategy.NewsAggregationStrategy"- def test_create_iterdrag_strategy(self):- """Test creating iterdrag strategy."""- mock_model = Mock()- mock_search = Mock()+ @pytest.mark.parametrize(+ "name", ["news", "news_aggregation", "news-aggregation"]+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_value- with patch(- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.IterDRAGStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy- from local_deep_research.search_system_factory import (- create_strategy,+class TestCreateStrategyIterDRAG:+ """Tests for iterdrag strategy."""++ PATCH_PATH = f"{_STRAT_BASE}.iterdrag_strategy.IterDRAGStrategy"++ def test_create_iterdrag(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="iterdrag",+ model=mock_model,+ search=mock_search,)+ cls.assert_called_once()+ assert result == cls.return_value+ def test_settings_snapshot_forwarded(self, mock_model, mock_search):+ snapshot = {"key": "val"}+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()create_strategy(strategy_name="iterdrag",model=mock_model,search=mock_search,+ settings_snapshot=snapshot,)+ kw = cls.call_args[1]+ assert kw["settings_snapshot"] is snapshot- mock_strategy_class.assert_called_once()+class TestCreateStrategyParallel:+ """Tests for parallel strategy."""-class TestCreateStrategyEvidence:- """Tests for create_strategy with evidence-based strategy."""-- def test_create_evidence_strategy(self):- """Test creating evidence strategy."""- mock_model = Mock()- mock_search = Mock()-- with patch(- "local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+ PATCH_PATH = (+ f"{_STRAT_BASE}.parallel_search_strategy.ParallelSearchStrategy"+ )- from local_deep_research.search_system_factory import (- create_strategy,+ def test_create_parallel(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="parallel",+ model=mock_model,+ search=mock_search,)+ cls.assert_called_once()+ assert result == cls.return_value+ def test_kwargs_passed_through(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="evidence",+ strategy_name="parallel",model=mock_model,search=mock_search,+ include_text_content=False,+ use_cross_engine_filter=False,)+ kw = cls.call_args[1]+ assert kw["include_text_content"] is False+ assert kw["use_cross_engine_filter"] is False- mock_strategy_class.assert_called_once()+class TestCreateStrategyRapid:+ """Tests for rapid strategy."""-class TestCreateStrategyConstraint:- """Tests for create_strategy with constraint-based strategies."""+ PATCH_PATH = f"{_STRAT_BASE}.rapid_search_strategy.RapidSearchStrategy"- def test_create_constrained_strategy(self):- """Test creating constrained strategy."""- mock_model = Mock()- mock_search = Mock()+ def test_create_rapid(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="rapid",+ model=mock_model,+ search=mock_search,+ )+ cls.assert_called_once()+ assert result == cls.return_value- with patch(- "local_deep_research.advanced_search_system.strategies.constrained_search_strategy.ConstrainedSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy- from local_deep_research.search_system_factory import (- create_strategy,+class TestCreateStrategyRecursive:+ """Tests for recursive strategy."""++ PATCH_PATH = f"{_STRAT_BASE}.recursive_decomposition_strategy.RecursiveDecompositionStrategy"++ @pytest.mark.parametrize("name", ["recursive", "recursive-decomposition"])+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search)+ cls.assert_called_once()+ assert result == cls.return_value+++class TestCreateStrategyIterative:+ """Tests for 'iterative' strategy (distinct from iterative-reasoning)."""++ PATCH_PATH = (+ f"{_STRAT_BASE}.iterative_reasoning_strategy.IterativeReasoningStrategy"+ )+ def test_create_iterative(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="iterative",+ model=mock_model,+ search=mock_search,+ )+ cls.assert_called_once()+ assert result == cls.return_value++ def test_iterative_passes_extra_kwargs(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="constrained",+ strategy_name="iterative",model=mock_model,search=mock_search,+ max_iterations=10,+ questions_per_iteration=5,+ confidence_threshold=0.8,+ search_iterations_per_round=2,)+ kw = cls.call_args[1]+ assert kw["max_iterations"] == 10+ assert kw["questions_per_search"] == 5+ assert kw["confidence_threshold"] == 0.8+ assert kw["search_iterations_per_round"] == 2- mock_strategy_class.assert_called_once()- def test_create_parallel_constrained_strategy(self):- """Test creating parallel-constrained strategy."""- mock_model = Mock()- mock_search = Mock()+class TestCreateStrategyAdaptive:+ """Tests for adaptive strategy."""- with patch(- "local_deep_research.advanced_search_system.strategies.parallel_constrained_strategy.ParallelConstrainedStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+ PATCH_PATH = f"{_STRAT_BASE}.adaptive_decomposition_strategy.AdaptiveDecompositionStrategy"- from local_deep_research.search_system_factory import (- create_strategy,+ def test_create_adaptive(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="adaptive",+ model=mock_model,+ search=mock_search,)-+ cls.assert_called_once()+ assert result == cls.return_value++ def test_adaptive_default_max_steps_from_max_iterations(+ self, mock_model, mock_search+ ):+ """max_steps falls back to max_iterations kwarg."""+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="parallel-constrained",+ strategy_name="adaptive",model=mock_model,search=mock_search,+ max_iterations=12,)+ kw = cls.call_args[1]+ assert kw["max_steps"] == 12- mock_strategy_class.assert_called_once()+class TestCreateStrategySmart:+ """Tests for smart strategy."""-class TestCreateStrategyDualConfidence:- """Tests for create_strategy with dual-confidence strategies."""+ PATCH_PATH = (+ f"{_STRAT_BASE}.smart_decomposition_strategy.SmartDecompositionStrategy"+ )- def test_create_dual_confidence_strategy(self):- """Test creating dual-confidence strategy."""- mock_model = Mock()- mock_search = Mock()+ def test_create_smart(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="smart",+ model=mock_model,+ search=mock_search,+ )+ cls.assert_called_once()+ assert result == cls.return_value- with patch(- "local_deep_research.advanced_search_system.strategies.dual_confidence_strategy.DualConfidenceStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy- from local_deep_research.search_system_factory import (- create_strategy,- )+class TestCreateStrategyBrowsecomp:+ """Tests for browsecomp strategy."""- create_strategy(- strategy_name="dual-confidence",+ PATCH_PATH = f"{_STRAT_BASE}.browsecomp_optimized_strategy.BrowseCompOptimizedStrategy"++ def test_create_browsecomp(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="browsecomp",model=mock_model,search=mock_search,)+ cls.assert_called_once()+ assert result == cls.return_value- mock_strategy_class.assert_called_once()- def test_create_concurrent_dual_confidence(self):- """Test creating concurrent-dual-confidence strategy."""- mock_model = Mock()- mock_search = Mock()+class TestCreateStrategyEvidence:+ """Tests for evidence strategy."""- with patch(- "local_deep_research.advanced_search_system.strategies.concurrent_dual_confidence_strategy.ConcurrentDualConfidenceStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+ PATCH_PATH = f"{_STRAT_BASE}.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"- from local_deep_research.search_system_factory import (- create_strategy,+ def test_create_evidence(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="evidence",+ model=mock_model,+ search=mock_search,)+ cls.assert_called_once()+ assert result == cls.return_value+ def test_evidence_kwargs(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="concurrent-dual-confidence",+ strategy_name="evidence",model=mock_model,search=mock_search,+ candidate_limit=50,+ enable_pattern_learning=False,)+ kw = cls.call_args[1]+ assert kw["candidate_limit"] == 50+ assert kw["enable_pattern_learning"] is False- mock_strategy_class.assert_called_once()+class TestCreateStrategyConstrained:+ """Tests for constrained strategy."""-class TestCreateStrategyBrowsecomp:- """Tests for create_strategy with browsecomp-optimized strategy."""+ PATCH_PATH = (+ f"{_STRAT_BASE}.constrained_search_strategy.ConstrainedSearchStrategy"+ )++ def test_create_constrained(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="constrained",+ model=mock_model,+ search=mock_search,+ )+ cls.assert_called_once()+ assert result == cls.return_value- def test_create_browsecomp_strategy(self):- """Test creating browsecomp-optimized strategy."""- mock_model = Mock()- mock_search = Mock()- with patch(- "local_deep_research.advanced_search_system.strategies.browsecomp_optimized_strategy.BrowseCompOptimizedStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+class TestCreateStrategyStandard:+ """Tests for standard strategy."""- from local_deep_research.search_system_factory import (- create_strategy,+ PATCH_PATH = f"{_STRAT_BASE}.standard_strategy.StandardSearchStrategy"++ def test_create_standard(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="standard",+ model=mock_model,+ search=mock_search,)+ cls.assert_called_once()+ assert result == cls.return_value+ def test_settings_snapshot_forwarded(self, mock_model, mock_search):+ snapshot = {"foo": "bar"}+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="browsecomp",+ strategy_name="standard",model=mock_model,search=mock_search,+ settings_snapshot=snapshot,)+ kw = cls.call_args[1]+ assert kw["settings_snapshot"] is snapshot- mock_strategy_class.assert_called_once()+class TestCreateStrategyIterativeRefinement:+ """Tests for iterative-refinement strategy (recursive create_strategy)."""-class TestCreateStrategyNews:- """Tests for create_strategy with news strategy."""-- def test_create_news_strategy(self):- """Test creating news strategy."""- mock_model = Mock()- mock_search = Mock()+ PATCH_PATH = f"{_STRAT_BASE}.iterative_refinement_strategy.IterativeRefinementStrategy"+ SOURCE_PATCH = (+ f"{_STRAT_BASE}.source_based_strategy.SourceBasedSearchStrategy"+ )- with patch(- "local_deep_research.advanced_search_system.strategies.news_strategy.NewsAggregationStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+ @pytest.mark.parametrize(+ "name", ["iterative-refinement", "iterative_refinement"]+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls, patch(self.SOURCE_PATCH):+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_value++ def test_recursive_call_creates_initial_strategy(+ self, mock_model, mock_search+ ):+ """The factory recursively calls create_strategy for the initial_strategy."""+ with (+ patch(self.PATCH_PATH) as ref_cls,+ patch(self.SOURCE_PATCH) as src_cls,+ ):+ initial_mock = Mock(name="initial_strategy")+ src_cls.return_value = initial_mock+ ref_cls.return_value = Mock(name="refinement_strategy")- from local_deep_research.search_system_factory import (- create_strategy,+ create_strategy(+ strategy_name="iterative-refinement",+ model=mock_model,+ search=mock_search,)+ # Source-based strategy was created for the initial strategy+ src_cls.assert_called_once()+ # The refinement strategy got the initial strategy as a param+ ref_kw = ref_cls.call_args[1]+ assert ref_kw["initial_strategy"] is initial_mock++ def test_custom_initial_strategy(self, mock_model, mock_search):+ """Uses a custom initial_strategy name via kwargs."""+ rapid_path = f"{_STRAT_BASE}.rapid_search_strategy.RapidSearchStrategy"+ with patch(self.PATCH_PATH) as ref_cls, patch(rapid_path) as rapid_cls:+ rapid_cls.return_value = Mock(name="rapid_initial")+ ref_cls.return_value = Mock()+create_strategy(- strategy_name="news",+ strategy_name="iterative-refinement",model=mock_model,search=mock_search,+ initial_strategy="rapid",)- mock_strategy_class.assert_called_once()+ rapid_cls.assert_called_once()+ ref_kw = ref_cls.call_args[1]+ assert ref_kw["initial_strategy"] is rapid_cls.return_value-class TestCreateStrategyFocusedIteration:- """Tests for create_strategy with focused-iteration strategy."""+# ===========================================================================+# Case-insensitivity tests+# ===========================================================================- def test_create_focused_iteration_strategy(self):- """Test creating focused-iteration strategy."""- mock_model = Mock()- mock_search = Mock()- with patch(- "local_deep_research.advanced_search_system.strategies.focused_iteration_strategy.FocusedIterationStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+class TestCaseInsensitivity:+ """Strategy name matching is case-insensitive via .lower()."""- from local_deep_research.search_system_factory import (- create_strategy,+ def test_uppercase_standard(self, mock_model, mock_search):+ with patch(+ f"{_STRAT_BASE}.standard_strategy.StandardSearchStrategy"+ ) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="STANDARD",+ model=mock_model,+ search=mock_search,)+ cls.assert_called_once()+ def test_mixed_case_source_based(self, mock_model, mock_search):+ with patch(+ f"{_STRAT_BASE}.source_based_strategy.SourceBasedSearchStrategy"+ ) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="focused-iteration",+ strategy_name="Source-Based",model=mock_model,search=mock_search,)+ cls.assert_called_once()- mock_strategy_class.assert_called_once()-- def test_focused_iteration_with_settings(self):- """Test focused-iteration strategy uses settings."""- mock_model = Mock()- mock_search = Mock()- settings = {- "focused_iteration.adaptive_questions": 1,- "focused_iteration.knowledge_summary_limit": 5,- }-+ def test_uppercase_news(self, mock_model, mock_search):with patch(- "local_deep_research.advanced_search_system.strategies.focused_iteration_strategy.FocusedIterationStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy-- from local_deep_research.search_system_factory import (- create_strategy,+ f"{_STRAT_BASE}.news_strategy.NewsAggregationStrategy"+ ) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="NEWS",+ model=mock_model,+ search=mock_search,)+ cls.assert_called_once()+ def test_mixed_case_focused_iteration(self, mock_model, mock_search):+ with patch(+ f"{_STRAT_BASE}.focused_iteration_strategy.FocusedIterationStrategy"+ ) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="focused-iteration",+ strategy_name="Focused-Iteration",model=mock_model,search=mock_search,- settings_snapshot=settings,)+ cls.assert_called_once()- call_kwargs = mock_strategy_class.call_args[1]- assert call_kwargs["enable_adaptive_questions"] is True+# ===========================================================================+# Unknown strategy fallback+# ===========================================================================-class TestCreateStrategyCaseInsensitive:- """Tests for strategy name case insensitivity."""- def test_strategy_name_lowercase(self):- """Test strategy name is case-insensitive."""- mock_model = Mock()- mock_search = Mock()+class TestUnknownStrategyFallback:+ """Unknown strategy names fall back to SourceBasedSearchStrategy."""- with patch(- "local_deep_research.advanced_search_system.strategies.standard_strategy.StandardSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+ PATCH_PATH = (+ f"{_STRAT_BASE}.source_based_strategy.SourceBasedSearchStrategy"+ )- from local_deep_research.search_system_factory import (- create_strategy,+ def test_unknown_strategy_falls_back_to_source_based(+ self, mock_model, mock_search+ ):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name="unknown-strategy-xyz",+ model=mock_model,+ search=mock_search,)-+ cls.assert_called_once()+ assert result == cls.return_value++ def test_unknown_strategy_logs_warning(self, mock_model, mock_search):+ with (+ patch(self.PATCH_PATH) as cls,+ patch(+ "local_deep_research.search_system_factory.logger"+ ) as mock_logger,+ ):+ cls.return_value = Mock()create_strategy(- strategy_name="STANDARD",+ strategy_name="unknown-strategy-xyz",model=mock_model,search=mock_search,)+ mock_logger.warning.assert_called_once()+ warning_msg = mock_logger.warning.call_args[0][0]+ assert "unknown-strategy-xyz" in warning_msg.lower()- mock_strategy_class.assert_called_once()-- def test_strategy_name_mixed_case(self):- """Test mixed case strategy name."""- mock_model = Mock()- mock_search = Mock()-- with patch(- "local_deep_research.advanced_search_system.strategies.standard_strategy.StandardSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy-- from local_deep_research.search_system_factory import (- create_strategy,+ def test_another_unknown_name(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="totally-made-up",+ model=mock_model,+ search=mock_search,)+ cls.assert_called_once()+ def test_fallback_uses_hardcoded_defaults(self, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()create_strategy(- strategy_name="Standard",+ strategy_name="nonexistent",model=mock_model,search=mock_search,)+ kw = cls.call_args[1]+ assert kw["include_text_content"] is True+ assert kw["use_cross_engine_filter"] is True+ assert kw["use_atomic_facts"] is False- mock_strategy_class.assert_called_once()+# ===========================================================================+# all_links_of_system handling+# ===========================================================================-class TestCreateStrategyWithAllLinks:- """Tests for create_strategy with all_links_of_system parameter."""- def test_create_strategy_with_empty_links(self):- """Test create_strategy with empty links."""- mock_model = Mock()- mock_search = Mock()+class TestAllLinksHandling:+ """Tests for all_links_of_system parameter normalization."""+ def test_none_becomes_empty_list(self, mock_model, mock_search):with patch(- "local_deep_research.advanced_search_system.strategies.standard_strategy.StandardSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy-- from local_deep_research.search_system_factory import (- create_strategy,+ f"{_STRAT_BASE}.standard_strategy.StandardSearchStrategy"+ ) as cls:+ cls.return_value = Mock()+ create_strategy(+ strategy_name="standard",+ model=mock_model,+ search=mock_search,+ all_links_of_system=None,)+ kw = cls.call_args[1]+ assert kw["all_links_of_system"] == []+ def test_existing_links_passed_through(self, mock_model, mock_search):+ links = [{"link": "http://a.com"}, {"link": "http://b.com"}]+ with patch(+ f"{_STRAT_BASE}.standard_strategy.StandardSearchStrategy"+ ) as cls:+ cls.return_value = Mock()create_strategy(strategy_name="standard",model=mock_model,search=mock_search,- all_links_of_system=[],+ all_links_of_system=links,)+ kw = cls.call_args[1]+ assert kw["all_links_of_system"] is links- call_kwargs = mock_strategy_class.call_args[1]- assert call_kwargs["all_links_of_system"] == []- def test_create_strategy_with_existing_links(self):- """Test create_strategy with existing links."""- mock_model = Mock()- mock_search = Mock()- links = [{"link": "url1"}, {"link": "url2"}]+# ===========================================================================+# Additional strategies to confirm correct class is used+# ===========================================================================- with patch(- "local_deep_research.advanced_search_system.strategies.standard_strategy.StandardSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy- from local_deep_research.search_system_factory import (- create_strategy,+class TestCreateStrategyParallelConstrained:+ """Tests for parallel-constrained strategy."""++ PATCH_PATH = f"{_STRAT_BASE}.parallel_constrained_strategy.ParallelConstrainedStrategy"++ @pytest.mark.parametrize(+ "name", ["parallel-constrained", "parallel_constrained"]+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search)+ cls.assert_called_once()+ assert result == cls.return_value- create_strategy(- strategy_name="standard",- model=mock_model,- search=mock_search,- all_links_of_system=links,++class TestCreateStrategyEarlyStopConstrained:+ """Tests for early-stop-constrained strategy."""++ PATCH_PATH = f"{_STRAT_BASE}.early_stop_constrained_strategy.EarlyStopConstrainedStrategy"++ @pytest.mark.parametrize(+ "name", ["early-stop-constrained", "early_stop_constrained"]+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search)+ cls.assert_called_once()+ assert result == cls.return_value- call_kwargs = mock_strategy_class.call_args[1]- assert call_kwargs["all_links_of_system"] == links- def test_create_strategy_none_links_becomes_empty_list(self):- """Test None links becomes empty list."""- mock_model = Mock()- mock_search = Mock()+class TestCreateStrategySmartQuery:+ """Tests for smart-query strategy."""- with patch(- "local_deep_research.advanced_search_system.strategies.standard_strategy.StandardSearchStrategy"- ) as mock_strategy_class:- mock_strategy = Mock()- mock_strategy_class.return_value = mock_strategy+ PATCH_PATH = f"{_STRAT_BASE}.smart_query_strategy.SmartQueryStrategy"- from local_deep_research.search_system_factory import (- create_strategy,+ @pytest.mark.parametrize("name", ["smart-query", "smart_query"])+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search)+ cls.assert_called_once()+ assert result == cls.return_value- create_strategy(- strategy_name="standard",- model=mock_model,- search=mock_search,- all_links_of_system=None,++class TestCreateStrategyDualConfidence:+ """Tests for dual-confidence strategy."""++ PATCH_PATH = (+ f"{_STRAT_BASE}.dual_confidence_strategy.DualConfidenceStrategy"+ )++ @pytest.mark.parametrize("name", ["dual-confidence", "dual_confidence"])+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_value+++class TestCreateStrategyDualConfidenceWithRejection:+ """Tests for dual-confidence-with-rejection strategy."""++ PATCH_PATH = f"{_STRAT_BASE}.dual_confidence_with_rejection.DualConfidenceWithRejectionStrategy"++ @pytest.mark.parametrize(+ "name",+ ["dual-confidence-with-rejection", "dual_confidence_with_rejection"],+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search)+ cls.assert_called_once()+ assert result == cls.return_value+- call_kwargs = mock_strategy_class.call_args[1]- assert call_kwargs["all_links_of_system"] == []+class TestCreateStrategyConcurrentDualConfidence:+ """Tests for concurrent-dual-confidence strategy."""++ PATCH_PATH = f"{_STRAT_BASE}.concurrent_dual_confidence_strategy.ConcurrentDualConfidenceStrategy"++ @pytest.mark.parametrize(+ "name",+ ["concurrent-dual-confidence", "concurrent_dual_confidence"],+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_value+++class TestCreateStrategyConstraintParallel:+ """Tests for constraint-parallel strategy."""++ PATCH_PATH = (+ f"{_STRAT_BASE}.constraint_parallel_strategy.ConstraintParallelStrategy"+ )++ @pytest.mark.parametrize(+ "name", ["constraint-parallel", "constraint_parallel"]+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_value+++class TestCreateStrategyModular:+ """Tests for modular strategy."""++ PATCH_PATH = f"{_STRAT_BASE}.modular_strategy.ModularStrategy"++ @pytest.mark.parametrize("name", ["modular", "modular-strategy"])+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_value+++class TestCreateStrategyModularParallel:+ """Tests for modular-parallel strategy."""++ PATCH_PATH = f"{_STRAT_BASE}.modular_strategy.ModularStrategy"++ @pytest.mark.parametrize("name", ["modular-parallel", "modular_parallel"])+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ kw = cls.call_args[1]+ assert kw["exploration_strategy"] == "parallel"+ assert result == cls.return_value+++class TestCreateStrategyBrowsecompEntity:+ """Tests for browsecomp-entity strategy."""++ PATCH_PATH = (+ f"{_STRAT_BASE}.browsecomp_entity_strategy.BrowseCompEntityStrategy"+ )++ @pytest.mark.parametrize("name", ["browsecomp-entity", "browsecomp_entity"])+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_value+++class TestCreateStrategyTopicOrganization:+ """Tests for topic-organization strategy."""++ PATCH_PATH = (+ f"{_STRAT_BASE}.topic_organization_strategy.TopicOrganizationStrategy"+ )++ @pytest.mark.parametrize(+ "name", ["topic-organization", "topic_organization", "topic"]+ )+ def test_name_variants(self, name, mock_model, mock_search):+ with patch(self.PATCH_PATH) as cls:+ cls.return_value = Mock()+ result = create_strategy(+ strategy_name=name, model=mock_model, search=mock_search+ )+ cls.assert_called_once()+ assert result == cls.return_valuediff --git a/tests/database/test_thread_metrics_writer.py b/tests/database/test_thread_metrics_writer.pynew file mode 100644index 0000000000..2fd64034ea--- /dev/null+++ b/tests/database/test_thread_metrics_writer.py@@ -0,0 +1,581 @@+"""Comprehensive tests for ThreadSafeMetricsWriter in database/thread_metrics.py."""++import threading+from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.database.thread_metrics import (+ ThreadSafeMetricsWriter,+ metrics_writer,+)+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def writer():+ """Return a fresh ThreadSafeMetricsWriter instance."""+ return ThreadSafeMetricsWriter()+++def writer_with_password(writer):+ """Return a writer that already has a password stored for 'testuser'."""+ writer.set_user_password("testuser", "testpass")+ return writer+++def mock_db_manager():+ """Patch db_manager and yield (mock_db_manager, mock_session)."""+ with patch(+ "local_deep_research.database.thread_metrics.db_manager"+ ) as mock_db:+ mock_session = MagicMock()+ mock_db.create_thread_safe_session_for_metrics.return_value = (+ mock_session+ )+ yield mock_db, mock_session+++# ===========================================================================+# set_user_password+# ===========================================================================+++class TestSetUserPassword:+ """Tests for ThreadSafeMetricsWriter.set_user_password."""++ def test_stores_password_in_thread_local(self, writer):+ """set_user_password stores the password under _thread_local.passwords."""+ writer.set_user_password("alice", "secret123")++ assert writer._thread_local.passwords["alice"] == "secret123"++ def test_creates_passwords_dict_if_not_exists(self, writer):+ """Passwords dict is lazily created on first call."""+ assert not hasattr(writer._thread_local, "passwords")++ writer.set_user_password("alice", "secret")++ assert hasattr(writer._thread_local, "passwords")+ assert isinstance(writer._thread_local.passwords, dict)++ def test_can_store_multiple_users(self, writer):+ """Multiple users can be stored simultaneously."""+ writer.set_user_password("alice", "pass_a")+ writer.set_user_password("bob", "pass_b")+ writer.set_user_password("charlie", "pass_c")++ assert writer._thread_local.passwords == {+ "alice": "pass_a",+ "bob": "pass_b",+ "charlie": "pass_c",+ }++ def test_overwrites_existing_password(self, writer):+ """Setting a password for the same user replaces the old value."""+ writer.set_user_password("alice", "old_password")+ writer.set_user_password("alice", "new_password")++ assert writer._thread_local.passwords["alice"] == "new_password"+ assert len(writer._thread_local.passwords) == 1+++# ===========================================================================+# get_session+# ===========================================================================+++class TestGetSession:+ """Tests for ThreadSafeMetricsWriter.get_session."""++ # --- error paths -------------------------------------------------------++ def test_raises_when_no_passwords_dict(self, writer):+ """Raises ValueError when passwords dict has never been created."""+ with pytest.raises(ValueError, match="No password set"):+ with writer.get_session("testuser"):+ pass++ def test_raises_when_password_not_found_for_user(self, writer):+ """Raises ValueError when the requested user has no stored password."""+ writer.set_user_password("other_user", "other_pass")++ with pytest.raises(ValueError, match="No password available"):+ with writer.get_session("missing_user"):+ pass++ def test_raises_when_username_none_and_no_flask_context(self, writer):+ """Raises ValueError when username=None and Flask context is absent."""+ writer.set_user_password("alice", "pass")++ # The real code does `from flask import session as flask_session`+ # inside the function body. A RuntimeError simulates no app context.+ with pytest.raises((ValueError, RuntimeError)):+ with writer.get_session(username=None):+ pass++ def test_raises_when_db_manager_returns_none_session(+ self, writer_with_password+ ):+ """Raises ValueError when db_manager returns None for the session."""+ with patch(+ "local_deep_research.database.thread_metrics.db_manager"+ ) as mock_db:+ mock_db.create_thread_safe_session_for_metrics.return_value = None++ with pytest.raises(ValueError, match="Failed to create session"):+ with writer_with_password.get_session("testuser"):+ pass++ # --- happy path --------------------------------------------------------++ def test_yields_session_on_success(+ self, writer_with_password, mock_db_manager+ ):+ """Successfully yields a session object when password is available."""+ _mock_db, mock_session = mock_db_manager++ with writer_with_password.get_session("testuser") as session:+ assert session is mock_session++ def test_creates_session_with_correct_args(+ self, writer_with_password, mock_db_manager+ ):+ """Passes correct username and password to db_manager."""+ mock_db, _mock_session = mock_db_manager++ with writer_with_password.get_session("testuser"):+ pass++ mock_db.create_thread_safe_session_for_metrics.assert_called_once_with(+ "testuser", "testpass"+ )++ def test_commits_session_on_success(+ self, writer_with_password, mock_db_manager+ ):+ """Session is committed when context manager exits normally."""+ _mock_db, mock_session = mock_db_manager++ with writer_with_password.get_session("testuser"):+ pass++ mock_session.commit.assert_called_once()+ mock_session.rollback.assert_not_called()++ def test_rollback_on_exception(self, writer_with_password, mock_db_manager):+ """Session is rolled back when an exception occurs inside the block."""+ _mock_db, mock_session = mock_db_manager++ with pytest.raises(RuntimeError, match="boom"):+ with writer_with_password.get_session("testuser"):+ raise RuntimeError("boom")++ mock_session.rollback.assert_called_once()+ mock_session.commit.assert_not_called()++ def test_closes_session_on_success(+ self, writer_with_password, mock_db_manager+ ):+ """Session is closed in the finally block after normal exit."""+ _mock_db, mock_session = mock_db_manager++ with writer_with_password.get_session("testuser"):+ pass++ mock_session.close.assert_called_once()++ def test_closes_session_on_exception(+ self, writer_with_password, mock_db_manager+ ):+ """Session is closed in the finally block even after an exception."""+ _mock_db, mock_session = mock_db_manager++ with pytest.raises(RuntimeError):+ with writer_with_password.get_session("testuser"):+ raise RuntimeError("failure")++ mock_session.close.assert_called_once()++ def test_closes_session_when_db_manager_returns_none(+ self, writer_with_password+ ):+ """When db_manager returns None, session is not closed (it is None)."""+ with patch(+ "local_deep_research.database.thread_metrics.db_manager"+ ) as mock_db:+ mock_db.create_thread_safe_session_for_metrics.return_value = None++ with pytest.raises(ValueError, match="Failed to create session"):+ with writer_with_password.get_session("testuser"):+ pass++ # session was None, so close should never be called on it+++# ===========================================================================+# write_token_metrics+# ===========================================================================+++class TestWriteTokenMetrics:+ """Tests for ThreadSafeMetricsWriter.write_token_metrics."""++ def _run_write(self, writer, mock_db_manager, token_data, research_id=42):+ """Helper: call write_token_metrics with mocked session and TokenUsage."""+ mock_db, mock_session = mock_db_manager+ mock_token_cls = MagicMock()++ with patch(+ "local_deep_research.database.models.TokenUsage",+ mock_token_cls,+ ):+ writer.write_token_metrics("testuser", research_id, token_data)++ return mock_token_cls, mock_session++ # --- field mapping -----------------------------------------------------++ def test_creates_token_usage_with_correct_fields(+ self, writer_with_password, mock_db_manager+ ):+ """TokenUsage is constructed with all expected fields from token_data."""+ token_data = {+ "model_name": "gpt-4",+ "provider": "openai",+ "prompt_tokens": 100,+ "completion_tokens": 50,+ "research_query": "test query",+ "research_mode": "deep",+ "research_phase": "search",+ "search_iteration": 2,+ "response_time_ms": 1234,+ "success_status": "success",+ "error_type": None,+ "search_engines_planned": ["google", "bing"],+ "search_engine_selected": "google",+ "calling_file": "main.py",+ "calling_function": "run_search",+ "call_stack": ["a", "b"],+ "context_limit": 4096,+ "context_truncated": True,+ "tokens_truncated": 500,+ "truncation_ratio": 0.12,+ "ollama_prompt_eval_count": 90,+ "ollama_eval_count": 45,+ "ollama_total_duration": 999999,+ "ollama_load_duration": 111111,+ "ollama_prompt_eval_duration": 222222,+ "ollama_eval_duration": 333333,+ }++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data, research_id=7+ )++ call_kwargs = mock_token_cls.call_args[1]++ assert call_kwargs["research_id"] == 7+ assert call_kwargs["model_name"] == "gpt-4"+ assert call_kwargs["model_provider"] == "openai"+ assert call_kwargs["prompt_tokens"] == 100+ assert call_kwargs["completion_tokens"] == 50+ assert call_kwargs["total_tokens"] == 150+ assert call_kwargs["research_query"] == "test query"+ assert call_kwargs["research_mode"] == "deep"+ assert call_kwargs["research_phase"] == "search"+ assert call_kwargs["search_iteration"] == 2+ assert call_kwargs["response_time_ms"] == 1234+ assert call_kwargs["success_status"] == "success"+ assert call_kwargs["error_type"] is None+ assert call_kwargs["search_engines_planned"] == ["google", "bing"]+ assert call_kwargs["search_engine_selected"] == "google"+ assert call_kwargs["calling_file"] == "main.py"+ assert call_kwargs["calling_function"] == "run_search"+ assert call_kwargs["call_stack"] == ["a", "b"]+ assert call_kwargs["context_limit"] == 4096+ assert call_kwargs["context_truncated"] is True+ assert call_kwargs["tokens_truncated"] == 500+ assert call_kwargs["truncation_ratio"] == 0.12+ assert call_kwargs["ollama_prompt_eval_count"] == 90+ assert call_kwargs["ollama_eval_count"] == 45+ assert call_kwargs["ollama_total_duration"] == 999999+ assert call_kwargs["ollama_load_duration"] == 111111+ assert call_kwargs["ollama_prompt_eval_duration"] == 222222+ assert call_kwargs["ollama_eval_duration"] == 333333++ def test_adds_record_to_session(+ self, writer_with_password, mock_db_manager+ ):+ """The TokenUsage record is added to the session via session.add()."""+ token_data = {+ "model_name": "gpt-4",+ "provider": "openai",+ "prompt_tokens": 10,+ "completion_tokens": 5,+ }++ mock_token_cls, mock_session = self._run_write(+ writer_with_password, mock_db_manager, token_data+ )++ mock_session.add.assert_called_once_with(mock_token_cls.return_value)++ def test_total_tokens_calculated_as_sum(+ self, writer_with_password, mock_db_manager+ ):+ """total_tokens equals prompt_tokens + completion_tokens."""+ token_data = {+ "prompt_tokens": 200,+ "completion_tokens": 75,+ }++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data+ )++ call_kwargs = mock_token_cls.call_args[1]+ assert call_kwargs["total_tokens"] == 275+ assert (+ call_kwargs["total_tokens"]+ == call_kwargs["prompt_tokens"] + call_kwargs["completion_tokens"]+ )++ # --- defaults ----------------------------------------------------------++ def test_default_prompt_tokens_zero(+ self, writer_with_password, mock_db_manager+ ):+ """prompt_tokens defaults to 0 when not provided."""+ token_data = {"completion_tokens": 30}++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data+ )++ call_kwargs = mock_token_cls.call_args[1]+ assert call_kwargs["prompt_tokens"] == 0++ def test_default_completion_tokens_zero(+ self, writer_with_password, mock_db_manager+ ):+ """completion_tokens defaults to 0 when not provided."""+ token_data = {"prompt_tokens": 50}++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data+ )++ call_kwargs = mock_token_cls.call_args[1]+ assert call_kwargs["completion_tokens"] == 0++ def test_default_success_status(+ self, writer_with_password, mock_db_manager+ ):+ """success_status defaults to 'success' when not provided."""+ token_data = {}++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data+ )++ call_kwargs = mock_token_cls.call_args[1]+ assert call_kwargs["success_status"] == "success"++ def test_default_context_truncated_false(+ self, writer_with_password, mock_db_manager+ ):+ """context_truncated defaults to False when not provided."""+ token_data = {}++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data+ )++ call_kwargs = mock_token_cls.call_args[1]+ assert call_kwargs["context_truncated"] is False++ def test_default_total_tokens_zero_when_both_missing(+ self, writer_with_password, mock_db_manager+ ):+ """total_tokens is 0 when both prompt_tokens and completion_tokens are absent."""+ token_data = {}++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data+ )++ call_kwargs = mock_token_cls.call_args[1]+ assert call_kwargs["total_tokens"] == 0++ # --- missing optional fields -------------------------------------------++ def test_missing_optional_fields_are_none(+ self, writer_with_password, mock_db_manager+ ):+ """Optional fields not present in token_data resolve to None via .get()."""+ token_data = {}++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data+ )++ call_kwargs = mock_token_cls.call_args[1]+ assert call_kwargs["model_name"] is None+ assert call_kwargs["model_provider"] is None+ assert call_kwargs["research_query"] is None+ assert call_kwargs["research_mode"] is None+ assert call_kwargs["research_phase"] is None+ assert call_kwargs["search_iteration"] is None+ assert call_kwargs["response_time_ms"] is None+ assert call_kwargs["error_type"] is None+ assert call_kwargs["search_engines_planned"] is None+ assert call_kwargs["search_engine_selected"] is None+ assert call_kwargs["calling_file"] is None+ assert call_kwargs["calling_function"] is None+ assert call_kwargs["call_stack"] is None+ assert call_kwargs["context_limit"] is None+ assert call_kwargs["tokens_truncated"] is None+ assert call_kwargs["truncation_ratio"] is None+ assert call_kwargs["ollama_prompt_eval_count"] is None+ assert call_kwargs["ollama_eval_count"] is None+ assert call_kwargs["ollama_total_duration"] is None+ assert call_kwargs["ollama_load_duration"] is None+ assert call_kwargs["ollama_prompt_eval_duration"] is None+ assert call_kwargs["ollama_eval_duration"] is None++ def test_research_id_passed_directly(+ self, writer_with_password, mock_db_manager+ ):+ """research_id comes from the function argument, not from token_data."""+ token_data = {"model_name": "test-model"}++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data, research_id=999+ )++ call_kwargs = mock_token_cls.call_args[1]+ assert call_kwargs["research_id"] == 999++ def test_research_id_none(self, writer_with_password, mock_db_manager):+ """research_id can be None."""+ token_data = {"model_name": "test-model"}++ mock_token_cls, _ = self._run_write(+ writer_with_password, mock_db_manager, token_data, research_id=None+ )++ call_kwargs = mock_token_cls.call_args[1]+ assert call_kwargs["research_id"] is None+++# ===========================================================================+# Global instance+# ===========================================================================+++class TestGlobalInstance:+ """Tests for the module-level metrics_writer singleton."""++ def test_metrics_writer_exists(self):+ """A global metrics_writer instance is importable."""+ assert metrics_writer is not None++ def test_metrics_writer_is_correct_type(self):+ """The global instance is a ThreadSafeMetricsWriter."""+ assert isinstance(metrics_writer, ThreadSafeMetricsWriter)++ def test_metrics_writer_has_thread_local(self):+ """The global instance has _thread_local attribute."""+ assert hasattr(metrics_writer, "_thread_local")+ assert isinstance(metrics_writer._thread_local, threading.local)+++# ===========================================================================+# Thread isolation+# ===========================================================================+++class TestThreadIsolation:+ """Verify that thread-local storage is genuinely isolated between threads."""++ def test_passwords_not_shared_across_threads(self, writer):+ """Password set in one thread is invisible in another thread."""+ results = {}++ def thread_a():+ writer.set_user_password("alice", "alice_pass")+ results["a_passwords"] = dict(writer._thread_local.passwords)++ def thread_b():+ # Wait for thread_a to finish writing+ import time++ time.sleep(0.05)+ results["b_has_passwords"] = hasattr(+ writer._thread_local, "passwords"+ )++ t_a = threading.Thread(target=thread_a)+ t_b = threading.Thread(target=thread_b)+ t_a.start()+ t_b.start()+ t_a.join()+ t_b.join()++ assert results["a_passwords"] == {"alice": "alice_pass"}+ assert results["b_has_passwords"] is False++ def test_each_thread_has_own_password_store(self, writer):+ """Two threads can independently store passwords without interference."""+ results = {}+ barrier = threading.Barrier(2)++ def thread_one():+ writer.set_user_password("user_one", "pass_one")+ barrier.wait()+ results["one"] = dict(writer._thread_local.passwords)++ def thread_two():+ writer.set_user_password("user_two", "pass_two")+ barrier.wait()+ results["two"] = dict(writer._thread_local.passwords)++ t1 = threading.Thread(target=thread_one)+ t2 = threading.Thread(target=thread_two)+ t1.start()+ t2.start()+ t1.join()+ t2.join()++ assert results["one"] == {"user_one": "pass_one"}+ assert results["two"] == {"user_two": "pass_two"}+ # Neither thread sees the other's password+ assert "user_two" not in results["one"]+ assert "user_one" not in results["two"]++ def test_get_session_fails_in_different_thread(self, writer):+ """get_session in a thread that hasn't called set_user_password raises."""+ writer.set_user_password("alice", "pass")++ errors = []++ def other_thread():+ try:+ with writer.get_session("alice"):+ pass+ except ValueError as e:+ errors.append(str(e))++ t = threading.Thread(target=other_thread)+ t.start()+ t.join()++ assert len(errors) == 1+ assert "No password set" in errors[0]