~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 10 coverage tests for thread_context.py (#2782)
LearningCircuit31c63bd43b39
diff --git a/tests/utilities/test_thread_context_coverage.py b/tests/utilities/test_thread_context_coverage.pynew file mode 100644index 0000000000..bfaf2140f1--- /dev/null+++ b/tests/utilities/test_thread_context_coverage.py@@ -0,0 +1,264 @@+"""Coverage tests for thread_context.py.++Focuses on untested paths:+- _get_search_tracker_if_needed: successful import+cache, cached return,+ ImportError, RuntimeError+- preserve_research_context: cleanup_current_thread called on success,+ cleanup_current_thread exception suppressed+"""++import sys+from types import ModuleType+from unittest.mock import MagicMock, patch++import pytest++import local_deep_research.utilities.thread_context as tc+from local_deep_research.utilities.thread_context import (+ _g_thread_data,+ clear_search_context,+ get_search_context,+ preserve_research_context,+ set_search_context,+)+++def _cleanup():+ """Remove any leftover context on the current thread."""+ if hasattr(_g_thread_data, "context"):+ del _g_thread_data.context+++# ---------------------------------------------------------------------------+# _get_search_tracker_if_needed+# ---------------------------------------------------------------------------+++class TestGetSearchTrackerIfNeeded:+ """Tests for _get_search_tracker_if_needed covering all branches."""++ def setup_method(self):+ tc._search_tracker = None+ sys.modules.pop("local_deep_research.metrics.search_tracker", None)++ def teardown_method(self):+ tc._search_tracker = None+ sys.modules.pop("local_deep_research.metrics.search_tracker", None)++ def test_successful_import_returns_tracker(self):+ """When the import succeeds, the tracker object is returned."""+ fake_tracker = MagicMock(name="FakeSearchTracker")++ fake_module = ModuleType("local_deep_research.metrics.search_tracker")+ fake_module.get_search_tracker = lambda: fake_tracker++ with patch.dict(+ sys.modules,+ {"local_deep_research.metrics.search_tracker": fake_module},+ ):+ result = tc._get_search_tracker_if_needed()++ assert result is fake_tracker+ assert tc._search_tracker is fake_tracker++ def test_cached_return_skips_import(self):+ """When _search_tracker is already set, the function returns it+ immediately without importing anything."""+ sentinel = object()+ tc._search_tracker = sentinel++ with patch.dict(+ sys.modules,+ {"local_deep_research.metrics.search_tracker": None},+ ):+ result = tc._get_search_tracker_if_needed()++ assert result is sentinel++ def test_import_error_returns_none(self):+ """When importing search_tracker raises ImportError, None is returned+ and the cache remains unset."""+ with patch.dict(+ sys.modules,+ {"local_deep_research.metrics.search_tracker": None},+ ):+ result = tc._get_search_tracker_if_needed()++ assert result is None+ assert tc._search_tracker is None++ def test_runtime_error_returns_none(self):+ """When get_search_tracker() raises RuntimeError, None is returned+ and the cache remains unset."""+ fake_module = ModuleType("local_deep_research.metrics.search_tracker")++ def boom():+ raise RuntimeError("database locked")++ fake_module.get_search_tracker = boom++ with patch.dict(+ sys.modules,+ {"local_deep_research.metrics.search_tracker": fake_module},+ ):+ result = tc._get_search_tracker_if_needed()++ assert result is None+ assert tc._search_tracker is None++ def test_import_error_logs_debug_message(self):+ """When import fails, a debug message is logged via loguru."""+ with patch.dict(+ sys.modules,+ {"local_deep_research.metrics.search_tracker": None},+ ):+ with patch("loguru.logger.debug") as mock_debug:+ tc._get_search_tracker_if_needed()+ mock_debug.assert_called_once()+ msg = str(mock_debug.call_args)+ assert (+ "not available" in msg.lower() or "disabled" in msg.lower()+ )+++# ---------------------------------------------------------------------------+# preserve_research_context — cleanup paths+# ---------------------------------------------------------------------------+++class TestPreserveResearchContextCleanup:+ """Tests for the cleanup logic inside preserve_research_context wrapper."""++ def setup_method(self):+ _cleanup()+ sys.modules.pop(+ "local_deep_research.database.thread_local_session", None+ )++ def teardown_method(self):+ _cleanup()+ sys.modules.pop(+ "local_deep_research.database.thread_local_session", None+ )++ def test_cleanup_current_thread_called_on_success(self):+ """When context is set and the function succeeds,+ cleanup_current_thread is called in the finally block."""+ set_search_context({"research_id": "cleanup-success"})++ @preserve_research_context+ def task():+ return 42++ clear_search_context()++ mock_cleanup_fn = MagicMock()+ fake_module = ModuleType(+ "local_deep_research.database.thread_local_session"+ )+ fake_module.cleanup_current_thread = mock_cleanup_fn++ with patch.dict(+ sys.modules,+ {+ "local_deep_research.database.thread_local_session": fake_module,+ },+ ):+ result = task()++ assert result == 42+ mock_cleanup_fn.assert_called_once()++ def test_cleanup_current_thread_called_on_exception(self):+ """When context is set and the function raises,+ cleanup_current_thread is still called in the finally block."""+ set_search_context({"research_id": "cleanup-exception"})++ @preserve_research_context+ def failing_task():+ raise ValueError("boom")++ clear_search_context()++ mock_cleanup_fn = MagicMock()+ fake_module = ModuleType(+ "local_deep_research.database.thread_local_session"+ )+ fake_module.cleanup_current_thread = mock_cleanup_fn++ with patch.dict(+ sys.modules,+ {+ "local_deep_research.database.thread_local_session": fake_module,+ },+ ):+ with pytest.raises(ValueError, match="boom"):+ failing_task()++ mock_cleanup_fn.assert_called_once()++ def test_cleanup_exception_is_suppressed(self):+ """If cleanup_current_thread raises, the exception is suppressed+ and does not propagate to the caller."""+ set_search_context({"research_id": "cleanup-suppressed"})++ @preserve_research_context+ def task():+ return "ok"++ clear_search_context()++ fake_module = ModuleType(+ "local_deep_research.database.thread_local_session"+ )+ fake_module.cleanup_current_thread = MagicMock(+ side_effect=RuntimeError("db engine error")+ )++ with patch.dict(+ sys.modules,+ {+ "local_deep_research.database.thread_local_session": fake_module,+ },+ ):+ result = task()++ assert result == "ok"+ assert get_search_context() is None++ def test_cleanup_import_failure_is_suppressed(self):+ """If importing thread_local_session itself fails, the exception+ is suppressed (caught by the bare except)."""+ set_search_context({"research_id": "import-fail"})++ @preserve_research_context+ def task():+ return "fine"++ clear_search_context()++ with patch.dict(+ sys.modules,+ {"local_deep_research.database.thread_local_session": None},+ ):+ result = task()++ assert result == "fine"+ assert get_search_context() is None++ def test_no_cleanup_when_no_context(self):+ """When no context was captured at decoration time, the cleanup+ block is never entered (context is None branch)."""+ assert get_search_context() is None++ @preserve_research_context+ def task():+ return "no-context"++ with patch.dict(+ sys.modules,+ {"local_deep_research.database.thread_local_session": None},+ ):+ result = task()++ assert result == "no-context"