Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

test: add 20 branch-coverage tests for loader/auth/mcp/playwright guards (#3509)

LearningCircuitd69b85711ec0
diff --git a/tests/document_loaders/test_loader_registry_import_guards.py b/tests/document_loaders/test_loader_registry_import_guards.py
new file mode 100644
index 0000000000..a702d3e6d3
--- /dev/null
+++ b/tests/document_loaders/test_loader_registry_import_guards.py
@@ -0,0 +1,108 @@
+"""
+Import-guard tests for loader_registry module.
+
+Covers the ImportError branches on optional loader imports (lines 36-38,
+44-46, 52-54, 60-62, 68-70, 78-80 in loader_registry.py) and the conditional
+registry-population branches they gate (148->155, 165->172, 172->179,
+185->192, 192->199, 227->235).
+
+Existing tests in test_loader_registry_full_coverage.py only assert
+consistency between the HAS_* flags and the registry given whatever the
+current environment happens to have installed; they never force the
+ImportError path. This file simulates the missing-optional-dep case by
+reloading the module with a patched import hook.
+"""
+
+import builtins
+import importlib
+from unittest.mock import patch
+
+import pytest
+
+MODULE_NAME = "local_deep_research.document_loaders.loader_registry"
+
+
+def _reload_with_blocked_symbol(blocked_name):
+ """Reload loader_registry while raising ImportError for a specific symbol.
+
+ Only raises for `from langchain_community.document_loaders import <blocked_name>`
+ where the fromlist is exactly a single-item tuple matching blocked_name.
+ Leaves the bulk import at the top of loader_registry (16-item fromlist)
+ untouched.
+ """
+ original_import = builtins.__import__
+
+ def fake_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if (
+ name == "langchain_community.document_loaders"
+ and fromlist is not None
+ and len(fromlist) == 1
+ and fromlist[0] == blocked_name
+ ):
+ raise ImportError(f"simulated ImportError for {blocked_name}")
+ return original_import(name, globals, locals, fromlist, level)
+
+ module = importlib.import_module(MODULE_NAME)
+ with patch.object(builtins, "__import__", side_effect=fake_import):
+ return importlib.reload(module)
+
+
+def restore_module():
+ """Restore loader_registry to its natural import state after each test.
+
+ The tests in this file force ImportError on specific loader imports
+ via module reload. Without this fixture, a reload-with-patched-import
+ would persist into later tests and leave the module in a degraded state.
+ """
+ yield
+ module = importlib.import_module(MODULE_NAME)
+ importlib.reload(module)
+
+
+class TestOptionalLoaderImportErrors:
+ """When each optional loader import fails, its flag goes False and the
+ corresponding extensions are absent from the registry."""
+
+ def test_odt_importerror_disables_flag_and_registry_entry(
+ self, restore_module
+ ):
+ reloaded = _reload_with_blocked_symbol("UnstructuredODTLoader")
+ assert reloaded.HAS_ODT_LOADER is False
+ assert ".odt" not in reloaded.LOADER_REGISTRY
+
+ def test_epub_importerror_disables_flag_and_registry_entry(
+ self, restore_module
+ ):
+ reloaded = _reload_with_blocked_symbol("UnstructuredEPubLoader")
+ assert reloaded.HAS_EPUB_LOADER is False
+ assert ".epub" not in reloaded.LOADER_REGISTRY
+
+ def test_rtf_importerror_disables_flag_and_registry_entry(
+ self, restore_module
+ ):
+ reloaded = _reload_with_blocked_symbol("UnstructuredRTFLoader")
+ assert reloaded.HAS_RTF_LOADER is False
+ assert ".rtf" not in reloaded.LOADER_REGISTRY
+
+ def test_rst_importerror_disables_flag_and_registry_entry(
+ self, restore_module
+ ):
+ reloaded = _reload_with_blocked_symbol("UnstructuredRSTLoader")
+ assert reloaded.HAS_RST_LOADER is False
+ assert ".rst" not in reloaded.LOADER_REGISTRY
+
+ def test_org_importerror_disables_flag_and_registry_entry(
+ self, restore_module
+ ):
+ reloaded = _reload_with_blocked_symbol("UnstructuredOrgModeLoader")
+ assert reloaded.HAS_ORG_LOADER is False
+ assert ".org" not in reloaded.LOADER_REGISTRY
+
+ def test_image_importerror_disables_flag_and_all_image_extensions(
+ self, restore_module
+ ):
+ reloaded = _reload_with_blocked_symbol("UnstructuredImageLoader")
+ assert reloaded.HAS_IMAGE_LOADER is False
+ for ext in (".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".heic"):
+ assert ext not in reloaded.LOADER_REGISTRY
diff --git a/tests/mcp/test_mcp_client_gaps.py b/tests/mcp/test_mcp_client_gaps.py
new file mode 100644
index 0000000000..2ef4e24df5
--- /dev/null
+++ b/tests/mcp/test_mcp_client_gaps.py
@@ -0,0 +1,109 @@
+"""
+Branch-coverage gap tests for mcp/client.py.
+
+Targets uncovered paths that existing tests miss:
+- Init retry loop exhausting on asyncio.TimeoutError → MCPClientError with
+ "Timeout initializing" (lines 224-228)
+- Init retry loop exhausting on an exception whose message contains
+ "before initialization" → MCPClientError (lines 231-236)
+- call_tool with a non-iterable, non-None content value — goes through the
+ elif branch at line 325-327 and stringifies the value. The existing
+ test_mcp_call_tool_parsing.py tests a LOCAL copy of this logic; this
+ exercises the real MCPClient.call_tool().
+"""
+
+import asyncio
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+MODULE = "local_deep_research.mcp.client"
+
+
+def _mcp_available():
+ try:
+ import mcp # noqa: F401
+
+ return True
+ except ImportError:
+ return False
+
+
+pytestmark = pytest.mark.skipif(
+ not _mcp_available(),
+ reason="mcp package not installed",
+)
+
+
+def _valid_config(command="python", name="test-server"):
+ return {"command": command, "args": ["server.py"], "name": name}
+
+
+def _make_client():
+ from local_deep_research.mcp.client import MCPClient
+
+ return MCPClient(_valid_config())
+
+
+def _make_connected_client():
+ client = _make_client()
+ client._connected = True
+ client._session = MagicMock()
+ return client
+
+
+class TestInitializeWithRetry:
+ """Retry loop exhaustion paths for _initialize_with_retry."""
+
+ @patch(f"{MODULE}.INIT_RETRY_ATTEMPTS", 2)
+ @patch(f"{MODULE}.INIT_RETRY_BASE_DELAY", 0.01)
+ @patch(f"{MODULE}.INIT_RETRY_MAX_DELAY", 0.01)
+ def test_timeout_exhaustion_raises_mcp_timeout_error(self):
+ from local_deep_research.mcp.client import MCPClientError
+
+ client = _make_client()
+ client._session = MagicMock()
+ client._session.initialize = AsyncMock(
+ side_effect=asyncio.TimeoutError()
+ )
+ client.timeout = 0.1
+
+ with pytest.raises(MCPClientError, match="Timeout initializing"):
+ asyncio.run(client._initialize_with_retry())
+
+ @patch(f"{MODULE}.INIT_RETRY_ATTEMPTS", 2)
+ @patch(f"{MODULE}.INIT_RETRY_BASE_DELAY", 0.01)
+ @patch(f"{MODULE}.INIT_RETRY_MAX_DELAY", 0.01)
+ def test_before_initialization_exhaustion_raises_mcp_client_error(self):
+ from local_deep_research.mcp.client import MCPClientError
+
+ client = _make_client()
+ client._session = MagicMock()
+ client._session.initialize = AsyncMock(
+ side_effect=RuntimeError(
+ "Received request before initialization was complete"
+ )
+ )
+ client.timeout = 0.1
+
+ with pytest.raises(MCPClientError, match="Failed to initialize"):
+ asyncio.run(client._initialize_with_retry())
+
+
+class TestCallToolNonIterableContent:
+ """call_tool stringifies non-None content that lacks __iter__."""
+
+ def test_integer_content_stringified(self):
+ client = _make_connected_client()
+
+ mock_result = MagicMock()
+ mock_result.isError = False
+ # Plain int — not None, no __iter__ — must hit the elif branch.
+ mock_result.content = 42
+ client._session.call_tool = AsyncMock(return_value=mock_result)
+
+ result = asyncio.run(client.call_tool("numeric_tool"))
+
+ assert result["status"] == "success"
+ assert result["content"] == "42"
+ assert result["raw"] == 42
diff --git a/tests/research_library/downloaders/test_playwright_html_guards.py b/tests/research_library/downloaders/test_playwright_html_guards.py
new file mode 100644
index 0000000000..d3f2fb5814
--- /dev/null
+++ b/tests/research_library/downloaders/test_playwright_html_guards.py
@@ -0,0 +1,98 @@
+"""
+Guard-path tests for playwright_html that don't require a real browser.
+
+Targets pure-logic branches in
+src/local_deep_research/research_library/downloaders/playwright_html.py:
+- Lines 57-62: _run_async ThreadPoolExecutor fallback when an event loop
+ is already running.
+- Lines 117-119: Crawl4AI ImportError path in _fetch_with_crawl4ai.
+- Lines 267-269: playwright ImportError path in _fetch_with_playwright.
+
+The existing test_playwright_html.py covers inheritance and SPA-signal
+detection but not these ImportError / event-loop fallback guards.
+"""
+
+import asyncio
+import builtins
+from unittest.mock import MagicMock, patch
+
+
+from local_deep_research.research_library.downloaders.playwright_html import (
+ PlaywrightHTMLDownloader,
+ _run_async,
+)
+
+
+class TestRunAsyncEventLoopHandling:
+ """_run_async detects whether an event loop is already running and
+ chooses between asyncio.run() and a ThreadPoolExecutor fallback."""
+
+ def test_no_running_loop_uses_asyncio_run(self):
+ async def make_value():
+ return 7
+
+ # Called from plain sync code — no running loop — takes the
+ # asyncio.run() branch.
+ result = _run_async(make_value())
+ assert result == 7
+
+ def test_fallback_via_threadpool_inside_active_loop(self):
+ async def make_value():
+ await asyncio.sleep(0)
+ return 42
+
+ async def driver():
+ # Inside a running loop: _run_async must spawn a thread that
+ # calls asyncio.run on its own loop.
+ return _run_async(make_value(), timeout=5)
+
+ result = asyncio.run(driver())
+ assert result == 42
+
+
+def _import_blocker(blocked_prefix):
+ """Return a fake __import__ that raises ImportError for blocked_prefix."""
+ original_import = builtins.__import__
+
+ def fake_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if name == blocked_prefix or name.startswith(f"{blocked_prefix}."):
+ raise ImportError(f"simulated: {blocked_prefix} not installed")
+ return original_import(name, globals, locals, fromlist, level)
+
+ return fake_import
+
+
+class TestCrawl4aiImportErrorGuard:
+ """When crawl4ai is not installed, _fetch_with_crawl4ai returns None."""
+
+ def test_returns_none_when_crawl4ai_missing(self):
+ dl = PlaywrightHTMLDownloader(timeout=5)
+ try:
+ with patch.object(
+ builtins, "__import__", side_effect=_import_blocker("crawl4ai")
+ ):
+ result = dl._fetch_with_crawl4ai("https://example.com")
+ assert result is None
+ finally:
+ dl.close()
+
+
+class TestPlaywrightImportErrorGuard:
+ """When playwright is not installed, _fetch_with_playwright returns None
+ and logs a warning rather than raising."""
+
+ def test_returns_none_when_playwright_missing(self):
+ dl = PlaywrightHTMLDownloader(timeout=5)
+ try:
+ # Mock rate_tracker to avoid needing the full rate-limit setup.
+ dl.rate_tracker = MagicMock()
+ dl.rate_tracker.apply_rate_limit.return_value = 0
+ with patch.object(
+ builtins,
+ "__import__",
+ side_effect=_import_blocker("playwright"),
+ ):
+ result = dl._fetch_with_playwright("https://example.com")
+ assert result is None
+ finally:
+ dl.close()
diff --git a/tests/web/auth/test_connection_cleanup_fallback.py b/tests/web/auth/test_connection_cleanup_fallback.py
new file mode 100644
index 0000000000..df66ea97c3
--- /dev/null
+++ b/tests/web/auth/test_connection_cleanup_fallback.py
@@ -0,0 +1,262 @@
+"""
+Branch/defensive-path tests for connection_cleanup that exercise fallback
+and error-handling paths not reached by test_connection_cleanup.py.
+
+Targets uncovered lines in src/local_deep_research/web/auth/connection_cleanup.py:
+- 56-68: _count_open_fds fallback via resource.getrlimit + os.fstat loop
+- 107->113: scheduler.is_running == False branch
+- 157-167: periodic pool dispose block (_last_dispose_time gate, engine.dispose
+ loop with exception swallowed, disposed count log)
+- 179-182: engine.pool.checkedout() raising inside FD monitor
+- 190-195: high-FD (>800) warning and outer FD-monitor exception handler
+"""
+
+import datetime
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.web.auth import connection_cleanup as cc_module
+from local_deep_research.web.auth.connection_cleanup import (
+ cleanup_idle_connections,
+)
+from local_deep_research.web.auth.session_manager import SessionManager
+
+
+def sm():
+ with patch(
+ "local_deep_research.web.auth.session_manager.get_security_default",
+ return_value=1,
+ ):
+ mgr = SessionManager()
+ mgr.session_timeout = datetime.timedelta(seconds=1)
+ mgr.remember_me_timeout = datetime.timedelta(seconds=2)
+ return mgr
+
+
+def db():
+ mock = MagicMock()
+ mock.get_connected_usernames.return_value = set()
+ mock.connections = {}
+ # _connections_lock must be a context manager
+ mock._connections_lock = MagicMock()
+ mock._connections_lock.__enter__ = MagicMock(return_value=None)
+ mock._connections_lock.__exit__ = MagicMock(return_value=None)
+ return mock
+
+
[email protected](autouse=True)
+def reset_dispose_timer():
+ """Ensure _last_dispose_time doesn't leak across tests in this file.
+
+ Set it far below any realistic time.monotonic() return so the
+ elapsed-interval gate (>= _DISPOSE_INTERVAL_SECONDS, 1800s) is always
+ satisfied by default. On freshly-booted systems time.monotonic() can
+ still be below 1800s, so initializing to 0.0 isn't sufficient.
+ """
+ original = cc_module._last_dispose_time
+ cc_module._last_dispose_time = -1e9
+ yield
+ cc_module._last_dispose_time = original
+
+
+class TestCountOpenFdsFallback:
+ """When /proc/self/fd is unavailable, _count_open_fds falls back to
+ resource.getrlimit + os.fstat loop."""
+
+ def test_falls_back_when_proc_fd_not_a_directory(self):
+ """is_dir() returning False triggers the resource.getrlimit path."""
+ from local_deep_research.web.auth.connection_cleanup import (
+ _count_open_fds,
+ )
+
+ fake_limit = (5, 1024)
+ valid_fds = {0, 1, 2, 4}
+
+ def fake_fstat(fd):
+ if fd in valid_fds:
+ return MagicMock()
+ raise OSError("bad fd")
+
+ with (
+ patch(
+ "local_deep_research.web.auth.connection_cleanup.Path"
+ ) as MockPath,
+ patch(
+ "local_deep_research.web.auth.connection_cleanup.os.fstat",
+ side_effect=fake_fstat,
+ ),
+ patch("resource.getrlimit", return_value=fake_limit),
+ ):
+ mock_proc = MagicMock()
+ mock_proc.is_dir.return_value = False
+ MockPath.return_value = mock_proc
+
+ result = _count_open_fds()
+
+ assert result == len(valid_fds)
+
+ def test_falls_back_when_proc_fd_iterdir_raises(self):
+ """is_dir() True but iterdir() raising OSError falls through to fstat."""
+ from local_deep_research.web.auth.connection_cleanup import (
+ _count_open_fds,
+ )
+
+ fake_limit = (3, 1024)
+
+ def fake_fstat(fd):
+ if fd in (0, 1):
+ return MagicMock()
+ raise OSError("bad fd")
+
+ with (
+ patch(
+ "local_deep_research.web.auth.connection_cleanup.Path"
+ ) as MockPath,
+ patch(
+ "local_deep_research.web.auth.connection_cleanup.os.fstat",
+ side_effect=fake_fstat,
+ ),
+ patch("resource.getrlimit", return_value=fake_limit),
+ ):
+ mock_proc = MagicMock()
+ mock_proc.is_dir.return_value = True
+ mock_proc.iterdir.side_effect = OSError("permission denied")
+ MockPath.return_value = mock_proc
+
+ result = _count_open_fds()
+
+ assert result == 2
+
+
+class TestSchedulerNotRunningBranch:
+ """When scheduler.is_running is False, unregister_user is not called."""
+
+ @patch(
+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",
+ )
+ @patch(
+ "local_deep_research.web.auth.connection_cleanup.get_usernames_with_active_research",
+ return_value=set(),
+ )
+ def test_unregister_skipped_when_scheduler_not_running(
+ self, _mock_research, mock_get_sched, sm, db
+ ):
+ mock_scheduler = MagicMock()
+ mock_scheduler.is_running = False
+ mock_get_sched.return_value = mock_scheduler
+
+ db.get_connected_usernames.return_value = {"alice"}
+
+ cleanup_idle_connections(sm, db)
+
+ mock_scheduler.unregister_user.assert_not_called()
+ db.close_user_database.assert_called_once_with("alice")
+
+
+class TestPeriodicPoolDispose:
+ """When the dispose interval has elapsed, all engines are disposed and
+ individual dispose() exceptions are swallowed."""
+
+ @patch(
+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",
+ )
+ @patch(
+ "local_deep_research.web.auth.connection_cleanup.get_usernames_with_active_research",
+ return_value=set(),
+ )
+ def test_disposes_all_engines_and_swallows_errors(
+ self, _mock_research, _mock_sched, sm, db
+ ):
+ # _last_dispose_time = 0 (from autouse fixture), so the interval
+ # elapsed gate is satisfied and the dispose block runs.
+ bad_engine = MagicMock()
+ bad_engine.dispose.side_effect = RuntimeError("dispose failed")
+ good_engine = MagicMock()
+
+ db.connections = {"alice": bad_engine, "bob": good_engine}
+
+ cleanup_idle_connections(sm, db)
+
+ # Both dispose calls attempted despite the first raising.
+ bad_engine.dispose.assert_called_once()
+ good_engine.dispose.assert_called_once()
+ # The timer was updated so a rapid second call would NOT re-dispose.
+ assert cc_module._last_dispose_time > 0
+
+ @patch(
+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",
+ )
+ @patch(
+ "local_deep_research.web.auth.connection_cleanup.get_usernames_with_active_research",
+ return_value=set(),
+ )
+ def test_skip_dispose_when_interval_not_elapsed(
+ self, _mock_research, _mock_sched, sm, db
+ ):
+ """If _last_dispose_time is recent, the dispose block is skipped."""
+ import time
+
+ cc_module._last_dispose_time = time.monotonic() # just now
+ engine = MagicMock()
+ db.connections = {"alice": engine}
+
+ cleanup_idle_connections(sm, db)
+
+ engine.dispose.assert_not_called()
+
+
+class TestFdMonitoringErrorPaths:
+ """Exception handling inside and around the FD monitor block."""
+
+ @patch(
+ "local_deep_research.web.auth.connection_cleanup._count_open_fds",
+ return_value=801,
+ )
+ @patch(
+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",
+ )
+ @patch(
+ "local_deep_research.web.auth.connection_cleanup.get_usernames_with_active_research",
+ return_value=set(),
+ )
+ def test_high_fd_warning_and_checkedout_exception(
+ self, _mock_research, _mock_sched, _mock_fd, sm, db
+ ):
+ """FD count > 800 emits a warning; engine.pool.checkedout() raising
+ is swallowed silently."""
+ flaky_engine = MagicMock()
+ flaky_engine.pool.checkedout.side_effect = RuntimeError("pool gone")
+ db.connections = {"alice": flaky_engine}
+
+ with patch.object(cc_module.logger, "warning") as mock_warn:
+ cleanup_idle_connections(sm, db)
+
+ # Verify checkedout was attempted (the inner try path ran).
+ flaky_engine.pool.checkedout.assert_called_once()
+ # High-FD warning fired with the count.
+ assert any(
+ "801" in str(call) or "High FD" in str(call)
+ for call in mock_warn.call_args_list
+ )
+
+ @patch(
+ "local_deep_research.web.auth.connection_cleanup._count_open_fds",
+ side_effect=RuntimeError("getrlimit unavailable"),
+ )
+ @patch(
+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",
+ )
+ @patch(
+ "local_deep_research.web.auth.connection_cleanup.get_usernames_with_active_research",
+ return_value=set(),
+ )
+ def test_outer_fd_monitor_exception_swallowed(
+ self, _mock_research, _mock_sched, _mock_fd, sm, db
+ ):
+ """If _count_open_fds itself raises, cleanup still completes."""
+ db.get_connected_usernames.return_value = set()
+ # Should not propagate.
+ cleanup_idle_connections(sm, db)