~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 35 integration-style tests for error handlers, teardown, socket concurrency, and middleware (round 17) (#2661)
LearningCircuitc294b22ba4db
diff --git a/tests/web/services/test_socket_service_concurrency.py b/tests/web/services/test_socket_service_concurrency.pynew file mode 100644index 0000000000..8e66f1639c--- /dev/null+++ b/tests/web/services/test_socket_service_concurrency.py@@ -0,0 +1,322 @@+"""+Tests for SocketIOService concurrency and edge cases.++Covers: emit_to_subscribers snapshot safety, logging restoration,+empty subscriptions, mixed success/failure, remove_subscriptions,+and emit_socket_event modes.++Source: socket_service.py lines 129-216.+"""++from unittest.mock import patch, Mock+++class MockSocketIO:+ """Mock SocketIO that records emitted events."""++ def __init__(self, app=None, **kwargs):+ self.emitted_events = []+ self._handlers = {}++ def emit(self, event, data, room=None):+ self.emitted_events.append({"event": event, "data": data, "room": room})++ def on(self, event):+ def decorator(f):+ self._handlers[event] = f+ return f++ return decorator++ @property+ def on_error(self):+ def decorator(f):+ self._handlers["error"] = f+ return f++ return decorator++ @property+ def on_error_default(self):+ def decorator(f):+ self._handlers["error_default"] = f+ return f++ return decorator++ def run(self, app, **kwargs):+ pass+++def _make_service():+ """Create a fresh SocketIOService with mocked dependencies."""+ from local_deep_research.web.services.socket_service import SocketIOService++ # Reset singleton+ SocketIOService._instance = None++ try:+ mock_app = Mock()+ mock_app.config = {}+ mock_app.debug = False++ with (+ patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ MockSocketIO,+ ),+ patch(+ "local_deep_research.settings.env_registry.get_env_setting",+ return_value=None,+ ),+ ):+ service = SocketIOService(app=mock_app)+ return service+ finally:+ # Restore singleton after each test via cleanup+ pass+++def _cleanup_singleton(original):+ from local_deep_research.web.services.socket_service import SocketIOService++ SocketIOService._instance = original+++class TestEmitToSubscribersConcurrency:+ """Tests for emit_to_subscribers concurrency edge cases."""++ def setup_method(self):+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ self._original = SocketIOService._instance++ def teardown_method(self):+ _cleanup_singleton(self._original)++ def test_snapshot_prevents_runtime_error_during_iteration(self):+ """Modifying subscriptions during emit doesn't cause RuntimeError."""+ service = _make_service()+ research_id = "r1"++ # Add subscriptions+ with service._SocketIOService__lock:+ service._SocketIOService__socket_subscriptions[research_id] = {+ "sid1",+ "sid2",+ "sid3",+ }++ # Mock emit to modify subscriptions mid-iteration+ original_emit = service._SocketIOService__socketio.emit+ call_count = 0++ def emit_and_modify(event, data, room=None):+ nonlocal call_count+ call_count += 1+ if call_count == 1:+ # Modify the original set during iteration+ with service._SocketIOService__lock:+ service._SocketIOService__socket_subscriptions[+ research_id+ ].add("sid4")+ service._SocketIOService__socket_subscriptions[+ research_id+ ].discard("sid3")+ original_emit(event, data, room=room)++ service._SocketIOService__socketio.emit = emit_and_modify++ # Should not raise RuntimeError+ result = service.emit_to_subscribers(+ "event", research_id, {"key": "val"}+ )+ assert result is True++ def test_logging_re_enabled_after_subscriber_exception(self):+ """__logging_enabled is restored to True even when subscriber emit raises."""+ service = _make_service()+ research_id = "r2"++ with service._SocketIOService__lock:+ service._SocketIOService__socket_subscriptions[research_id] = {+ "sid1"+ }++ # Make emit raise — caught by inner per-subscriber try/except+ def raise_on_emit(event, data, room=None):+ raise ConnectionError("socket broken")++ service._SocketIOService__socketio.emit = raise_on_emit++ result = service.emit_to_subscribers(+ "event", research_id, {}, enable_logging=False+ )++ # logging should be re-enabled via finally block+ assert service._SocketIOService__logging_enabled is True+ # Inner exception is caught, outer try returns True+ assert result is True++ def test_logging_re_enabled_after_outer_exception(self):+ """__logging_enabled is restored even if the outer try block fails."""+ service = _make_service()++ # Force an exception in the outer try block by making the lock+ # context manager's __enter__ raise after the first call+ original_lock = service._SocketIOService__lock++ class ExplodingLock:+ def __enter__(self):+ raise RuntimeError("lock exploded")++ def __exit__(self, *args):+ pass++ service._SocketIOService__lock = ExplodingLock()++ result = service.emit_to_subscribers(+ "event", "r_outer", {}, enable_logging=False+ )++ # Restore lock for cleanup+ service._SocketIOService__lock = original_lock++ # logging should still be re-enabled via finally+ assert service._SocketIOService__logging_enabled is True+ assert result is False++ def test_empty_subscription_set_broadcasts(self):+ """When subscriptions is an empty set, it's falsy → broadcast."""+ service = _make_service()+ research_id = "r3"++ with service._SocketIOService__lock:+ service._SocketIOService__socket_subscriptions[research_id] = set()++ result = service.emit_to_subscribers("event", research_id, {"data": 1})+ assert result is True++ # Should broadcast (no room specified) since empty set is falsy+ events = service._SocketIOService__socketio.emitted_events+ assert len(events) == 1+ assert events[0]["room"] is None # broadcast++ def test_one_subscriber_fails_others_succeed(self):+ """If one subscriber's emit raises, others still receive the event."""+ service = _make_service()+ research_id = "r4"++ with service._SocketIOService__lock:+ service._SocketIOService__socket_subscriptions[research_id] = {+ "sid1",+ "sid2",+ "sid3",+ }++ call_log = []++ def selective_emit(event, data, room=None):+ call_log.append(room)+ if room == "sid2":+ raise RuntimeError("connection lost")++ service._SocketIOService__socketio.emit = selective_emit++ # Should still return True (outer try succeeds)+ result = service.emit_to_subscribers("event", research_id, {})+ assert result is True+ # All 3 subscribers were attempted+ assert len(call_log) == 3++ def test_none_subscription_broadcasts(self):+ """When research_id has no subscription entry, broadcast fallback."""+ service = _make_service()++ result = service.emit_to_subscribers("event", "nonexistent", {"x": 1})+ assert result is True++ events = service._SocketIOService__socketio.emitted_events+ assert len(events) == 1+ assert events[0]["room"] is None # broadcast+++class TestRemoveSubscriptions:+ """Tests for remove_subscriptions_for_research."""++ def setup_method(self):+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ self._original = SocketIOService._instance++ def teardown_method(self):+ _cleanup_singleton(self._original)++ def test_removes_existing_subscriptions(self):+ """Removes subscriptions for a known research_id."""+ service = _make_service()+ rid = "r10"++ with service._SocketIOService__lock:+ service._SocketIOService__socket_subscriptions[rid] = {"s1", "s2"}++ service.remove_subscriptions_for_research(rid)++ with service._SocketIOService__lock:+ assert rid not in service._SocketIOService__socket_subscriptions++ def test_remove_nonexistent_no_error(self):+ """Removing subscriptions for unknown research_id doesn't raise."""+ service = _make_service()+ service.remove_subscriptions_for_research("unknown_id")+ # Should not raise+++class TestEmitSocketEvent:+ """Tests for emit_socket_event broadcast vs room modes."""++ def setup_method(self):+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ self._original = SocketIOService._instance++ def teardown_method(self):+ _cleanup_singleton(self._original)++ def test_broadcast_mode_no_room(self):+ """Without room, socketio.emit is called without room kwarg."""+ service = _make_service()+ result = service.emit_socket_event("test_event", {"key": "val"})++ assert result is True+ events = service._SocketIOService__socketio.emitted_events+ assert len(events) == 1+ assert events[0]["room"] is None++ def test_room_mode(self):+ """With room specified, socketio.emit is called with room=room."""+ service = _make_service()+ result = service.emit_socket_event(+ "test_event", {"key": "val"}, room="abc123"+ )++ assert result is True+ events = service._SocketIOService__socketio.emitted_events+ assert len(events) == 1+ assert events[0]["room"] == "abc123"++ def test_exception_returns_false(self):+ """If socketio.emit raises, emit_socket_event returns False."""+ service = _make_service()+ service._SocketIOService__socketio.emit = Mock(+ side_effect=RuntimeError("boom")+ )++ result = service.emit_socket_event("test_event", {})+ assert result is Falsediff --git a/tests/web/test_error_handler_behavior.py b/tests/web/test_error_handler_behavior.pynew file mode 100644index 0000000000..a20e433ece--- /dev/null+++ b/tests/web/test_error_handler_behavior.py@@ -0,0 +1,191 @@+"""+Tests for error handler *behavior* in app_factory.register_error_handlers().++Existing tests cover registration and 404 content; these test:+- 500 handler JSON vs text branching+- CSRF handler IP-based messaging (private/public/proxied/HTTPS)+- NewsAPIException handler JSON conversion+- _is_private_ip edge cases (IPv4-mapped IPv6, link-local, multicast)+"""++import pytest+from unittest.mock import patch+++def app():+ """Create a test app with error handlers registered."""+ from local_deep_research.web.app_factory import create_app++ with patch("local_deep_research.web.app_factory.SocketIOService"):+ app, _ = create_app()+ app.config["TESTING"] = True+ app.config["WTF_CSRF_ENABLED"] = False+ # Must disable exception propagation so 500 handler is invoked+ app.config["PROPAGATE_EXCEPTIONS"] = False+ app.config["TRAP_HTTP_EXCEPTIONS"] = False++ # Add routes that trigger 500 errors+ @app.route("/api/trigger-500")+ def api_trigger_500():+ raise Exception("boom")++ @app.route("/trigger-500")+ def web_trigger_500():+ raise Exception("boom")++ # Add route that raises NewsAPIException+ @app.route("/api/trigger-news-error")+ def trigger_news_error():+ from local_deep_research.news.exceptions import NewsAPIException++ raise NewsAPIException(+ message="Feed unavailable",+ status_code=503,+ error_code="FEED_ERROR",+ )++ return app+++def client(app):+ return app.test_client()+++class TestServerErrorHandler:+ """Tests for the 500 error handler behavior."""++ def test_500_returns_json_for_api_path(self, client):+ """API paths get JSON error response for 500."""+ response = client.get("/api/trigger-500")+ assert response.status_code == 500+ data = response.get_json()+ assert data is not None+ assert data["error"] == "Server error"++ def test_500_returns_text_for_web_path(self, client):+ """Non-API paths get plain text error response for 500."""+ response = client.get("/trigger-500")+ assert response.status_code == 500+ assert response.data == b"Server error"+++class TestCsrfErrorHandler:+ """Tests for CSRF error handler IP-based branching."""++ def _trigger_csrf(+ self, app, remote_addr, is_secure=False, forwarded_for=None+ ):+ """Trigger a CSRF error with controlled request environment."""+ from flask_wtf.csrf import CSRFError++ # Must set PREFERRED_URL_SCHEME to match is_secure, because Flask+ # uses it to determine request.scheme / request.is_secure+ app.config["PREFERRED_URL_SCHEME"] = "https" if is_secure else "http"++ ctx_kwargs = {+ "environ_base": {+ "REMOTE_ADDR": remote_addr,+ "wsgi.url_scheme": "https" if is_secure else "http",+ },+ }+ if forwarded_for:+ ctx_kwargs["headers"] = {"X-Forwarded-For": forwarded_for}++ with app.test_request_context("/api/test", **ctx_kwargs):+ # CSRF handler is registered under status code 400+ handlers_400 = app.error_handler_spec.get(None, {}).get(400, {})+ handler = handlers_400.get(CSRFError)+ if handler is None:+ pytest.skip("CSRFError handler not registered")+ error = CSRFError("CSRF token missing")+ response = handler(error)+ return response++ def test_csrf_private_ip_http_generic_message(self, app):+ """Private IP over HTTP gets generic CSRF error (no public IP warning)."""+ response = self._trigger_csrf(app, "192.168.1.1")+ data = response.get_json()+ assert "public IP" not in data["error"]+ assert "HTTP from a" not in data["error"]++ def test_csrf_public_ip_http_detailed_message(self, app):+ """Public IP over HTTP gets detailed guidance about HTTPS."""+ response = self._trigger_csrf(app, "8.8.8.8")+ data = response.get_json()+ assert "HTTP" in data["error"] or "public IP" in data["error"]+ assert "Solutions" in data["error"]++ def test_csrf_proxied_request_gets_guidance(self, app):+ """Proxied request (X-Forwarded-For) gets proxy/HTTPS guidance."""+ response = self._trigger_csrf(+ app, "192.168.1.1", forwarded_for="203.0.113.1"+ )+ data = response.get_json()+ # Proxied + private IP + HTTP => is_proxied=True => detailed message+ assert "Solutions" in data["error"]++ def test_csrf_https_no_http_warning(self, app):+ """HTTPS requests get standard CSRF error, no HTTP-specific warning."""+ response = self._trigger_csrf(app, "8.8.8.8", is_secure=True)+ data = response.get_json()+ # is_http=False, so the detailed message branch is not taken+ assert "HTTP from a" not in data["error"]++ def test_csrf_error_does_not_leak_raw_ip(self, app):+ """Error message should not contain the raw client IP address."""+ response = self._trigger_csrf(app, "8.8.8.8")+ data = response.get_json()+ assert "8.8.8.8" not in data["error"]++ def test_csrf_returns_400_status(self, app):+ """CSRF errors return 400 status code."""+ from flask_wtf.csrf import CSRFError++ with app.test_request_context("/api/test"):+ handlers_400 = app.error_handler_spec.get(None, {}).get(400, {})+ handler = handlers_400.get(CSRFError)+ if handler is None:+ pytest.skip("CSRFError handler not registered")+ response = handler(CSRFError("bad token"))+ assert response.status_code == 400+++class TestNewsAPIExceptionHandler:+ """Tests for NewsAPIException error handler."""++ def test_news_exception_returns_json(self, client):+ """NewsAPIException is converted to JSON with error_code and status."""+ response = client.get("/api/trigger-news-error")+ assert response.status_code == 503+ data = response.get_json()+ assert data["error"] == "Feed unavailable"+ assert data["error_code"] == "FEED_ERROR"+ assert data["status_code"] == 503+++class TestIsPrivateIpEdgeCases:+ """Edge cases for _is_private_ip not covered by existing tests."""++ def test_ipv4_mapped_ipv6_private(self):+ """IPv4-mapped IPv6 address with private IPv4 is treated as private."""+ from local_deep_research.web.app_factory import _is_private_ip++ assert _is_private_ip("::ffff:192.168.1.1") is True++ def test_link_local_address(self):+ """Link-local addresses (169.254.x.x) are private."""+ from local_deep_research.web.app_factory import _is_private_ip++ # 169.254.x.x is link-local, treated as private by ipaddress module+ assert _is_private_ip("169.254.1.1") is True++ def test_multicast_address(self):+ """Multicast addresses (224.x.x.x) are not private/loopback."""+ from local_deep_research.web.app_factory import _is_private_ip+ import ipaddress++ ip = ipaddress.ip_address("224.0.0.1")+ expected = ip.is_private or ip.is_loopback+ assert _is_private_ip("224.0.0.1") is expecteddiff --git a/tests/web/test_teardown_cleanup.py b/tests/web/test_teardown_cleanup.pynew file mode 100644index 0000000000..2d69811aa4--- /dev/null+++ b/tests/web/test_teardown_cleanup.py@@ -0,0 +1,118 @@+"""+Tests for cleanup_db_session teardown behavior in apply_middleware().++Source: app_factory.py lines 547-596.+Tests the teardown_appcontext handler that cleans up DB sessions,+thread-local sessions, and sweeps dead engines after each request.+"""++import pytest+from unittest.mock import patch, Mock++from flask import g+++def app():+ """Create a minimal Flask app with the teardown handler registered."""+ from local_deep_research.web.app_factory import create_app++ with patch("local_deep_research.web.app_factory.SocketIOService"):+ app, _ = create_app()+ app.config["TESTING"] = True+ app.config["WTF_CSRF_ENABLED"] = False+ return app+++class TestCleanupDbSession:+ """Tests for the cleanup_db_session teardown handler."""++ def test_normal_cleanup_rollback_and_close(self, app):+ """Session in g.db_session gets rollback() and close() called."""+ mock_session = Mock()++ with app.test_request_context("/"):+ g.db_session = mock_session++ # After exiting context, teardown runs+ mock_session.rollback.assert_called_once()+ mock_session.close.assert_called_once()++ def test_no_session_in_g_no_error(self, app):+ """When g has no db_session, teardown completes without error."""+ with app.test_request_context("/"):+ # Don't set g.db_session+ pass+ # Should not raise++ def test_rollback_fails_close_still_called(self, app):+ """If rollback() raises, close() is still called."""+ mock_session = Mock()+ mock_session.rollback.side_effect = RuntimeError("rollback failed")++ with app.test_request_context("/"):+ g.db_session = mock_session++ mock_session.rollback.assert_called_once()+ mock_session.close.assert_called_once()++ def test_close_fails_no_propagation(self, app):+ """If close() raises, the exception does not propagate."""+ mock_session = Mock()+ mock_session.close.side_effect = RuntimeError("close failed")++ with app.test_request_context("/"):+ g.db_session = mock_session++ # Should not raise despite close() failure+ mock_session.rollback.assert_called_once()+ mock_session.close.assert_called_once()++ def test_cleanup_current_thread_called(self, app):+ """cleanup_current_thread from thread_local_session is called."""+ mock_cleanup = Mock()++ with patch(+ "local_deep_research.database.thread_local_session.cleanup_current_thread",+ mock_cleanup,+ ):+ with app.test_request_context("/"):+ pass++ mock_cleanup.assert_called_once()++ def test_cleanup_current_thread_import_fails_no_error(self, app):+ """If cleanup_current_thread import fails, no exception propagates."""+ with patch(+ "local_deep_research.database.thread_local_session.cleanup_current_thread",+ side_effect=ImportError("no module"),+ ):+ with app.test_request_context("/"):+ pass+ # Should not raise++ def test_maybe_sweep_dead_engines_called(self, app):+ """db_manager.maybe_sweep_dead_engines is called during teardown."""+ mock_db_manager = Mock()++ with patch(+ "local_deep_research.database.encrypted_db.db_manager",+ mock_db_manager,+ ):+ with app.test_request_context("/"):+ pass++ mock_db_manager.maybe_sweep_dead_engines.assert_called_once()++ def test_thread_session_manager_cleanup_called(self, app):+ """thread_session_manager.cleanup_dead_threads is called during teardown."""+ mock_manager = Mock()++ with patch(+ "local_deep_research.database.thread_local_session.thread_session_manager",+ mock_manager,+ ):+ with app.test_request_context("/"):+ pass++ mock_manager.cleanup_dead_threads.assert_called_once()diff --git a/tests/web/test_websocket_middleware.py b/tests/web/test_websocket_middleware.pynew file mode 100644index 0000000000..ac007689a0--- /dev/null+++ b/tests/web/test_websocket_middleware.py@@ -0,0 +1,101 @@+"""+Tests for handle_websocket_requests middleware and DiskSpoolingRequest.++Source: app_factory.py lines 599-608 (middleware), 45-57 (DiskSpoolingRequest).++Existing tests cover DiskSpoolingRequest attributes and _is_private_ip;+these test the websocket middleware *behavior* through the test client.+"""++import pytest+from unittest.mock import patch+++def app():+ """Create a test app with middleware registered."""+ from local_deep_research.web.app_factory import create_app++ with patch("local_deep_research.web.app_factory.SocketIOService"):+ app, _ = create_app()+ app.config["TESTING"] = True+ app.config["WTF_CSRF_ENABLED"] = False++ # Add a simple test route to verify passthrough+ @app.route("/api/research")+ def api_research():+ return "ok"++ return app+++def client(app):+ return app.test_client()+++class TestHandleWebsocketRequests:+ """Tests for the handle_websocket_requests before_request hook."""++ def test_non_socket_path_passes_through(self, client):+ """Non-socket.io paths are unaffected by the middleware."""+ response = client.get("/api/research")+ assert response.status_code == 200+ assert response.data == b"ok"++ def test_socket_path_without_werkzeug_socket(self, client):+ """socket.io path without werkzeug.socket returns None (pass-through).++ The middleware checks environ.get('werkzeug.socket') — if absent,+ it returns None which lets Flask continue to the next handler.+ Since there's no actual socket.io route registered, this results+ in 404 from Flask's normal routing.+ """+ response = client.get("/socket.io/")+ # The middleware returns None (pass-through), so Flask routes normally+ # and returns 404 since there's no actual socket.io route+ assert response.status_code in (200, 404)++ def test_socket_path_with_werkzeug_socket(self, app):+ """socket.io path with werkzeug.socket set goes through normally."""+ with app.test_request_context(+ "/socket.io/",+ environ_base={"werkzeug.socket": True},+ ):+ # Middleware should not interfere when werkzeug.socket is present+ from flask import request++ assert request.path == "/socket.io/"++ def test_socket_path_exception_returns_empty_200(self, app):+ """If werkzeug.socket check raises, middleware returns ("", 200)."""+ # We need to test the middleware directly by simulating the exception path.+ # The middleware does: if not request.environ.get("werkzeug.socket")+ # which can't normally raise. But the outer try/except catches any exception.++ # Create a custom environ that raises on .get()+ class ExplodingDict(dict):+ def get(self, key, default=None):+ if key == "werkzeug.socket":+ raise RuntimeError("socket check failed")+ return super().get(key, default)++ with app.test_request_context("/socket.io/"):+ from flask import request++ # Replace environ with our exploding version+ original_environ = request.environ+ exploding = ExplodingDict(original_environ)+ request.environ = exploding++ # Find and call the before_request handler+ # The handle_websocket_requests function is registered as before_request+ for func in app.before_request_funcs.get(None, []):+ if func.__name__ == "handle_websocket_requests":+ result = func()+ assert result == ("", 200)+ break+ else:+ pytest.fail(+ "handle_websocket_requests not found in before_request_funcs"+ )