~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
fix: make API rate limit tests resilient to xdist test pollution (#3022)
LearningCircuitc60bfdc0ee8a
diff --git a/tests/web/test_api_coverage.py b/tests/web/test_api_coverage.pyindex f920603081..089a06fd02 100644--- a/tests/web/test_api_coverage.py+++ b/tests/web/test_api_coverage.py@@ -28,10 +28,18 @@ def _auth_session(client, username="testuser"):@contextmanager-def _mock_access_control(*, api_enabled=True):+def _mock_access_control(*, api_enabled=True, rate_limit=60):"""Context manager that patches get_user_db_session + get_settings_managerso that the api_access_control decorator lets requests through (or blocks- them if api_enabled=False)."""+ them if api_enabled=False).++ The rate_limit parameter controls the per-user API rate limit cached on+ ``g._api_rate_limit`` by the ``api_access_control`` decorator. Setting it+ here ensures that the real ``_get_user_api_rate_limit`` function reads the+ correct value from the cache, which keeps Flask-Limiter's enforcement+ consistent even under xdist test-parallelism where the global ``limiter``+ singleton may carry stale state from other test modules.+ """with patch("local_deep_research.web.api.get_user_db_session") as mock_ctx:mock_session = MagicMock()mock_ctx.return_value.__enter__ = MagicMock(return_value=mock_session)@@ -43,6 +51,7 @@ def _mock_access_control(*, api_enabled=True):mock_manager = MagicMock()mock_manager.get_setting.side_effect = lambda key, default: {"app.enable_api": api_enabled,+ "app.api_rate_limit": rate_limit,}.get(key, default)mock_sm.return_value = mock_manager@@ -55,13 +64,23 @@ def _mock_access_control(*, api_enabled=True):@pytest.fixture(autouse=True)-def _reset_limiter():- """Reset Flask-Limiter storage between tests."""+def _reset_limiter(app):+ """Reset Flask-Limiter storage before and after each test.++ Resetting *before* the test prevents stale counters left by other test+ modules that share the global ``limiter`` singleton (common under xdist).+ """+ with app.app_context():+ try:+ limiter.reset()+ except Exception:+ passyield- try:- limiter.reset()- except Exception:- pass+ with app.app_context():+ try:+ limiter.reset()+ except Exception:+ pass@pytest.fixture@@ -172,19 +191,15 @@ class TestApiAccessControl:assert "disabled" in resp.get_json()["error"].lower()def test_rate_limit_exceeded_returns_429(self, authed_client):- with _mock_access_control():- with patch(- "local_deep_research.security.rate_limiter._get_user_api_rate_limit",- return_value=2,- ):- # First two should pass- resp1 = authed_client.get("/api/v1/")- assert resp1.status_code == 200- resp2 = authed_client.get("/api/v1/")- assert resp2.status_code == 200- # Third should be rate-limited- resp3 = authed_client.get("/api/v1/")- assert resp3.status_code == 429+ with _mock_access_control(rate_limit=2):+ # First two should pass+ resp1 = authed_client.get("/api/v1/")+ assert resp1.status_code == 200+ resp2 = authed_client.get("/api/v1/")+ assert resp2.status_code == 200+ # Third should be rate-limited+ resp3 = authed_client.get("/api/v1/")+ assert resp3.status_code == 429def test_rate_limit_429_returns_json_with_custom_handler(self, app):"""429 response has JSON body with 'error' and 'message' keys@@ -204,83 +219,63 @@ class TestApiAccessControl:with app.test_client() as client:_auth_session(client)- with _mock_access_control():- with patch(- "local_deep_research.security.rate_limiter._get_user_api_rate_limit",- return_value=1,- ):- # First request passes- resp1 = client.get("/api/v1/")- assert resp1.status_code == 200- # Second hits the limit- resp2 = client.get("/api/v1/")- assert resp2.status_code == 429- body = resp2.get_json()- assert body is not None, "429 response should be JSON"- assert body["error"] == "Too many requests"- assert "message" in body+ with _mock_access_control(rate_limit=1):+ # First request passes+ resp1 = client.get("/api/v1/")+ assert resp1.status_code == 200+ # Second hits the limit+ resp2 = client.get("/api/v1/")+ assert resp2.status_code == 429+ body = resp2.get_json()+ assert body is not None, "429 response should be JSON"+ assert body["error"] == "Too many requests"+ assert "message" in bodydef test_rate_limit_headers_present_on_success(self, authed_client):"""Successful responses include X-RateLimit headers."""- with _mock_access_control():- with patch(- "local_deep_research.security.rate_limiter._get_user_api_rate_limit",- return_value=10,- ):- resp = authed_client.get("/api/v1/")- assert resp.status_code == 200- # Flask-Limiter adds these headers when headers_enabled=True- assert "X-RateLimit-Limit" in resp.headers- assert "X-RateLimit-Remaining" in resp.headers- assert "X-RateLimit-Reset" in resp.headers+ with _mock_access_control(rate_limit=10):+ resp = authed_client.get("/api/v1/")+ assert resp.status_code == 200+ # Flask-Limiter adds these headers when headers_enabled=True+ assert "X-RateLimit-Limit" in resp.headers+ assert "X-RateLimit-Remaining" in resp.headers+ assert "X-RateLimit-Reset" in resp.headersdef test_rate_limit_remaining_header_decrements(self, authed_client):"""X-RateLimit-Remaining decrements with each request."""- with _mock_access_control():- with patch(- "local_deep_research.security.rate_limiter._get_user_api_rate_limit",- return_value=5,- ):- resp1 = authed_client.get("/api/v1/")- assert resp1.status_code == 200- remaining1 = int(resp1.headers["X-RateLimit-Remaining"])+ with _mock_access_control(rate_limit=5):+ resp1 = authed_client.get("/api/v1/")+ assert resp1.status_code == 200+ remaining1 = int(resp1.headers["X-RateLimit-Remaining"])- resp2 = authed_client.get("/api/v1/")- assert resp2.status_code == 200- remaining2 = int(resp2.headers["X-RateLimit-Remaining"])+ resp2 = authed_client.get("/api/v1/")+ assert resp2.status_code == 200+ remaining2 = int(resp2.headers["X-RateLimit-Remaining"])- assert remaining2 == remaining1 - 1+ assert remaining2 == remaining1 - 1def test_different_users_have_independent_buckets(self, app):"""User A hitting their limit does not affect User B."""- with _mock_access_control():- with patch(- "local_deep_research.security.rate_limiter._get_user_api_rate_limit",- return_value=2,- ):- # User A exhausts their limit- client_a = app.test_client()- _auth_session(client_a, username="alice")- assert client_a.get("/api/v1/").status_code == 200- assert client_a.get("/api/v1/").status_code == 200- assert client_a.get("/api/v1/").status_code == 429-- # User B is unaffected- client_b = app.test_client()- _auth_session(client_b, username="bob")- assert client_b.get("/api/v1/").status_code == 200- assert client_b.get("/api/v1/").status_code == 200+ with _mock_access_control(rate_limit=2):+ # User A exhausts their limit+ client_a = app.test_client()+ _auth_session(client_a, username="alice")+ assert client_a.get("/api/v1/").status_code == 200+ assert client_a.get("/api/v1/").status_code == 200+ assert client_a.get("/api/v1/").status_code == 429++ # User B is unaffected+ client_b = app.test_client()+ _auth_session(client_b, username="bob")+ assert client_b.get("/api/v1/").status_code == 200+ assert client_b.get("/api/v1/").status_code == 200def test_rate_limit_zero_means_no_limiting(self, authed_client):"""rate_limit=0 (falsy) should exempt from rate limiting."""- with _mock_access_control():- with patch(- "local_deep_research.security.rate_limiter._get_user_api_rate_limit",- return_value=0,- ):- for _ in range(5):- resp = authed_client.get("/api/v1/")- assert resp.status_code == 200+ with _mock_access_control(rate_limit=0):+ for _ in range(5):+ resp = authed_client.get("/api/v1/")+ assert resp.status_code == 200def test_g_current_user_fallback(self, app):"""When g.current_user is set, it should be used instead of session."""