Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(api): enable strict typing for rate limit test fixtures (#44391)

Eddy ZHANG8a43dbf752d0
diff --git a/api/tests/unit_tests/core/app/features/rate_limiting/conftest.py b/api/tests/unit_tests/core/app/features/rate_limiting/conftest.py
index 9e750bd5954..90c7e1df478 100644
--- a/api/tests/unit_tests/core/app/features/rate_limiting/conftest.py
+++ b/api/tests/unit_tests/core/app/features/rate_limiting/conftest.py
@@ -1,4 +1,6 @@
import time
+from collections.abc import Callable, Generator
+from datetime import timedelta
from unittest.mock import MagicMock, patch
import pytest
@@ -7,43 +9,43 @@ from core.app.features.rate_limiting.rate_limit import RateLimit
@pytest.fixture
-def mock_redis():
+def mock_redis() -> MagicMock:
"""Mock Redis client with realistic behavior for rate limiting tests."""
mock_client = MagicMock()
# Redis data storage for simulation
- mock_data = {}
- mock_hashes = {}
- mock_expiry = {}
+ mock_data: dict[str, str] = {}
+ mock_hashes: dict[str, dict[str, bytes]] = {}
+ mock_expiry: dict[str, float] = {}
- def mock_setex(key, ttl, value):
+ def mock_setex(key: str, ttl: int | timedelta, value: object) -> bool:
mock_data[key] = str(value)
- mock_expiry[key] = time.time() + ttl.total_seconds() if hasattr(ttl, "total_seconds") else time.time() + ttl
+ mock_expiry[key] = time.time() + (ttl.total_seconds() if isinstance(ttl, timedelta) else ttl)
return True
- def mock_get(key):
+ def mock_get(key: str) -> bytes | None:
if key in mock_data and (key not in mock_expiry or time.time() < mock_expiry[key]):
return mock_data[key].encode("utf-8")
return None
- def mock_exists(key):
+ def mock_exists(key: str) -> bool:
return key in mock_data or key in mock_hashes
- def mock_expire(key, ttl):
+ def mock_expire(key: str, ttl: int | timedelta) -> bool:
if key in mock_data or key in mock_hashes:
- mock_expiry[key] = time.time() + ttl.total_seconds() if hasattr(ttl, "total_seconds") else time.time() + ttl
+ mock_expiry[key] = time.time() + (ttl.total_seconds() if isinstance(ttl, timedelta) else ttl)
return True
- def mock_hset(key, field, value):
+ def mock_hset(key: str, field: str, value: object) -> bool:
if key not in mock_hashes:
mock_hashes[key] = {}
mock_hashes[key][field] = str(value).encode("utf-8")
return True
- def mock_hgetall(key):
+ def mock_hgetall(key: str) -> dict[str, bytes]:
return mock_hashes.get(key, {})
- def mock_hdel(key, *fields):
+ def mock_hdel(key: str, *fields: str) -> int:
if key in mock_hashes:
count = 0
for field in fields:
@@ -53,7 +55,7 @@ def mock_redis():
return count
return 0
- def mock_hlen(key):
+ def mock_hlen(key: str) -> int:
return len(mock_hashes.get(key, {}))
# Configure mock methods
@@ -75,25 +77,17 @@ def mock_redis():
@pytest.fixture
-def mock_time():
+def mock_time() -> Generator[MagicMock]:
"""Mock time.time() for deterministic tests."""
- mock_time_val = 1000.0
-
- def increment_time(seconds=1):
- nonlocal mock_time_val
- mock_time_val += seconds
- return mock_time_val
-
- with patch("time.time", return_value=mock_time_val, autospec=True) as mock:
- mock.increment = increment_time
+ with patch("time.time", return_value=1000.0, autospec=True) as mock:
yield mock
@pytest.fixture
-def sample_generator():
+def sample_generator() -> Callable[..., Generator[str]]:
"""Sample generator for testing RateLimitGenerator."""
- def _create_generator(items=None, raise_error=False):
+ def _create_generator(items: list[str] | None = None, raise_error: bool = False) -> Generator[str]:
items = items or ["item1", "item2", "item3"]
for item in items:
if raise_error and item == "item2":
@@ -104,13 +98,13 @@ def sample_generator():
@pytest.fixture
-def sample_mapping():
+def sample_mapping() -> dict[str, str]:
"""Sample mapping for testing RateLimitGenerator."""
return {"key1": "value1", "key2": "value2"}
@pytest.fixture(autouse=True)
-def reset_rate_limit_instances():
+def reset_rate_limit_instances() -> Generator[None]:
"""Clear RateLimit singleton instances between tests."""
RateLimit._instance_dict.clear()
yield
@@ -118,7 +112,7 @@ def reset_rate_limit_instances():
@pytest.fixture
-def redis_patch():
+def redis_patch() -> Generator[MagicMock]:
"""Patch redis_client globally for rate limit tests."""
with patch("core.app.features.rate_limiting.rate_limit.redis_client") as mock:
yield mock
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 887a879d1c8..8245c53b4ba 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -219,7 +219,6 @@ project-excludes = [
"core/app/apps/workflow/test_generate_task_pipeline.py",
"core/app/apps/workflow/test_generate_task_pipeline_core.py",
"core/app/entities/test_app_invoke_entities.py",
- "core/app/features/rate_limiting/conftest.py",
"core/app/features/rate_limiting/test_rate_limit.py",
"core/app/features/test_annotation_reply.py",
"core/app/features/test_hosting_moderation.py",