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: eliminate remaining whole config mocks (#40855)

Asuka Minato5fde1d096e5c
diff --git a/api/tests/unit_tests/controllers/console/auth/test_oauth.py b/api/tests/unit_tests/controllers/console/auth/test_oauth.py
index 114612fe5e8..05fa93aa3b3 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_oauth.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_oauth.py
@@ -19,6 +19,11 @@ from models.account import AccountStatus
from services.errors.account import AccountRegisterError
[email protected](autouse=True)
+def _oauth_config(config_overrides) -> None:
+ config_overrides(CONSOLE_WEB_URL="http://localhost:3000")
+
+
class TestGetOAuthProviders:
@pytest.mark.parametrize(
("github_config", "google_config", "expected_github", "expected_google"),
@@ -38,15 +43,16 @@ class TestGetOAuthProviders:
({"id": None, "secret": None}, {"id": None, "secret": None}, False, False),
],
)
- @patch("controllers.console.auth.oauth.dify_config")
def test_should_configure_oauth_providers_correctly(
- self, mock_config, app: Flask, github_config, google_config, expected_github, expected_google
+ self, app: Flask, github_config, google_config, expected_github, expected_google, config_overrides
):
- mock_config.GITHUB_CLIENT_ID = github_config["id"]
- mock_config.GITHUB_CLIENT_SECRET = github_config["secret"]
- mock_config.GOOGLE_CLIENT_ID = google_config["id"]
- mock_config.GOOGLE_CLIENT_SECRET = google_config["secret"]
- mock_config.CONSOLE_API_URL = "http://localhost"
+ config_overrides(
+ GITHUB_CLIENT_ID=github_config["id"],
+ GITHUB_CLIENT_SECRET=github_config["secret"],
+ GOOGLE_CLIENT_ID=google_config["id"],
+ GOOGLE_CLIENT_SECRET=google_config["secret"],
+ CONSOLE_API_URL="http://localhost",
+ )
with app.app_context():
providers = get_oauth_providers()
@@ -188,7 +194,6 @@ class TestOAuthCallback:
return {"provider": oauth_provider, "account": account, "token_pair": token_pair}
- @patch("controllers.console.auth.oauth.dify_config")
@patch("controllers.console.auth.oauth.get_oauth_providers")
@patch("controllers.console.auth.oauth._generate_account")
@patch("controllers.console.auth.oauth.AccountService")
@@ -201,12 +206,10 @@ class TestOAuthCallback:
mock_account_service,
mock_generate_account,
mock_get_providers,
- mock_config,
resource: OAuthCallback,
app: Flask,
oauth_setup,
):
- mock_config.CONSOLE_WEB_URL = "http://localhost:3000"
mock_get_providers.return_value = {"github": oauth_setup["provider"]}
mock_generate_account.return_value = (oauth_setup["account"], True)
mock_account_service.login.return_value = oauth_setup["token_pair"]
@@ -257,7 +260,6 @@ class TestOAuthCallback:
assert status_code == 400
assert response["error"] == expected_error
- @patch("controllers.console.auth.oauth.dify_config")
@patch("controllers.console.auth.oauth.get_oauth_providers")
@patch("controllers.console.auth.oauth.RegisterService")
@patch("controllers.console.auth.oauth.AccountService")
@@ -268,12 +270,10 @@ class TestOAuthCallback:
mock_account_service,
mock_register_service,
mock_get_providers,
- mock_config,
resource: OAuthCallback,
app: Flask,
oauth_setup,
):
- mock_config.CONSOLE_WEB_URL = "http://localhost:3000"
oauth_setup["provider"].get_user_info.return_value = OAuthUserInfo(
id="123", name="Test User", email="[email protected]"
)
@@ -309,7 +309,6 @@ class TestOAuthCallback:
)
@patch("controllers.console.auth.oauth.AccountService")
@patch("controllers.console.auth.oauth.TenantService")
- @patch("controllers.console.auth.oauth.dify_config")
@patch("controllers.console.auth.oauth.get_oauth_providers")
@patch("controllers.console.auth.oauth._generate_account")
@patch("controllers.console.auth.oauth.redirect")
@@ -318,7 +317,6 @@ class TestOAuthCallback:
mock_redirect,
mock_generate_account,
mock_get_providers,
- mock_config,
mock_tenant_service,
mock_account_service,
resource: OAuthCallback,
@@ -328,7 +326,6 @@ class TestOAuthCallback:
expected_redirect,
):
- mock_config.CONSOLE_WEB_URL = "http://localhost:3000"
mock_get_providers.return_value = {"github": oauth_setup["provider"]}
account = MagicMock()
@@ -348,7 +345,6 @@ class TestOAuthCallback:
mock_redirect.assert_called_once_with(expected_redirect)
- @patch("controllers.console.auth.oauth.dify_config")
@patch("controllers.console.auth.oauth.get_oauth_providers")
@patch("controllers.console.auth.oauth._generate_account")
@patch("controllers.console.auth.oauth.TenantService")
@@ -359,7 +355,6 @@ class TestOAuthCallback:
mock_tenant_service,
mock_generate_account,
mock_get_providers,
- mock_config,
resource: OAuthCallback,
app: Flask,
oauth_setup,
@@ -382,7 +377,6 @@ class TestOAuthCallback:
assert mock_account.status == AccountStatus.ACTIVE
assert mock_account.initialized_at is not None
- @patch("controllers.console.auth.oauth.dify_config")
@patch("controllers.console.auth.oauth.get_oauth_providers")
@patch("controllers.console.auth.oauth._generate_account")
@patch("controllers.console.auth.oauth.TenantService")
@@ -395,7 +389,6 @@ class TestOAuthCallback:
mock_tenant_service,
mock_generate_account,
mock_get_providers,
- mock_config,
resource: OAuthCallback,
app: Flask,
oauth_setup,
@@ -421,7 +414,6 @@ class TestOAuthCallback:
Security consideration: Until properly implemented, CLOSED status provides no protection.
"""
# Setup
- mock_config.CONSOLE_WEB_URL = "http://localhost:3000"
mock_get_providers.return_value = {"github": oauth_setup["provider"]}
# Create account with CLOSED status
diff --git a/api/tests/unit_tests/controllers/console/auth/test_oauth_timezone.py b/api/tests/unit_tests/controllers/console/auth/test_oauth_timezone.py
index bb21d6f8ce9..631122177b1 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_oauth_timezone.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_oauth_timezone.py
@@ -109,7 +109,6 @@ def test_generate_account_prefers_state_language_over_accept_language(
mock_link_account.assert_called_once_with("github", "github-123", account, session=ANY)
-@patch("controllers.console.auth.oauth.dify_config")
@patch("controllers.console.auth.oauth.RegisterService")
@patch("controllers.console.auth.oauth.FeatureService")
@patch("controllers.console.auth.oauth._get_account_by_openid_or_email", return_value=None)
@@ -117,11 +116,11 @@ def test_generate_account_rejects_new_user_when_registration_disabled(
mock_get_account,
mock_feature_service,
mock_register_service,
- mock_config,
app: Flask,
+ config_overrides,
):
mock_feature_service.get_system_features.return_value.is_allow_register = False
- mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
user_info = OAuthUserInfo(id="github-123", name="Test User", email="[email protected]")
with app.test_request_context(headers={"Accept-Language": "en-US,en;q=0.9"}):
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py b/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py
index 3e8df467ad1..bc963f7065d 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py
@@ -63,7 +63,6 @@ def controller_module(monkeypatch: pytest.MonkeyPatch):
("controllers.console.wraps.is_admin_or_owner_required", _noop),
("controllers.console.wraps.enterprise_license_required", _noop),
]
- monkeypatch.setenv("DIFY_SETUP_READY", "true")
with ExitStack() as stack:
for target, value in patch_targets:
stack.enter_context(patch(target, value))
diff --git a/api/tests/unit_tests/controllers/openapi/test_oauth_sso_host_header.py b/api/tests/unit_tests/controllers/openapi/test_oauth_sso_host_header.py
index 95f31482e9f..6d0bb826ff4 100644
--- a/api/tests/unit_tests/controllers/openapi/test_oauth_sso_host_header.py
+++ b/api/tests/unit_tests/controllers/openapi/test_oauth_sso_host_header.py
@@ -28,13 +28,14 @@ def _ee_features():
@patch("controllers.openapi.oauth_device_sso.EnterpriseService")
@patch("controllers.openapi.oauth_device_sso.jws")
@patch("controllers.openapi.oauth_device_sso.DeviceFlowRedis")
-@patch("controllers.openapi.oauth_device_sso.dify_config")
@patch("libs.device_flow_security.FeatureService.get_system_features")
@patch("libs.rate_limit.RateLimiter.is_rate_limited", new=MagicMock(return_value=False))
@patch("libs.rate_limit.RateLimiter.increment_rate_limit", new=MagicMock())
-def test_idp_callback_url_uses_console_api_url_not_host_header(ee_feat, cfg, redis_cls, jws_mod, ent, app: Flask):
+def test_idp_callback_url_uses_console_api_url_not_host_header(
+ ee_feat, redis_cls, jws_mod, ent, app: Flask, config_overrides
+):
ee_feat.return_value = _ee_features()
- cfg.CONSOLE_API_URL = "https://api.dify.example"
+ config_overrides(CONSOLE_API_URL="https://api.dify.example")
state = MagicMock()
from services.oauth_device_flow import DeviceFlowStatus
@@ -60,13 +61,12 @@ def test_idp_callback_url_uses_console_api_url_not_host_header(ee_feat, cfg, red
@patch("controllers.openapi.oauth_device_sso.DeviceFlowRedis")
-@patch("controllers.openapi.oauth_device_sso.dify_config")
@patch("libs.device_flow_security.FeatureService.get_system_features")
@patch("libs.rate_limit.RateLimiter.is_rate_limited", new=MagicMock(return_value=False))
@patch("libs.rate_limit.RateLimiter.increment_rate_limit", new=MagicMock())
-def test_sso_initiate_fails_closed_when_console_api_url_unset(ee_feat, cfg, redis_cls, app: Flask):
+def test_sso_initiate_fails_closed_when_console_api_url_unset(ee_feat, redis_cls, app: Flask, config_overrides):
ee_feat.return_value = _ee_features()
- cfg.CONSOLE_API_URL = ""
+ config_overrides(CONSOLE_API_URL="")
from services.oauth_device_flow import DeviceFlowStatus
state = MagicMock()
diff --git a/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py b/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py
index e9fca80d61f..c888bef060d 100644
--- a/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py
+++ b/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py
@@ -392,8 +392,10 @@ class TestMessageCycleManagerOptimization:
cycle_db: Session,
sqlite_engine: Engine,
caplog: pytest.LogCaptureFixture,
+ config_overrides,
):
"""Fallback to truncated query when LLM generation fails."""
+ config_overrides(DEBUG=True)
flask_app = Flask(__name__)
cycle_db.add_all([_app(), _conversation()])
cycle_db.commit()
@@ -402,12 +404,9 @@ class TestMessageCycleManagerOptimization:
with (
patch("core.app.task_pipeline.message_cycle_manager.redis_client") as mock_redis,
patch("core.app.task_pipeline.message_cycle_manager.LLMGenerator") as mock_llm_generator,
- patch("core.app.task_pipeline.message_cycle_manager.dify_config") as mock_dify_config,
):
mock_redis.get.return_value = None
mock_llm_generator.generate_conversation_name.side_effect = RuntimeError("generation failed")
- mock_dify_config.DEBUG = True
-
with caplog.at_level(logging.ERROR, logger="core.app.task_pipeline.message_cycle_manager"):
message_cycle_manager._generate_conversation_name_worker(flask_app, "conv-1", long_query)
diff --git a/api/tests/unit_tests/core/trigger/test_trigger_manager.py b/api/tests/unit_tests/core/trigger/test_trigger_manager.py
index 612be25ec9d..e1999d92caa 100644
--- a/api/tests/unit_tests/core/trigger/test_trigger_manager.py
+++ b/api/tests/unit_tests/core/trigger/test_trigger_manager.py
@@ -31,10 +31,9 @@ PID_STR = str(PID)
class TestGetTriggerPluginIcon:
- @patch("core.trigger.trigger_manager.dify_config")
@patch("core.trigger.trigger_manager.PluginTriggerClient")
- def test_builds_correct_url(self, mock_client, mock_config):
- mock_config.CONSOLE_API_URL = "https://console.example.com"
+ def test_builds_correct_url(self, mock_client, config_overrides):
+ config_overrides(CONSOLE_API_URL="https://console.example.com")
provider = MagicMock()
provider.declaration.identity.icon = "my-icon.svg"
mock_client.return_value.fetch_trigger_provider.return_value = provider
diff --git a/api/tests/unit_tests/oss/volcengine_tos/test_volcengine_tos.py b/api/tests/unit_tests/oss/volcengine_tos/test_volcengine_tos.py
index 8adea888115..d33988be741 100644
--- a/api/tests/unit_tests/oss/volcengine_tos/test_volcengine_tos.py
+++ b/api/tests/unit_tests/oss/volcengine_tos/test_volcengine_tos.py
@@ -1,5 +1,3 @@
-from unittest.mock import patch
-
import pytest
from tos import TosClientV2
@@ -14,14 +12,15 @@ pytest_plugins = ("tests.unit_tests.oss.__mock.volcengine_tos",)
class TestVolcengineTos(BaseStorageTest):
@pytest.fixture(autouse=True)
- def setup_method(self, setup_volcengine_tos_mock):
+ def setup_method(self, setup_volcengine_tos_mock, config_overrides):
"""Executed before each test method."""
- with patch("extensions.storage.volcengine_tos_storage.dify_config") as mock_config:
- mock_config.VOLCENGINE_TOS_ACCESS_KEY = "test_access_key"
- mock_config.VOLCENGINE_TOS_SECRET_KEY = "test_secret_key"
- mock_config.VOLCENGINE_TOS_ENDPOINT = "test_endpoint"
- mock_config.VOLCENGINE_TOS_REGION = "test_region"
- self.storage = VolcengineTosStorage()
+ config_overrides(
+ VOLCENGINE_TOS_ACCESS_KEY="test_access_key",
+ VOLCENGINE_TOS_SECRET_KEY="test_secret_key",
+ VOLCENGINE_TOS_ENDPOINT="test_endpoint",
+ VOLCENGINE_TOS_REGION="test_region",
+ )
+ self.storage = VolcengineTosStorage()
self.storage.bucket_name = get_example_bucket()
self.storage.client = TosClientV2(
diff --git a/api/tests/unit_tests/services/openapi/test_mint_policy.py b/api/tests/unit_tests/services/openapi/test_mint_policy.py
index 80425725f39..e3bf6cd9d0e 100644
--- a/api/tests/unit_tests/services/openapi/test_mint_policy.py
+++ b/api/tests/unit_tests/services/openapi/test_mint_policy.py
@@ -75,21 +75,18 @@ def test_message_carries_both_drift_reasons():
assert "scopes" in msg
-def test_license_required_decorator_skips_on_ce():
- from unittest.mock import patch
-
+def test_license_required_decorator_skips_on_ce(config_overrides):
from services.openapi.license_gate import license_required
@license_required
def view():
return "ok"
- with patch("services.openapi.license_gate.dify_config") as cfg:
- cfg.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY
- assert view() == "ok"
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
+ assert view() == "ok"
-def test_license_required_decorator_403_on_invalid_ee_license():
+def test_license_required_decorator_403_on_invalid_ee_license(config_overrides):
from unittest.mock import patch
from werkzeug.exceptions import Forbidden
@@ -100,17 +97,16 @@ def test_license_required_decorator_403_on_invalid_ee_license():
def view():
return "ok"
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
with (
- patch("services.openapi.license_gate.dify_config") as cfg,
patch("services.openapi.license_gate._is_license_valid", return_value=False),
):
- cfg.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISE
with pytest.raises(Forbidden) as exc:
view()
assert "license_required" in exc.value.description
-def test_license_required_decorator_passes_on_valid_ee_license():
+def test_license_required_decorator_passes_on_valid_ee_license(config_overrides):
from unittest.mock import patch
from services.openapi.license_gate import license_required
@@ -119,9 +115,8 @@ def test_license_required_decorator_passes_on_valid_ee_license():
def view():
return "ok"
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
with (
- patch("services.openapi.license_gate.dify_config") as cfg,
patch("services.openapi.license_gate._is_license_valid", return_value=True),
):
- cfg.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISE
assert view() == "ok"
diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.py
index 21f183f6dda..457ddbc7081 100644
--- a/api/tests/unit_tests/services/test_account_service.py
+++ b/api/tests/unit_tests/services/test_account_service.py
@@ -1,5 +1,5 @@
import json
-from collections.abc import Iterator, Sequence
+from collections.abc import Callable, Iterator, Sequence
from datetime import datetime, timedelta
from unittest.mock import MagicMock, patch
from uuid import UUID
@@ -2288,18 +2288,19 @@ class TestRegisterService:
# ==================== RBAC Member Invitation Tests ====================
@pytest.mark.usefixtures("mock_task_dependencies")
- def test_invite_new_member_rbac_enabled_new_account(self, sqlite_session: Session) -> None:
+ def test_invite_new_member_rbac_enabled_new_account(
+ self, sqlite_session: Session, config_overrides: Callable[..., None]
+ ) -> None:
"""When RBAC is enabled, create the member join and replace RBAC member roles."""
+ config_overrides(RBAC_ENABLED=True)
mock_tenant = _tenant(sqlite_session)
mock_tenant.id = "tenant-789"
mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-456", name="Inviter")
with (
patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,
- patch("services.account_service.dify_config") as mock_config,
):
mock_lookup.return_value = None
- mock_config.RBAC_ENABLED = True
mock_new_account = TestAccountAssociatedDataFactory.create_account_mock(
account_id="new-user-rbac", email="[email protected]", name="rbacuser", status="pending"
@@ -2336,8 +2337,11 @@ class TestRegisterService:
)
@pytest.mark.usefixtures("mock_task_dependencies")
- def test_invite_new_member_rbac_enabled_existing_account(self, sqlite_session: Session) -> None:
+ def test_invite_new_member_rbac_enabled_existing_account(
+ self, sqlite_session: Session, config_overrides: Callable[..., None]
+ ) -> None:
"""When RBAC is enabled and account exists, create the member join and replace RBAC member roles."""
+ config_overrides(RBAC_ENABLED=True)
mock_tenant = _tenant(sqlite_session)
mock_tenant.id = "tenant-789"
mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-456", name="Inviter")
@@ -2347,10 +2351,8 @@ class TestRegisterService:
with (
patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,
- patch("services.account_service.dify_config") as mock_config,
):
mock_lookup.return_value = mock_existing_account
- mock_config.RBAC_ENABLED = True
with (
patch("services.account_service.TenantService.check_member_permission"),
@@ -2383,9 +2385,13 @@ class TestRegisterService:
)
def test_invite_new_member_rbac_enabled_existing_active_account_adds_role_before_signin_response(
- self, sqlite_session: Session, mock_task_dependencies: MagicMock
+ self,
+ sqlite_session: Session,
+ mock_task_dependencies: MagicMock,
+ config_overrides: Callable[..., None],
) -> None:
"""Existing active accounts still need an RBAC membership before the API returns the signin URL."""
+ config_overrides(RBAC_ENABLED=True)
mock_tenant = _tenant(sqlite_session)
mock_tenant.id = "tenant-789"
mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-456", name="Inviter")
@@ -2395,10 +2401,8 @@ class TestRegisterService:
with (
patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,
- patch("services.account_service.dify_config") as mock_config,
):
mock_lookup.return_value = mock_existing_account
- mock_config.RBAC_ENABLED = True
with (
patch("services.account_service.TenantService.check_member_permission"),
@@ -2431,18 +2435,19 @@ class TestRegisterService:
mock_task_dependencies.delay.assert_not_called()
@pytest.mark.usefixtures("mock_task_dependencies")
- def test_invite_new_member_rbac_disabled_uses_legacy_role(self, sqlite_session: Session) -> None:
+ def test_invite_new_member_rbac_disabled_uses_legacy_role(
+ self, sqlite_session: Session, config_overrides: Callable[..., None]
+ ) -> None:
"""When RBAC is disabled, create_tenant_member should be called and MemberRoles.replace should NOT."""
+ config_overrides(RBAC_ENABLED=False)
mock_tenant = _tenant(sqlite_session)
mock_tenant.id = "tenant-legacy"
mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-789", name="Inviter")
with (
patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,
- patch("services.account_service.dify_config") as mock_config,
):
mock_lookup.return_value = None
- mock_config.RBAC_ENABLED = False
mock_new_account = TestAccountAssociatedDataFactory.create_account_mock(
account_id="legacy-user", email="[email protected]", name="legacyuser", status="pending"
diff --git a/api/tests/unit_tests/services/test_app_service.py b/api/tests/unit_tests/services/test_app_service.py
index 794e146db97..f33c3082e52 100644
--- a/api/tests/unit_tests/services/test_app_service.py
+++ b/api/tests/unit_tests/services/test_app_service.py
@@ -642,7 +642,6 @@ class TestAgentAppType:
patch("services.app_service.BillingService"),
patch("services.app_service.EnterpriseService"),
patch("services.app_service.FeatureService"),
- patch("services.app_service.dify_config"),
patch("services.app_service.remove_app_and_related_data_task"),
patch(
"services.app_service.AgentHomeSnapshotService.retire_all_for_agent",
diff --git a/api/tests/unit_tests/services/test_archive_workflow_run_logs.py b/api/tests/unit_tests/services/test_archive_workflow_run_logs.py
index 5177167ed0e..bf54be40405 100644
--- a/api/tests/unit_tests/services/test_archive_workflow_run_logs.py
+++ b/api/tests/unit_tests/services/test_archive_workflow_run_logs.py
@@ -15,13 +15,12 @@ from enums import DeploymentEdition
class TestWorkflowRunArchiver:
"""Tests for the WorkflowRunArchiver class."""
- @patch("services.retention.workflow_run.archive_paid_plan_workflow_run.dify_config")
@patch("services.retention.workflow_run.archive_paid_plan_workflow_run.get_archive_storage", autospec=True)
- def test_archiver_initialization(self, mock_get_storage, mock_config):
+ def test_archiver_initialization(self, mock_get_storage, config_overrides):
"""Test archiver can be initialized with various options."""
from services.retention.workflow_run.archive_paid_plan_workflow_run import WorkflowRunArchiver
- mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
archiver = WorkflowRunArchiver(
days=90,
diff --git a/api/tests/unit_tests/services/test_conversation_service.py b/api/tests/unit_tests/services/test_conversation_service.py
index 9476de34394..0f2d94a877f 100644
--- a/api/tests/unit_tests/services/test_conversation_service.py
+++ b/api/tests/unit_tests/services/test_conversation_service.py
@@ -8,7 +8,7 @@ in-memory SQLite sessions with persisted ORM rows.
"""
import json
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock
import pytest
from sqlalchemy import asc, desc, event
@@ -389,11 +389,10 @@ class TestConversationServiceConversationalVariable:
"""Test conversational variable operations."""
@pytest.mark.parametrize("sqlite_session", [(Conversation, ConversationVariable)], indirect=True)
- @patch("services.conversation_service.dify_config")
def test_get_conversational_variable_with_name_filter_mysql(
self,
- mock_config,
sqlite_session: Session,
+ config_overrides,
):
"""
Test variable filtering by name for MySQL databases.
@@ -436,7 +435,7 @@ class TestConversationServiceConversationalVariable:
]
)
sqlite_session.commit()
- mock_config.DB_TYPE = "mysql"
+ config_overrides(DB_TYPE="mysql")
# Act
result = ConversationService.get_conversational_variable(
diff --git a/api/tests/unit_tests/services/test_feature_service_vector_space.py b/api/tests/unit_tests/services/test_feature_service_vector_space.py
index 54f98d4b6db..5a7cfc1dda4 100644
--- a/api/tests/unit_tests/services/test_feature_service_vector_space.py
+++ b/api/tests/unit_tests/services/test_feature_service_vector_space.py
@@ -7,7 +7,7 @@ from services.entities.feature_entities import LimitationModel
from services.feature_service import FeatureService
-def test_get_features_exclude_vector_space_sets_vector_space_to_none():
+def test_get_features_exclude_vector_space_sets_vector_space_to_none(config_overrides):
tenant_id = "tenant-id"
billing_info = {
"enabled": True,
@@ -23,17 +23,17 @@ def test_get_features_exclude_vector_space_sets_vector_space_to_none():
"knowledge_pipeline_publish_enabled": True,
}
+ config_overrides(
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ CAN_REPLACE_LOGO=False,
+ MODEL_LB_ENABLED=False,
+ DATASET_OPERATOR_ENABLED=False,
+ EDUCATION_ENABLED=False,
+ )
with (
- patch("services.feature_service.dify_config") as mock_config,
patch("services.feature_service.BillingService.get_info", return_value=billing_info) as get_info,
patch("services.feature_service.BillingService.get_quota_info", return_value={}),
):
- mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD
- mock_config.CAN_REPLACE_LOGO = False
- mock_config.MODEL_LB_ENABLED = False
- mock_config.DATASET_OPERATOR_ENABLED = False
- mock_config.EDUCATION_ENABLED = False
-
features = FeatureService.get_features(tenant_id, exclude_vector_space=True)
assert features.vector_space is None
diff --git a/api/tests/unit_tests/services/test_messages_clean_service.py b/api/tests/unit_tests/services/test_messages_clean_service.py
index a7b0a68d2ec..fc659e7b5cf 100644
--- a/api/tests/unit_tests/services/test_messages_clean_service.py
+++ b/api/tests/unit_tests/services/test_messages_clean_service.py
@@ -403,11 +403,10 @@ class TestBillingDisabledPolicyFilterMessageIds:
class TestCreateMessageCleanPolicy:
"""Unit tests for create_message_clean_policy factory function."""
- @patch("services.retention.conversation.messages_clean_policy.dify_config")
- def test_non_cloud_edition_returns_billing_disabled_policy(self, mock_config):
+ def test_non_cloud_edition_returns_billing_disabled_policy(self, config_overrides):
"""Test that the Community edition returns BillingDisabledPolicy."""
# Arrange
- mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
# Act
policy = create_message_clean_policy(graceful_period_days=21)
@@ -416,11 +415,10 @@ class TestCreateMessageCleanPolicy:
assert isinstance(policy, BillingDisabledPolicy)
@patch("services.retention.conversation.messages_clean_policy.BillingService", autospec=True)
- @patch("services.retention.conversation.messages_clean_policy.dify_config")
- def test_cloud_edition_policy_has_correct_internals(self, mock_config, mock_billing_service):
+ def test_cloud_edition_policy_has_correct_internals(self, mock_billing_service, config_overrides):
"""Test that BillingSandboxPolicy is created with correct internal values."""
# Arrange
- mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
whitelist = ["tenant1", "tenant2"]
mock_billing_service.get_expired_subscription_cleanup_whitelist.return_value = whitelist
mock_plan_provider = MagicMock()
diff --git a/api/tests/unit_tests/services/tools/test_tools_transform_service.py b/api/tests/unit_tests/services/tools/test_tools_transform_service.py
index dcc02d0cf00..04e1651c7e0 100644
--- a/api/tests/unit_tests/services/tools/test_tools_transform_service.py
+++ b/api/tests/unit_tests/services/tools/test_tools_transform_service.py
@@ -401,18 +401,16 @@ class TestWorkflowProviderToUserProvider:
class TestGetToolProviderIconUrl:
- def test_builtin_provider_returns_console_url(self):
- with patch(f"{MODULE}.dify_config") as cfg:
- cfg.CONSOLE_API_URL = "https://app.dify.ai"
- url = ToolTransformService.get_tool_provider_icon_url("builtin", "google", "icon.png")
+ def test_builtin_provider_returns_console_url(self, config_overrides):
+ config_overrides(CONSOLE_API_URL="https://app.dify.ai")
+ url = ToolTransformService.get_tool_provider_icon_url("builtin", "google", "icon.png")
assert "/builtin/google/icon" in url
assert url.startswith("https://app.dify.ai/console/api/workspaces/current/tool-provider")
- def test_builtin_provider_with_no_console_url(self):
- with patch(f"{MODULE}.dify_config") as cfg:
- cfg.CONSOLE_API_URL = None
- url = ToolTransformService.get_tool_provider_icon_url("builtin", "slack", "icon.png")
+ def test_builtin_provider_with_no_console_url(self, config_overrides):
+ config_overrides(CONSOLE_API_URL=None)
+ url = ToolTransformService.get_tool_provider_icon_url("builtin", "slack", "icon.png")
assert "/builtin/slack/icon" in url
diff --git a/api/tests/unit_tests/tasks/test_mail_send_task.py b/api/tests/unit_tests/tasks/test_mail_send_task.py
index 6862daaeb90..e14c0a3a0de 100644
--- a/api/tests/unit_tests/tasks/test_mail_send_task.py
+++ b/api/tests/unit_tests/tasks/test_mail_send_task.py
@@ -15,7 +15,6 @@ from unittest.mock import ANY, MagicMock, patch
import pytest
from python_http_client.exceptions import ForbiddenError, UnauthorizedError
-from configs import dify_config
from configs.feature import TemplateMode
from extensions.ext_mail import Mail
from libs.email_i18n import EmailI18nConfig, EmailI18nService, EmailLanguage, EmailTemplate, EmailType
@@ -36,93 +35,90 @@ from tasks.mail_reset_password_task import (
class TestEmailTemplateRendering:
"""Test email template rendering with various scenarios."""
- def test_render_template_unsafe_mode(self):
+ def test_render_template_unsafe_mode(self, config_overrides):
"""Test template rendering in unsafe mode with Jinja2 syntax."""
# Arrange
body = "Hello {{ name }}, your code is {{ code }}"
substitutions = {"name": "John", "code": "123456"}
# Act
- with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.UNSAFE):
- result = _render_template_with_strategy(body, substitutions)
+ config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.UNSAFE)
+ result = _render_template_with_strategy(body, substitutions)
# Assert
assert result == "Hello John, your code is 123456"
- def test_render_template_sandbox_mode(self):
+ def test_render_template_sandbox_mode(self, config_overrides):
"""Test template rendering in sandbox mode for security."""
# Arrange
body = "Hello {{ name }}, your code is {{ code }}"
substitutions = {"name": "Alice", "code": "654321"}
# Act
- with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
- with patch.object(dify_config, "MAIL_TEMPLATING_TIMEOUT", 3):
- result = _render_template_with_strategy(body, substitutions)
+ config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX, MAIL_TEMPLATING_TIMEOUT=3)
+ result = _render_template_with_strategy(body, substitutions)
# Assert
assert result == "Hello Alice, your code is 654321"
- def test_render_template_disabled_mode(self):
+ def test_render_template_disabled_mode(self, config_overrides):
"""Test template rendering when templating is disabled."""
# Arrange
body = "Hello {{ name }}, your code is {{ code }}"
substitutions = {"name": "Bob", "code": "999999"}
# Act
- with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.DISABLED):
- result = _render_template_with_strategy(body, substitutions)
+ config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.DISABLED)
+ result = _render_template_with_strategy(body, substitutions)
# Assert - should return body unchanged
assert result == "Hello {{ name }}, your code is {{ code }}"
- def test_render_template_sandbox_timeout(self):
+ def test_render_template_sandbox_timeout(self, config_overrides):
"""Test that sandbox mode respects timeout settings and range limits."""
# Arrange - template with very large range (exceeds sandbox MAX_RANGE)
body = "{% for i in range(1000000) %}{{ i }}{% endfor %}"
substitutions: dict[str, str] = {}
# Act & Assert - sandbox blocks ranges larger than MAX_RANGE (100000)
- with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
- with patch.object(dify_config, "MAIL_TEMPLATING_TIMEOUT", 1):
- # Should raise OverflowError for range too big
- with pytest.raises((TimeoutError, RuntimeError, OverflowError)):
- _render_template_with_strategy(body, substitutions)
+ config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX, MAIL_TEMPLATING_TIMEOUT=1)
+ with pytest.raises((TimeoutError, RuntimeError, OverflowError)):
+ _render_template_with_strategy(body, substitutions)
- def test_render_template_invalid_mode(self):
+ def test_render_template_invalid_mode(self, config_overrides):
"""Test that invalid template mode raises ValueError."""
# Arrange
body = "Test"
substitutions: dict[str, str] = {}
# Act & Assert
- with patch.object(dify_config, "MAIL_TEMPLATING_MODE", "invalid_mode"):
- with pytest.raises(ValueError, match="Unsupported mail templating mode"):
- _render_template_with_strategy(body, substitutions)
+ config_overrides(MAIL_TEMPLATING_MODE="invalid_mode")
+ with pytest.raises(ValueError, match="Unsupported mail templating mode"):
+ _render_template_with_strategy(body, substitutions)
- def test_render_template_with_special_characters(self):
+ def test_render_template_with_special_characters(self, config_overrides):
"""Test template rendering with special characters and HTML."""
# Arrange
body = "<h1>Hello {{ name }}</h1><p>Code: {{ code }}</p>"
substitutions = {"name": "Test<User>", "code": "ABC&123"}
# Act
- with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
- result = _render_template_with_strategy(body, substitutions)
+ config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX)
+ result = _render_template_with_strategy(body, substitutions)
# Assert
assert "Test<User>" in result
assert "ABC&123" in result
- def test_render_template_missing_variable_sandbox(self):
+ def test_render_template_missing_variable_sandbox(self, config_overrides):
"""Test sandbox mode handles missing variables gracefully."""
# Arrange
body = "Hello {{ name }}, your code is {{ missing_var }}"
substitutions = {"name": "John"}
# Act - sandbox mode renders undefined variables as empty strings by default
- with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
- result = _render_template_with_strategy(body, substitutions)
+ config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX)
+ result = _render_template_with_strategy(body, substitutions)
# Assert - undefined variable is rendered as empty string
assert "Hello John" in result
@@ -426,12 +422,11 @@ class TestMailTaskRetryLogic:
@patch("tasks.mail_reset_password_task.get_email_i18n_service")
@patch("tasks.mail_reset_password_task.mail")
- @patch("tasks.mail_reset_password_task.dify_config")
- def test_reset_password_when_account_not_exist_with_register(self, mock_config, mock_mail, mock_email_service):
+ def test_reset_password_when_account_not_exist_with_register(self, mock_mail, mock_email_service, config_overrides):
"""Test reset password task when account doesn't exist and registration is allowed."""
# Arrange
mock_mail.is_inited.return_value = True
- mock_config.CONSOLE_WEB_URL = "https://console.example.com"
+ config_overrides(CONSOLE_WEB_URL="https://console.example.com")
mock_service = MagicMock()
mock_email_service.return_value = mock_service
@@ -504,12 +499,11 @@ class TestMailTaskInternationalization:
@patch("tasks.mail_register_task.get_email_i18n_service")
@patch("tasks.mail_register_task.mail")
- @patch("tasks.mail_register_task.dify_config")
- def test_account_exist_task_includes_urls(self, mock_config, mock_mail, mock_email_service):
+ def test_account_exist_task_includes_urls(self, mock_mail, mock_email_service, config_overrides):
"""Test account exist task includes proper URLs in template context."""
# Arrange
mock_mail.is_inited.return_value = True
- mock_config.CONSOLE_WEB_URL = "https://console.example.com"
+ config_overrides(CONSOLE_WEB_URL="https://console.example.com")
mock_service = MagicMock()
mock_email_service.return_value = mock_service
@@ -682,19 +676,22 @@ class TestSendGridIntegration:
class TestMailExtension:
"""Test mail extension initialization and configuration."""
- @patch("extensions.ext_mail.dify_config")
- def test_mail_init_smtp_configuration(self, mock_config):
+ @pytest.fixture(autouse=True)
+ def _smtp_config(self, config_overrides) -> None:
+ config_overrides(
+ MAIL_TYPE="smtp",
+ SMTP_SERVER="smtp.example.com",
+ SMTP_PORT=465,
+ SMTP_USERNAME="[email protected]",
+ SMTP_PASSWORD="password123",
+ SMTP_USE_TLS=True,
+ SMTP_OPPORTUNISTIC_TLS=False,
+ MAIL_DEFAULT_SEND_FROM="[email protected]",
+ )
+
+ def test_mail_init_smtp_configuration(self):
"""Test mail extension initializes SMTP client correctly."""
# Arrange
- mock_config.MAIL_TYPE = "smtp"
- mock_config.SMTP_SERVER = "smtp.example.com"
- mock_config.SMTP_PORT = 465
- mock_config.SMTP_USERNAME = "[email protected]"
- mock_config.SMTP_PASSWORD = "password123"
- mock_config.SMTP_USE_TLS = True
- mock_config.SMTP_OPPORTUNISTIC_TLS = False
- mock_config.MAIL_DEFAULT_SEND_FROM = "[email protected]"
-
mail = Mail()
mock_app = MagicMock()
@@ -705,11 +702,10 @@ class TestMailExtension:
assert mail.is_inited() is True
assert mail._client is not None
- @patch("extensions.ext_mail.dify_config")
- def test_mail_init_without_mail_type(self, mock_config):
+ def test_mail_init_without_mail_type(self, config_overrides):
"""Test mail extension skips initialization when MAIL_TYPE is not set."""
# Arrange
- mock_config.MAIL_TYPE = None
+ config_overrides(MAIL_TYPE=None)
mail = Mail()
mock_app = MagicMock()
@@ -720,8 +716,7 @@ class TestMailExtension:
# Assert
assert mail.is_inited() is False
- @patch("extensions.ext_mail.dify_config")
- def test_mail_send_validates_parameters(self, mock_config):
+ def test_mail_send_validates_parameters(self):
"""Test mail send validates required parameters."""
# Arrange
mail = Mail()
@@ -740,8 +735,7 @@ class TestMailExtension:
with pytest.raises(ValueError, match="mail html is not set"):
mail.send(to="[email protected]", subject="Test", html="")
- @patch("extensions.ext_mail.dify_config")
- def test_mail_send_uses_default_from(self, mock_config):
+ def test_mail_send_uses_default_from(self):
"""Test mail send uses default from address when not provided."""
# Arrange
mail = Mail()
@@ -892,8 +886,7 @@ class TestEdgeCasesAndErrorHandling:
and various error scenarios to ensure robust error handling.
"""
- @patch("extensions.ext_mail.dify_config")
- def test_mail_init_invalid_smtp_config_missing_server(self, mock_config):
+ def test_mail_init_invalid_smtp_config_missing_server(self, config_overrides):
"""
Test mail initialization fails when SMTP server is missing.
@@ -901,9 +894,7 @@ class TestEdgeCasesAndErrorHandling:
configuration parameters are not provided.
"""
# Arrange
- mock_config.MAIL_TYPE = "smtp"
- mock_config.SMTP_SERVER = None # Missing required parameter
- mock_config.SMTP_PORT = 465
+ config_overrides(MAIL_TYPE="smtp", SMTP_SERVER=None, SMTP_PORT=465)
mail = Mail()
mock_app = MagicMock()
@@ -912,8 +903,7 @@ class TestEdgeCasesAndErrorHandling:
with pytest.raises(ValueError, match="SMTP_SERVER and SMTP_PORT are required"):
mail.init_app(mock_app)
- @patch("extensions.ext_mail.dify_config")
- def test_mail_init_invalid_smtp_opportunistic_tls_without_tls(self, mock_config):
+ def test_mail_init_invalid_smtp_opportunistic_tls_without_tls(self, config_overrides):
"""
Test mail initialization fails with opportunistic TLS but TLS disabled.
@@ -921,11 +911,13 @@ class TestEdgeCasesAndErrorHandling:
This test ensures the configuration is validated properly.
"""
# Arrange
- mock_config.MAIL_TYPE = "smtp"
- mock_config.SMTP_SERVER = "smtp.example.com"
- mock_config.SMTP_PORT = 587
- mock_config.SMTP_USE_TLS = False # TLS disabled
- mock_config.SMTP_OPPORTUNISTIC_TLS = True # But opportunistic TLS enabled
+ config_overrides(
+ MAIL_TYPE="smtp",
+ SMTP_SERVER="smtp.example.com",
+ SMTP_PORT=587,
+ SMTP_USE_TLS=False,
+ SMTP_OPPORTUNISTIC_TLS=True,
+ )
mail = Mail()
mock_app = MagicMock()
@@ -934,8 +926,7 @@ class TestEdgeCasesAndErrorHandling:
with pytest.raises(ValueError, match="SMTP_OPPORTUNISTIC_TLS is not supported without enabling SMTP_USE_TLS"):
mail.init_app(mock_app)
- @patch("extensions.ext_mail.dify_config")
- def test_mail_init_unsupported_mail_type(self, mock_config):
+ def test_mail_init_unsupported_mail_type(self, config_overrides):
"""
Test mail initialization fails with unsupported mail type.
@@ -943,7 +934,7 @@ class TestEdgeCasesAndErrorHandling:
are accepted and invalid types are rejected.
"""
# Arrange
- mock_config.MAIL_TYPE = "unsupported_provider"
+ config_overrides(MAIL_TYPE="unsupported_provider")
mail = Mail()
mock_app = MagicMock()
@@ -1081,9 +1072,17 @@ class TestResendIntegration:
instead of SMTP or SendGrid.
"""
+ @pytest.fixture(autouse=True)
+ def _resend_config(self, config_overrides) -> None:
+ config_overrides(
+ MAIL_TYPE="resend",
+ RESEND_API_KEY="re_test_api_key",
+ RESEND_API_URL=None,
+ MAIL_DEFAULT_SEND_FROM="[email protected]",
+ )
+
@patch("builtins.__import__", side_effect=__import__)
- @patch("extensions.ext_mail.dify_config")
- def test_mail_init_resend_configuration(self, mock_config, mock_import):
+ def test_mail_init_resend_configuration(self, mock_import):
"""
Test mail extension initializes Resend client correctly.
@@ -1091,11 +1090,6 @@ class TestResendIntegration:
and the client is initialized.
"""
# Arrange
- mock_config.MAIL_TYPE = "resend"
- mock_config.RESEND_API_KEY = "re_test_api_key"
- mock_config.RESEND_API_URL = None
- mock_config.MAIL_DEFAULT_SEND_FROM = "[email protected]"
-
# Create mock resend module
mock_resend = MagicMock()
mock_emails = MagicMock()
@@ -1122,8 +1116,7 @@ class TestResendIntegration:
assert mock_resend.api_key == "re_test_api_key"
@patch("builtins.__import__", side_effect=__import__)
- @patch("extensions.ext_mail.dify_config")
- def test_mail_init_resend_with_custom_url(self, mock_config, mock_import):
+ def test_mail_init_resend_with_custom_url(self, mock_import, config_overrides):
"""
Test mail extension initializes Resend with custom API URL.
@@ -1131,10 +1124,7 @@ class TestResendIntegration:
This test ensures custom URLs are properly configured.
"""
# Arrange
- mock_config.MAIL_TYPE = "resend"
- mock_config.RESEND_API_KEY = "re_test_api_key"
- mock_config.RESEND_API_URL = "https://custom-resend.example.com"
- mock_config.MAIL_DEFAULT_SEND_FROM = "[email protected]"
+ config_overrides(RESEND_API_URL="https://custom-resend.example.com")
# Create mock resend module
mock_resend = MagicMock()
@@ -1161,8 +1151,7 @@ class TestResendIntegration:
assert mail.is_inited() is True
assert mock_resend.api_url == "https://custom-resend.example.com"
- @patch("extensions.ext_mail.dify_config")
- def test_mail_init_resend_missing_api_key(self, mock_config):
+ def test_mail_init_resend_missing_api_key(self, config_overrides):
"""
Test mail initialization fails when Resend API key is missing.
@@ -1170,8 +1159,7 @@ class TestResendIntegration:
proper validation of required configuration.
"""
# Arrange
- mock_config.MAIL_TYPE = "resend"
- mock_config.RESEND_API_KEY = None # Missing API key
+ config_overrides(RESEND_API_KEY=None)
mail = Mail()
mock_app = MagicMock()
@@ -1216,7 +1204,7 @@ class TestTemplateContextValidation:
assert context["to"] == "[email protected]"
assert context["code"] == "ABC123"
- def test_render_template_with_complex_nested_data(self):
+ def test_render_template_with_complex_nested_data(self, config_overrides):
"""
Test template rendering with complex nested data structures.
@@ -1231,8 +1219,8 @@ class TestTemplateContextValidation:
substitutions = {"user": {"name": "John Doe"}, "items": ["apple", "banana", "cherry"]}
# Act
- with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
- result = _render_template_with_strategy(body, substitutions)
+ config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX)
+ result = _render_template_with_strategy(body, substitutions)
# Assert
assert "John Doe" in result
@@ -1240,7 +1228,7 @@ class TestTemplateContextValidation:
assert "banana" in result
assert "cherry" in result
- def test_render_template_with_conditional_logic(self):
+ def test_render_template_with_conditional_logic(self, config_overrides):
"""
Test template rendering with conditional logic.
@@ -1251,9 +1239,9 @@ class TestTemplateContextValidation:
body = "{% if is_premium %}Premium User{% else %}Free User{% endif %}"
# Act - Test with premium user
- with patch.object(dify_config, "MAIL_TEMPLATING_MODE", TemplateMode.SANDBOX):
- result_premium = _render_template_with_strategy(body, {"is_premium": True})
- result_free = _render_template_with_strategy(body, {"is_premium": False})
+ config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX)
+ result_premium = _render_template_with_strategy(body, {"is_premium": True})
+ result_free = _render_template_with_strategy(body, {"is_premium": False})
# Assert
assert "Premium User" in result_premium
@@ -1268,8 +1256,7 @@ class TestEmailValidation:
validated before sending to prevent errors.
"""
- @patch("extensions.ext_mail.dify_config")
- def test_mail_send_with_invalid_email_format(self, mock_config):
+ def test_mail_send_with_invalid_email_format(self):
"""
Test mail send with malformed email address.
diff --git a/api/tests/unit_tests/tasks/test_workflow_node_execution_tasks.py b/api/tests/unit_tests/tasks/test_workflow_node_execution_tasks.py
deleted file mode 100644
index 8cac696d98f..00000000000
--- a/api/tests/unit_tests/tasks/test_workflow_node_execution_tasks.py
+++ /dev/null
@@ -1,488 +0,0 @@
-# """
-# Unit tests for workflow node execution Celery tasks.
-
-# These tests verify the asynchronous storage functionality for workflow node execution data,
-# including truncation and offloading logic.
-# """
-
-# import json
-# from unittest.mock import MagicMock, Mock, patch
-# from uuid import uuid4
-
-# import pytest
-
-# from graphon.entities.workflow_node_execution import (
-# WorkflowNodeExecution,
-# WorkflowNodeExecutionStatus,
-# )
-# from graphon.enums import BuiltinNodeTypes
-# from libs.datetime_utils import naive_utc_now
-# from models import WorkflowNodeExecutionModel
-# from models.enums import ExecutionOffLoadType
-# from models.model import UploadFile
-# from models.workflow import WorkflowNodeExecutionOffload, WorkflowNodeExecutionTriggeredFrom
-# from tasks.workflow_node_execution_tasks import (
-# _create_truncator,
-# _json_encode,
-# _replace_or_append_offload,
-# _truncate_and_upload_async,
-# save_workflow_node_execution_data_task,
-# save_workflow_node_execution_task,
-# )
-
-
-# @pytest.fixture
-# def sample_execution_data():
-# """Sample execution data for testing."""
-# execution = WorkflowNodeExecution(
-# id=str(uuid4()),
-# node_execution_id=str(uuid4()),
-# workflow_id=str(uuid4()),
-# workflow_execution_id=str(uuid4()),
-# index=1,
-# node_id="test_node",
-# node_type=BuiltinNodeTypes.LLM,
-# title="Test Node",
-# inputs={"input_key": "input_value"},
-# outputs={"output_key": "output_value"},
-# process_data={"process_key": "process_value"},
-# status=WorkflowNodeExecutionStatus.RUNNING,
-# created_at=naive_utc_now(),
-# )
-# return execution.model_dump()
-
-
-# @pytest.fixture
-# def mock_db_model():
-# """Mock database model for testing."""
-# db_model = Mock(spec=WorkflowNodeExecutionModel)
-# db_model.id = "test-execution-id"
-# db_model.offload_data = []
-# return db_model
-
-
-# @pytest.fixture
-# def mock_file_service():
-# """Mock file service for testing."""
-# file_service = Mock()
-# mock_upload_file = Mock(spec=UploadFile)
-# mock_upload_file.id = "mock-file-id"
-# file_service.upload_file.return_value = mock_upload_file
-# return file_service
-
-
-# class TestSaveWorkflowNodeExecutionDataTask:
-# """Test cases for save_workflow_node_execution_data_task."""
-
-# @patch("tasks.workflow_node_execution_tasks.sessionmaker")
-# @patch("tasks.workflow_node_execution_tasks.select")
-# def test_save_execution_data_task_success(
-# self, mock_select, mock_sessionmaker, sample_execution_data, mock_db_model
-# ):
-# """Test successful execution of save_workflow_node_execution_data_task."""
-# # Setup mocks
-# mock_session = MagicMock()
-# mock_sessionmaker.return_value.return_value.__enter__.return_value = mock_session
-# mock_session.execute.return_value.scalars.return_value.first.return_value = mock_db_model
-
-# # Execute task
-# result = save_workflow_node_execution_data_task(
-# execution_data=sample_execution_data,
-# tenant_id="test-tenant-id",
-# app_id="test-app-id",
-# user_data={"user_id": "test-user-id", "user_type": "account"},
-# )
-
-# # Verify success
-# assert result is True
-# mock_session.merge.assert_called_once_with(mock_db_model)
-# mock_session.commit.assert_called_once()
-
-# @patch("tasks.workflow_node_execution_tasks.sessionmaker")
-# @patch("tasks.workflow_node_execution_tasks.select")
-# def test_save_execution_data_task_execution_not_found(self, mock_select, mock_sessionmaker,
-# sample_execution_data):
-# """Test task when execution is not found in database."""
-# # Setup mocks
-# mock_session = MagicMock()
-# mock_sessionmaker.return_value.return_value.__enter__.return_value = mock_session
-# mock_session.execute.return_value.scalars.return_value.first.return_value = None
-
-# # Execute task
-# result = save_workflow_node_execution_data_task(
-# execution_data=sample_execution_data,
-# tenant_id="test-tenant-id",
-# app_id="test-app-id",
-# user_data={"user_id": "test-user-id", "user_type": "account"},
-# )
-
-# # Verify failure
-# assert result is False
-# mock_session.merge.assert_not_called()
-# mock_session.commit.assert_not_called()
-
-# @patch("tasks.workflow_node_execution_tasks.sessionmaker")
-# @patch("tasks.workflow_node_execution_tasks.select")
-# def test_save_execution_data_task_with_truncation(self, mock_select, mock_sessionmaker, mock_db_model):
-# """Test task with data that requires truncation."""
-# # Create execution with large data
-# large_data = {"large_field": "x" * 10000}
-# execution = WorkflowNodeExecution(
-# id=str(uuid4()),
-# node_execution_id=str(uuid4()),
-# workflow_id=str(uuid4()),
-# workflow_execution_id=str(uuid4()),
-# index=1,
-# node_id="test_node",
-# node_type=BuiltinNodeTypes.LLM,
-# title="Test Node",
-# inputs=large_data,
-# outputs=large_data,
-# process_data=large_data,
-# status=WorkflowNodeExecutionStatus.RUNNING,
-# created_at=naive_utc_now(),
-# )
-# execution_data = execution.model_dump()
-
-# # Setup mocks
-# mock_session = MagicMock()
-# mock_sessionmaker.return_value.return_value.__enter__.return_value = mock_session
-# mock_session.execute.return_value.scalars.return_value.first.return_value = mock_db_model
-
-# # Create mock upload file
-# mock_upload_file = Mock(spec=UploadFile)
-# mock_upload_file.id = "mock-file-id"
-
-# # Execute task
-# with patch("tasks.workflow_node_execution_tasks._truncate_and_upload_async") as mock_truncate:
-# # Mock truncation results
-# mock_truncate.return_value = {
-# "truncated_value": {"large_field": "[TRUNCATED]"},
-# "file": mock_upload_file,
-# "offload": WorkflowNodeExecutionOffload(
-# id=str(uuid4()),
-# tenant_id="test-tenant-id",
-# app_id="test-app-id",
-# node_execution_id=execution.id,
-# type_=ExecutionOffLoadType.INPUTS,
-# file_id=mock_upload_file.id,
-# ),
-# }
-
-# result = save_workflow_node_execution_data_task(
-# execution_data=execution_data,
-# tenant_id="test-tenant-id",
-# app_id="test-app-id",
-# user_data={"user_id": "test-user-id", "user_type": "account"},
-# )
-
-# # Verify success and truncation was called
-# assert result is True
-# assert mock_truncate.call_count == 3 # inputs, outputs, process_data
-# mock_session.merge.assert_called_once_with(mock_db_model)
-# mock_session.commit.assert_called_once()
-
-# @patch("tasks.workflow_node_execution_tasks.sessionmaker")
-# def test_save_execution_data_task_retry_on_exception(self, mock_sessionmaker, sample_execution_data):
-# """Test task retry mechanism on exception."""
-# # Setup mock to raise exception
-# mock_sessionmaker.side_effect = Exception("Database error")
-
-# # Create a mock task instance with proper retry behavior
-# with patch.object(save_workflow_node_execution_data_task, "retry") as mock_retry:
-# mock_retry.side_effect = Exception("Retry called")
-
-# # Execute task and expect retry
-# with pytest.raises(Exception, match="Retry called"):
-# save_workflow_node_execution_data_task(
-# execution_data=sample_execution_data,
-# tenant_id="test-tenant-id",
-# app_id="test-app-id",
-# user_data={"user_id": "test-user-id", "user_type": "account"},
-# )
-
-# # Verify retry was called
-# mock_retry.assert_called_once()
-
-
-# class TestTruncateAndUploadAsync:
-# """Test cases for _truncate_and_upload_async function."""
-
-# def test_truncate_and_upload_with_none_values(self, mock_file_service):
-# """Test _truncate_and_upload_async with None values."""
-# # The function handles None values internally, so we test with empty dict instead
-# result = _truncate_and_upload_async(
-# values={},
-# execution_id="test-id",
-# type_=ExecutionOffLoadType.INPUTS,
-# tenant_id="test-tenant",
-# app_id="test-app",
-# user_data={"user_id": "test-user", "user_type": "account"},
-# file_service=mock_file_service,
-# )
-
-# # Empty dict should not require truncation
-# assert result is None
-# mock_file_service.upload_file.assert_not_called()
-
-# @patch("tasks.workflow_node_execution_tasks._create_truncator")
-# def test_truncate_and_upload_no_truncation_needed(self, mock_create_truncator, mock_file_service):
-# """Test _truncate_and_upload_async when no truncation is needed."""
-# # Mock truncator to return no truncation
-# mock_truncator = Mock()
-# mock_truncator.truncate_variable_mapping.return_value = ({"small": "data"}, False)
-# mock_create_truncator.return_value = mock_truncator
-
-# small_values = {"small": "data"}
-# result = _truncate_and_upload_async(
-# values=small_values,
-# execution_id="test-id",
-# type_=ExecutionOffLoadType.INPUTS,
-# tenant_id="test-tenant",
-# app_id="test-app",
-# user_data={"user_id": "test-user", "user_type": "account"},
-# file_service=mock_file_service,
-# )
-
-# assert result is None
-# mock_file_service.upload_file.assert_not_called()
-
-# @patch("tasks.workflow_node_execution_tasks._create_truncator")
-# @patch("models.Account")
-# @patch("models.Tenant")
-# def test_truncate_and_upload_with_account_user(
-# self, mock_tenant_class, mock_account_class, mock_create_truncator, mock_file_service
-# ):
-# """Test _truncate_and_upload_async with account user."""
-# # Mock truncator to return truncation needed
-# mock_truncator = Mock()
-# mock_truncator.truncate_variable_mapping.return_value = ({"truncated": "data"}, True)
-# mock_create_truncator.return_value = mock_truncator
-
-# # Mock user and tenant creation
-# mock_account = Mock()
-# mock_account.id = "test-user"
-# mock_account_class.return_value = mock_account
-
-# mock_tenant = Mock()
-# mock_tenant.id = "test-tenant"
-# mock_tenant_class.return_value = mock_tenant
-
-# large_values = {"large": "x" * 10000}
-# result = _truncate_and_upload_async(
-# values=large_values,
-# execution_id="test-id",
-# type_=ExecutionOffLoadType.INPUTS,
-# tenant_id="test-tenant",
-# app_id="test-app",
-# user_data={"user_id": "test-user", "user_type": "account"},
-# file_service=mock_file_service,
-# )
-
-# # Verify result structure
-# assert result is not None
-# assert "truncated_value" in result
-# assert "file" in result
-# assert "offload" in result
-# assert result["truncated_value"] == {"truncated": "data"}
-
-# # Verify file upload was called
-# mock_file_service.upload_file.assert_called_once()
-# upload_call = mock_file_service.upload_file.call_args
-# assert upload_call[1]["filename"] == "node_execution_test-id_inputs.json"
-# assert upload_call[1]["mimetype"] == "application/json"
-# assert upload_call[1]["user"] == mock_account
-
-# @patch("tasks.workflow_node_execution_tasks._create_truncator")
-# @patch("models.EndUser")
-# def test_truncate_and_upload_with_end_user(self, mock_end_user_class, mock_create_truncator, mock_file_service):
-# """Test _truncate_and_upload_async with end user."""
-# # Mock truncator to return truncation needed
-# mock_truncator = Mock()
-# mock_truncator.truncate_variable_mapping.return_value = ({"truncated": "data"}, True)
-# mock_create_truncator.return_value = mock_truncator
-
-# # Mock end user creation
-# mock_end_user = Mock()
-# mock_end_user.id = "test-user"
-# mock_end_user.tenant_id = "test-tenant"
-# mock_end_user_class.return_value = mock_end_user
-
-# large_values = {"large": "x" * 10000}
-# result = _truncate_and_upload_async(
-# values=large_values,
-# execution_id="test-id",
-# type_=ExecutionOffLoadType.OUTPUTS,
-# tenant_id="test-tenant",
-# app_id="test-app",
-# user_data={"user_id": "test-user", "user_type": "end_user"},
-# file_service=mock_file_service,
-# )
-
-# # Verify result structure
-# assert result is not None
-# assert result["truncated_value"] == {"truncated": "data"}
-
-# # Verify file upload was called with end user
-# mock_file_service.upload_file.assert_called_once()
-# upload_call = mock_file_service.upload_file.call_args
-# assert upload_call[1]["filename"] == "node_execution_test-id_outputs.json"
-# assert upload_call[1]["user"] == mock_end_user
-
-
-# class TestHelperFunctions:
-# """Test cases for helper functions."""
-
-# @patch("tasks.workflow_node_execution_tasks.dify_config")
-# def test_create_truncator(self, mock_config):
-# """Test _create_truncator function."""
-# mock_config.WORKFLOW_VARIABLE_TRUNCATION_MAX_SIZE = 1000
-# mock_config.WORKFLOW_VARIABLE_TRUNCATION_ARRAY_LENGTH = 100
-# mock_config.WORKFLOW_VARIABLE_TRUNCATION_STRING_LENGTH = 500
-
-# truncator = _create_truncator()
-
-# # Verify truncator was created with correct config
-# assert truncator is not None
-
-# def test_json_encode(self):
-# """Test _json_encode function."""
-# test_data = {"key": "value", "number": 42}
-# result = _json_encode(test_data)
-
-# assert isinstance(result, str)
-# decoded = json.loads(result)
-# assert decoded == test_data
-
-# def test_replace_or_append_offload_replace_existing(self):
-# """Test _replace_or_append_offload replaces existing offload of same type."""
-# existing_offload = WorkflowNodeExecutionOffload(
-# id=str(uuid4()),
-# tenant_id="test-tenant",
-# app_id="test-app",
-# node_execution_id="test-execution",
-# type_=ExecutionOffLoadType.INPUTS,
-# file_id="old-file-id",
-# )
-
-# new_offload = WorkflowNodeExecutionOffload(
-# id=str(uuid4()),
-# tenant_id="test-tenant",
-# app_id="test-app",
-# node_execution_id="test-execution",
-# type_=ExecutionOffLoadType.INPUTS,
-# file_id="new-file-id",
-# )
-
-# result = _replace_or_append_offload([existing_offload], new_offload)
-
-# assert len(result) == 1
-# assert result[0].file_id == "new-file-id"
-
-# def test_replace_or_append_offload_append_new_type(self):
-# """Test _replace_or_append_offload appends new offload of different type."""
-# existing_offload = WorkflowNodeExecutionOffload(
-# id=str(uuid4()),
-# tenant_id="test-tenant",
-# app_id="test-app",
-# node_execution_id="test-execution",
-# type_=ExecutionOffLoadType.INPUTS,
-# file_id="inputs-file-id",
-# )
-
-# new_offload = WorkflowNodeExecutionOffload(
-# id=str(uuid4()),
-# tenant_id="test-tenant",
-# app_id="test-app",
-# node_execution_id="test-execution",
-# type_=ExecutionOffLoadType.OUTPUTS,
-# file_id="outputs-file-id",
-# )
-
-# result = _replace_or_append_offload([existing_offload], new_offload)
-
-# assert len(result) == 2
-# file_ids = [offload.file_id for offload in result]
-# assert "inputs-file-id" in file_ids
-# assert "outputs-file-id" in file_ids
-
-
-# class TestSaveWorkflowNodeExecutionTask:
-# """Test cases for save_workflow_node_execution_task."""
-
-# @patch("tasks.workflow_node_execution_tasks.sessionmaker")
-# @patch("tasks.workflow_node_execution_tasks.select")
-# def test_save_workflow_node_execution_task_create_new(self, mock_select, mock_sessionmaker,
-# sample_execution_data):
-# """Test creating a new workflow node execution."""
-# # Setup mocks
-# mock_session = MagicMock()
-# mock_sessionmaker.return_value.return_value.__enter__.return_value = mock_session
-# mock_session.scalar.return_value = None # No existing execution
-
-# # Execute task
-# result = save_workflow_node_execution_task(
-# execution_data=sample_execution_data,
-# tenant_id="test-tenant-id",
-# app_id="test-app-id",
-# triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN.value,
-# creator_user_id="test-user-id",
-# creator_user_role="account",
-# )
-
-# # Verify success
-# assert result is True
-# mock_session.add.assert_called_once()
-# mock_session.commit.assert_called_once()
-
-# @patch("tasks.workflow_node_execution_tasks.sessionmaker")
-# @patch("tasks.workflow_node_execution_tasks.select")
-# def test_save_workflow_node_execution_task_update_existing(
-# self, mock_select, mock_sessionmaker, sample_execution_data
-# ):
-# """Test updating an existing workflow node execution."""
-# # Setup mocks
-# mock_session = MagicMock()
-# mock_sessionmaker.return_value.return_value.__enter__.return_value = mock_session
-
-# existing_execution = Mock(spec=WorkflowNodeExecutionModel)
-# mock_session.scalar.return_value = existing_execution
-
-# # Execute task
-# result = save_workflow_node_execution_task(
-# execution_data=sample_execution_data,
-# tenant_id="test-tenant-id",
-# app_id="test-app-id",
-# triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN.value,
-# creator_user_id="test-user-id",
-# creator_user_role="account",
-# )
-
-# # Verify success
-# assert result is True
-# mock_session.add.assert_not_called() # Should not add new, just update existing
-# mock_session.commit.assert_called_once()
-
-# @patch("tasks.workflow_node_execution_tasks.sessionmaker")
-# def test_save_workflow_node_execution_task_retry_on_exception(self, mock_sessionmaker, sample_execution_data):
-# """Test task retry mechanism on exception."""
-# # Setup mock to raise exception
-# mock_sessionmaker.side_effect = Exception("Database error")
-
-# # Create a mock task instance with proper retry behavior
-# with patch.object(save_workflow_node_execution_task, "retry") as mock_retry:
-# mock_retry.side_effect = Exception("Retry called")
-
-# # Execute task and expect retry
-# with pytest.raises(Exception, match="Retry called"):
-# save_workflow_node_execution_task(
-# execution_data=sample_execution_data,
-# tenant_id="test-tenant-id",
-# app_id="test-app-id",
-# triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN.value,
-# creator_user_id="test-user-id",
-# creator_user_role="account",
-# )
-
-# # Verify retry was called
-# mock_retry.assert_called_once()