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.

test: use real Redis clients for tokens tasks and setup locks (#43168)

Asuka Minato6423a83b78b3
diff --git a/api/tests/unit_tests/conftest.py b/api/tests/unit_tests/conftest.py
index 5afbd4ddb3d..4312e24fe9a 100644
--- a/api/tests/unit_tests/conftest.py
+++ b/api/tests/unit_tests/conftest.py
@@ -10,6 +10,7 @@ from unittest.mock import MagicMock, patch
import pytest
from flask import Flask
+from redis import Redis
from sqlalchemy import create_engine
from sqlalchemy.engine import URL, Engine
from sqlalchemy.orm import Session, sessionmaker
@@ -69,6 +70,16 @@ def _patch_redis_clients_on_loaded_modules() -> None:
setattr(module, client_attribute, redis_mock)
+def redis_transport(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[ext_redis.RedisClientWrapper, MagicMock]]:
+ """Exercise the wrapper and Redis command builders with network dispatch replaced."""
+ apply_config_overrides(monkeypatch, REDIS_KEY_PREFIX="")
+ with Redis() as client, patch.object(client, "execute_command", return_value=None) as commands:
+ wrapper = ext_redis.RedisClientWrapper()
+ wrapper.initialize(client)
+ yield wrapper, commands
+
+
@pytest.fixture
def app() -> Flask:
return CACHED_APP
diff --git a/api/tests/unit_tests/repositories/test_oauth_server_repository.py b/api/tests/unit_tests/repositories/test_oauth_server_repository.py
index 863e93e22ee..fc75780803b 100644
--- a/api/tests/unit_tests/repositories/test_oauth_server_repository.py
+++ b/api/tests/unit_tests/repositories/test_oauth_server_repository.py
@@ -107,8 +107,10 @@ def test_get_account_by_id_returns_none_for_unknown_account(
assert repository.get_account_by_id("missing") is None
-def test_issue_authorization_code_stores_code_with_expiry() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
+def test_issue_authorization_code_stores_code_with_expiry(
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+) -> None:
+ redis, commands = redis_transport
repository = RedisOAuthServerTokenRepository(redis)
deterministic_uuid = uuid.UUID("00000000-0000-0000-0000-000000000111")
@@ -116,16 +118,20 @@ def test_issue_authorization_code_stores_code_with_expiry() -> None:
code = repository.issue_authorization_code("client-1", "account-1")
assert code == str(deterministic_uuid)
- redis.set.assert_called_once_with(
+ commands.assert_called_once_with(
+ "SET",
f"oauth_provider:client-1:authorization_code:{code}",
"account-1",
- ex=OAUTH_AUTHORIZATION_CODE_EXPIRES_IN,
+ "EX",
+ OAUTH_AUTHORIZATION_CODE_EXPIRES_IN,
)
-def test_exchange_authorization_code_consumes_code_and_issues_tokens() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.getdel.return_value = b"account-1"
+def test_exchange_authorization_code_consumes_code_and_issues_tokens(
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+) -> None:
+ redis, commands = redis_transport
+ commands.return_value = b"account-1"
repository = RedisOAuthServerTokenRepository(redis)
token_uuids = [
uuid.UUID("00000000-0000-0000-0000-000000000201"),
@@ -135,31 +141,40 @@ def test_exchange_authorization_code_consumes_code_and_issues_tokens() -> None:
with patch("repositories.oauth_server_repository.uuid.uuid4", side_effect=token_uuids):
access_token, refresh_token = repository.exchange_authorization_code("client-1", "code-1")
- redis.getdel.assert_called_once_with("oauth_provider:client-1:authorization_code:code-1")
- redis.set.assert_any_call(
+ assert commands.call_count == 3
+ commands.assert_any_call("GETDEL", "oauth_provider:client-1:authorization_code:code-1")
+ commands.assert_any_call(
+ "SET",
f"oauth_provider:client-1:access_token:{access_token}",
"account-1",
- ex=OAUTH_ACCESS_TOKEN_EXPIRES_IN,
+ "EX",
+ OAUTH_ACCESS_TOKEN_EXPIRES_IN,
)
- redis.set.assert_any_call(
+ commands.assert_any_call(
+ "SET",
f"oauth_provider:client-1:refresh_token:{refresh_token}",
"account-1",
- ex=OAUTH_REFRESH_TOKEN_EXPIRES_IN,
+ "EX",
+ OAUTH_REFRESH_TOKEN_EXPIRES_IN,
)
-def test_exchange_authorization_code_rejects_unknown_code() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.getdel.return_value = None
+def test_exchange_authorization_code_rejects_unknown_code(
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+) -> None:
+ redis, commands = redis_transport
+ commands.return_value = None
repository = RedisOAuthServerTokenRepository(redis)
with pytest.raises(OAuthServerRequestError, match="invalid code"):
repository.exchange_authorization_code("client-1", "invalid")
-def test_refresh_access_token_issues_access_token_and_reuses_refresh_token() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.return_value = "account-1"
+def test_refresh_access_token_issues_access_token_and_reuses_refresh_token(
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+) -> None:
+ redis, commands = redis_transport
+ commands.return_value = "account-1"
repository = RedisOAuthServerTokenRepository(redis)
deterministic_uuid = uuid.UUID("00000000-0000-0000-0000-000000000301")
@@ -168,12 +183,17 @@ def test_refresh_access_token_issues_access_token_and_reuses_refresh_token() ->
assert access_token == str(deterministic_uuid)
assert refresh_token == "refresh-1"
- redis.get.assert_called_once_with("oauth_provider:client-1:refresh_token:refresh-1")
+ assert commands.call_count == 2
+ commands.assert_any_call(
+ "GET",
+ "oauth_provider:client-1:refresh_token:refresh-1",
+ keys=["oauth_provider:client-1:refresh_token:refresh-1"],
+ )
-def test_refresh_access_token_rejects_unknown_token() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.return_value = None
+def test_refresh_access_token_rejects_unknown_token(redis_transport: tuple[RedisClientWrapper, MagicMock]) -> None:
+ redis, commands = redis_transport
+ commands.return_value = None
repository = RedisOAuthServerTokenRepository(redis)
with pytest.raises(OAuthServerRequestError, match="invalid refresh token"):
@@ -188,10 +208,14 @@ def test_refresh_access_token_rejects_unknown_token() -> None:
(None, None),
],
)
-def test_resolve_account_id(stored_account_id: str | bytes | None, expected: str | None) -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.return_value = stored_account_id
+def test_resolve_account_id(
+ redis_transport: tuple[RedisClientWrapper, MagicMock], stored_account_id: str | bytes | None, expected: str | None
+) -> None:
+ redis, commands = redis_transport
+ commands.return_value = stored_account_id
repository = RedisOAuthServerTokenRepository(redis)
assert repository.resolve_account_id("client-1", "access-1") == expected
- redis.get.assert_called_once_with("oauth_provider:client-1:access_token:access-1")
+ commands.assert_called_once_with(
+ "GET", "oauth_provider:client-1:access_token:access-1", keys=["oauth_provider:client-1:access_token:access-1"]
+ )
diff --git a/api/tests/unit_tests/services/test_app_task_control_service.py b/api/tests/unit_tests/services/test_app_task_control_service.py
index bb1d36f2790..40cc19ff98a 100644
--- a/api/tests/unit_tests/services/test_app_task_control_service.py
+++ b/api/tests/unit_tests/services/test_app_task_control_service.py
@@ -10,10 +10,12 @@ from services.app_task_service import AppTaskControlService
@pytest.mark.parametrize("command_fails", [False, True])
@pytest.mark.parametrize("task_id", ["task-1", ""])
-def test_workflow_stop_sets_flag_before_sending_command(command_fails: bool, task_id: str) -> None:
- redis = MagicMock(spec=RedisClientWrapper)
+def test_workflow_stop_sets_flag_before_sending_command(
+ redis_transport: tuple[RedisClientWrapper, MagicMock], command_fails: bool, task_id: str
+) -> None:
+ redis, commands = redis_transport
events: list[str] = []
- redis.setex.side_effect = lambda *_: events.append("flag")
+ commands.side_effect = lambda *_, **__: events.append("flag")
failure = RuntimeError("command channel unavailable")
def send_stop(requested_task_id: str) -> None:
@@ -35,16 +37,15 @@ def test_workflow_stop_sets_flag_before_sending_command(command_fails: bool, tas
if task_id:
assert events == ["flag", "command"]
- redis.setex.assert_called_once_with("generate_task_stopped:task-1", 600, 1)
+ commands.assert_called_once_with("SETEX", "generate_task_stopped:task-1", 600, 1)
else:
assert events == ["command"]
- redis.setex.assert_not_called()
- redis.get.assert_not_called()
+ commands.assert_not_called()
-def test_flag_failure_does_not_send_command() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.setex.side_effect = RuntimeError("flag store unavailable")
+def test_flag_failure_does_not_send_command(redis_transport: tuple[RedisClientWrapper, MagicMock]) -> None:
+ redis, commands = redis_transport
+ commands.side_effect = RuntimeError("flag store unavailable")
with patch("services.app_task_service.GraphEngineManager") as manager:
with pytest.raises(RuntimeError, match="flag store unavailable"):
AppTaskControlService(redis_client=redis).stop_workflow_task_no_user_check(task_id="task-1")
diff --git a/api/tests/unit_tests/services/test_setup_adapters.py b/api/tests/unit_tests/services/test_setup_adapters.py
index 5457a578a2b..550039b3897 100644
--- a/api/tests/unit_tests/services/test_setup_adapters.py
+++ b/api/tests/unit_tests/services/test_setup_adapters.py
@@ -1,27 +1,31 @@
-from contextlib import nullcontext
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
import pytest
from redis.exceptions import ConnectionError as RedisConnectionError
from redis.exceptions import LockError
+from redis.lock import Lock
from extensions.ext_redis import RedisClientWrapper
from services.setup_adapters import RedisSetupLock
-def test_acquire_uses_bounded_distributed_lock() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.lock.return_value = nullcontext()
- lock = RedisSetupLock(client=redis)
+def test_acquire_uses_bounded_distributed_lock(redis_transport: tuple[RedisClientWrapper, MagicMock]) -> None:
+ redis, commands = redis_transport
+ lock_context = RedisSetupLock(client=redis).acquire()
+ assert isinstance(lock_context, Lock)
+ assert lock_context.name == "setup:initialize"
+ assert lock_context.timeout == 300
+ assert lock_context.blocking_timeout == 300
- with lock.acquire():
- pass
-
- redis.lock.assert_called_once_with(
- "setup:initialize",
- timeout=300,
- blocking_timeout=300,
- )
+ with (
+ patch.object(lock_context, "acquire", return_value=True) as acquire,
+ patch.object(lock_context, "release") as release,
+ ):
+ with lock_context:
+ acquire.assert_called_once()
+ release.assert_not_called()
+ release.assert_called_once()
+ commands.assert_not_called()
@pytest.mark.parametrize(
@@ -31,16 +35,18 @@ def test_acquire_uses_bounded_distributed_lock() -> None:
pytest.param(RedisConnectionError("redis unavailable"), id="connection"),
],
)
-def test_acquire_propagates_distributed_lock_failure(error: Exception) -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- lock_context = MagicMock()
- lock_context.__enter__.side_effect = error
- redis.lock.return_value = lock_context
- lock = RedisSetupLock(client=redis)
-
- with pytest.raises(type(error), match=str(error)) as raised:
- with lock.acquire():
- pytest.fail("lock body must not run")
+def test_acquire_propagates_distributed_lock_failure(
+ redis_transport: tuple[RedisClientWrapper, MagicMock], error: Exception
+) -> None:
+ redis, commands = redis_transport
+ lock_context = RedisSetupLock(client=redis).acquire()
+ assert isinstance(lock_context, Lock)
+
+ with patch.object(lock_context, "acquire", side_effect=error), patch.object(lock_context, "release") as release:
+ with pytest.raises(type(error), match=str(error)) as raised:
+ with lock_context:
+ pytest.fail("lock body must not run")
+ release.assert_not_called()
assert raised.value is error
- lock_context.__exit__.assert_not_called()
+ commands.assert_not_called()