~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 full coverage for resource cleanup (PR #1832)
LearningCircuit0846c94ad5b1
diff --git a/tests/library/download_management/test_database_init.py b/tests/library/download_management/test_database_init.pynew file mode 100644index 0000000000..344b70856c--- /dev/null+++ b/tests/library/download_management/test_database_init.py@@ -0,0 +1,225 @@+"""+Tests for database_init.py engine disposal.++These tests verify that SQLAlchemy engines are properly disposed in the+database initialization module to prevent file descriptor leaks.+"""++from unittest.mock import MagicMock, patch+++class TestInitDatabaseEngineDisposal:+ """Tests for engine disposal in init_database()."""++ @patch(+ "local_deep_research.library.download_management.database_init.create_engine"+ )+ @patch("local_deep_research.library.download_management.database_init.Base")+ def test_init_database_disposes_engine_on_success(+ self, mock_base, mock_create_engine+ ):+ """Test that init_database() disposes engine even on success."""+ from local_deep_research.library.download_management.database_init import (+ init_database,+ )++ mock_engine = MagicMock()+ mock_create_engine.return_value = mock_engine++ result = init_database()++ # Engine should be disposed+ mock_engine.dispose.assert_called_once()+ # Function should return None since engine is disposed+ assert result is None++ @patch(+ "local_deep_research.library.download_management.database_init.create_engine"+ )+ @patch("local_deep_research.library.download_management.database_init.Base")+ def test_init_database_disposes_engine_on_create_all_exception(+ self, mock_base, mock_create_engine+ ):+ """Test that init_database() disposes engine when create_all fails."""+ from local_deep_research.library.download_management.database_init import (+ init_database,+ )++ mock_engine = MagicMock()+ mock_create_engine.return_value = mock_engine+ mock_base.metadata.create_all.side_effect = Exception(+ "Table creation failed"+ )++ try:+ init_database()+ except Exception:+ pass++ # Engine should still be disposed in finally block+ mock_engine.dispose.assert_called_once()++ @patch(+ "local_deep_research.library.download_management.database_init.create_engine"+ )+ @patch("local_deep_research.library.download_management.database_init.Base")+ def test_init_database_calls_create_all(+ self, mock_base, mock_create_engine+ ):+ """Test that init_database() calls Base.metadata.create_all()."""+ from local_deep_research.library.download_management.database_init import (+ init_database,+ )++ mock_engine = MagicMock()+ mock_create_engine.return_value = mock_engine++ init_database()++ # Should create tables+ mock_base.metadata.create_all.assert_called_once_with(mock_engine)+++class TestVerifyTableExistsEngineDisposal:+ """Tests for engine disposal in verify_table_exists()."""++ @patch(+ "local_deep_research.library.download_management.database_init.create_engine"+ )+ @patch(+ "local_deep_research.library.download_management.database_init.inspect"+ )+ def test_verify_table_exists_disposes_engine_when_table_exists(+ self, mock_inspect, mock_create_engine+ ):+ """Test that verify_table_exists() disposes engine when table exists."""+ from local_deep_research.library.download_management.database_init import (+ verify_table_exists,+ )++ mock_engine = MagicMock()+ mock_create_engine.return_value = mock_engine++ mock_inspector = MagicMock()+ mock_inspector.get_table_names.return_value = [+ "resource_download_status"+ ]+ mock_inspect.return_value = mock_inspector++ result = verify_table_exists()++ # Engine should be disposed+ mock_engine.dispose.assert_called_once()+ # Should return True since table exists+ assert result is True++ @patch(+ "local_deep_research.library.download_management.database_init.create_engine"+ )+ @patch(+ "local_deep_research.library.download_management.database_init.inspect"+ )+ def test_verify_table_exists_disposes_engine_when_table_missing(+ self, mock_inspect, mock_create_engine+ ):+ """Test that verify_table_exists() disposes engine when table is missing."""+ from local_deep_research.library.download_management.database_init import (+ verify_table_exists,+ )++ mock_engine = MagicMock()+ mock_create_engine.return_value = mock_engine++ mock_inspector = MagicMock()+ mock_inspector.get_table_names.return_value = ["other_table"]+ mock_inspect.return_value = mock_inspector++ result = verify_table_exists()++ # Engine should be disposed+ mock_engine.dispose.assert_called_once()+ # Should return False since table doesn't exist+ assert result is False++ @patch(+ "local_deep_research.library.download_management.database_init.create_engine"+ )+ @patch(+ "local_deep_research.library.download_management.database_init.inspect"+ )+ def test_verify_table_exists_disposes_engine_on_inspect_exception(+ self, mock_inspect, mock_create_engine+ ):+ """Test that verify_table_exists() disposes engine on inspect error."""+ from local_deep_research.library.download_management.database_init import (+ verify_table_exists,+ )++ mock_engine = MagicMock()+ mock_create_engine.return_value = mock_engine+ mock_inspect.side_effect = Exception("Inspection failed")++ try:+ verify_table_exists()+ except Exception:+ pass++ # Engine should still be disposed in finally block+ mock_engine.dispose.assert_called_once()++ @patch(+ "local_deep_research.library.download_management.database_init.create_engine"+ )+ @patch(+ "local_deep_research.library.download_management.database_init.inspect"+ )+ def test_verify_table_exists_disposes_engine_on_get_table_names_exception(+ self, mock_inspect, mock_create_engine+ ):+ """Test that verify_table_exists() disposes engine on get_table_names error."""+ from local_deep_research.library.download_management.database_init import (+ verify_table_exists,+ )++ mock_engine = MagicMock()+ mock_create_engine.return_value = mock_engine++ mock_inspector = MagicMock()+ mock_inspector.get_table_names.side_effect = Exception(+ "Cannot read tables"+ )+ mock_inspect.return_value = mock_inspector++ try:+ verify_table_exists()+ except Exception:+ pass++ # Engine should still be disposed in finally block+ mock_engine.dispose.assert_called_once()++ @patch(+ "local_deep_research.library.download_management.database_init.create_engine"+ )+ @patch(+ "local_deep_research.library.download_management.database_init.inspect"+ )+ def test_verify_table_exists_uses_inspect_function(+ self, mock_inspect, mock_create_engine+ ):+ """Test that verify_table_exists() uses SQLAlchemy inspect()."""+ from local_deep_research.library.download_management.database_init import (+ verify_table_exists,+ )++ mock_engine = MagicMock()+ mock_create_engine.return_value = mock_engine++ mock_inspector = MagicMock()+ mock_inspector.get_table_names.return_value = []+ mock_inspect.return_value = mock_inspector++ verify_table_exists()++ # Should call inspect with the engine+ mock_inspect.assert_called_once_with(mock_engine)diff --git a/tests/web/routes/test_open_folder_subprocess.py b/tests/web/routes/test_open_folder_subprocess.pynew file mode 100644index 0000000000..ed8a60a26e--- /dev/null+++ b/tests/web/routes/test_open_folder_subprocess.py@@ -0,0 +1,276 @@+"""+Tests for subprocess.run usage in open folder functions.++These tests verify that subprocess.run is used with start_new_session=True+on Linux and macOS to prevent zombie processes and file descriptor leaks.++The tests use source code inspection to verify the implementation details,+which is more reliable than integration tests for verifying specific+subprocess parameters.+"""++import inspect+import re+++class TestSubprocessRunNotPopen:+ """Tests to verify Popen is NOT used (would cause zombie processes)."""++ def test_settings_routes_open_file_location_uses_subprocess_run_not_popen(+ self,+ ):+ """Verify settings_routes.open_file_location uses subprocess.run, not Popen."""+ from local_deep_research.web.routes import settings_routes++ func_source = inspect.getsource(settings_routes.open_file_location)++ # subprocess.run should be used+ assert "subprocess.run" in func_source, (+ "open_file_location should use subprocess.run"+ )++ # Popen should NOT be called in this function+ # Note: "Popen" may appear in comments explaining why we don't use it,+ # so we check for actual Popen calls (Popen( or subprocess.Popen)+ assert (+ "Popen(" not in func_source+ and "subprocess.Popen" not in func_source+ ), "open_file_location should NOT call Popen (causes zombie processes)"++ def test_research_routes_open_file_location_uses_subprocess_run_not_popen(+ self,+ ):+ """Verify research_routes.open_file_location uses subprocess.run, not Popen."""+ from local_deep_research.web.routes import research_routes++ func_source = inspect.getsource(research_routes.open_file_location)++ # subprocess.run should be used+ assert "subprocess.run" in func_source, (+ "open_file_location should use subprocess.run"+ )++ # Popen should NOT be used in this function+ assert "Popen" not in func_source, (+ "open_file_location should NOT use Popen (causes zombie processes)"+ )+++class TestStartNewSessionOnUnix:+ """Tests to verify start_new_session=True is used on Unix systems."""++ def test_settings_routes_uses_start_new_session_for_xdg_open(self):+ """Verify settings_routes uses start_new_session=True with xdg-open (Linux)."""+ from local_deep_research.web.routes import settings_routes++ func_source = inspect.getsource(settings_routes.open_file_location)++ # Check for xdg-open usage+ assert "xdg-open" in func_source, (+ "open_file_location should use xdg-open on Linux"+ )++ # Check for start_new_session parameter+ assert "start_new_session=True" in func_source, (+ "open_file_location should use start_new_session=True"+ )++ # Verify the subprocess.run call with xdg-open has start_new_session+ # Look for the pattern: subprocess.run(["xdg-open", ...], start_new_session=True+ linux_block_match = re.search(+ r'else:.*?#.*?Linux.*?subprocess\.run\(\s*\["xdg-open".*?start_new_session\s*=\s*True',+ func_source,+ re.DOTALL,+ )+ assert linux_block_match is not None, (+ "Linux xdg-open call should include start_new_session=True"+ )++ def test_settings_routes_uses_start_new_session_for_macos_open(self):+ """Verify settings_routes uses start_new_session=True with open (macOS)."""+ from local_deep_research.web.routes import settings_routes++ func_source = inspect.getsource(settings_routes.open_file_location)++ # Check for Darwin/macOS handling+ assert "Darwin" in func_source, (+ "open_file_location should handle Darwin/macOS"+ )++ # Check that macOS uses the 'open' command with start_new_session+ macos_block_match = re.search(+ r'Darwin.*?subprocess\.run\(\s*\["open".*?start_new_session\s*=\s*True',+ func_source,+ re.DOTALL,+ )+ assert macos_block_match is not None, (+ "macOS open call should include start_new_session=True"+ )++ def test_research_routes_uses_start_new_session_for_xdg_open(self):+ """Verify research_routes uses start_new_session=True with xdg-open (Linux)."""+ from local_deep_research.web.routes import research_routes++ func_source = inspect.getsource(research_routes.open_file_location)++ # Check for xdg-open usage+ assert "xdg-open" in func_source, (+ "open_file_location should use xdg-open on Linux"+ )++ # Check for start_new_session parameter+ assert "start_new_session=True" in func_source, (+ "open_file_location should use start_new_session=True"+ )++ # Verify the subprocess.run call with xdg-open has start_new_session+ linux_block_match = re.search(+ r'else:.*?#.*?Linux.*?subprocess\.run\(\s*\["xdg-open".*?start_new_session\s*=\s*True',+ func_source,+ re.DOTALL,+ )+ assert linux_block_match is not None, (+ "Linux xdg-open call should include start_new_session=True"+ )++ def test_research_routes_uses_start_new_session_for_macos_open(self):+ """Verify research_routes uses start_new_session=True with open (macOS)."""+ from local_deep_research.web.routes import research_routes++ func_source = inspect.getsource(research_routes.open_file_location)++ # Check for Darwin/macOS handling+ assert "Darwin" in func_source, (+ "open_file_location should handle Darwin/macOS"+ )++ # Check that macOS uses the 'open' command with start_new_session+ macos_block_match = re.search(+ r'Darwin.*?subprocess\.run\(\s*\["open".*?start_new_session\s*=\s*True',+ func_source,+ re.DOTALL,+ )+ assert macos_block_match is not None, (+ "macOS open call should include start_new_session=True"+ )+++class TestWindowsDoesNotUseStartNewSession:+ """Tests to verify Windows does not need start_new_session (uses explorer)."""++ def test_settings_routes_windows_uses_explorer(self):+ """Verify settings_routes uses explorer on Windows (no start_new_session needed)."""+ from local_deep_research.web.routes import settings_routes++ func_source = inspect.getsource(settings_routes.open_file_location)++ # Windows should use explorer+ assert '"Windows"' in func_source or "'Windows'" in func_source, (+ "open_file_location should check for Windows platform"+ )++ # Windows block should use explorer+ windows_match = re.search(+ r'Windows.*?subprocess\.run\(\s*\["explorer"',+ func_source,+ re.DOTALL,+ )+ assert windows_match is not None, "Windows should use explorer command"++ def test_research_routes_windows_uses_explorer(self):+ """Verify research_routes uses explorer on Windows."""+ from local_deep_research.web.routes import research_routes++ func_source = inspect.getsource(research_routes.open_file_location)++ # Windows should use explorer+ assert '"Windows"' in func_source or "'Windows'" in func_source, (+ "open_file_location should check for Windows platform"+ )++ # Windows block should use explorer+ windows_match = re.search(+ r'Windows.*?subprocess\.run\(\s*\["explorer"',+ func_source,+ re.DOTALL,+ )+ assert windows_match is not None, "Windows should use explorer command"+++class TestSubprocessCommentDocumentation:+ """Tests to verify the code has proper comments about zombie process prevention."""++ def test_settings_routes_has_zombie_prevention_comment(self):+ """Verify settings_routes documents why start_new_session is used."""+ from local_deep_research.web.routes import settings_routes++ func_source = inspect.getsource(settings_routes.open_file_location)++ # Should have comment explaining the fix+ assert "start_new_session" in func_source and (+ "zombie" in func_source.lower()+ or "detach" in func_source.lower()+ or "file descriptor" in func_source.lower()+ ), "Code should document why start_new_session is used"++ def test_research_routes_has_detach_comment(self):+ """Verify research_routes documents subprocess detachment."""+ from local_deep_research.web.routes import research_routes++ func_source = inspect.getsource(research_routes.open_file_location)++ # Should have comment explaining the fix+ assert "start_new_session" in func_source and (+ "detach" in func_source.lower()+ or "fully detach" in func_source.lower()+ ), (+ "Code should document why start_new_session is used (detach subprocess)"+ )+++class TestPlatformHandling:+ """Tests for proper platform detection and handling."""++ def test_settings_routes_handles_all_platforms(self):+ """Verify settings_routes handles Windows, macOS, and Linux."""+ from local_deep_research.web.routes import settings_routes++ func_source = inspect.getsource(settings_routes.open_file_location)++ # Should handle all three platforms+ assert "Windows" in func_source, "Should handle Windows"+ assert "Darwin" in func_source, "Should handle macOS (Darwin)"+ # Linux is the else case, verified by xdg-open+ assert "xdg-open" in func_source, "Should handle Linux with xdg-open"++ def test_research_routes_handles_all_platforms(self):+ """Verify research_routes handles Windows, macOS, and Linux."""+ from local_deep_research.web.routes import research_routes++ func_source = inspect.getsource(research_routes.open_file_location)++ # Should handle all three platforms+ assert "Windows" in func_source, "Should handle Windows"+ assert "Darwin" in func_source, "Should handle macOS (Darwin)"+ # Linux is the else case, verified by xdg-open+ assert "xdg-open" in func_source, "Should handle Linux with xdg-open"++ def test_settings_routes_uses_platform_system(self):+ """Verify settings_routes uses platform.system() for OS detection."""+ from local_deep_research.web.routes import settings_routes++ func_source = inspect.getsource(settings_routes.open_file_location)++ assert "platform.system()" in func_source, (+ "Should use platform.system() for OS detection"+ )++ def test_research_routes_uses_platform_system(self):+ """Verify research_routes uses platform.system() for OS detection."""+ from local_deep_research.web.routes import research_routes++ func_source = inspect.getsource(research_routes.open_file_location)++ assert "platform.system()" in func_source, (+ "Should use platform.system() for OS detection"+ )diff --git a/tests/web/services/test_socket_service.py b/tests/web/services/test_socket_service.pyindex 0639db082c..84c86c7815 100644--- a/tests/web/services/test_socket_service.py+++ b/tests/web/services/test_socket_service.py@@ -550,3 +550,234 @@ class TestSocketIOServiceSingletonBehavior:assert service1 is service2finally:SocketIOService._instance = original_instance+++class TestSocketServiceDisconnectCleanup:+ """Tests for thread cleanup on socket disconnect.++ These tests verify that __handle_disconnect properly calls+ cleanup_current_thread() to prevent file descriptor leaks from+ unclosed SQLAlchemy sessions in socket handler threads.+ """++ @patch("local_deep_research.web.services.socket_service.SocketIO")+ def test_disconnect_handler_exists(self, mock_socketio_class):+ """Test that the disconnect handler is registered."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ original_instance = SocketIOService._instance+ SocketIOService._instance = None++ mock_socketio = MagicMock()+ mock_socketio_class.return_value = mock_socketio++ try:+ app = MockFlaskApp()+ service = SocketIOService(app=app)++ # The service should register handlers via @socketio.on decorators+ # We verify the service initializes without error+ assert service is not None+ finally:+ SocketIOService._instance = original_instance++ @patch("local_deep_research.web.services.socket_service.SocketIO")+ def test_disconnect_removes_subscriptions(self, mock_socketio_class):+ """Test that disconnect removes client from subscriptions dict."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ original_instance = SocketIOService._instance+ SocketIOService._instance = None++ mock_socketio = MagicMock()+ mock_socketio_class.return_value = mock_socketio++ try:+ app = MockFlaskApp()+ service = SocketIOService(app=app)++ # Access the private subscriptions dict+ subscriptions = service._SocketIOService__socket_subscriptions++ # Add a test subscription+ test_sid = "test_client_123"+ subscriptions[test_sid] = {"research_1", "research_2"}++ # Verify it was added+ assert test_sid in subscriptions++ # Create a mock request+ mock_request = MagicMock()+ mock_request.sid = test_sid++ # Call the disconnect handler directly+ service._SocketIOService__handle_disconnect(+ mock_request, "test reason"+ )++ # Verify subscription was removed+ assert test_sid not in subscriptions+ finally:+ SocketIOService._instance = original_instance++ @patch("local_deep_research.web.services.socket_service.SocketIO")+ def test_disconnect_calls_cleanup_current_thread(self, mock_socketio_class):+ """Test that disconnect handler calls cleanup_current_thread()."""+ import inspect+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ original_instance = SocketIOService._instance+ SocketIOService._instance = None++ mock_socketio = MagicMock()+ mock_socketio_class.return_value = mock_socketio++ try:+ app = MockFlaskApp()+ service = SocketIOService(app=app)++ # Verify by source code inspection that cleanup_current_thread+ # is called in the disconnect handler+ func_source = inspect.getsource(+ service._SocketIOService__handle_disconnect+ )++ # Check that the cleanup function is imported and called+ assert "cleanup_current_thread" in func_source, (+ "Disconnect handler should call cleanup_current_thread()"+ )+ assert (+ "from ...database.thread_local_session import" in func_source+ ), "Disconnect handler should import from thread_local_session"+ finally:+ SocketIOService._instance = original_instance++ @patch("local_deep_research.web.services.socket_service.SocketIO")+ def test_disconnect_handles_cleanup_import_error_gracefully(+ self, mock_socketio_class+ ):+ """Test that disconnect handles ImportError gracefully."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ original_instance = SocketIOService._instance+ SocketIOService._instance = None++ mock_socketio = MagicMock()+ mock_socketio_class.return_value = mock_socketio++ try:+ app = MockFlaskApp()+ service = SocketIOService(app=app)++ mock_request = MagicMock()+ mock_request.sid = "test_client_import_error"++ # The handler should handle ImportError gracefully (pass)+ # This is already handled in the source code with:+ # except ImportError: pass++ # Call should not raise even if import fails+ # (the actual import might succeed or fail depending on environment)+ try:+ service._SocketIOService__handle_disconnect(+ mock_request, "import error test"+ )+ except ImportError:+ # Should not propagate+ assert False, "ImportError should be caught internally"++ # Handler completed without propagating ImportError+ assert True+ finally:+ SocketIOService._instance = original_instance++ @patch("local_deep_research.web.services.socket_service.SocketIO")+ def test_disconnect_handles_cleanup_exception_gracefully(+ self, mock_socketio_class+ ):+ """Test that disconnect handles cleanup exceptions gracefully."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ original_instance = SocketIOService._instance+ SocketIOService._instance = None++ mock_socketio = MagicMock()+ mock_socketio_class.return_value = mock_socketio++ try:+ app = MockFlaskApp()+ service = SocketIOService(app=app)++ mock_request = MagicMock()+ mock_request.sid = "test_client_cleanup_error"++ # The handler has a try/except block that catches Exception+ # and logs it rather than propagating++ # Call should not raise+ try:+ service._SocketIOService__handle_disconnect(+ mock_request, "cleanup error test"+ )+ except Exception as e:+ # Only outer exceptions should propagate, not cleanup errors+ # The source has: except Exception: self.__log_exception(...)+ if "Error cleaning up thread session" in str(e):+ assert False, (+ "Cleanup exception should be caught internally"+ )++ # Handler completed+ assert True+ finally:+ SocketIOService._instance = original_instance++ @patch("local_deep_research.web.services.socket_service.SocketIO")+ def test_disconnect_logs_client_info(self, mock_socketio_class):+ """Test that disconnect logs client disconnect information."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ original_instance = SocketIOService._instance+ SocketIOService._instance = None++ mock_socketio = MagicMock()+ mock_socketio_class.return_value = mock_socketio++ try:+ app = MockFlaskApp()+ service = SocketIOService(app=app)++ mock_request = MagicMock()+ mock_request.sid = "logged_client_123"++ # Mock the logging method+ with patch.object(+ service, "_SocketIOService__log_info"+ ) as mock_log_info:+ service._SocketIOService__handle_disconnect(+ mock_request, "client initiated"+ )++ # Should log disconnect info+ assert mock_log_info.called+ # Check that the client ID appears in at least one log call+ log_messages = [+ str(call) for call in mock_log_info.call_args_list+ ]+ assert any(+ "logged_client_123" in msg for msg in log_messages+ ), "Client ID should be logged on disconnect"+ finally:+ SocketIOService._instance = original_instance