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: enforce centralized config overrides (#40869)

Asuka Minato2bdcbe96c521
diff --git a/api/tests/unit_tests/clients/agent_backend/test_factory.py b/api/tests/unit_tests/clients/agent_backend/test_factory.py
index 626bf5f1dfd..490c1bc6360 100644
--- a/api/tests/unit_tests/clients/agent_backend/test_factory.py
+++ b/api/tests/unit_tests/clients/agent_backend/test_factory.py
@@ -9,6 +9,7 @@ from clients.agent_backend.factory import create_agent_backend_client, create_ag
from configs import dify_config
from services import agent_app_sandbox_service
from services.agent import home_snapshot_service, workspace_service
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.mark.parametrize(
@@ -78,9 +79,12 @@ def test_default_agent_backend_clients_forward_authentication(
module: ModuleType,
extra_kwargs: dict[str, float],
) -> None:
- monkeypatch.setattr(dify_config, "AGENT_BACKEND_BASE_URL", "http://agent-backend")
- monkeypatch.setattr(dify_config, "AGENT_BACKEND_API_TOKEN", "secret-token")
- monkeypatch.setattr(dify_config, "AGENT_BACKEND_BINDING_FILE_DOWNLOAD_TIMEOUT_SECONDS", 123.5)
+ apply_config_overrides(
+ monkeypatch,
+ AGENT_BACKEND_BASE_URL="http://agent-backend",
+ AGENT_BACKEND_API_TOKEN="secret-token",
+ AGENT_BACKEND_BINDING_FILE_DOWNLOAD_TIMEOUT_SECONDS=123.5,
+ )
create_client = MagicMock()
monkeypatch.setattr(module, "create_agent_backend_client", create_client)
diff --git a/api/tests/unit_tests/commands/test_generate_swagger_specs.py b/api/tests/unit_tests/commands/test_generate_swagger_specs.py
index fc1ae3f5904..26857efbe7b 100644
--- a/api/tests/unit_tests/commands/test_generate_swagger_specs.py
+++ b/api/tests/unit_tests/commands/test_generate_swagger_specs.py
@@ -9,6 +9,8 @@ from pathlib import Path
from jsonschema import Draft202012Validator
+from tests.unit_tests.config_override import apply_config_overrides
+
def _walk_values(value):
yield value
@@ -162,7 +164,7 @@ def test_apply_runtime_defaults_forces_swagger_routes_on(monkeypatch):
from configs import dify_config
monkeypatch.setenv("SWAGGER_UI_ENABLED", "false")
- monkeypatch.setattr(dify_config, "SWAGGER_UI_ENABLED", False)
+ apply_config_overrides(monkeypatch, SWAGGER_UI_ENABLED=False)
module.apply_runtime_defaults()
diff --git a/api/tests/unit_tests/commands/test_reset_encrypt_key_pair.py b/api/tests/unit_tests/commands/test_reset_encrypt_key_pair.py
index 5e2f8ffaa09..d8c47e2747e 100644
--- a/api/tests/unit_tests/commands/test_reset_encrypt_key_pair.py
+++ b/api/tests/unit_tests/commands/test_reset_encrypt_key_pair.py
@@ -21,6 +21,7 @@ from graphon.model_runtime.entities.model_entities import ModelType
from models import Tenant
from models.provider import Provider, ProviderModel, ProviderType
from models.tools import ApiToolProvider, BuiltinToolProvider, MCPToolProvider
+from tests.unit_tests.config_override import apply_config_overrides
def _invoke_reset() -> int:
@@ -88,7 +89,7 @@ def _bind_command_to_sqlite(monkeypatch: pytest.MonkeyPatch, session: Session) -
def test_reset_aborts_when_not_self_hosted(monkeypatch, capsys):
- monkeypatch.setattr(system_commands.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
exit_code = _invoke_reset()
captured = capsys.readouterr()
@@ -107,7 +108,7 @@ def test_reset_purges_provider_and_tool_tables_for_each_tenant(
) -> None:
"""The command must purge LLM provider rows AND every tool provider table
that stores ciphertext encrypted under the tenant key (#35396)."""
- monkeypatch.setattr(system_commands.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
monkeypatch.setattr(system_commands, "generate_key_pair", lambda tenant_id: f"new-key-{tenant_id}")
_bind_command_to_sqlite(monkeypatch, sqlite_session)
@@ -147,7 +148,7 @@ def test_reset_purges_provider_and_tool_tables_for_each_tenant(
)
def test_reset_iterates_all_tenants(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
"""Multi-tenant deployments must purge every tenant, not just the first."""
- monkeypatch.setattr(system_commands.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
monkeypatch.setattr(system_commands, "generate_key_pair", lambda tenant_id: f"new-key-{tenant_id}")
_bind_command_to_sqlite(monkeypatch, sqlite_session)
diff --git a/api/tests/unit_tests/config_override.py b/api/tests/unit_tests/config_override.py
index 2c3175ce9ce..9a65679fcc7 100644
--- a/api/tests/unit_tests/config_override.py
+++ b/api/tests/unit_tests/config_override.py
@@ -1,5 +1,8 @@
"""Typed config override support shared by unit-test fixtures and helpers."""
+from collections.abc import Generator
+from contextlib import contextmanager
+
import pytest
from configs import dify_config
@@ -13,3 +16,11 @@ def apply_config_overrides(monkeypatch: pytest.MonkeyPatch, **values: object) ->
for name, value in values.items():
monkeypatch.setattr(dify_config, name, value)
+
+
+@contextmanager
+def config_overrides_context(**values: object) -> Generator[None]:
+ """Apply validated config overrides as a context manager or decorator."""
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ apply_config_overrides(monkeypatch, **values)
+ yield
diff --git a/api/tests/unit_tests/conftest.py b/api/tests/unit_tests/conftest.py
index 556e89f7780..9ca5f9774e6 100644
--- a/api/tests/unit_tests/conftest.py
+++ b/api/tests/unit_tests/conftest.py
@@ -100,17 +100,9 @@ def reset_redis_mock() -> None:
@pytest.fixture(autouse=True)
-def reset_secret_key() -> Iterator[None]:
+def reset_secret_key(monkeypatch: pytest.MonkeyPatch) -> None:
"""Ensure SECRET_KEY-dependent logic sees an empty config value by default."""
-
- from configs import dify_config
-
- original = dify_config.SECRET_KEY
- dify_config.SECRET_KEY = ""
- try:
- yield
- finally:
- dify_config.SECRET_KEY = original
+ apply_config_overrides(monkeypatch, SECRET_KEY="")
@pytest.fixture
diff --git a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
index 112b3a0264f..c2251709838 100644
--- a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
+++ b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
@@ -74,6 +74,7 @@ from services.entities.agent_entities import (
WorkflowAgentComposerQuery,
WorkflowComposerCopyFromRosterPayload,
)
+from tests.unit_tests.config_override import apply_config_overrides
def _persist_conversation_message(
@@ -864,7 +865,7 @@ def test_agent_api_access_uses_agent_id_and_returns_service_api_metadata(monkeyp
monkeypatch.setattr(roster_controller, "_resolve_agent_app_model", lambda _session, **kwargs: app_model)
monkeypatch.setattr(roster_controller, "_agent_api_key_count", lambda _session, _app: 2)
monkeypatch.setattr(roster_controller, "_agent_app_access_ready", lambda _session, _app: True)
- monkeypatch.setattr("models.model.dify_config.SERVICE_API_URL", "https://api.example.test/v1")
+ apply_config_overrides(monkeypatch, SERVICE_API_URL="https://api.example.test/v1")
response = unwrap(AgentApiAccessApi.get)(AgentApiAccessApi(), MagicMock(), "tenant-1", agent_id)
assert response == {
"access_ready": True,
diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_manage_guard.py b/api/tests/unit_tests/controllers/console/app/test_agent_manage_guard.py
index a261f4c998b..707b11a3f97 100644
--- a/api/tests/unit_tests/controllers/console/app/test_agent_manage_guard.py
+++ b/api/tests/unit_tests/controllers/console/app/test_agent_manage_guard.py
@@ -10,6 +10,7 @@ from core.rbac import RBACPermission, RBACResourceScope
from models import Account
from models.agent import Agent, AgentScope, AgentSource, AgentStatus
from models.model import App, AppMode
+from tests.unit_tests.config_override import config_overrides_context
TENANT_ID = "tenant-1"
@@ -58,7 +59,7 @@ def _persist_app(
def _patch_guard(account: Account, rbac_enabled: bool):
return (
patch("controllers.console.app.wraps.current_account_with_tenant", return_value=(account, TENANT_ID)),
- patch("controllers.console.app.wraps.dify_config.RBAC_ENABLED", rbac_enabled),
+ config_overrides_context(RBAC_ENABLED=rbac_enabled),
)
diff --git a/api/tests/unit_tests/controllers/console/app/test_app_apis.py b/api/tests/unit_tests/controllers/console/app/test_app_apis.py
index c7f8286fac5..6d574657017 100644
--- a/api/tests/unit_tests/controllers/console/app/test_app_apis.py
+++ b/api/tests/unit_tests/controllers/console/app/test_app_apis.py
@@ -77,6 +77,7 @@ from services.app_site_service import (
AppSiteCommandResult,
AppSiteNotFoundError,
)
+from tests.unit_tests.config_override import apply_config_overrides
APP_ID = "11111111-1111-1111-1111-111111111111"
TENANT_ID = "22222222-2222-2222-2222-222222222222"
@@ -261,8 +262,11 @@ class TestAppEndpoints:
oauth_server.issue_authorization_code.return_value = MagicMock(code="oauth-code-1")
services = MagicMock(oauth_server=oauth_server)
- monkeypatch.setattr(app_module.dify_config, "CREATORS_PLATFORM_FEATURES_ENABLED", True)
- monkeypatch.setattr(app_module.dify_config, "CREATORS_PLATFORM_OAUTH_CLIENT_ID", "client-1")
+ apply_config_overrides(
+ monkeypatch,
+ CREATORS_PLATFORM_FEATURES_ENABLED=True,
+ CREATORS_PLATFORM_OAUTH_CLIENT_ID="client-1",
+ )
monkeypatch.setattr(app_module, "application_services", lambda: services)
monkeypatch.setattr(app_module.AppDslService, "export_dsl", MagicMock(return_value="app: demo"))
diff --git a/api/tests/unit_tests/controllers/console/app/test_app_import_api.py b/api/tests/unit_tests/controllers/console/app/test_app_import_api.py
index 5a08cad43bf..16c2ae1007d 100644
--- a/api/tests/unit_tests/controllers/console/app/test_app_import_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_app_import_api.py
@@ -21,6 +21,7 @@ from models.model import App, AppMode
from services.app_dsl_service import ImportStatus
from services.entities.dsl_entities import CheckDependenciesResult
from services.entities.feature_entities import SystemFeatureModel, WebAppAuthModel
+from tests.unit_tests.config_override import apply_config_overrides
def _unwrap(func):
@@ -240,7 +241,7 @@ class TestAppImportApi:
"current_account_with_tenant",
lambda: (_make_account(), "tenant-1"),
)
- monkeypatch.setattr(app_import_module.dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
app_id = _install_persisting_service_result(
monkeypatch,
method_name="import_app",
@@ -276,7 +277,7 @@ class TestAppImportApi:
"current_account_with_tenant",
lambda: (_make_account(), "tenant-1"),
)
- monkeypatch.setattr(app_import_module.dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
app_id = _install_persisting_service_result(
monkeypatch,
method_name="import_app",
@@ -353,7 +354,7 @@ class TestAppImportConfirmApi:
)
)
monkeypatch.setattr(app_import_module.redis_client, "get", redis_get)
- monkeypatch.setattr(app_import_module.dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
app_id = _install_persisting_service_result(
monkeypatch,
method_name="confirm_import",
@@ -397,7 +398,7 @@ class TestAppImportConfirmApi:
b'"name":null,"description":null,"icon_type":null,"icon":null,"icon_background":null}'
),
)
- monkeypatch.setattr(app_import_module.dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
app_id = _install_persisting_service_result(
monkeypatch,
method_name="confirm_import",
diff --git a/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py b/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py
index 075997b40f9..5e5762f9260 100644
--- a/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py
+++ b/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py
@@ -21,6 +21,7 @@ from models import Account
from models.account import AccountStatus
from models.enums import AppMCPServerStatus
from models.model import App, AppMCPServer, AppMode, IconType
+from tests.unit_tests.config_override import config_overrides_context
def _app(
@@ -309,7 +310,7 @@ class TestAppMCPServerRefreshController:
current_user = Account(name="Current user", email="[email protected]", status=AccountStatus.ACTIVE)
current_user.id = "account-1"
with (
- patch("controllers.common.wraps.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch(
"controllers.common.wraps.current_account_with_tenant",
return_value=(current_user, "tenant-1"),
diff --git a/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py b/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py
index 08b3799de34..1c1ee83e19a 100644
--- a/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_ops_trace_api.py
@@ -18,6 +18,7 @@ from libs import login as login_lib
from models import Tenant
from models.account import Account, AccountStatus, TenantAccountRole
from models.model import App, AppMode, IconType
+from tests.unit_tests.config_override import apply_config_overrides
def _make_account(role: TenantAccountRole) -> Account:
@@ -55,9 +56,12 @@ def _patch_console_guards(
*,
rbac_enabled: bool = False,
) -> None:
- monkeypatch.setattr(login_lib.dify_config, "LOGIN_DISABLED", True)
- monkeypatch.setattr(login_lib.dify_config, "RBAC_ENABLED", rbac_enabled)
- monkeypatch.setattr(console_wraps.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
+ apply_config_overrides(
+ monkeypatch,
+ LOGIN_DISABLED=True,
+ RBAC_ENABLED=rbac_enabled,
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ )
monkeypatch.setattr(login_lib, "current_user", account)
monkeypatch.setattr(login_lib, "current_account_with_tenant", lambda: (account, account.current_tenant_id))
monkeypatch.setattr(console_wraps, "current_account_with_tenant", lambda: (account, account.current_tenant_id))
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow.py b/api/tests/unit_tests/controllers/console/app/test_workflow.py
index 5ef2a3a832f..e4e30edd21d 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow.py
@@ -22,6 +22,7 @@ from core.workflow.llm_environment_variable import LLMEnvironmentVariable
from graphon.file import File, FileTransferMethod, FileType
from graphon.variables import SecretVariable, StringVariable
from graphon.variables.variables import RAGPipelineVariable
+from tests.unit_tests.config_override import apply_config_overrides
def _make_workflow(**overrides):
@@ -875,7 +876,7 @@ def test_workflow_online_users_filters_inaccessible_workflow(app: Flask, monkeyp
access_filter = SimpleNamespace(is_app_accessible=lambda app_id, _maintainer, _account_id: app_id == app_id_1)
resolve_access = Mock(return_value=access_filter)
monkeypatch.setattr(workflow_module, "resolve_app_access_filter", resolve_access)
- monkeypatch.setattr(workflow_module.dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
monkeypatch.setattr(workflow_module.file_helpers, "get_signed_file_url", sign_avatar)
short_session = Mock()
monkeypatch.setattr(workflow_module.session_factory, "create_session", lambda: nullcontext(short_session))
@@ -966,7 +967,7 @@ def test_workflow_online_users_batches_redis_reads(app: Flask, monkeypatch: pyte
"WorkflowService",
lambda: SimpleNamespace(get_tenant_app_maintainers=lambda app_ids, tenant_id, session: dict.fromkeys(app_ids)),
)
- monkeypatch.setattr(workflow_module.dify_config, "RBAC_ENABLED", False)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=False)
monkeypatch.setattr(workflow_module.session_factory, "create_session", lambda: nullcontext(Mock()))
first_pipeline = Mock()
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_comment_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_comment_api.py
index 56049936f27..337a4f31881 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow_comment_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_comment_api.py
@@ -18,6 +18,7 @@ from libs import login as login_lib
from models import App, Tenant, WorkflowComment, WorkflowCommentMention, WorkflowCommentReply
from models.account import Account, AccountStatus, TenantAccountRole
from models.model import AppMode, IconType
+from tests.unit_tests.config_override import apply_config_overrides
JAN_1_2024_NOON = datetime(2024, 1, 1, 12, 0, 0)
JAN_1_2024_NOON_TS = int(JAN_1_2024_NOON.timestamp())
@@ -58,12 +59,11 @@ def _make_app() -> App:
def _patch_console_guards(monkeypatch: pytest.MonkeyPatch, account: Account, app_model: App) -> None:
- monkeypatch.setattr(login_lib.dify_config, "LOGIN_DISABLED", True)
+ apply_config_overrides(monkeypatch, LOGIN_DISABLED=True, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
monkeypatch.setattr(login_lib, "current_user", account)
monkeypatch.setattr(login_lib, "current_account_with_tenant", lambda: (account, account.current_tenant_id))
monkeypatch.setattr(login_lib, "check_csrf_token", lambda *_, **__: None)
monkeypatch.setattr(console_wraps, "current_account_with_tenant", lambda: (account, account.current_tenant_id))
- monkeypatch.setattr(console_wraps.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
monkeypatch.setattr(app_wraps, "current_account_with_tenant", lambda: (account, account.current_tenant_id))
monkeypatch.setattr(app_wraps, "_load_app_model_from_scoped_session", lambda _app_id: app_model)
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_human_input_debug_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_human_input_debug_api.py
index b825d379f82..f223228048d 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow_human_input_debug_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_human_input_debug_api.py
@@ -15,6 +15,7 @@ from libs import login as login_lib
from models import App, Tenant
from models.account import Account, AccountStatus, TenantAccountRole
from models.model import AppMode, IconType
+from tests.unit_tests.config_override import apply_config_overrides
def _make_account() -> Account:
@@ -47,14 +48,17 @@ def _make_app(mode: AppMode) -> App:
def _patch_console_guards(monkeypatch: pytest.MonkeyPatch, account: Account, app_model: App) -> None:
# Skip setup and auth guardrails
- monkeypatch.setattr("configs.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
- monkeypatch.setattr(login_lib.dify_config, "LOGIN_DISABLED", True)
+ apply_config_overrides(
+ monkeypatch,
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ LOGIN_DISABLED=True,
+ INIT_PASSWORD="",
+ )
monkeypatch.setattr(login_lib, "current_user", account)
monkeypatch.setattr(login_lib, "current_account_with_tenant", lambda: (account, account.current_tenant_id))
monkeypatch.setattr(login_lib, "check_csrf_token", lambda *_, **__: None)
monkeypatch.setattr(console_wraps, "current_account_with_tenant", lambda: (account, account.current_tenant_id))
monkeypatch.setattr(app_wraps, "current_account_with_tenant", lambda: (account, account.current_tenant_id))
- monkeypatch.setattr(console_wraps.dify_config, "INIT_PASSWORD", "")
# Avoid hitting the database when resolving the app model
monkeypatch.setattr(app_wraps, "_load_app_model_from_scoped_session", lambda _app_id: app_model)
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_pause_details_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_pause_details_api.py
index 88aed318fb2..a1be8254d63 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow_pause_details_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_pause_details_api.py
@@ -20,6 +20,7 @@ from core.workflow.nodes.human_input.pause_reason import HumanInputRequired
from graphon.enums import WorkflowExecutionStatus
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
from models.workflow import WorkflowPause, WorkflowRun, WorkflowType
+from tests.unit_tests.config_override import apply_config_overrides
@dataclass(frozen=True)
@@ -77,7 +78,7 @@ class _PauseEntity:
def test_pause_details_returns_backstage_input_url(
app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
) -> None:
- monkeypatch.setattr(workflow_run_module.dify_config, "APP_WEB_URL", "https://web.example.com")
+ apply_config_overrides(monkeypatch, APP_WEB_URL="https://web.example.com")
tenant_id = str(uuid4())
run_id = str(uuid4())
@@ -137,7 +138,7 @@ def test_pause_details_returns_backstage_input_url(
def test_pause_details_tenant_isolation(app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
- monkeypatch.setattr(workflow_run_module.dify_config, "APP_WEB_URL", "https://web.example.com")
+ apply_config_overrides(monkeypatch, APP_WEB_URL="https://web.example.com")
run_id = str(uuid4())
_persist_run(
diff --git a/api/tests/unit_tests/controllers/console/auth/test_authentication_security.py b/api/tests/unit_tests/controllers/console/auth/test_authentication_security.py
index 37e67cf6fc5..64e2813f62f 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_authentication_security.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_authentication_security.py
@@ -12,6 +12,7 @@ from controllers.console.auth.error import AuthenticationFailedError
from controllers.console.auth.login import LoginApi
from enums import DeploymentEdition
from models.account import Account
+from tests.unit_tests.config_override import config_overrides_context
def encode_password(password: str) -> str:
@@ -35,7 +36,7 @@ class TestAuthenticationSecurity:
@patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")
@patch("controllers.console.auth.login.AccountService.authenticate")
@patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")
- @patch("controllers.console.auth.login.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
@patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")
def test_login_invalid_email_with_registration_allowed(
self, mock_get_invitation, mock_add_rate_limit, mock_authenticate, mock_is_rate_limit, mock_features, mock_db
@@ -67,7 +68,7 @@ class TestAuthenticationSecurity:
@patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")
@patch("controllers.console.auth.login.AccountService.authenticate")
@patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")
- @patch("controllers.console.auth.login.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
@patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")
def test_login_wrong_password_returns_error(
self, mock_get_invitation, mock_add_rate_limit, mock_authenticate, mock_is_rate_limit, mock_db
@@ -99,7 +100,7 @@ class TestAuthenticationSecurity:
@patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")
@patch("controllers.console.auth.login.AccountService.authenticate")
@patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")
- @patch("controllers.console.auth.login.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
@patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")
def test_login_invalid_email_with_registration_disabled(
self, mock_get_invitation, mock_add_rate_limit, mock_authenticate, mock_is_rate_limit, mock_features, mock_db
diff --git a/api/tests/unit_tests/controllers/console/auth/test_data_source_oauth.py b/api/tests/unit_tests/controllers/console/auth/test_data_source_oauth.py
index 1f6cd681a75..72d28c0385b 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_data_source_oauth.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_data_source_oauth.py
@@ -19,6 +19,7 @@ from services.data_source_oauth_service import (
InvalidDataSourceOAuthProviderError,
)
from services.entities.data_source_oauth_entities import DataSourceOAuthCallback
+from tests.unit_tests.config_override import config_overrides_context
def _request_context() -> RequestContext:
@@ -72,10 +73,7 @@ def test_callback_parses_query_and_returns_flask_redirect() -> None:
with (
app.test_request_context("/?code=code-1"),
- patch(
- "controllers.console.auth.data_source_oauth.dify_config.CONSOLE_WEB_URL",
- "https://console.example/root?lang=en#top",
- ),
+ config_overrides_context(CONSOLE_WEB_URL="https://console.example/root?lang=en#top"),
patch(
"controllers.console.auth.data_source_oauth.application_services",
return_value=_services(service),
diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_register.py b/api/tests/unit_tests/controllers/console/auth/test_email_register.py
index 4f1bec336e5..7eee2e68102 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_email_register.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_email_register.py
@@ -108,8 +108,6 @@ class TestEmailRegisterSendEmailApi:
)
with (
- patch("controllers.console.auth.email_register.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
- patch("controllers.console.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),
):
with app.test_request_context(
diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py b/api/tests/unit_tests/controllers/console/auth/test_email_verification.py
index 75ed9f5b6af..930ac17279b 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_email_verification.py
@@ -461,14 +461,17 @@ class TestEmailCodeLoginApi:
mock_verify_challenge,
mock_db,
app: Flask,
+ config_overrides: Callable[..., None],
):
+ config_overrides(
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED=True,
+ )
mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(
status=EmailCodeLoginChallengeStatus.INVALID_TOKEN
)
with (
- patch("controllers.console.auth.login.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
- patch("controllers.console.auth.login.dify_config.TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED", True),
app.test_request_context(
"/email-code-login/validity",
method="POST",
@@ -502,10 +505,13 @@ class TestEmailCodeLoginApi:
mock_verify_challenge,
mock_db,
app: Flask,
+ config_overrides: Callable[..., None],
):
+ config_overrides(
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED=True,
+ )
with (
- patch("controllers.console.auth.login.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
- patch("controllers.console.auth.login.dify_config.TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED", True),
app.test_request_context(
"/email-code-login/validity",
method="POST",
@@ -527,14 +533,17 @@ class TestEmailCodeLoginApi:
mock_verify_challenge,
mock_db,
app: Flask,
+ config_overrides: Callable[..., None],
):
+ config_overrides(
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED=False,
+ )
mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(
status=EmailCodeLoginChallengeStatus.INVALID_TOKEN
)
with (
- patch("controllers.console.auth.login.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
- patch("controllers.console.auth.login.dify_config.TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED", False),
app.test_request_context(
"/email-code-login/validity",
method="POST",
diff --git a/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py b/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py
index 783aac0a5df..b9eda4eeb0a 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py
@@ -17,6 +17,7 @@ from enums import DeploymentEdition
from models.account import Account
from models.engine import db
from services.entities.feature_entities import SystemFeatureModel
+from tests.unit_tests.config_override import config_overrides_context
@pytest.fixture
@@ -61,7 +62,7 @@ class TestForgotPasswordSendEmailApi:
"controllers.console.auth.forgot_password.FeatureService.get_system_features",
return_value=controller_features,
),
- patch("controllers.console.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),
patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),
):
with app.test_request_context(
@@ -108,7 +109,7 @@ class TestForgotPasswordCheckApi:
enable_email_password_login=True,
)
with (
- patch("controllers.console.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),
patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),
):
with app.test_request_context(
@@ -154,7 +155,7 @@ class TestForgotPasswordResetApi:
enable_email_password_login=True,
)
with (
- patch("controllers.console.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),
patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),
):
with database_app.test_request_context(
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 969e84505aa..1d95860e1b4 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_oauth.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_oauth.py
@@ -22,6 +22,7 @@ from services.errors.account import AccountRegisterError
from services.errors.account import (
EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,
)
+from tests.unit_tests.config_override import config_overrides_context
@pytest.fixture(autouse=True)
@@ -586,7 +587,7 @@ class TestAccountGeneration:
("freeze", AccountRegisterError),
],
)
- @patch("controllers.console.auth.oauth.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
+ @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("controllers.console.auth.oauth.BillingService.get_email_freeze_type")
@patch("controllers.console.auth.oauth._get_account_by_openid_or_email", return_value=None)
@patch("controllers.console.auth.oauth.FeatureService")
diff --git a/api/tests/unit_tests/controllers/console/auth/test_oauth_redirect.py b/api/tests/unit_tests/controllers/console/auth/test_oauth_redirect.py
index 59a12a9b329..e3910d4a348 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_oauth_redirect.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_oauth_redirect.py
@@ -7,6 +7,7 @@ from flask import Flask
from controllers.console.auth.oauth import OAuthCallback, OAuthLogin
from libs.oauth import OAuthUserInfo, encode_oauth_state
from models.account import Account, AccountStatus, Tenant
+from tests.unit_tests.config_override import config_overrides_context
REDIRECT_URL = "/apps?category=workflow"
CONSOLE_WEB_URL = "https://console.example.com"
@@ -74,7 +75,7 @@ def test_oauth_callback_validates_redirect_url_and_appends_new_user_flag(
with (
patch("controllers.console.auth.oauth.get_oauth_providers", return_value={"google": oauth_provider}),
- patch("controllers.console.auth.oauth.dify_config.CONSOLE_WEB_URL", CONSOLE_WEB_URL),
+ config_overrides_context(CONSOLE_WEB_URL=CONSOLE_WEB_URL),
patch("controllers.console.auth.oauth._generate_account", return_value=(account, oauth_new_user)),
patch("controllers.console.auth.oauth.TenantService.create_owner_tenant_if_not_exist"),
patch("controllers.console.auth.oauth.AccountService.login", return_value=token_pair),
@@ -109,7 +110,7 @@ def test_oauth_callback_with_invitation_establishes_console_session(app: Flask)
with (
patch("controllers.console.auth.oauth.get_oauth_providers", return_value={"google": oauth_provider}),
- patch("controllers.console.auth.oauth.dify_config.CONSOLE_WEB_URL", CONSOLE_WEB_URL),
+ config_overrides_context(CONSOLE_WEB_URL=CONSOLE_WEB_URL),
patch("controllers.console.auth.oauth.RegisterService") as register_service,
patch("controllers.console.auth.oauth.AccountService.link_account_integrate") as link_account,
patch("controllers.console.auth.oauth.AccountService.login", return_value=token_pair) as login,
@@ -155,7 +156,7 @@ def test_oauth_callback_with_invitation_rejects_another_account(app: Flask) -> N
with (
patch("controllers.console.auth.oauth.get_oauth_providers", return_value={"google": oauth_provider}),
- patch("controllers.console.auth.oauth.dify_config.CONSOLE_WEB_URL", CONSOLE_WEB_URL),
+ config_overrides_context(CONSOLE_WEB_URL=CONSOLE_WEB_URL),
patch("controllers.console.auth.oauth.RegisterService") as register_service,
patch("controllers.console.auth.oauth.AccountService.link_account_integrate") as link_account,
patch("controllers.console.auth.oauth.AccountService.login") as login,
diff --git a/api/tests/unit_tests/controllers/console/auth/test_password_reset.py b/api/tests/unit_tests/controllers/console/auth/test_password_reset.py
index c2375fab888..a94816949ac 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_password_reset.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_password_reset.py
@@ -26,6 +26,7 @@ from controllers.console.error import AccountNotFound, EmailSendIpLimitError
from enums import DeploymentEdition
from models.account import Account, Tenant, TenantAccountJoin
from services.entities.feature_entities import SystemFeatureModel
+from tests.unit_tests.config_override import apply_config_overrides
SQLITE_MODELS = (Account, Tenant, TenantAccountJoin)
@@ -46,7 +47,7 @@ def _bind_database_session(session: Session) -> Generator[scoped_session[Session
def enable_password_login_wrappers(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep endpoint decorators deterministic without requiring the configured app database."""
- monkeypatch.setattr("controllers.console.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
monkeypatch.setattr(
"controllers.console.wraps.FeatureService.get_system_features",
lambda: SystemFeatureModel(
diff --git a/api/tests/unit_tests/controllers/console/billing/test_billing.py b/api/tests/unit_tests/controllers/console/billing/test_billing.py
index ce26f4a8c6d..b69671a598d 100644
--- a/api/tests/unit_tests/controllers/console/billing/test_billing.py
+++ b/api/tests/unit_tests/controllers/console/billing/test_billing.py
@@ -24,6 +24,7 @@ from services.errors.billing import (
BillingUpstreamInvalidResponseError,
BillingUpstreamUnavailableError,
)
+from tests.unit_tests.config_override import config_overrides_context
class TestBillingPortal:
@@ -188,8 +189,7 @@ class TestPartnerTenants:
console_wraps._is_setup_completed.reset_success()
monkeypatch.setattr(console_wraps.db, "session", sqlite_session)
with (
- patch("controllers.console.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
- patch("libs.login.dify_config.LOGIN_DISABLED", False),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, LOGIN_DISABLED=False),
patch("libs.login.check_csrf_token") as mock_csrf,
):
mock_csrf.return_value = None
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py
index 91815612355..f3b0cb25953 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py
@@ -27,6 +27,7 @@ from models.engine import db
from services.entities.knowledge_entities.rag_pipeline_entities import PipelineTemplateInfoEntity
from services.errors.account import NoPermissionError
from services.errors.rag_pipeline import RagPipelineResourceNotFoundError
+from tests.unit_tests.config_override import config_overrides_context
def _template_item() -> dict[str, object]:
@@ -376,7 +377,7 @@ class TestPublishCustomizedPipelineTemplateApi:
dataset = object()
with (
- patch.object(module.dify_config, "RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(Pipeline, "retrieve_dataset", return_value=dataset),
patch.object(module.DatasetService, "check_dataset_permission") as legacy_acl,
patch.object(module.RagPipelineService, "publish_customized_pipeline_template") as publish,
@@ -409,7 +410,7 @@ class TestPublishCustomizedPipelineTemplateApi:
dataset = object()
with (
- patch.object(module.dify_config, "RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(Pipeline, "retrieve_dataset", return_value=dataset),
patch.object(module.RagPipelineService, "publish_customized_pipeline_template") as publish,
):
@@ -425,7 +426,7 @@ class TestPublishCustomizedPipelineTemplateApi:
payload = _payload()
with (
- patch.object(module.dify_config, "RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(Pipeline, "retrieve_dataset", return_value=object()),
patch.object(
module.RagPipelineService,
@@ -446,7 +447,7 @@ class TestPublishCustomizedPipelineTemplateApi:
payload = _payload()
with (
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(Pipeline, "retrieve_dataset", return_value=dataset),
patch.object(module.DatasetService, "check_dataset_permission") as check_permission,
patch.object(module.RagPipelineService, "publish_customized_pipeline_template") as publish,
@@ -464,7 +465,7 @@ class TestPublishCustomizedPipelineTemplateApi:
account.role = TenantAccountRole.NORMAL
with (
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(Pipeline, "retrieve_dataset", return_value=object()),
patch.object(module.DatasetService, "check_dataset_permission") as check_permission,
patch.object(module.RagPipelineService, "publish_customized_pipeline_template") as publish,
@@ -482,7 +483,7 @@ class TestPublishCustomizedPipelineTemplateApi:
account.role = TenantAccountRole.EDITOR
with (
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(Pipeline, "retrieve_dataset", return_value=object()),
patch.object(
module.DatasetService,
@@ -503,7 +504,7 @@ class TestPublishCustomizedPipelineTemplateApi:
account.role = TenantAccountRole.EDITOR
with (
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(Pipeline, "retrieve_dataset", return_value=None),
patch.object(module.DatasetService, "check_dataset_permission") as check_permission,
patch.object(module.RagPipelineService, "publish_customized_pipeline_template") as publish,
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py
index fdc9dfe54f7..f4a2e2c948f 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py
@@ -34,6 +34,7 @@ from models.workflow import Workflow, WorkflowType
from services.errors.llm import InvokeRateLimitError
from services.errors.rag_pipeline import RagPipelineResourceNotFoundError
from services.rag_pipeline.rag_pipeline import RagPipelineService
+from tests.unit_tests.config_override import config_overrides_context
DEFAULT_WORKFLOW_TENANT_ID = "00000000-0000-0000-0000-000000000001"
DEFAULT_WORKFLOW_APP_ID = "00000000-0000-0000-0000-000000000002"
@@ -259,7 +260,7 @@ def test_rag_pipeline_transform_rejects_read_only_member(sqlite_engine: Engine)
session.add(_dataset())
with (
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
pytest.raises(Forbidden),
):
handler(api, session, DEFAULT_WORKFLOW_TENANT_ID, account, UUID(DEFAULT_DATASET_ID))
@@ -293,7 +294,7 @@ def test_rag_pipeline_transform_enforces_legacy_dataset_permission_before_servic
session.add(_dataset(maintainer="00000000-0000-0000-0000-000000000099"))
with (
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module.RagPipelineTransformService, "transform_dataset") as transform_dataset,
pytest.raises(Forbidden),
):
@@ -315,7 +316,7 @@ def test_rag_pipeline_transform_passes_authorized_dataset_and_account_to_service
session.add(dataset)
with (
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module.RagPipelineTransformService, "transform_dataset", return_value=expected) as transform,
):
response = handler(api, session, DEFAULT_WORKFLOW_TENANT_ID, account, UUID(DEFAULT_DATASET_ID))
@@ -333,7 +334,7 @@ def test_rag_pipeline_transform_maps_missing_pipeline_to_not_found(sqlite_engine
session.add(_dataset())
with (
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(
module.RagPipelineTransformService,
"transform_dataset",
@@ -355,7 +356,7 @@ def test_rag_pipeline_transform_skips_legacy_acl_when_rbac_is_enabled(sqlite_eng
session.add(_dataset(maintainer="00000000-0000-0000-0000-000000000099"))
with (
- patch.object(module.dify_config, "RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(module.RagPipelineTransformService, "transform_dataset", return_value=expected) as transform,
):
response = handler(api, session, DEFAULT_WORKFLOW_TENANT_ID, account, UUID(DEFAULT_DATASET_ID))
diff --git a/api/tests/unit_tests/controllers/console/datasets/test_datasets_document.py b/api/tests/unit_tests/controllers/console/datasets/test_datasets_document.py
index 459af12ba76..060b6029bc7 100644
--- a/api/tests/unit_tests/controllers/console/datasets/test_datasets_document.py
+++ b/api/tests/unit_tests/controllers/console/datasets/test_datasets_document.py
@@ -55,6 +55,7 @@ from services.vector_space_admission_service import (
VECTOR_SPACE_ADMISSION_ERROR_CODE,
format_vector_space_admission_error,
)
+from tests.unit_tests.config_override import config_overrides_context
def make_serializable_document(**overrides):
@@ -504,7 +505,7 @@ class TestDatasetInitApi:
with (
app.test_request_context("/", json=payload),
patch.object(type(console_ns), "payload", payload),
- patch("controllers.console.datasets.datasets_document.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch(
"controllers.console.datasets.datasets_document.DocumentService.document_create_args_validate",
return_value=None,
@@ -560,7 +561,7 @@ class TestDocumentResource:
api = DocumentResource()
session = MagicMock()
with (
- patch("controllers.console.datasets.datasets_document.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch(
"controllers.console.datasets.datasets_document.DatasetService.get_dataset_for_tenant",
return_value=dataset,
diff --git a/api/tests/unit_tests/controllers/console/datasets/test_metadata.py b/api/tests/unit_tests/controllers/console/datasets/test_metadata.py
index 6cf5664bd96..696e0223255 100644
--- a/api/tests/unit_tests/controllers/console/datasets/test_metadata.py
+++ b/api/tests/unit_tests/controllers/console/datasets/test_metadata.py
@@ -22,6 +22,7 @@ from services.entities.knowledge_entities.knowledge_entities import MetadataArgs
from services.errors.account import NoPermissionError
from services.errors.metadata import MetadataResourceNotFoundError
from services.metadata_service import MetadataService
+from tests.unit_tests.config_override import config_overrides_context
@pytest.fixture
@@ -150,7 +151,7 @@ class TestDatasetMetadataGetApi:
method = unwrap(api.get)
with (
app.test_request_context("/"),
- patch("controllers.console.datasets.metadata.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(DatasetService, "get_dataset_for_tenant", return_value=dataset),
patch.object(DatasetService, "check_dataset_permission") as check_permission,
patch.object(
diff --git a/api/tests/unit_tests/controllers/console/tag/test_tags.py b/api/tests/unit_tests/controllers/console/tag/test_tags.py
index 573698ed9e4..5d19e08a557 100644
--- a/api/tests/unit_tests/controllers/console/tag/test_tags.py
+++ b/api/tests/unit_tests/controllers/console/tag/test_tags.py
@@ -31,6 +31,7 @@ from services.tag_application_service import (
TagSummary,
UpdateTagInput,
)
+from tests.unit_tests.config_override import config_overrides_context
def unwrap(func):
@@ -142,7 +143,7 @@ class TestTagListApi:
with (
app.test_request_context("/", json={"name": "Tag", "type": "knowledge"}),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(dataset_operator, "tenant-1")),
):
result, status = unwrap(TagListApi().post)(
@@ -163,7 +164,7 @@ class TestTagListApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
patch.object(module, "enforce_rbac_access") as enforce_rbac_access,
):
@@ -186,7 +187,7 @@ class TestTagListApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(readonly, "tenant-1")),
):
with pytest.raises(Forbidden):
@@ -204,7 +205,7 @@ class TestTagListApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
):
with pytest.raises(ValueError, match="Tag name already exists") as exc_info:
@@ -225,7 +226,7 @@ class TestTagListApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
):
with pytest.raises(TagApplicationError, match="unexpected"):
@@ -246,7 +247,7 @@ class TestTagUpdateDeleteApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
patch.object(module, "enforce_rbac_access") as enforce_rbac_access,
):
@@ -273,7 +274,7 @@ class TestTagUpdateDeleteApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(readonly, "tenant-1")),
):
with pytest.raises(Forbidden):
@@ -292,7 +293,7 @@ class TestTagUpdateDeleteApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
):
with pytest.raises(NotFound, match="Tag not found") as exc_info:
@@ -313,7 +314,7 @@ class TestTagUpdateDeleteApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(dataset_operator, "tenant-1")),
):
with pytest.raises(Forbidden):
@@ -326,7 +327,7 @@ class TestTagUpdateDeleteApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
):
result, status = unwrap(TagUpdateDeleteApi().delete)(TagUpdateDeleteApi(), request_context, "tag-1")
@@ -342,7 +343,7 @@ class TestTagUpdateDeleteApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
patch.object(module, "enforce_rbac_access") as enforce_rbac_access,
):
@@ -360,7 +361,7 @@ class TestTagUpdateDeleteApi:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
patch.object(module, "enforce_rbac_access") as enforce_rbac_access,
):
@@ -383,7 +384,7 @@ class TestTagBindings:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
):
result, status = unwrap(TagBindingCollectionApi().post)(TagBindingCollectionApi(), payload, request_context)
@@ -402,7 +403,7 @@ class TestTagBindings:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
):
result, status = unwrap(TagBindingCollectionApi().post)(TagBindingCollectionApi(), payload, request_context)
@@ -422,7 +423,7 @@ class TestTagBindings:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
):
with pytest.raises(NotFound, match="App not found") as exc_info:
@@ -437,7 +438,7 @@ class TestTagBindings:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(readonly, "tenant-1")),
):
with pytest.raises(Forbidden):
@@ -455,7 +456,7 @@ class TestTagBindings:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
):
result, status = unwrap(TagBindingRemoveApi().post)(TagBindingRemoveApi(), payload, request_context)
@@ -475,7 +476,7 @@ class TestTagBindings:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(owner, "tenant-1")),
):
with pytest.raises(NotFound, match="Dataset not found") as exc_info:
@@ -490,7 +491,7 @@ class TestTagBindings:
with (
app.test_request_context("/"),
- patch.object(module.dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch.object(module, "current_account_with_tenant", return_value=(readonly, "tenant-1")),
):
with pytest.raises(Forbidden):
diff --git a/api/tests/unit_tests/controllers/console/test_extension.py b/api/tests/unit_tests/controllers/console/test_extension.py
index 97bad4420f7..ea60db4a1a3 100644
--- a/api/tests/unit_tests/controllers/console/test_extension.py
+++ b/api/tests/unit_tests/controllers/console/test_extension.py
@@ -9,6 +9,8 @@ import pytest
from flask import Flask
from flask.views import MethodView as FlaskMethodView
+from tests.unit_tests.config_override import apply_config_overrides
+
_NEEDS_METHOD_VIEW_CLEANUP = False
if not hasattr(builtins, "MethodView"):
builtins.__dict__["MethodView"] = FlaskMethodView
@@ -63,9 +65,12 @@ def _mock_console_guards(monkeypatch: pytest.MonkeyPatch) -> Account:
account.id = "account-123"
account._current_tenant = tenant
- monkeypatch.setattr(wraps_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
- monkeypatch.setattr(wraps_module.dify_config, "INIT_PASSWORD", "")
- monkeypatch.setattr("libs.login.dify_config.LOGIN_DISABLED", True)
+ apply_config_overrides(
+ monkeypatch,
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ INIT_PASSWORD="",
+ LOGIN_DISABLED=True,
+ )
monkeypatch.setattr(wraps_module, "current_account_with_tenant", lambda: (account, "tenant-123"))
# The login_required decorator consults the shared LocalProxy in libs.login.
diff --git a/api/tests/unit_tests/controllers/console/test_fastopenapi_init_validate.py b/api/tests/unit_tests/controllers/console/test_fastopenapi_init_validate.py
index 1d73ee30a68..dc8604a88f7 100644
--- a/api/tests/unit_tests/controllers/console/test_fastopenapi_init_validate.py
+++ b/api/tests/unit_tests/controllers/console/test_fastopenapi_init_validate.py
@@ -14,6 +14,7 @@ from services.init_validation_service import (
InitValidationService,
InvalidInitializationPasswordError,
)
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture
@@ -59,10 +60,7 @@ def test_validate_init_password_success(
init_validation: Mock,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(
- "controllers.console.wraps.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- )
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
client = app.test_client()
response = client.post("/console/api/init", json={"password": "expected"})
@@ -79,10 +77,7 @@ def test_validate_init_password_rejects_a_mismatch(
init_validation: Mock,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(
- "controllers.console.wraps.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- )
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
init_validation.validate_password.side_effect = InvalidInitializationPasswordError
client = app.test_client()
@@ -98,10 +93,7 @@ def test_validate_init_password_rejects_an_initialized_installation(
init_validation: Mock,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(
- "controllers.console.wraps.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- )
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
init_validation.validate_password.side_effect = AlreadyInitializedError
response = app.test_client().post("/console/api/init", json={"password": "expected"})
@@ -122,10 +114,7 @@ def test_validate_init_password_rejects_an_invalid_payload(
monkeypatch: pytest.MonkeyPatch,
payload: dict[str, str],
) -> None:
- monkeypatch.setattr(
- "controllers.console.wraps.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- )
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
response = app.test_client().post("/console/api/init", json=payload)
@@ -138,10 +127,7 @@ def test_validate_init_password_is_not_available_in_cloud(
init_validation: Mock,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(
- "controllers.console.wraps.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.CLOUD,
- )
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
response = app.test_client().post("/console/api/init", json={"password": "expected"})
diff --git a/api/tests/unit_tests/controllers/console/test_fastopenapi_system.py b/api/tests/unit_tests/controllers/console/test_fastopenapi_system.py
index 08aa94e6ca3..e82eca70956 100644
--- a/api/tests/unit_tests/controllers/console/test_fastopenapi_system.py
+++ b/api/tests/unit_tests/controllers/console/test_fastopenapi_system.py
@@ -1,5 +1,4 @@
import builtins
-from unittest.mock import patch
import pytest
from flask.views import MethodView
@@ -7,6 +6,7 @@ from flask.views import MethodView
from configs import dify_config
from dify_app import DifyApp
from extensions import ext_fastopenapi
+from tests.unit_tests.config_override import config_overrides_context
if not hasattr(builtins, "MethodView"):
builtins.MethodView = MethodView # type: ignore[attr-defined]
@@ -31,7 +31,7 @@ def test_console_ping_fastopenapi_returns_pong(app: DifyApp) -> None:
def test_console_version_fastopenapi_returns_current_version(app: DifyApp) -> None:
ext_fastopenapi.init_app(app)
- with patch("controllers.console.system.dify_config.CHECK_UPDATE_URL", None):
+ with config_overrides_context(CHECK_UPDATE_URL=None):
response = app.test_client().get("/console/api/version", query_string={"current_version": "0.0.0"})
assert response.status_code == 200
diff --git a/api/tests/unit_tests/controllers/console/test_human_input_form.py b/api/tests/unit_tests/controllers/console/test_human_input_form.py
index 7265f98b504..39e8f089ce9 100644
--- a/api/tests/unit_tests/controllers/console/test_human_input_form.py
+++ b/api/tests/unit_tests/controllers/console/test_human_input_form.py
@@ -28,6 +28,7 @@ from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
from models.human_input import RecipientType
from models.model import App, AppMode
from models.workflow import WorkflowRun
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture(autouse=True)
@@ -256,7 +257,7 @@ def test_post_form_decorated_success_validates_request_body(app: Flask, monkeypa
"controllers.console.wraps.current_account_with_tenant",
lambda: (current_user, "tenant-1"),
)
- monkeypatch.setattr("libs.login.dify_config.LOGIN_DISABLED", True)
+ apply_config_overrides(monkeypatch, LOGIN_DISABLED=True)
with app.test_request_context(
"/console/api/form/human_input/token",
diff --git a/api/tests/unit_tests/controllers/console/test_init_validate.py b/api/tests/unit_tests/controllers/console/test_init_validate.py
index 80145f7cae6..cfd6efd230b 100644
--- a/api/tests/unit_tests/controllers/console/test_init_validate.py
+++ b/api/tests/unit_tests/controllers/console/test_init_validate.py
@@ -6,7 +6,7 @@ from unittest.mock import Mock, create_autospec
import pytest
from flask import Flask
-from controllers.console import init_validate, wraps
+from controllers.console import init_validate
from controllers.console.error import AlreadySetupError, InitValidateFailedError
from enums import DeploymentEdition
from services.init_validation_service import (
@@ -14,6 +14,7 @@ from services.init_validation_service import (
InitValidationService,
InvalidInitializationPasswordError,
)
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture
@@ -49,7 +50,7 @@ def test_validate_init_password_already_setup(
init_validation: Mock,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(wraps.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
init_validation.validate_password.side_effect = AlreadyInitializedError
app.secret_key = "test-secret"
@@ -63,7 +64,7 @@ def test_validate_init_password_wrong_password(
init_validation: Mock,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(wraps.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
init_validation.validate_password.side_effect = InvalidInitializationPasswordError
app.secret_key = "test-secret"
@@ -78,7 +79,7 @@ def test_validate_init_password_success(
init_validation: Mock,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(wraps.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
app.secret_key = "test-secret"
with app.test_request_context("/console/api/init", method="POST"):
diff --git a/api/tests/unit_tests/controllers/console/test_system.py b/api/tests/unit_tests/controllers/console/test_system.py
index 3c390003eb1..8eeb5e48ab1 100644
--- a/api/tests/unit_tests/controllers/console/test_system.py
+++ b/api/tests/unit_tests/controllers/console/test_system.py
@@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patch
import pytest
import controllers.console.system as system_module
+from tests.unit_tests.config_override import config_overrides_context
class TestHasNewVersion:
@@ -37,11 +38,7 @@ class TestCheckVersionUpdate:
query = system_module.VersionQuery(current_version="1.0.0")
with (
- patch.object(
- system_module.dify_config,
- "CHECK_UPDATE_URL",
- "",
- ),
+ config_overrides_context(CHECK_UPDATE_URL=""),
patch.object(
system_module.dify_config.project,
"version",
@@ -56,11 +53,7 @@ class TestCheckVersionUpdate:
query = system_module.VersionQuery(current_version="1.0.0")
with (
- patch.object(
- system_module.dify_config,
- "CHECK_UPDATE_URL",
- "http://example.com",
- ),
+ config_overrides_context(CHECK_UPDATE_URL="http://example.com"),
patch.object(
system_module.httpx,
"get",
@@ -83,11 +76,7 @@ class TestCheckVersionUpdate:
}
with (
- patch.object(
- system_module.dify_config,
- "CHECK_UPDATE_URL",
- "http://example.com",
- ),
+ config_overrides_context(CHECK_UPDATE_URL="http://example.com"),
patch.object(
system_module.httpx,
"get",
@@ -113,11 +102,7 @@ class TestCheckVersionUpdate:
}
with (
- patch.object(
- system_module.dify_config,
- "CHECK_UPDATE_URL",
- "http://example.com",
- ),
+ config_overrides_context(CHECK_UPDATE_URL="http://example.com"),
patch.object(
system_module.httpx,
"get",
diff --git a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py
index ea0fc9c2dc8..0a33e67163b 100644
--- a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py
+++ b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py
@@ -6,7 +6,6 @@ import pytest
from flask import Flask
from werkzeug.exceptions import Conflict, Forbidden, NotFound
-from configs import dify_config
from controllers.console import flask_admission, workflow_run_archive
from controllers.console.workflow_run_archive import (
WorkflowRunArchiveDownloadApi,
@@ -37,6 +36,7 @@ _ENDPOINTS = [
WorkflowRunArchiveDownloadApi.get,
WorkflowRunArchiveDownloadFileApi.get,
]
+from tests.unit_tests.config_override import apply_config_overrides
def _account(role: TenantAccountRole) -> Account:
@@ -82,7 +82,7 @@ def test_workflow_run_archive_endpoints_reject_non_manager_when_rbac_is_disabled
method,
) -> None:
account = _account(TenantAccountRole.NORMAL)
- monkeypatch.setattr(dify_config, "RBAC_ENABLED", False)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=False)
monkeypatch.setattr(
flask_admission,
"current_account_with_tenant",
@@ -108,7 +108,7 @@ def test_workflow_run_archive_endpoints_are_hidden_outside_cloud(
method,
args: tuple[object, ...],
) -> None:
- monkeypatch.setattr(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
app = Flask(__name__)
with app.test_request_context(), pytest.raises(NotFound):
@@ -119,7 +119,7 @@ def test_workflow_run_archive_endpoint_allows_admitted_role_when_rbac_is_enabled
monkeypatch: pytest.MonkeyPatch,
) -> None:
account = _account(TenantAccountRole.NORMAL)
- monkeypatch.setattr(dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
account_with_tenant = AccountWithTenant(account=account, tenant_id="tenant-1")
monkeypatch.setattr(flask_admission, "current_account_with_tenant", lambda: account_with_tenant)
monkeypatch.setattr("controllers.console.wraps.current_account_with_tenant", lambda: account_with_tenant)
diff --git a/api/tests/unit_tests/controllers/console/test_wraps.py b/api/tests/unit_tests/controllers/console/test_wraps.py
index ee9a54a21cd..be562c20133 100644
--- a/api/tests/unit_tests/controllers/console/test_wraps.py
+++ b/api/tests/unit_tests/controllers/console/test_wraps.py
@@ -45,6 +45,7 @@ from models import Account, DifySetup
from models.account import AccountStatus, TenantAccountRole
from models.dataset import Dataset, RateLimitLog
from services.entities.feature_entities import LicenseStatus
+from tests.unit_tests.config_override import config_overrides_context
@pytest.fixture(autouse=True)
@@ -228,10 +229,7 @@ class TestCurrentContextInjection:
return request_context
with (
- patch(
- "controllers.console.flask_admission.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- ),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY),
Flask(__name__).test_request_context(),
pytest.raises(HTTPException) as exc_info,
):
@@ -247,7 +245,7 @@ class TestCurrentContextInjection:
patch("controllers.console.flask_admission.setup_required", side_effect=lambda view: view),
patch("controllers.console.flask_admission.login_required", side_effect=lambda view: view),
patch("controllers.console.flask_admission.account_initialization_required", side_effect=lambda view: view),
- patch("controllers.console.flask_admission.dify_config.RBAC_ENABLED", False),
+ config_overrides_context(RBAC_ENABLED=False),
patch(
"controllers.console.flask_admission.current_account_with_tenant",
return_value=AccountWithTenant(account=current_user, tenant_id="tenant-123"),
@@ -273,7 +271,7 @@ class TestCurrentContextInjection:
patch("controllers.console.flask_admission.setup_required", side_effect=lambda view: view),
patch("controllers.console.flask_admission.login_required", side_effect=lambda view: view),
patch("controllers.console.flask_admission.account_initialization_required", side_effect=lambda view: view),
- patch("controllers.console.flask_admission.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch(
"controllers.console.flask_admission.current_account_with_tenant",
return_value=AccountWithTenant(account=current_user, tenant_id="tenant-123"),
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_accounts.py b/api/tests/unit_tests/controllers/console/workspace/test_accounts.py
index d0178451eb2..d8ec8dce60b 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_accounts.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_accounts.py
@@ -59,6 +59,7 @@ from services.account_errors import (
MissingInvitationCodeError,
)
from services.entities.account_entities import AccountIntegrationStatus, AccountProfileChanges
+from tests.unit_tests.config_override import config_overrides_context
def make_account(account_id: str = "u1", *, status: AccountStatus = AccountStatus.ACTIVE) -> Account:
@@ -409,7 +410,7 @@ class TestAccountAvatarApiGet:
with (
app.test_request_context("/account/avatar"),
patch("controllers.console.wraps._is_setup_completed", return_value=True),
- patch("libs.login.dify_config.LOGIN_DISABLED", True),
+ config_overrides_context(LOGIN_DISABLED=True),
patch(
"controllers.console.wraps.current_account_with_tenant",
return_value=(account, "workspace-1"),
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py b/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py
index 93a6133007c..a4f14e5255d 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py
@@ -38,6 +38,7 @@ from services.entities.model_provider_entities import (
SystemConfigurationResponse,
)
from services.workspace_service import EffectiveCreditPool
+from tests.unit_tests.config_override import config_overrides_context
VALID_UUID = "123e4567-e89b-12d3-a456-426614174000"
INVALID_UUID = "123"
@@ -603,9 +604,11 @@ class TestModelProviderPaymentCheckoutUrlApi:
with (
app.test_request_context("/"),
- patch.object(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
- patch.object(dify_config, "LOGIN_DISABLED", True),
- patch.object(dify_config, "RBAC_ENABLED", False),
+ config_overrides_context(
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ LOGIN_DISABLED=True,
+ RBAC_ENABLED=False,
+ ),
patch(
"controllers.console.workspace.model_providers.BillingService.get_model_provider_payment_link",
) as get_model_provider_payment_link,
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_plugin.py b/api/tests/unit_tests/controllers/console/workspace/test_plugin.py
index 88e9487f5dc..ea0f79a851c 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_plugin.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_plugin.py
@@ -82,6 +82,7 @@ from models.account import (
TenantPluginDebugPermission,
TenantPluginInstallPermission,
)
+from tests.unit_tests.config_override import config_overrides_context
def _plugin_category_list_item(category: str = "tool") -> dict[str, Any]:
@@ -653,7 +654,7 @@ class TestPluginUploadFromPkgApi:
with (
app.test_request_context("/", data=data, content_type="multipart/form-data"),
- patch("controllers.console.workspace.plugin.dify_config.PLUGIN_MAX_PACKAGE_SIZE", 0),
+ config_overrides_context(PLUGIN_MAX_PACKAGE_SIZE=0),
patch("controllers.console.workspace.plugin.PluginService.upload_pkg") as upload_pkg_mock,
):
with pytest.raises(ValueError) as exc_info:
@@ -937,7 +938,7 @@ class TestPluginUploadFromBundleApi:
data={"bundle": file},
content_type="multipart/form-data",
),
- patch("controllers.console.workspace.plugin.dify_config.PLUGIN_MAX_BUNDLE_SIZE", 0),
+ config_overrides_context(PLUGIN_MAX_BUNDLE_SIZE=0),
patch("controllers.console.workspace.plugin.PluginService.upload_bundle") as upload_bundle_mock,
):
with pytest.raises(ValueError) as exc_info:
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_workspace.py b/api/tests/unit_tests/controllers/console/workspace/test_workspace.py
index 9c399e18add..6a7d95d0f0a 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_workspace.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_workspace.py
@@ -45,6 +45,7 @@ from models.account import Account, Tenant, TenantAccountJoin, TenantCustomConfi
from repositories.workspace_query_repository import WorkspaceQueryRepository
from services import workspace_plan_gateway
from services.workspace_query_service import WorkspaceQueryService, WorkspaceRecord
+from tests.unit_tests.config_override import config_overrides_context
@pytest.fixture
@@ -485,7 +486,7 @@ class TestCustomConfigWorkspaceApi:
with (
app.test_request_context("/workspaces/custom-config"),
- patch("controllers.console.workspace.workspace.dify_config.FILES_URL", "https://files.example.com"),
+ config_overrides_context(FILES_URL="https://files.example.com"),
):
result = method(api, workspace_session, tenant.id)
diff --git a/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin.py b/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin.py
index 102c4ab4b53..3f8a6efde6b 100644
--- a/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin.py
+++ b/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin.py
@@ -35,6 +35,7 @@ from controllers.inner_api.plugin.plugin import (
)
from core.workflow.file_reference import build_file_reference
from models import Account, Tenant
+from tests.unit_tests.config_override import apply_config_overrides
def _tenant() -> Tenant:
@@ -280,7 +281,7 @@ class TestPluginUploadFileRequestApi:
"""Test that post() generates a signed URL and returns it"""
# Arrange
mock_get_uri.return_value = "/files/upload/for-plugin?sign=1"
- monkeypatch.setattr(plugin_module.dify_config, "INTERNAL_FILES_URL", "http://api:5001")
+ apply_config_overrides(monkeypatch, INTERNAL_FILES_URL="http://api:5001")
tenant = _tenant()
user = _user()
mock_payload = MagicMock()
@@ -350,8 +351,11 @@ class TestPluginDownloadFileRequestApi:
size=123,
download_uri="/files/tools/report.pdf?sign=1",
)
- monkeypatch.setattr(plugin_module.dify_config, "FILES_URL", "https://files.example.com")
- monkeypatch.setattr(plugin_module.dify_config, "INTERNAL_FILES_URL", "http://api:5001")
+ apply_config_overrides(
+ monkeypatch,
+ FILES_URL="https://files.example.com",
+ INTERNAL_FILES_URL="http://api:5001",
+ )
mock_payload = MagicMock()
mock_payload.tenant_id = tenant.id
mock_payload.user_id = "user-id"
diff --git a/api/tests/unit_tests/controllers/inner_api/test_agent_files.py b/api/tests/unit_tests/controllers/inner_api/test_agent_files.py
index a4874ae2077..f5bb418d76a 100644
--- a/api/tests/unit_tests/controllers/inner_api/test_agent_files.py
+++ b/api/tests/unit_tests/controllers/inner_api/test_agent_files.py
@@ -15,6 +15,7 @@ from controllers.inner_api.agent.files import (
from core.workflow.file_reference import build_file_reference
from models.account import Account, Tenant
from services.file_request_service import DownloadFileRequestResult
+from tests.unit_tests.config_override import apply_config_overrides
MODULE = "controllers.inner_api.agent.files"
@@ -132,7 +133,7 @@ def test_download_request_binds_frontend_url(
"file": {"transfer_method": "tool_file", "reference": reference},
"for_frontend": True,
}
- monkeypatch.setattr(f"{MODULE}.dify_config.FILES_URL", "https://files.example.com")
+ apply_config_overrides(monkeypatch, FILES_URL="https://files.example.com")
session = unbound_session
with app.test_request_context("/", method="POST", json=payload):
with (
diff --git a/api/tests/unit_tests/controllers/inner_api/test_agent_llm.py b/api/tests/unit_tests/controllers/inner_api/test_agent_llm.py
index 15160f8e749..f37e1acd971 100644
--- a/api/tests/unit_tests/controllers/inner_api/test_agent_llm.py
+++ b/api/tests/unit_tests/controllers/inner_api/test_agent_llm.py
@@ -15,6 +15,7 @@ from graphon.model_runtime.entities.llm_entities import LLMResultChunk, LLMResul
from graphon.model_runtime.entities.message_entities import AssistantPromptMessage, UserPromptMessage
from services.agent_llm_inner_service import AgentLLMInnerServiceError, PreparedAgentLLMInvocation
from services.entities.agent_llm_inner import AgentLLMInvokeRequest
+from tests.unit_tests.config_override import config_overrides_context
def _payload() -> dict[str, object]:
@@ -44,8 +45,7 @@ def _payload() -> dict[str, object]:
@contextmanager
def _agent_inner_auth() -> Generator[None]:
with (
- patch("configs.dify_config.PLUGIN_DAEMON_KEY", "plugin-daemon-key"),
- patch("configs.dify_config.INNER_API_KEY_FOR_PLUGIN", "inner-key"),
+ config_overrides_context(PLUGIN_DAEMON_KEY="plugin-daemon-key", INNER_API_KEY_FOR_PLUGIN="inner-key"),
):
yield
diff --git a/api/tests/unit_tests/controllers/inner_api/test_agent_tools.py b/api/tests/unit_tests/controllers/inner_api/test_agent_tools.py
index 2a92ecbbc10..186615f3d90 100644
--- a/api/tests/unit_tests/controllers/inner_api/test_agent_tools.py
+++ b/api/tests/unit_tests/controllers/inner_api/test_agent_tools.py
@@ -9,6 +9,7 @@ from flask import Flask
from controllers.inner_api import bp as inner_api_bp
from services.entities.agent_tool_inner import AgentToolInvokeResponse
from services.errors.agent_tool_inner import AgentToolInnerServiceError
+from tests.unit_tests.config_override import config_overrides_context
def _headers(api_key: str | None = "inner-key") -> dict[str, str]:
@@ -48,8 +49,7 @@ def _payload() -> dict[str, object]:
@contextmanager
def _agent_inner_auth() -> Generator[None]:
with (
- patch("configs.dify_config.PLUGIN_DAEMON_KEY", "plugin-daemon-key"),
- patch("configs.dify_config.INNER_API_KEY_FOR_PLUGIN", "inner-key"),
+ config_overrides_context(PLUGIN_DAEMON_KEY="plugin-daemon-key", INNER_API_KEY_FOR_PLUGIN="inner-key"),
):
yield
diff --git a/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.py b/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.py
index 00eab81cbe6..805385b09b2 100644
--- a/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.py
+++ b/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.py
@@ -16,6 +16,7 @@ from services.errors.knowledge_retrieval import (
InnerKnowledgeRetrieveAppNotFoundError,
InnerKnowledgeRetrieveDatasetTenantMismatchError,
)
+from tests.unit_tests.config_override import config_overrides_context
@pytest.fixture
@@ -58,8 +59,7 @@ def _payload() -> dict[str, object]:
@contextmanager
def _plugin_inner_auth() -> Iterator[None]:
with (
- patch("configs.dify_config.PLUGIN_DAEMON_KEY", "plugin-daemon-key"),
- patch("configs.dify_config.INNER_API_KEY_FOR_PLUGIN", "inner-key"),
+ config_overrides_context(PLUGIN_DAEMON_KEY="plugin-daemon-key", INNER_API_KEY_FOR_PLUGIN="inner-key"),
):
yield
diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_composition.py b/api/tests/unit_tests/controllers/openapi/auth/test_composition.py
index 41d4416efc5..e1b7a4f3cd3 100644
--- a/api/tests/unit_tests/controllers/openapi/auth/test_composition.py
+++ b/api/tests/unit_tests/controllers/openapi/auth/test_composition.py
@@ -17,6 +17,7 @@ from enums import DeploymentEdition
from libs.oauth_bearer import Scope, TokenType
from models.account import TenantAccountRole
from services.enterprise.enterprise_service import WebAppAccessMode
+from tests.unit_tests.config_override import config_overrides_context
def test_account_pipeline_is_auth_pipeline():
@@ -163,10 +164,7 @@ def _selected_webapp_steps(*, scope, app_access_mode):
features.webapp_auth.enabled = True
selected = []
with (
- patch(
- "controllers.openapi.auth.conditions.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.ENTERPRISE,
- ),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE),
patch("controllers.openapi.auth.conditions.FeatureService.get_system_features", return_value=features),
):
for step in account_pipeline._auth:
diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py b/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py
index b9cd877f0bf..a1f6b26c9ca 100644
--- a/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py
+++ b/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py
@@ -24,6 +24,7 @@ from enums import DeploymentEdition
from libs.oauth_bearer import Scope, TokenType
from models.account import TenantAccountRole
from services.enterprise.enterprise_service import WebAppAccessMode
+from tests.unit_tests.config_override import config_overrides_context
def _ctx(token_type=TokenType.OAUTH_ACCOUNT, path_params=None, **kwargs):
@@ -117,29 +118,20 @@ def test_path_has_app_id_false():
def test_edition_community():
- with patch(
- "controllers.openapi.auth.conditions.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- ):
+ with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY):
assert EDITION_COMMUNITY(_ctx()) is True
assert EDITION_ENTERPRISE(_ctx()) is False
assert EDITION_CLOUD(_ctx()) is False
def test_edition_enterprise():
- with patch(
- "controllers.openapi.auth.conditions.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.ENTERPRISE,
- ):
+ with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE):
assert EDITION_ENTERPRISE(_ctx()) is True
assert EDITION_COMMUNITY(_ctx()) is False
def test_edition_cloud():
- with patch(
- "controllers.openapi.auth.conditions.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.CLOUD,
- ):
+ with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD):
assert EDITION_CLOUD(_ctx()) is True
diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.py b/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.py
index a9f5df5aae6..f483c80eb38 100644
--- a/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.py
+++ b/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.py
@@ -9,6 +9,7 @@ from controllers.openapi.auth.data import AuthData
from controllers.openapi.auth.pipeline import AuthPipeline, PipelineRoute, PipelineRouter
from enums import DeploymentEdition
from libs.oauth_bearer import Scope, TokenType
+from tests.unit_tests.config_override import config_overrides_context
def _make_identity(
@@ -76,10 +77,7 @@ def test_guard_edition_gate_returns_404(app):
router = _make_router()
with app.test_request_context("/test"):
- with patch(
- "controllers.openapi.auth.pipeline.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- ):
+ with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY):
@router.guard(scope=Scope.FULL, edition=frozenset({DeploymentEdition.ENTERPRISE}))
def view(*, auth_data):
@@ -97,10 +95,7 @@ def test_guard_token_type_gate_returns_403(app):
patch("controllers.openapi.auth.pipeline.extract_bearer", return_value="tok"),
patch("controllers.openapi.auth.pipeline.get_authenticator") as mock_auth,
patch("controllers.openapi.auth.pipeline.emit_wrong_surface"),
- patch(
- "controllers.openapi.auth.pipeline.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- ),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY),
):
identity = _fake_identity()
identity.token_type = TokenType.OAUTH_EXTERNAL_SSO
@@ -121,10 +116,7 @@ def test_guard_unregistered_token_type_returns_403(app):
with (
patch("controllers.openapi.auth.pipeline.extract_bearer", return_value="tok"),
patch("controllers.openapi.auth.pipeline.get_authenticator") as mock_auth,
- patch(
- "controllers.openapi.auth.pipeline.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- ),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY),
):
identity = _fake_identity()
identity.token_type = TokenType.OAUTH_EXTERNAL_SSO
@@ -213,10 +205,7 @@ def test_router_rejects_token_type_on_wrong_edition(app):
with (
patch("controllers.openapi.auth.pipeline.extract_bearer", return_value="tok"),
patch("controllers.openapi.auth.pipeline.get_authenticator") as mock_auth,
- patch(
- "controllers.openapi.auth.pipeline.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- ),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY),
):
identity = _make_identity(token_type=TokenType.OAUTH_EXTERNAL_SSO)
mock_auth.return_value.authenticate.return_value = identity
diff --git a/api/tests/unit_tests/controllers/openapi/test_meta_version.py b/api/tests/unit_tests/controllers/openapi/test_meta_version.py
index 3da3c4fca21..9befa1c9551 100644
--- a/api/tests/unit_tests/controllers/openapi/test_meta_version.py
+++ b/api/tests/unit_tests/controllers/openapi/test_meta_version.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import pytest
from enums import DeploymentEdition
+from tests.unit_tests.config_override import apply_config_overrides
def test_version_endpoint_returns_200_without_auth(openapi_app):
@@ -35,9 +36,7 @@ def test_version_endpoint_ignores_bearer_header(openapi_app):
def test_version_endpoint_reflects_edition_config(openapi_app, monkeypatch: pytest.MonkeyPatch):
- from configs import dify_config
-
- monkeypatch.setattr(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
client = openapi_app.test_client()
response = client.get("/openapi/v1/_version")
@@ -47,9 +46,7 @@ def test_version_endpoint_reflects_edition_config(openapi_app, monkeypatch: pyte
def test_version_endpoint_reflects_enterprise_edition(openapi_app, monkeypatch: pytest.MonkeyPatch):
- from configs import dify_config
-
- monkeypatch.setattr(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
client = openapi_app.test_client()
response = client.get("/openapi/v1/_version")
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_completion.py b/api/tests/unit_tests/controllers/service_api/app/test_completion.py
index 39c986e3ca2..a83e8b9f734 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_completion.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_completion.py
@@ -54,6 +54,7 @@ from services.conversation_service import ConversationService
from services.errors.app import IsDraftWorkflowError, WorkflowIdFormatError, WorkflowNotFoundError
from services.errors.conversation import ConversationNotExistsError
from services.errors.llm import InvokeRateLimitError
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture
@@ -556,7 +557,7 @@ class TestChatApiController:
self, app: Flask, monkeypatch: pytest.MonkeyPatch, orm_session: Session
) -> None:
completion_module = sys.modules["controllers.service_api.app.completion"]
- monkeypatch.setattr(completion_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
billing_get_info = Mock(return_value={"enabled": True, "subscription": {"plan": CloudPlan.SANDBOX}})
generate = Mock()
@@ -602,7 +603,7 @@ class TestChatApiController:
workflow_id: str | None,
) -> None:
completion_module = sys.modules["controllers.service_api.app.completion"]
- monkeypatch.setattr(completion_module.dify_config, "DEPLOYMENT_EDITION", deployment_edition)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=deployment_edition)
billing_get_info = Mock(return_value={"enabled": billing_enabled, "subscription": {"plan": plan}})
generate = Mock(return_value={"result": "ok"})
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py b/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py
index 55a130d8b09..d0d77557cad 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py
@@ -50,6 +50,7 @@ from repositories.api_workflow_node_execution_repository import WorkflowNodeExec
from repositories.entities.workflow_pause import WorkflowPauseEntity
from services.app_generate_service import AppGenerateService
from services.workflow_event_snapshot_service import _build_snapshot_events
+from tests.unit_tests.config_override import apply_config_overrides
class _DummyRateLimit:
@@ -380,7 +381,7 @@ class TestHitlServiceApi:
monkeypatch: pytest.MonkeyPatch,
sqlite_engine: Engine,
) -> None:
- monkeypatch.setattr(ags_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
monkeypatch.setattr(ags_module, "RateLimit", _DummyRateLimit)
workflow = MagicMock()
diff --git a/api/tests/unit_tests/controllers/service_api/test_wraps.py b/api/tests/unit_tests/controllers/service_api/test_wraps.py
index 9b058fc889c..82c03952c8d 100644
--- a/api/tests/unit_tests/controllers/service_api/test_wraps.py
+++ b/api/tests/unit_tests/controllers/service_api/test_wraps.py
@@ -29,6 +29,7 @@ from models.account import TenantAccountRole
from models.dataset import Dataset, RateLimitLog
from models.enums import ApiTokenType
from models.model import ApiToken, App, AppMode, IconType
+from tests.unit_tests.config_override import config_overrides_context
def _configure_current_app_mock(mock_current_app):
@@ -346,7 +347,7 @@ class TestCloudEditionBillingResourceCheck:
# Act
with (
app.test_request_context("/", method="GET"),
- patch("controllers.service_api.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),
):
result = add_segment()
@@ -376,7 +377,7 @@ class TestCloudEditionBillingResourceCheck:
with (
app.test_request_context("/", method="GET"),
- patch("controllers.service_api.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),
pytest.raises(ServiceUnavailable) as exc_info,
):
upload_document()
@@ -406,7 +407,7 @@ class TestCloudEditionBillingResourceCheck:
with (
app.test_request_context("/", method="GET"),
- patch("controllers.service_api.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),
):
result = upload_document()
diff --git a/api/tests/unit_tests/controllers/test_swagger.py b/api/tests/unit_tests/controllers/test_swagger.py
index af2e3a1396f..6f9f4677bb4 100644
--- a/api/tests/unit_tests/controllers/test_swagger.py
+++ b/api/tests/unit_tests/controllers/test_swagger.py
@@ -626,12 +626,9 @@ def test_console_member_invite_documents_bad_request_response():
}
-def test_console_billing_routes_document_error_responses(monkeypatch: pytest.MonkeyPatch):
- from configs import dify_config
+def test_console_billing_routes_document_error_responses():
from controllers.console import bp as console_bp
- monkeypatch.setattr(dify_config, "SWAGGER_UI_ENABLED", True)
-
app = Flask(__name__)
app.config["TESTING"] = True
app.config["RESTX_INCLUDE_ALL_MODELS"] = True
@@ -684,12 +681,9 @@ def test_console_billing_routes_document_error_responses(monkeypatch: pytest.Mon
assert compliance_response["required"] == ["url"]
-def test_console_model_provider_checkout_route_is_deprecated(monkeypatch: pytest.MonkeyPatch):
- from configs import dify_config
+def test_console_model_provider_checkout_route_is_deprecated():
from controllers.console import bp as console_bp
- monkeypatch.setattr(dify_config, "SWAGGER_UI_ENABLED", True)
-
app = Flask(__name__)
app.config["TESTING"] = True
app.config["RESTX_INCLUDE_ALL_MODELS"] = True
diff --git a/api/tests/unit_tests/controllers/web/test_web_forgot_password.py b/api/tests/unit_tests/controllers/web/test_web_forgot_password.py
index 5532220f52f..f43bf1fbf0a 100644
--- a/api/tests/unit_tests/controllers/web/test_web_forgot_password.py
+++ b/api/tests/unit_tests/controllers/web/test_web_forgot_password.py
@@ -18,6 +18,7 @@ from enums import DeploymentEdition
from models.account import Account
from models.engine import db
from services.entities.feature_entities import SystemFeatureModel
+from tests.unit_tests.config_override import config_overrides_context
@pytest.fixture
@@ -39,7 +40,7 @@ def _patch_wraps():
)
with (
patch("controllers.console.wraps.db") as mock_db,
- patch("controllers.console.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE),
patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),
):
yield
diff --git a/api/tests/unit_tests/core/app/app_config/common/test_parameters_mapping.py b/api/tests/unit_tests/core/app/app_config/common/test_parameters_mapping.py
index 6dbf301f656..56a19e54149 100644
--- a/api/tests/unit_tests/core/app/app_config/common/test_parameters_mapping.py
+++ b/api/tests/unit_tests/core/app/app_config/common/test_parameters_mapping.py
@@ -1,26 +1,24 @@
-from unittest.mock import MagicMock
-
import pytest
# Module under test
from core.app.app_config.common import parameters_mapping
+from tests.unit_tests.config_override import apply_config_overrides
class TestGetParametersFromFeatureDict:
"""Test suite for get_parameters_from_feature_dict"""
@pytest.fixture
- def mock_config(self, monkeypatch: pytest.MonkeyPatch):
- """Mock dify_config values"""
- mock = MagicMock()
- mock.UPLOAD_IMAGE_FILE_SIZE_LIMIT = 1
- mock.UPLOAD_VIDEO_FILE_SIZE_LIMIT = 2
- mock.UPLOAD_AUDIO_FILE_SIZE_LIMIT = 3
- mock.UPLOAD_FILE_SIZE_LIMIT = 4
- mock.WORKFLOW_FILE_UPLOAD_LIMIT = 5
-
- monkeypatch.setattr(parameters_mapping, "dify_config", mock)
- return mock
+ def mock_config(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Override file limits on the shared typed config."""
+ apply_config_overrides(
+ monkeypatch,
+ UPLOAD_IMAGE_FILE_SIZE_LIMIT=1,
+ UPLOAD_VIDEO_FILE_SIZE_LIMIT=2,
+ UPLOAD_AUDIO_FILE_SIZE_LIMIT=3,
+ UPLOAD_FILE_SIZE_LIMIT=4,
+ WORKFLOW_FILE_UPLOAD_LIMIT=5,
+ )
@pytest.fixture
def mock_default_file_limits(self, monkeypatch: pytest.MonkeyPatch):
diff --git a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_generator.py b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_generator.py
index b5396e3acd5..2f69b1ed877 100644
--- a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_generator.py
@@ -23,6 +23,7 @@ from core.ops.ops_trace_manager import TraceQueueManager
from libs.datetime_utils import naive_utc_now
from models.enums import MessageStatus
from models.model import AppMode
+from tests.unit_tests.config_override import apply_config_overrides
class TestAdvancedChatAppGeneratorValidation:
@@ -945,7 +946,7 @@ class TestAdvancedChatAppGeneratorInternals:
"core.app.apps.advanced_chat.app_generator.AdvancedChatAppRunner",
_make_runner(raised_error),
)
- monkeypatch.setattr("core.app.apps.advanced_chat.app_generator.dify_config", SimpleNamespace(DEBUG=True))
+ apply_config_overrides(monkeypatch, DEBUG=True)
monkeypatch.setattr(
"core.app.apps.advanced_chat.app_generator.db",
SimpleNamespace(engine=object(), session=SimpleNamespace(close=lambda: None)),
diff --git a/api/tests/unit_tests/core/app/apps/agent_chat/test_agent_chat_app_generator.py b/api/tests/unit_tests/core/app/apps/agent_chat/test_agent_chat_app_generator.py
index 29bfe2b4bb3..b64cb1c645a 100644
--- a/api/tests/unit_tests/core/app/apps/agent_chat/test_agent_chat_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/agent_chat/test_agent_chat_app_generator.py
@@ -11,6 +11,7 @@ from core.app.apps.agent_chat.app_generator import AgentChatAppGenerator
from core.app.apps.exc import GenerateTaskStoppedError
from core.app.entities.app_invoke_entities import InvokeFrom
from graphon.model_runtime.errors.invoke import InvokeAuthorizationError
+from tests.unit_tests.config_override import apply_config_overrides
class DummyAccount:
@@ -328,6 +329,7 @@ class TestAgentChatAppGeneratorWorker:
self,
generator,
mocker: MockerFixture,
+ monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
sqlite_session_factory: sessionmaker[Session],
):
@@ -343,7 +345,7 @@ class TestAgentChatAppGeneratorWorker:
side_effect=sqlite_session_factory,
)
- mocker.patch("core.app.apps.agent_chat.app_generator.dify_config", new=mocker.MagicMock(DEBUG=True))
+ apply_config_overrides(monkeypatch, DEBUG=True)
with caplog.at_level(logging.ERROR, logger="core.app.apps.agent_chat.app_generator"):
generator._generate_worker(
diff --git a/api/tests/unit_tests/core/app/workflow/test_observability_layer_extra.py b/api/tests/unit_tests/core/app/workflow/test_observability_layer_extra.py
index b283f8a211d..d13dea0c7b7 100644
--- a/api/tests/unit_tests/core/app/workflow/test_observability_layer_extra.py
+++ b/api/tests/unit_tests/core/app/workflow/test_observability_layer_extra.py
@@ -6,12 +6,13 @@ import pytest
from core.app.workflow.layers.observability import ObservabilityLayer
from graphon.enums import BuiltinNodeTypes
+from tests.unit_tests.config_override import apply_config_overrides
class TestObservabilityLayerExtras:
def test_init_tracer_enabled_sets_tracer(self, monkeypatch: pytest.MonkeyPatch):
tracer = object()
- monkeypatch.setattr("core.app.workflow.layers.observability.dify_config.ENABLE_OTEL", True)
+ apply_config_overrides(monkeypatch, ENABLE_OTEL=True)
monkeypatch.setattr("core.app.workflow.layers.observability.is_instrument_flag_enabled", lambda: False)
monkeypatch.setattr("core.app.workflow.layers.observability.get_tracer", lambda _: tracer)
@@ -23,7 +24,7 @@ class TestObservabilityLayerExtras:
def test_init_tracer_disables_when_get_tracer_fails(
self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
):
- monkeypatch.setattr("core.app.workflow.layers.observability.dify_config.ENABLE_OTEL", True)
+ apply_config_overrides(monkeypatch, ENABLE_OTEL=True)
monkeypatch.setattr("core.app.workflow.layers.observability.is_instrument_flag_enabled", lambda: False)
def _raise(*_args, **_kwargs):
@@ -38,7 +39,7 @@ class TestObservabilityLayerExtras:
assert "Failed to get OpenTelemetry tracer" in caplog.text
def test_init_tracer_disables_when_otel_disabled(self, monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr("core.app.workflow.layers.observability.dify_config.ENABLE_OTEL", False)
+ apply_config_overrides(monkeypatch, ENABLE_OTEL=False)
monkeypatch.setattr("core.app.workflow.layers.observability.is_instrument_flag_enabled", lambda: False)
layer = ObservabilityLayer()
diff --git a/api/tests/unit_tests/core/callback_handler/test_agent_tool_callback_handler.py b/api/tests/unit_tests/core/callback_handler/test_agent_tool_callback_handler.py
index f9b3b1864e0..9d22e2f633f 100644
--- a/api/tests/unit_tests/core/callback_handler/test_agent_tool_callback_handler.py
+++ b/api/tests/unit_tests/core/callback_handler/test_agent_tool_callback_handler.py
@@ -5,6 +5,7 @@ from pytest_mock import MockerFixture
import core.callback_handler.agent_tool_callback_handler as module
from core.callback_handler.agent_tool_callback_handler import DifyAgentCallbackHandler
+from tests.unit_tests.config_override import apply_config_overrides
# -----------------------------
# Fixtures
@@ -12,13 +13,13 @@ from core.callback_handler.agent_tool_callback_handler import DifyAgentCallbackH
@pytest.fixture
-def enable_debug(mocker: MockerFixture):
- mocker.patch.object(module.dify_config, "DEBUG", True)
+def enable_debug(monkeypatch: pytest.MonkeyPatch) -> None:
+ apply_config_overrides(monkeypatch, DEBUG=True)
@pytest.fixture
-def disable_debug(mocker: MockerFixture):
- mocker.patch.object(module.dify_config, "DEBUG", False)
+def disable_debug(monkeypatch: pytest.MonkeyPatch) -> None:
+ apply_config_overrides(monkeypatch, DEBUG=False)
@pytest.fixture
diff --git a/api/tests/unit_tests/core/ops/test_ops_trace_manager.py b/api/tests/unit_tests/core/ops/test_ops_trace_manager.py
index 3bb3827d629..f4bebc64c21 100644
--- a/api/tests/unit_tests/core/ops/test_ops_trace_manager.py
+++ b/api/tests/unit_tests/core/ops/test_ops_trace_manager.py
@@ -17,7 +17,6 @@ from sqlalchemy import Engine
from sqlalchemy.orm import Session, sessionmaker
import core.ops.ops_trace_manager as module
-from configs import dify_config
from core.ops.ops_trace_manager import OpsTraceManager, TraceQueueManager, TraceTask, TraceTaskName
from core.rag.models.document import Document as RetrievalDocument
from graphon.enums import WorkflowExecutionStatus
@@ -26,6 +25,7 @@ from models.enums import ConversationFromSource, CreatorUserRole, MessageStatus,
from models.model import App, AppMode, AppModelConfig, Conversation, Message, MessageFile, TraceAppConfig
from models.workflow import WorkflowAppLog, WorkflowAppLogCreatedFrom, WorkflowRun, WorkflowType
from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository
+from tests.unit_tests.config_override import apply_config_overrides
class DummyConfig:
@@ -155,7 +155,7 @@ def database(sqlite_engine: Engine, sqlite_session: Session) -> Iterator[Session
def trace_environment(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
monkeypatch.setattr(module, "provider_config_map", FakeProviderMap({"dummy": PROVIDER_ENTRY}))
monkeypatch.setattr(module, "unified_provider_config_map", FakeProviderMap({}))
- monkeypatch.setattr(dify_config, "OPS_TRACE_UNIFIED_ENABLED", False)
+ apply_config_overrides(monkeypatch, OPS_TRACE_UNIFIED_ENABLED=False)
OpsTraceManager.ops_trace_instances_cache.clear()
OpsTraceManager.decrypted_configs_cache.clear()
monkeypatch.setattr(module.threading, "Timer", DummyTimer)
@@ -386,7 +386,7 @@ def test_ops_trace_instance_routes_by_unified_switch(
app = _app(database, tracing=json.dumps({"enabled": True, "tracing_provider": "dummy"}))
database.add(TraceAppConfig(app_id=app.id, tracing_provider="dummy", tracing_config={}))
database.commit()
- monkeypatch.setattr(dify_config, "OPS_TRACE_UNIFIED_ENABLED", enabled)
+ apply_config_overrides(monkeypatch, OPS_TRACE_UNIFIED_ENABLED=enabled)
entries = {"dummy": UNIFIED_PROVIDER_ENTRY} if registered else {}
monkeypatch.setattr(module, "unified_provider_config_map", FakeProviderMap(entries))
@@ -404,7 +404,7 @@ def test_registered_unified_provider_does_not_fallback_when_construction_fails(
app = _app(database, tracing=json.dumps({"enabled": True, "tracing_provider": "dummy"}))
database.add(TraceAppConfig(app_id=app.id, tracing_provider="dummy", tracing_config={}))
database.commit()
- monkeypatch.setattr(dify_config, "OPS_TRACE_UNIFIED_ENABLED", True)
+ apply_config_overrides(monkeypatch, OPS_TRACE_UNIFIED_ENABLED=True)
monkeypatch.setattr(
module,
"unified_provider_config_map",
@@ -433,9 +433,9 @@ def test_unified_and_legacy_instances_have_separate_cache_entries(
database.commit()
monkeypatch.setattr(module, "unified_provider_config_map", FakeProviderMap({"dummy": UNIFIED_PROVIDER_ENTRY}))
- monkeypatch.setattr(dify_config, "OPS_TRACE_UNIFIED_ENABLED", False)
+ apply_config_overrides(monkeypatch, OPS_TRACE_UNIFIED_ENABLED=False)
legacy = OpsTraceManager.get_ops_trace_instance(app.id)
- monkeypatch.setattr(dify_config, "OPS_TRACE_UNIFIED_ENABLED", True)
+ apply_config_overrides(monkeypatch, OPS_TRACE_UNIFIED_ENABLED=True)
unified = OpsTraceManager.get_ops_trace_instance(app.id)
assert type(legacy) is DummyTraceInstance
diff --git a/api/tests/unit_tests/core/prompt/test_advanced_prompt_transform.py b/api/tests/unit_tests/core/prompt/test_advanced_prompt_transform.py
index e536c0831fd..6a5046154e8 100644
--- a/api/tests/unit_tests/core/prompt/test_advanced_prompt_transform.py
+++ b/api/tests/unit_tests/core/prompt/test_advanced_prompt_transform.py
@@ -3,7 +3,6 @@ from unittest.mock import MagicMock, patch
import pytest
-from configs import dify_config
from core.app.app_config.entities import ModelConfigEntity
from core.memory.token_buffer_memory import TokenBufferMemory
from core.prompt.advanced_prompt_transform import AdvancedPromptTransform
@@ -19,6 +18,7 @@ from graphon.model_runtime.entities.message_entities import (
UserPromptMessage,
)
from models.model import Conversation
+from tests.unit_tests.config_override import apply_config_overrides
def test__get_completion_model_prompt_messages():
@@ -128,9 +128,9 @@ def test__get_chat_model_prompt_messages_no_memory(get_chat_model_args):
)
-def test__get_chat_model_prompt_messages_with_files_no_memory(get_chat_model_args):
+def test__get_chat_model_prompt_messages_with_files_no_memory(get_chat_model_args, monkeypatch: pytest.MonkeyPatch):
model_config_mock, _, messages, inputs, context = get_chat_model_args
- dify_config.MULTIMODAL_SEND_FORMAT = "url"
+ apply_config_overrides(monkeypatch, MULTIMODAL_SEND_FORMAT="url")
files = [
File(
diff --git a/api/tests/unit_tests/core/rag/datasource/keyword/test_keyword_factory.py b/api/tests/unit_tests/core/rag/datasource/keyword/test_keyword_factory.py
index 9fa76dd9737..9b392493eda 100644
--- a/api/tests/unit_tests/core/rag/datasource/keyword/test_keyword_factory.py
+++ b/api/tests/unit_tests/core/rag/datasource/keyword/test_keyword_factory.py
@@ -9,6 +9,7 @@ from core.rag.datasource.keyword.keyword_factory import Keyword
from core.rag.datasource.keyword.keyword_type import KeyWordType
from core.rag.models.document import Document
from models.dataset import Dataset
+from tests.unit_tests.config_override import apply_config_overrides
def test_get_keyword_factory_returns_jieba_factory(monkeypatch: pytest.MonkeyPatch):
@@ -38,7 +39,7 @@ def test_keyword_initialization_uses_configured_factory(monkeypatch: pytest.Monk
)
fake_processor = MagicMock()
- monkeypatch.setattr("core.rag.datasource.keyword.keyword_factory.dify_config.KEYWORD_STORE", KeyWordType.JIEBA)
+ apply_config_overrides(monkeypatch, KEYWORD_STORE=KeyWordType.JIEBA)
monkeypatch.setattr(Keyword, "get_keyword_factory", staticmethod(lambda keyword_type: lambda _: fake_processor))
keyword = Keyword(dataset)
diff --git a/api/tests/unit_tests/core/rag/extractor/test_excel_extractor.py b/api/tests/unit_tests/core/rag/extractor/test_excel_extractor.py
index af12b8780f6..2797d55d39f 100644
--- a/api/tests/unit_tests/core/rag/extractor/test_excel_extractor.py
+++ b/api/tests/unit_tests/core/rag/extractor/test_excel_extractor.py
@@ -9,6 +9,7 @@ import core.rag.extractor.excel_extractor as excel_module
from core.rag.extractor.excel_extractor import ExcelExtractor
from models.base import TypeBase
from models.model import UploadFile
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture
@@ -77,8 +78,7 @@ def _patch_image_persistence(monkeypatch: pytest.MonkeyPatch):
saves.append((key, data))
monkeypatch.setattr(excel_module.storage, "save", save)
- monkeypatch.setattr(excel_module.dify_config, "FILES_URL", "http://files.local", raising=False)
- monkeypatch.setattr(excel_module.dify_config, "STORAGE_TYPE", "local", raising=False)
+ apply_config_overrides(monkeypatch, FILES_URL="http://files.local", STORAGE_TYPE="local")
return saves
diff --git a/api/tests/unit_tests/core/rag/extractor/test_notion_extractor.py b/api/tests/unit_tests/core/rag/extractor/test_notion_extractor.py
index 8f49647fe7c..1f313659fd8 100644
--- a/api/tests/unit_tests/core/rag/extractor/test_notion_extractor.py
+++ b/api/tests/unit_tests/core/rag/extractor/test_notion_extractor.py
@@ -17,6 +17,7 @@ from core.rag.index_processor.constant.index_type import IndexStructureType
from models.base import TypeBase
from models.dataset import Document as DocumentModel
from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture
@@ -74,7 +75,7 @@ class TestNotionExtractorInitAndPublicMethods:
"_get_access_token",
classmethod(lambda cls, tenant_id, credential_id: (_ for _ in ()).throw(Exception("credential error"))),
)
- monkeypatch.setattr(notion_extractor.dify_config, "NOTION_INTEGRATION_TOKEN", "env-token", raising=False)
+ apply_config_overrides(monkeypatch, NOTION_INTEGRATION_TOKEN="env-token")
extractor = notion_extractor.NotionExtractor(
notion_workspace_id="ws",
@@ -92,7 +93,7 @@ class TestNotionExtractorInitAndPublicMethods:
"_get_access_token",
classmethod(lambda cls, tenant_id, credential_id: (_ for _ in ()).throw(Exception("credential error"))),
)
- monkeypatch.setattr(notion_extractor.dify_config, "NOTION_INTEGRATION_TOKEN", None, raising=False)
+ apply_config_overrides(monkeypatch, NOTION_INTEGRATION_TOKEN=None)
with pytest.raises(ValueError, match="Must specify `integration_token`"):
notion_extractor.NotionExtractor(
diff --git a/api/tests/unit_tests/core/rag/indexing/processor/test_parent_child_index_processor.py b/api/tests/unit_tests/core/rag/indexing/processor/test_parent_child_index_processor.py
index cb3dc7b23da..2919c71e0a0 100644
--- a/api/tests/unit_tests/core/rag/indexing/processor/test_parent_child_index_processor.py
+++ b/api/tests/unit_tests/core/rag/indexing/processor/test_parent_child_index_processor.py
@@ -14,6 +14,7 @@ from core.rag.models.document import AttachmentDocument, ChildDocument, Document
from models.dataset import ChildChunk, Dataset, DatasetProcessRule, DocumentCreatedFrom, DocumentSegment
from models.dataset import Document as DatasetDocument
from models.enums import DataSourceType
+from tests.unit_tests.config_override import config_overrides_context
class TestParentChildIndexProcessor:
@@ -206,10 +207,7 @@ class TestParentChildIndexProcessor:
"core.rag.index_processor.processor.parent_child_index_processor.helper.generate_text_hash",
return_value="hash",
),
- patch(
- "core.rag.index_processor.processor.parent_child_index_processor.dify_config.CHILD_CHUNKS_PREVIEW_NUMBER",
- 2,
- ),
+ config_overrides_context(CHILD_CHUNKS_PREVIEW_NUMBER=2),
):
result = processor.transform(
docs,
diff --git a/api/tests/unit_tests/core/rag/indexing/test_index_processor_base.py b/api/tests/unit_tests/core/rag/indexing/test_index_processor_base.py
index ad8fb37ea67..6dc66e5ff59 100644
--- a/api/tests/unit_tests/core/rag/indexing/test_index_processor_base.py
+++ b/api/tests/unit_tests/core/rag/indexing/test_index_processor_base.py
@@ -16,6 +16,7 @@ from extensions.storage.storage_type import StorageType
from models.enums import CreatorUserRole
from models.model import UploadFile
from models.tools import ToolFile
+from tests.unit_tests.config_override import config_overrides_context
def _persist_upload(session: Session, *, upload_id: str, name: str) -> UploadFile:
@@ -115,9 +116,7 @@ class TestBaseIndexProcessor:
processor.format_preview([])
def test_get_splitter_validates_custom_length(self, processor: _ForwardingBaseIndexProcessor) -> None:
- with patch(
- "core.rag.index_processor.index_processor_base.dify_config.INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH", 1000
- ):
+ with config_overrides_context(INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH=1000):
with pytest.raises(ValueError, match="between 50 and 1000"):
processor._get_splitter("custom", 49, 0, "", None)
with pytest.raises(ValueError, match="between 50 and 1000"):
diff --git a/api/tests/unit_tests/core/test_provider_manager.py b/api/tests/unit_tests/core/test_provider_manager.py
index 935b983decd..bb40efc0ae9 100644
--- a/api/tests/unit_tests/core/test_provider_manager.py
+++ b/api/tests/unit_tests/core/test_provider_manager.py
@@ -36,6 +36,7 @@ from models.provider import (
TenantPreferredModelProvider,
)
from models.provider_ids import ModelProviderID
+from tests.unit_tests.config_override import config_overrides_context
def _build_provider_manager() -> ProviderManager:
@@ -302,7 +303,7 @@ def test_to_system_configuration_uses_owned_session_for_cloud_credit_pools() ->
paid_pool = SimpleNamespace(quota_used=0, quota_limit=0)
with (
- patch.object(provider_manager_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
+ config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),
patch(
"core.provider_manager.ext_hosting_provider.hosting_configuration.provider_map",
{provider_entity.provider: _build_hosting_provider()},
diff --git a/api/tests/unit_tests/core/tools/utils/test_system_oauth_encryption.py b/api/tests/unit_tests/core/tools/utils/test_system_oauth_encryption.py
index 081b1897455..d715a2633e5 100644
--- a/api/tests/unit_tests/core/tools/utils/test_system_oauth_encryption.py
+++ b/api/tests/unit_tests/core/tools/utils/test_system_oauth_encryption.py
@@ -4,6 +4,7 @@ import pytest
from core.tools.utils import system_encryption as encryption
from core.tools.utils.system_encryption import EncryptionError, SystemEncrypter
+from tests.unit_tests.config_override import apply_config_overrides
def test_system_encrypter_roundtrip():
@@ -36,7 +37,7 @@ def test_system_encrypter_raises_error_for_invalid_ciphertext():
def test_system_helpers_use_global_cached_instance(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(encryption, "_encrypter", None)
- monkeypatch.setattr("core.tools.utils.system_encryption.dify_config.SECRET_KEY", "global-secret")
+ apply_config_overrides(monkeypatch, SECRET_KEY="global-secret")
first = encryption.get_system_encrypter()
second = encryption.get_system_encrypter()
diff --git a/api/tests/unit_tests/core/workflow/test_workflow_entry_helpers.py b/api/tests/unit_tests/core/workflow/test_workflow_entry_helpers.py
index a23a6236487..5feb62d45f4 100644
--- a/api/tests/unit_tests/core/workflow/test_workflow_entry_helpers.py
+++ b/api/tests/unit_tests/core/workflow/test_workflow_entry_helpers.py
@@ -22,6 +22,7 @@ from graphon.nodes import BuiltinNodeTypes
from graphon.runtime import VariablePool
from graphon.variables.variables import StringVariable
from models.workflow import Workflow, WorkflowType
+from tests.unit_tests.config_override import config_overrides_context
def _build_typed_node_config(node_type: NodeType):
@@ -99,8 +100,7 @@ class TestWorkflowEntryInit:
observability_layer = sentinel.observability_layer
with (
- patch.object(workflow_entry.dify_config, "DEBUG", True),
- patch.object(workflow_entry.dify_config, "ENABLE_OTEL", False),
+ config_overrides_context(DEBUG=True, ENABLE_OTEL=False),
patch.object(workflow_entry, "is_instrument_flag_enabled", return_value=True),
patch.object(workflow_entry, "capture_current_context", return_value=sentinel.execution_context),
patch.object(workflow_entry, "GraphEngine", return_value=graph_engine) as graph_engine_cls,
diff --git a/api/tests/unit_tests/events/event_handlers/test_queue_default_plugin_install_when_tenant_created.py b/api/tests/unit_tests/events/event_handlers/test_queue_default_plugin_install_when_tenant_created.py
index 67c8c8e827f..14303aef5d9 100644
--- a/api/tests/unit_tests/events/event_handlers/test_queue_default_plugin_install_when_tenant_created.py
+++ b/api/tests/unit_tests/events/event_handlers/test_queue_default_plugin_install_when_tenant_created.py
@@ -5,6 +5,7 @@ import pytest
from events.event_handlers import queue_default_plugin_install_when_tenant_created as handler_module
from models.account import Tenant
+from tests.unit_tests.config_override import apply_config_overrides
def _tenant() -> Tenant:
@@ -15,7 +16,7 @@ def _tenant() -> Tenant:
def test_handle_skips_when_no_default_plugins_are_configured(monkeypatch: pytest.MonkeyPatch) -> None:
delay = MagicMock()
- monkeypatch.setattr(handler_module.dify_config, "NEW_USER_DEFAULT_PLUGIN_IDS", "")
+ apply_config_overrides(monkeypatch, NEW_USER_DEFAULT_PLUGIN_IDS="")
monkeypatch.setattr(handler_module.install_default_plugins_task, "delay", delay)
handler_module.handle(_tenant())
@@ -29,7 +30,7 @@ def test_handle_queues_configured_plugins(monkeypatch: pytest.MonkeyPatch) -> No
"langgenius/openai",
"langgenius/gemini",
]
- monkeypatch.setattr(handler_module.dify_config, "NEW_USER_DEFAULT_PLUGIN_IDS", ",".join(plugins))
+ apply_config_overrides(monkeypatch, NEW_USER_DEFAULT_PLUGIN_IDS=",".join(plugins))
monkeypatch.setattr(handler_module.install_default_plugins_task, "delay", delay)
handler_module.handle(_tenant())
@@ -41,11 +42,7 @@ def test_handle_does_not_fail_tenant_creation_when_queue_is_unavailable(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
- monkeypatch.setattr(
- handler_module.dify_config,
- "NEW_USER_DEFAULT_PLUGIN_IDS",
- "langgenius/openai",
- )
+ apply_config_overrides(monkeypatch, NEW_USER_DEFAULT_PLUGIN_IDS="langgenius/openai")
monkeypatch.setattr(
handler_module.install_default_plugins_task,
"delay",
diff --git a/api/tests/unit_tests/extensions/otel/decorators/handlers/test_generate_handler.py b/api/tests/unit_tests/extensions/otel/decorators/handlers/test_generate_handler.py
index b83602e98cf..c00fbaae36c 100644
--- a/api/tests/unit_tests/extensions/otel/decorators/handlers/test_generate_handler.py
+++ b/api/tests/unit_tests/extensions/otel/decorators/handlers/test_generate_handler.py
@@ -6,17 +6,18 @@ Test objectives:
2. Verify span attribute mapping correctness
"""
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock
from core.app.entities.app_invoke_entities import InvokeFrom
from extensions.otel.decorators.handlers.generate_handler import AppGenerateHandler
from extensions.otel.semconv import DifySpanAttributes, GenAIAttributes
+from tests.unit_tests.config_override import config_overrides_context
class TestAppGenerateHandler:
"""Core tests for AppGenerateHandler"""
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
+ @config_overrides_context(ENABLE_OTEL=True)
def test_compatible_with_real_function_signature(
self, tracer_provider_with_memory_exporter, mock_app_model, mock_account_user
):
@@ -48,7 +49,7 @@ class TestAppGenerateHandler:
assert "args" in arguments, "Handler uses args but parameter is missing"
assert "streaming" in arguments, "Handler uses streaming but parameter is missing"
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
+ @config_overrides_context(ENABLE_OTEL=True)
def test_all_span_attributes_set_correctly(
self, tracer_provider_with_memory_exporter, memory_span_exporter, mock_app_model, mock_account_user
):
diff --git a/api/tests/unit_tests/extensions/otel/decorators/handlers/test_workflow_app_runner_handler.py b/api/tests/unit_tests/extensions/otel/decorators/handlers/test_workflow_app_runner_handler.py
index 842e7f55e2f..3e312a665eb 100644
--- a/api/tests/unit_tests/extensions/otel/decorators/handlers/test_workflow_app_runner_handler.py
+++ b/api/tests/unit_tests/extensions/otel/decorators/handlers/test_workflow_app_runner_handler.py
@@ -6,10 +6,9 @@ Test objectives:
2. Verify span attribute mapping correctness
"""
-from unittest.mock import patch
-
from extensions.otel.decorators.handlers.workflow_app_runner_handler import WorkflowAppRunnerHandler
from extensions.otel.semconv import DifySpanAttributes, GenAIAttributes
+from tests.unit_tests.config_override import config_overrides_context
class TestWorkflowAppRunnerHandler:
@@ -41,7 +40,7 @@ class TestWorkflowAppRunnerHandler:
for field in required_config_fields:
assert field in config_fields, f"Handler expects app_config.{field} but field is missing"
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
+ @config_overrides_context(ENABLE_OTEL=True)
def test_all_span_attributes_set_correctly(
self, tracer_provider_with_memory_exporter, memory_span_exporter, mock_workflow_runner
):
diff --git a/api/tests/unit_tests/extensions/otel/test_runtime.py b/api/tests/unit_tests/extensions/otel/test_runtime.py
index d1038d30eb9..1bf4aff293a 100644
--- a/api/tests/unit_tests/extensions/otel/test_runtime.py
+++ b/api/tests/unit_tests/extensions/otel/test_runtime.py
@@ -6,6 +6,7 @@ from opentelemetry.sdk.trace import TracerProvider
from core.logging.context import clear_request_context
from models import Account
+from tests.unit_tests.config_override import config_overrides_context
def _user() -> Account:
@@ -29,7 +30,7 @@ def test_on_user_loaded_does_not_write_to_non_recording_span() -> None:
user = _user()
with (
- mock.patch.object(runtime.dify_config, "ENABLE_OTEL", True),
+ config_overrides_context(ENABLE_OTEL=True),
mock.patch("opentelemetry.trace.get_current_span", return_value=span),
mock.patch.object(runtime, "extract_tenant_id", return_value="tenant-id"),
):
@@ -49,7 +50,7 @@ def test_on_user_loaded_sets_attributes_on_recording_span() -> None:
user = _user()
with (
- mock.patch.object(runtime.dify_config, "ENABLE_OTEL", True),
+ config_overrides_context(ENABLE_OTEL=True),
mock.patch("opentelemetry.trace.get_current_span", return_value=span),
mock.patch.object(runtime, "extract_tenant_id", return_value="tenant-id"),
):
@@ -73,7 +74,7 @@ def test_on_user_loaded_ignores_ended_sdk_span(caplog) -> None:
with (
trace.use_span(span, end_on_exit=False),
- mock.patch.object(runtime.dify_config, "ENABLE_OTEL", True),
+ config_overrides_context(ENABLE_OTEL=True),
mock.patch.object(runtime, "extract_tenant_id", return_value="tenant-id"),
caplog.at_level("WARNING", logger="opentelemetry.sdk.trace"),
):
diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.py
index e5cf0b3b82c..1cf77a1f27b 100644
--- a/api/tests/unit_tests/extensions/test_ext_application_services.py
+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py
@@ -46,6 +46,7 @@ from services.retention.workflow_run.archive_log_service import WorkflowRunArchi
from services.tag_application_service import TagApplicationService
from services.webapp_access_query_service import WebAppAccessUnavailableError
from services.workflow_statistic_query_service import WorkflowStatisticQueryService
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.mark.parametrize(
@@ -103,12 +104,11 @@ def test_init_app_registers_services_for_the_current_app(
) -> None:
app = Flask(__name__)
monkeypatch.setattr(ext_application_services, "get_session_maker", lambda: sqlite_session_factory)
- monkeypatch.setattr(
- ext_application_services.dify_config,
- "DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
+ apply_config_overrides(
+ monkeypatch,
+ DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,
+ INIT_PASSWORD="expected",
)
- monkeypatch.setattr(ext_application_services.dify_config, "INIT_PASSWORD", "expected")
ext_application_services.init_app(app)
@@ -618,7 +618,7 @@ def test_build_application_services_wires_dynamic_recommended_catalog(
sqlite_session_factory: sessionmaker[Session],
monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(ext_application_services.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "builtin")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="builtin")
services = ext_application_services.build_application_services(
database_client=sqlite_session_factory,
deployment_edition=DeploymentEdition.COMMUNITY,
@@ -643,7 +643,7 @@ def test_build_application_services_wires_dynamic_recommended_catalog(
)
assert result.recommended_apps
- monkeypatch.setattr(ext_application_services.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "invalid")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="invalid")
with pytest.raises(ValueError, match="invalid fetch recommended apps mode: invalid"):
services.recommended_app_queries.list_recommended(
requested_language="en-US",
diff --git a/api/tests/unit_tests/extensions/test_ext_blueprints_openapi.py b/api/tests/unit_tests/extensions/test_ext_blueprints_openapi.py
index 602cd8f019c..43d768974fd 100644
--- a/api/tests/unit_tests/extensions/test_ext_blueprints_openapi.py
+++ b/api/tests/unit_tests/extensions/test_ext_blueprints_openapi.py
@@ -32,9 +32,9 @@ from collections.abc import Iterator
import pytest
from flask import Blueprint
-from configs import dify_config
from dify_app import DifyApp
from extensions import ext_blueprints
+from tests.unit_tests.config_override import apply_config_overrides
# Modules whose `bp` attribute is consumed by `ext_blueprints.init_app`.
# Keep in sync with the imports inside `init_app`.
@@ -90,7 +90,7 @@ def test_openapi_blueprint_registered_with_cors_when_enabled(
fresh_blueprints: dict[str, Blueprint],
) -> None:
"""Enabled gate: blueprint mounted, CORS wired, `/openapi/v1/*` rules live."""
- monkeypatch.setattr(dify_config, "OPENAPI_ENABLED", True)
+ apply_config_overrides(monkeypatch, OPENAPI_ENABLED=True)
app = _build_app()
ext_blueprints.init_app(app)
@@ -111,7 +111,7 @@ def test_openapi_blueprint_absent_when_disabled(
fresh_blueprints: dict[str, Blueprint],
) -> None:
"""Disabled gate: no blueprint, no CORS, no `/openapi/v1/*` URL rules."""
- monkeypatch.setattr(dify_config, "OPENAPI_ENABLED", False)
+ apply_config_overrides(monkeypatch, OPENAPI_ENABLED=False)
app = _build_app()
ext_blueprints.init_app(app)
diff --git a/api/tests/unit_tests/extensions/test_ext_request_logging.py b/api/tests/unit_tests/extensions/test_ext_request_logging.py
index 664de8cbd8b..38787ac63a2 100644
--- a/api/tests/unit_tests/extensions/test_ext_request_logging.py
+++ b/api/tests/unit_tests/extensions/test_ext_request_logging.py
@@ -6,9 +6,9 @@ from unittest.mock import MagicMock
import pytest
from flask import Flask, Response
-from configs import dify_config
from extensions import ext_request_logging
from extensions.ext_request_logging import _is_content_type_json, _log_request_finished, init_app
+from tests.unit_tests.config_override import apply_config_overrides
def test_is_content_type_json():
@@ -59,7 +59,7 @@ def mock_response_receiver(monkeypatch: pytest.MonkeyPatch) -> mock.Mock:
@pytest.fixture
def enable_request_logging(monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr(dify_config, "ENABLE_REQUEST_LOGGING", True)
+ apply_config_overrides(monkeypatch, ENABLE_REQUEST_LOGGING=True)
def _captured_records(caplog: pytest.LogCaptureFixture, level: int) -> list[logging.LogRecord]:
@@ -77,7 +77,7 @@ class TestRequestLoggingExtension:
mock_request_receiver: MagicMock,
mock_response_receiver: MagicMock,
):
- monkeypatch.setattr(dify_config, "ENABLE_REQUEST_LOGGING", False)
+ apply_config_overrides(monkeypatch, ENABLE_REQUEST_LOGGING=False)
app = _get_test_app()
init_app(app)
diff --git a/api/tests/unit_tests/extensions/test_pubsub_channel.py b/api/tests/unit_tests/extensions/test_pubsub_channel.py
index 2884509d22b..c63e29c3cbd 100644
--- a/api/tests/unit_tests/extensions/test_pubsub_channel.py
+++ b/api/tests/unit_tests/extensions/test_pubsub_channel.py
@@ -1,13 +1,13 @@
import pytest
-from configs import dify_config
from extensions import ext_redis
from libs.broadcast_channel.redis.pubsub_channel import BroadcastChannel as RedisBroadcastChannel
from libs.broadcast_channel.redis.sharded_channel import ShardedRedisBroadcastChannel
+from tests.unit_tests.config_override import apply_config_overrides
def test_get_pubsub_broadcast_channel_defaults_to_pubsub(monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr(dify_config, "PUBSUB_REDIS_CHANNEL_TYPE", "pubsub")
+ apply_config_overrides(monkeypatch, PUBSUB_REDIS_CHANNEL_TYPE="pubsub")
monkeypatch.setattr(ext_redis, "_pubsub_redis_client", object())
channel = ext_redis.get_pubsub_broadcast_channel()
@@ -16,7 +16,7 @@ def test_get_pubsub_broadcast_channel_defaults_to_pubsub(monkeypatch: pytest.Mon
def test_get_pubsub_broadcast_channel_sharded(monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr(dify_config, "PUBSUB_REDIS_CHANNEL_TYPE", "sharded")
+ apply_config_overrides(monkeypatch, PUBSUB_REDIS_CHANNEL_TYPE="sharded")
monkeypatch.setattr(ext_redis, "_pubsub_redis_client", object())
channel = ext_redis.get_pubsub_broadcast_channel()
diff --git a/api/tests/unit_tests/extensions/test_set_secretkey.py b/api/tests/unit_tests/extensions/test_set_secretkey.py
index 8a8e4e2b190..b49ff7107b8 100644
--- a/api/tests/unit_tests/extensions/test_set_secretkey.py
+++ b/api/tests/unit_tests/extensions/test_set_secretkey.py
@@ -4,6 +4,7 @@ import pytest
from flask import Flask
from extensions import ext_set_secretkey
+from tests.unit_tests.config_override import apply_config_overrides
class InMemoryStorage:
@@ -25,7 +26,7 @@ class InMemoryStorage:
def test_init_app_uses_configured_secret_key(monkeypatch: pytest.MonkeyPatch) -> None:
secret_key = "configured-secret-key"
storage = InMemoryStorage()
- monkeypatch.setattr("extensions.ext_set_secretkey.dify_config.SECRET_KEY", secret_key)
+ apply_config_overrides(monkeypatch, SECRET_KEY=secret_key)
monkeypatch.setattr("configs.secret_key.storage", storage)
app = Flask(__name__)
app.config["SECRET_KEY"] = secret_key
@@ -41,7 +42,7 @@ def test_init_app_generates_and_persists_secret_key_when_missing(
monkeypatch: pytest.MonkeyPatch,
) -> None:
storage = InMemoryStorage()
- monkeypatch.setattr("extensions.ext_set_secretkey.dify_config.SECRET_KEY", "")
+ apply_config_overrides(monkeypatch, SECRET_KEY="")
monkeypatch.setattr("configs.secret_key.storage", storage)
app = Flask(__name__)
app.config["SECRET_KEY"] = ""
@@ -61,7 +62,7 @@ def test_init_app_reuses_persisted_secret_key_when_missing(
) -> None:
persisted_key = "persisted-secret-key"
storage = InMemoryStorage({".dify_secret_key": f"{persisted_key}\n".encode()})
- monkeypatch.setattr("extensions.ext_set_secretkey.dify_config.SECRET_KEY", "")
+ apply_config_overrides(monkeypatch, SECRET_KEY="")
monkeypatch.setattr("configs.secret_key.storage", storage)
app = Flask(__name__)
app.config["SECRET_KEY"] = ""
diff --git a/api/tests/unit_tests/libs/test_archive_storage.py b/api/tests/unit_tests/libs/test_archive_storage.py
index f42bc63d5f4..4c0d51a1907 100644
--- a/api/tests/unit_tests/libs/test_archive_storage.py
+++ b/api/tests/unit_tests/libs/test_archive_storage.py
@@ -12,6 +12,7 @@ from libs.archive_storage import (
ArchiveStorageError,
ArchiveStorageNotConfiguredError,
)
+from tests.unit_tests.config_override import apply_config_overrides
BUCKET_NAME = "archive-bucket"
@@ -26,8 +27,7 @@ def _configure_storage(monkeypatch: pytest.MonkeyPatch, **overrides):
"ARCHIVE_STORAGE_REGION": "auto",
}
defaults.update(overrides)
- for key, value in defaults.items():
- monkeypatch.setattr(storage_module.dify_config, key, value, raising=False)
+ apply_config_overrides(monkeypatch, **defaults)
def _client_error(code: str) -> ClientError:
diff --git a/api/tests/unit_tests/libs/test_login.py b/api/tests/unit_tests/libs/test_login.py
index 8155dbd4c9d..420b640eb0c 100644
--- a/api/tests/unit_tests/libs/test_login.py
+++ b/api/tests/unit_tests/libs/test_login.py
@@ -10,6 +10,7 @@ import libs.login as login_module
from extensions.ext_login import DifyLoginManager
from libs.login import current_user
from models.account import Account, Tenant
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture
@@ -72,7 +73,7 @@ def login_app(mocker: MockerFixture) -> Flask:
@pytest.fixture(autouse=True)
def reset_login_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(login_module.dify_config, "LOGIN_DISABLED", False)
+ apply_config_overrides(monkeypatch, LOGIN_DISABLED=False)
@pytest.fixture
@@ -184,7 +185,7 @@ class TestLoginRequired:
"""Test that bypass conditions skip auth lookup, CSRF, and unauthorized handling."""
resolve_user = resolve_current_user(MockUser("test_user"))
- monkeypatch.setattr(login_module.dify_config, "LOGIN_DISABLED", login_disabled)
+ apply_config_overrides(monkeypatch, LOGIN_DISABLED=login_disabled)
with login_app.test_request_context(method=method):
result = protected_view()
diff --git a/api/tests/unit_tests/libs/test_workspace_member_helper.py b/api/tests/unit_tests/libs/test_workspace_member_helper.py
index d35a83e6430..6a202e79fa4 100644
--- a/api/tests/unit_tests/libs/test_workspace_member_helper.py
+++ b/api/tests/unit_tests/libs/test_workspace_member_helper.py
@@ -16,6 +16,7 @@ from enums import DeploymentEdition
from libs import oauth_bearer
from libs.oauth_bearer import AuthContext, Scope, SubjectType, TokenType, require_workspace_member
from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole
+from tests.unit_tests.config_override import apply_config_overrides
pytestmark = pytest.mark.usefixtures("community_edition")
@@ -47,7 +48,7 @@ def database(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) -> Iterat
@pytest.fixture
def community_edition(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(oauth_bearer.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
def _ctx(
@@ -100,7 +101,7 @@ def _account(account_id: uuid.UUID, *, status: AccountStatus = AccountStatus.ACT
def test_skips_for_enterprise_edition(database: Database, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(oauth_bearer.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
before = len(database.statements)
require_workspace_member(_ctx(), "tenant-1")
diff --git a/api/tests/unit_tests/models/test_dataset_models.py b/api/tests/unit_tests/models/test_dataset_models.py
index e724b6e0e86..5c058c42b10 100644
--- a/api/tests/unit_tests/models/test_dataset_models.py
+++ b/api/tests/unit_tests/models/test_dataset_models.py
@@ -47,6 +47,7 @@ from models.enums import (
SegmentStatus,
)
from models.model import App, AppMode, IconType, UploadFile
+from tests.unit_tests.config_override import apply_config_overrides
def _make_dataset(
@@ -1171,9 +1172,12 @@ class TestDocumentSegmentIndexing:
monkeypatch.setattr("models.dataset.time.time", lambda: 1700000000)
monkeypatch.setattr("models.dataset.os.urandom", lambda _: b"\x01" * 16)
- monkeypatch.setattr("models.dataset.dify_config.SECRET_KEY", "unit-secret")
- monkeypatch.setattr("models.dataset.dify_config.FILES_URL", "https://files.example.com")
- monkeypatch.setattr("models.dataset.dify_config.CONSOLE_API_URL", "https://console.example.com")
+ apply_config_overrides(
+ monkeypatch,
+ SECRET_KEY="unit-secret",
+ FILES_URL="https://files.example.com",
+ CONSOLE_API_URL="https://console.example.com",
+ )
# Act
attachments = segment.get_attachments(session=sqlite_session)
diff --git a/api/tests/unit_tests/services/agent/test_home_snapshot_service.py b/api/tests/unit_tests/services/agent/test_home_snapshot_service.py
index c66a26aeeb7..6cb64587818 100644
--- a/api/tests/unit_tests/services/agent/test_home_snapshot_service.py
+++ b/api/tests/unit_tests/services/agent/test_home_snapshot_service.py
@@ -6,7 +6,6 @@ import pytest
from dify_agent.client import DifyAgentHTTPError, DifyAgentNotFoundError, DifyAgentTimeoutError
from sqlalchemy.orm import Session
-from configs import dify_config
from models.agent import (
Agent,
AgentConfigDraft,
@@ -23,6 +22,7 @@ from services.agent.errors import (
)
from services.agent.home_snapshot_service import AgentHomeSnapshotService, validate_home_snapshot_binding
from services.agent.workspace_service import AgentWorkspaceService
+from tests.unit_tests.config_override import apply_config_overrides
def _build_draft(*, home_snapshot_id: str | None = "home-old") -> AgentConfigDraft:
@@ -46,7 +46,7 @@ def _client(*, snapshot_ref: str = "snapshot-ref-1") -> MagicMock:
def test_home_snapshot_client_outlasts_the_gateway_snapshot_budget(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(dify_config, "AGENT_BACKEND_BASE_URL", "http://agent.example")
+ apply_config_overrides(monkeypatch, AGENT_BACKEND_BASE_URL="http://agent.example")
client = AgentHomeSnapshotService._client()
diff --git a/api/tests/unit_tests/services/agent/test_workspace_service.py b/api/tests/unit_tests/services/agent/test_workspace_service.py
index e8ce1e1f657..733c09896de 100644
--- a/api/tests/unit_tests/services/agent/test_workspace_service.py
+++ b/api/tests/unit_tests/services/agent/test_workspace_service.py
@@ -7,7 +7,6 @@ import pytest
from sqlalchemy import select
from sqlalchemy.orm import Session
-from configs import dify_config
from models.agent import (
AgentConfigVersionKind,
AgentHomeSnapshot,
@@ -22,6 +21,7 @@ from services.agent.workspace_service import (
AgentWorkspaceService,
WorkspaceOwnerScope,
)
+from tests.unit_tests.config_override import apply_config_overrides
def _scope() -> WorkspaceOwnerScope:
@@ -94,8 +94,11 @@ def _binding(
def test_workspace_client_honors_the_configured_snapshot_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(dify_config, "AGENT_BACKEND_BASE_URL", "http://agent.example")
- monkeypatch.setattr(dify_config, "AGENT_BACKEND_HOME_SNAPSHOT_TIMEOUT_SECONDS", 123.5)
+ apply_config_overrides(
+ monkeypatch,
+ AGENT_BACKEND_BASE_URL="http://agent.example",
+ AGENT_BACKEND_HOME_SNAPSHOT_TIMEOUT_SECONDS=123.5,
+ )
client = AgentWorkspaceService._client()
diff --git a/api/tests/unit_tests/services/data_migration/test_import_service.py b/api/tests/unit_tests/services/data_migration/test_import_service.py
index 80e155c1dae..512d2f10e66 100644
--- a/api/tests/unit_tests/services/data_migration/test_import_service.py
+++ b/api/tests/unit_tests/services/data_migration/test_import_service.py
@@ -28,6 +28,7 @@ from services.data_migration.entities import (
)
from services.data_migration.import_service import ImportRequest, ImportTargetResolver, MigrationImportService
from services.entities.dsl_entities import ImportStatus
+from tests.unit_tests.config_override import apply_config_overrides
@dataclass(frozen=True)
@@ -347,7 +348,7 @@ def test_workflow_app_import_closes_read_transaction_before_dsl_overwrite(
return Import(id="import-id", status=ImportStatus.COMPLETED, app_id="imported-app-id")
monkeypatch.setattr(import_service, "AppDslService", StubAppDslService)
- monkeypatch.setattr(import_service.dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
existing_app = _persist_app(database.session, app_id="11111111-1111-4111-8111-111111111111")
database.session.begin()
diff --git a/api/tests/unit_tests/services/rag_pipeline/pipeline_template/test_remote_retrieval.py b/api/tests/unit_tests/services/rag_pipeline/pipeline_template/test_remote_retrieval.py
index 273f89b8db3..27eff6e2aeb 100644
--- a/api/tests/unit_tests/services/rag_pipeline/pipeline_template/test_remote_retrieval.py
+++ b/api/tests/unit_tests/services/rag_pipeline/pipeline_template/test_remote_retrieval.py
@@ -5,6 +5,7 @@ from sqlalchemy.orm import Session
from services.rag_pipeline.pipeline_template.database.database_retrieval import DatabasePipelineTemplateRetrieval
from services.rag_pipeline.pipeline_template.pipeline_template_type import PipelineTemplateType
from services.rag_pipeline.pipeline_template.remote.remote_retrieval import RemotePipelineTemplateRetrieval
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.mark.parametrize("sqlite_session", [()], indirect=True)
@@ -54,12 +55,8 @@ def test_get_pipeline_template_detail_fallbacks_to_database_on_error(
assert not sqlite_session.in_transaction()
-def test_fetch_pipeline_templates_from_dify_official(mocker: MockerFixture) -> None:
- mocker.patch(
- "services.rag_pipeline.pipeline_template.remote.remote_retrieval"
- ".dify_config.HOSTED_FETCH_PIPELINE_TEMPLATES_REMOTE_DOMAIN",
- "https://example.com",
- )
+def test_fetch_pipeline_templates_from_dify_official(mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch) -> None:
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_PIPELINE_TEMPLATES_REMOTE_DOMAIN="https://example.com")
success_response = mocker.Mock(status_code=200)
success_response.json.return_value = {"pipeline_templates": [{"id": "remote-1"}]}
@@ -80,12 +77,10 @@ def test_fetch_pipeline_templates_from_dify_official(mocker: MockerFixture) -> N
assert http_get_mock.call_count == 2
-def test_fetch_pipeline_template_detail_from_dify_official(mocker: MockerFixture) -> None:
- mocker.patch(
- "services.rag_pipeline.pipeline_template.remote.remote_retrieval"
- ".dify_config.HOSTED_FETCH_PIPELINE_TEMPLATES_REMOTE_DOMAIN",
- "https://example.com",
- )
+def test_fetch_pipeline_template_detail_from_dify_official(
+ mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_PIPELINE_TEMPLATES_REMOTE_DOMAIN="https://example.com")
success_response = mocker.Mock(status_code=200)
success_response.json.return_value = {"id": "remote-1", "name": "Remote Template"}
diff --git a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_transform_service.py b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_transform_service.py
index 8c4485b290c..586634bc12f 100644
--- a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_transform_service.py
+++ b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_transform_service.py
@@ -15,6 +15,7 @@ from models.model import UploadFile
from services.entities.knowledge_entities.rag_pipeline_entities import KnowledgeConfiguration
from services.errors.rag_pipeline import RagPipelineResourceNotFoundError
from services.rag_pipeline.rag_pipeline_transform_service import RagPipelineTransformService
+from tests.unit_tests.config_override import apply_config_overrides
def _dataset(**overrides: object) -> Dataset:
@@ -529,12 +530,9 @@ def _make_service():
def test_deal_dependencies_skips_marketplace_when_disabled(
- mocker: MockerFixture, caplog: pytest.LogCaptureFixture
+ mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
- mocker.patch(
- "services.rag_pipeline.rag_pipeline_transform_service.dify_config.MARKETPLACE_ENABLED",
- False,
- )
+ apply_config_overrides(monkeypatch, MARKETPLACE_ENABLED=False)
installer = mocker.patch("services.rag_pipeline.rag_pipeline_transform_service.PluginInstaller").return_value
installer.list_plugins.return_value = []
mocker.patch("services.rag_pipeline.rag_pipeline_transform_service.PluginMigration")
@@ -559,11 +557,8 @@ def test_deal_dependencies_skips_marketplace_when_disabled(
assert any("Marketplace disabled" in rec.message for rec in caplog.records)
-def test_deal_dependencies_installs_when_enabled(mocker: MockerFixture) -> None:
- mocker.patch(
- "services.rag_pipeline.rag_pipeline_transform_service.dify_config.MARKETPLACE_ENABLED",
- True,
- )
+def test_deal_dependencies_installs_when_enabled(mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch) -> None:
+ apply_config_overrides(monkeypatch, MARKETPLACE_ENABLED=True)
installer = mocker.patch("services.rag_pipeline.rag_pipeline_transform_service.PluginInstaller").return_value
installer.list_plugins.return_value = []
migration = mocker.patch("services.rag_pipeline.rag_pipeline_transform_service.PluginMigration").return_value
diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.py
index 664b96f3b78..7a926eba6a2 100644
--- a/api/tests/unit_tests/services/test_account_service.py
+++ b/api/tests/unit_tests/services/test_account_service.py
@@ -37,6 +37,7 @@ from services.errors.account import (
EmailDomainSuspendedError,
NoPermissionError,
)
+from tests.unit_tests.config_override import config_overrides_context
type _MockDependencies = dict[str, MagicMock]
@@ -391,7 +392,7 @@ class TestAccountService:
"billing_service"
].get_email_freeze_type.return_value = "email_domain_suspended"
- with patch("services.account_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD):
+ with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD):
with pytest.raises(EmailDomainSuspendedError):
AccountService.create_account(
@@ -408,7 +409,7 @@ class TestAccountService:
"billing_service"
].get_email_freeze_type.return_value = "email_domain_suspended"
- with patch("services.account_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD):
+ with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD):
with pytest.raises(EmailDomainSuspendedError):
AccountService.get_user_through_email("[email protected]", session=unbound_session)
@@ -417,9 +418,9 @@ class TestAccountService:
) -> None:
mock_external_service_dependencies["billing_service"].get_email_freeze_type.return_value = "freeze"
- with patch("services.account_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD):
+ with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD):
assert AccountService.get_account_freeze_type("[email protected]") == "freeze"
- with patch("services.account_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY):
+ with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY):
assert AccountService.get_account_freeze_type("[email protected]") is None
mock_external_service_dependencies["billing_service"].get_email_freeze_type.assert_called_once_with(
@@ -979,7 +980,7 @@ class TestTenantService:
service_session.commit()
with (
- patch("services.account_service.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(rbac_task_module.sync_joined_workspace_member_rbac_access_task, "delay", delay),
):
TenantService.create_tenant_member(
@@ -1012,7 +1013,7 @@ class TestTenantService:
service_session.commit()
with (
- patch("services.account_service.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch.object(rbac_task_module.sync_joined_workspace_member_rbac_access_task, "delay", delay),
):
TenantService.create_tenant_member(
diff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.py
index 18c16d5bfc1..b8fd7726f88 100644
--- a/api/tests/unit_tests/services/test_app_dsl_service.py
+++ b/api/tests/unit_tests/services/test_app_dsl_service.py
@@ -17,6 +17,7 @@ from services.app_dsl_service import AppDslService, PendingData
from services.entities.dsl_entities import ImportStatus
from services.errors.account import NoPermissionError
from services.errors.app import WorkflowNotFoundError
+from tests.unit_tests.config_override import apply_config_overrides
_OVERWRITE_APP_ID = "11111111-1111-4111-8111-111111111111"
_TENANT_ID = "22222222-2222-4222-8222-222222222222"
@@ -192,7 +193,7 @@ def test_import_app_checks_overwrite_rbac_before_database_access(
check = Mock(side_effect=deny_before_transaction)
setex = Mock()
- monkeypatch.setattr("services.app_dsl_service.dify_config.RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", check)
monkeypatch.setattr("services.app_dsl_service.redis_client.setex", setex)
@@ -230,7 +231,7 @@ def test_confirm_import_rechecks_overwrite_rbac_before_database_access(
return False
check = Mock(side_effect=deny_before_transaction)
- monkeypatch.setattr("services.app_dsl_service.dify_config.RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", check)
with pytest.raises(NoPermissionError, match="permission to overwrite"):
@@ -254,7 +255,7 @@ def test_confirm_import_does_not_create_when_overwrite_target_disappeared(
monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
) -> None:
monkeypatch.setattr("services.app_dsl_service.redis_client.get", Mock(return_value=_PENDING_DATA_JSON))
- monkeypatch.setattr("services.app_dsl_service.dify_config.RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", Mock(return_value=True))
redis_delete = Mock()
monkeypatch.setattr("services.app_dsl_service.redis_client.delete", redis_delete)
diff --git a/api/tests/unit_tests/services/test_app_generate_service_streaming_integration.py b/api/tests/unit_tests/services/test_app_generate_service_streaming_integration.py
index fe667ef5771..1595a1db952 100644
--- a/api/tests/unit_tests/services/test_app_generate_service_streaming_integration.py
+++ b/api/tests/unit_tests/services/test_app_generate_service_streaming_integration.py
@@ -9,6 +9,7 @@ from core.app.apps.message_based_app_generator import MessageBasedAppGenerator
from core.app.apps.message_generator import MessageGenerator
from models.model import AppMode
from services.app_generate_service import AppGenerateService
+from tests.unit_tests.config_override import apply_config_overrides
# -----------------------------
@@ -114,10 +115,7 @@ def _patch_get_channel_streams(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr("extensions.ext_redis.get_pubsub_broadcast_channel", lambda: chan)
monkeypatch.setattr("core.app.apps.message_generator.get_pubsub_broadcast_channel", lambda: chan)
monkeypatch.setattr("core.app.apps.message_based_app_generator.get_pubsub_broadcast_channel", lambda: chan)
- # Ensure AppGenerateService sees streams mode
- import services.app_generate_service as ags
-
- monkeypatch.setattr(ags.dify_config, "PUBSUB_REDIS_CHANNEL_TYPE", "streams", raising=False)
+ apply_config_overrides(monkeypatch, PUBSUB_REDIS_CHANNEL_TYPE="streams")
@pytest.fixture
@@ -134,10 +132,7 @@ def _patch_get_channel_pubsub(monkeypatch: pytest.MonkeyPatch):
# Patch both the source and the imported alias used by MessageGenerator
monkeypatch.setattr("extensions.ext_redis.get_pubsub_broadcast_channel", lambda: chan)
monkeypatch.setattr("core.app.apps.message_generator.get_pubsub_broadcast_channel", lambda: chan)
- # Ensure AppGenerateService sees pubsub mode
- import services.app_generate_service as ags
-
- monkeypatch.setattr(ags.dify_config, "PUBSUB_REDIS_CHANNEL_TYPE", "pubsub", raising=False)
+ apply_config_overrides(monkeypatch, PUBSUB_REDIS_CHANNEL_TYPE="pubsub")
def _publish_events(app_mode: AppMode, run_id: str, events: list[dict]):
diff --git a/api/tests/unit_tests/services/test_email_code_login_challenge.py b/api/tests/unit_tests/services/test_email_code_login_challenge.py
index 761c1bffe66..5ea11346eda 100644
--- a/api/tests/unit_tests/services/test_email_code_login_challenge.py
+++ b/api/tests/unit_tests/services/test_email_code_login_challenge.py
@@ -10,6 +10,7 @@ from services.email_code_login_challenge import (
EmailCodeLoginChallengeStore,
EmailCodeLoginChallengeUnavailableError,
)
+from tests.unit_tests.config_override import apply_config_overrides
TOKEN = "00000000-0000-4000-8000-000000000001"
@@ -23,8 +24,11 @@ def challenge_redis() -> Iterator[MagicMock]:
def test_create_stores_only_one_per_email_v2_challenge(
challenge_redis: MagicMock, monkeypatch: pytest.MonkeyPatch
) -> None:
- monkeypatch.setattr("services.email_code_login_challenge.dify_config.EMAIL_CODE_LOGIN_MAX_ATTEMPTS", 5)
- monkeypatch.setattr("services.email_code_login_challenge.dify_config.EMAIL_CODE_LOGIN_TOKEN_EXPIRY_MINUTES", 5)
+ apply_config_overrides(
+ monkeypatch,
+ EMAIL_CODE_LOGIN_MAX_ATTEMPTS=5,
+ EMAIL_CODE_LOGIN_TOKEN_EXPIRY_MINUTES=5,
+ )
with patch("services.email_code_login_challenge.uuid.uuid4", return_value=TOKEN):
token = EmailCodeLoginChallengeStore.create(
diff --git a/api/tests/unit_tests/services/test_feature_service_deployment_edition.py b/api/tests/unit_tests/services/test_feature_service_deployment_edition.py
index 089464da9f0..b31e398add4 100644
--- a/api/tests/unit_tests/services/test_feature_service_deployment_edition.py
+++ b/api/tests/unit_tests/services/test_feature_service_deployment_edition.py
@@ -57,12 +57,11 @@ def test_get_system_features_uses_configured_deployment_edition(
],
)
def test_trial_app_policy_is_cloud_only(
- monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
edition: DeploymentEdition,
feature_enabled: bool,
expected: bool,
) -> None:
- monkeypatch.setattr("services.feature_service.dify_config.DEPLOYMENT_EDITION", edition)
- monkeypatch.setattr("services.feature_service.dify_config.ENABLE_TRIAL_APP", feature_enabled)
+ config_overrides(DEPLOYMENT_EDITION=edition, ENABLE_TRIAL_APP=feature_enabled)
assert FeatureService.is_trial_app_enabled() is expected
diff --git a/api/tests/unit_tests/services/test_recommended_app_catalog_gateway.py b/api/tests/unit_tests/services/test_recommended_app_catalog_gateway.py
index bcd48c1b2d3..82a74d8d551 100644
--- a/api/tests/unit_tests/services/test_recommended_app_catalog_gateway.py
+++ b/api/tests/unit_tests/services/test_recommended_app_catalog_gateway.py
@@ -18,6 +18,7 @@ from services.recommended_app_query_service import (
RecommendedAppInfoRecord,
RecommendedAppRecord,
)
+from tests.unit_tests.config_override import apply_config_overrides
def _page_payload(*app_ids: str, learn_dify_ids: frozenset[str] = frozenset()) -> dict[str, object]:
@@ -224,7 +225,7 @@ class TestRemoteRecommendedAppCatalogGateway:
@pytest.fixture(autouse=True)
def _use_remote_mode(self, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
gateway_module.clear_remote_fetch_cache()
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "remote")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="remote")
yield
gateway_module.clear_remote_fetch_cache()
@@ -445,12 +446,11 @@ class TestRemoteRecommendedAppCatalogGateway:
response.json.return_value = _detail_payload()
http_get = MagicMock(return_value=response)
monkeypatch.setattr(gateway_module.httpx, "get", http_get)
- monkeypatch.setattr(
- gateway_module.dify_config,
- "HOSTED_FETCH_APP_TEMPLATES_REMOTE_DOMAIN",
- "https://catalog.example.com",
+ apply_config_overrides(
+ monkeypatch,
+ HOSTED_FETCH_APP_TEMPLATES_REMOTE_DOMAIN="https://catalog.example.com",
+ CONSOLE_WEB_URL="https://console.example.com",
)
- monkeypatch.setattr(gateway_module.dify_config, "CONSOLE_WEB_URL", "https://console.example.com")
gateway = RemoteRecommendedAppCatalogGateway()
gateway.get_detail("app-1")
@@ -466,12 +466,11 @@ class TestRemoteRecommendedAppCatalogGateway:
response.json.return_value = _page_payload()
http_get = MagicMock(return_value=response)
monkeypatch.setattr(gateway_module.httpx, "get", http_get)
- monkeypatch.setattr(
- gateway_module.dify_config,
- "HOSTED_FETCH_APP_TEMPLATES_REMOTE_DOMAIN",
- "https://catalog.example.com",
+ apply_config_overrides(
+ monkeypatch,
+ HOSTED_FETCH_APP_TEMPLATES_REMOTE_DOMAIN="https://catalog.example.com",
+ HOSTED_FETCH_APP_TEMPLATES_CACHE_TTL=600,
)
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_CACHE_TTL", 600)
gateway = RemoteRecommendedAppCatalogGateway()
assert gateway.list_recommended("en-US") == _expected_page()
@@ -482,7 +481,7 @@ class TestRemoteRecommendedAppCatalogGateway:
response = MagicMock(status_code=500)
http_get = MagicMock(return_value=response)
monkeypatch.setattr(gateway_module.httpx, "get", http_get)
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_CACHE_TTL", 600)
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_CACHE_TTL=600)
expected_page = _expected_page()
fallback = MagicMock()
fallback.list_recommended.return_value = expected_page
@@ -501,7 +500,7 @@ class TestRemoteRecommendedAppCatalogGateway:
response.json.return_value = _page_payload()
http_get = MagicMock(return_value=response)
monkeypatch.setattr(gateway_module.httpx, "get", http_get)
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_CACHE_TTL", 0)
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_CACHE_TTL=0)
gateway = RemoteRecommendedAppCatalogGateway()
gateway.list_recommended("en-US")
@@ -516,11 +515,11 @@ class TestRemoteRecommendedAppCatalogGateway:
response.json.return_value = _page_payload()
http_get = MagicMock(return_value=response)
monkeypatch.setattr(gateway_module.httpx, "get", http_get)
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_CACHE_TTL", 600)
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_CACHE_TTL=600)
gateway = RemoteRecommendedAppCatalogGateway()
- monkeypatch.setattr(gateway_module.dify_config, "CONSOLE_WEB_URL", "https://cloud-a.example.com")
+ apply_config_overrides(monkeypatch, CONSOLE_WEB_URL="https://cloud-a.example.com")
gateway.list_recommended("en-US")
- monkeypatch.setattr(gateway_module.dify_config, "CONSOLE_WEB_URL", "https://cloud-b.example.com")
+ apply_config_overrides(monkeypatch, CONSOLE_WEB_URL="https://cloud-b.example.com")
gateway.list_recommended("en-US")
assert http_get.call_count == 2
@@ -543,7 +542,7 @@ class TestRemoteRecommendedAppCatalogGateway:
response.json.return_value = _detail_payload()
http_get = MagicMock(return_value=response)
monkeypatch.setattr(gateway_module.httpx, "get", http_get)
- monkeypatch.setattr(gateway_module.dify_config, "CONSOLE_WEB_URL", console_web_url)
+ apply_config_overrides(monkeypatch, CONSOLE_WEB_URL=console_web_url)
gateway = RemoteRecommendedAppCatalogGateway()
gateway.get_detail("app-1")
@@ -565,10 +564,9 @@ class TestRemoteRecommendedAppCatalogGateway:
response = MagicMock(status_code=500)
http_get = MagicMock(return_value=response)
monkeypatch.setattr(gateway_module.httpx, "get", http_get)
- monkeypatch.setattr(
- gateway_module.dify_config,
- "HOSTED_FETCH_APP_TEMPLATES_REMOTE_DOMAIN",
- "https://catalog.example.com",
+ apply_config_overrides(
+ monkeypatch,
+ HOSTED_FETCH_APP_TEMPLATES_REMOTE_DOMAIN="https://catalog.example.com",
)
fallback = MagicMock()
database = MagicMock()
@@ -603,7 +601,7 @@ class TestRecommendedAppCatalogRouter:
database=MagicMock(),
builtin=builtin,
)
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "remote")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="remote")
assert gateway.list_recommended("ja-JP") == expected_page
remote.list_recommended.assert_called_once_with("ja-JP")
@@ -619,13 +617,13 @@ class TestRecommendedAppCatalogRouter:
builtin=builtin,
)
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "remote")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="remote")
gateway.list_recommended("en-US")
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "db")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="db")
gateway.list_learn_dify("en-US")
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "builtin")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="builtin")
gateway.get_detail("app-1")
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "remote")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="remote")
gateway.contains("app-1")
remote.list_recommended.assert_called_once_with("en-US")
@@ -643,7 +641,7 @@ class TestRecommendedAppCatalogRouter:
database=database,
builtin=builtin,
)
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "builtin")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="builtin")
assert gateway.list_learn_dify("en-US") == expected_page
builtin.list_learn_dify.assert_called_once_with("en-US")
@@ -655,7 +653,7 @@ class TestRecommendedAppCatalogRouter:
database=MagicMock(),
builtin=MagicMock(),
)
- monkeypatch.setattr(gateway_module.dify_config, "HOSTED_FETCH_APP_TEMPLATES_MODE", "invalid")
+ apply_config_overrides(monkeypatch, HOSTED_FETCH_APP_TEMPLATES_MODE="invalid")
with pytest.raises(ValueError, match="invalid fetch recommended apps mode: invalid"):
gateway.list_recommended("en-US")
diff --git a/api/tests/unit_tests/services/test_skill_management_service.py b/api/tests/unit_tests/services/test_skill_management_service.py
index 3ce4a745b7b..8e9fd12529b 100644
--- a/api/tests/unit_tests/services/test_skill_management_service.py
+++ b/api/tests/unit_tests/services/test_skill_management_service.py
@@ -64,6 +64,7 @@ from services.skill_management_service import (
validate_skill_description,
validate_skill_name,
)
+from tests.unit_tests.config_override import apply_config_overrides
TENANT = "11111111-1111-1111-1111-111111111111"
AGENT = "22222222-2222-2222-2222-222222222222"
@@ -2682,7 +2683,7 @@ def test_import_skill_package_rejects_missing_frontmatter_description() -> None:
def test_import_skill_package_rejects_archive_larger_than_upload_skill_limit(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr("services.skill_management_service.dify_config.UPLOAD_SKILL_FILE_SIZE_LIMIT", 0)
+ apply_config_overrides(monkeypatch, UPLOAD_SKILL_FILE_SIZE_LIMIT=0)
service = SkillManagementService(tool_file_manager=_FakeToolFileManager())
diff --git a/api/tests/unit_tests/services/test_workflow_collaboration_service.py b/api/tests/unit_tests/services/test_workflow_collaboration_service.py
index 3cf1f3c0a21..943677502f7 100644
--- a/api/tests/unit_tests/services/test_workflow_collaboration_service.py
+++ b/api/tests/unit_tests/services/test_workflow_collaboration_service.py
@@ -14,6 +14,7 @@ from models.base import TypeBase
from models.model import App, AppMode, IconType
from repositories.workflow_collaboration_repository import WorkflowCollaborationRepository
from services.workflow_collaboration_service import SYNC_REQUEST_TIMEOUT_SECONDS, WorkflowCollaborationService
+from tests.unit_tests.config_override import config_overrides_context
@pytest.fixture
@@ -71,7 +72,7 @@ class TestWorkflowCollaborationService:
db_session.commit()
with (
- patch("services.workflow_collaboration_service.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch(
"services.workflow_collaboration_service.RBACService.CheckAccess.check", return_value=True
) as check_access,
@@ -140,7 +141,7 @@ class TestWorkflowCollaborationService:
db_session.commit()
with (
- patch("services.workflow_collaboration_service.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch(
"services.workflow_collaboration_service.RBACService.CheckAccess.check", return_value=False
) as check_access,
@@ -195,7 +196,7 @@ class TestWorkflowCollaborationService:
)
db_session.commit()
- with patch("services.workflow_collaboration_service.dify_config.RBAC_ENABLED", False):
+ with config_overrides_context(RBAC_ENABLED=False):
result = collaboration_service._can_access_workflow("wf-1", "tenant-1", "user-1", session=db_session)
assert result is True
@@ -216,7 +217,7 @@ class TestWorkflowCollaborationService:
db_session.commit()
with (
- patch("services.workflow_collaboration_service.dify_config.RBAC_ENABLED", True),
+ config_overrides_context(RBAC_ENABLED=True),
patch("services.workflow_collaboration_service.RBACService.CheckAccess.check") as check_access,
):
result = collaboration_service._can_access_workflow("wf-1", "tenant-1", "owner-1", session=db_session)
diff --git a/api/tests/unit_tests/tasks/test_dataset_indexing_task.py b/api/tests/unit_tests/tasks/test_dataset_indexing_task.py
index 25dd16b2d58..e12e8b1b243 100644
--- a/api/tests/unit_tests/tasks/test_dataset_indexing_task.py
+++ b/api/tests/unit_tests/tasks/test_dataset_indexing_task.py
@@ -27,6 +27,7 @@ from tasks.document_indexing_task import (
normal_document_indexing_task,
priority_document_indexing_task,
)
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture
@@ -318,7 +319,7 @@ class TestDocumentIndexing:
document_ids=[control_document_id],
)
_patch_features(monkeypatch, features)
- monkeypatch.setattr("tasks.document_indexing_task.dify_config.BATCH_UPLOAD_LIMIT", str(batch_limit))
+ apply_config_overrides(monkeypatch, BATCH_UPLOAD_LIMIT=str(batch_limit))
_document_indexing(dataset_id, document_ids)
diff --git a/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py b/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py
index 7792f5b8e8d..be96c1d6285 100644
--- a/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py
+++ b/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py
@@ -111,7 +111,7 @@ def test_sync_joined_workspace_member_rbac_access_task_appends_auto_included_res
app_append = MagicMock()
dataset_append = MagicMock()
- monkeypatch.setattr(task_module.dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
monkeypatch.setattr(task_module, "_iter_resource_config_batches", lambda tenant_id, batch_size: iter([resources]))
monkeypatch.setattr(rbac.RBACService.ResourceWhitelistConfigs, "batch_get", batch_get)
monkeypatch.setattr(rbac.RBACService.AppAccess, "append_whitelist_members_batch", app_append)
diff --git a/api/tests/unit_tests/tasks/test_new_agent_beta_task.py b/api/tests/unit_tests/tasks/test_new_agent_beta_task.py
index f6fba0cb7ed..18fbe774117 100644
--- a/api/tests/unit_tests/tasks/test_new_agent_beta_task.py
+++ b/api/tests/unit_tests/tasks/test_new_agent_beta_task.py
@@ -18,6 +18,7 @@ from tasks.new_agent_beta_task import (
schedule_new_agent_beta_ensure,
schedule_new_agent_beta_workflow_ensure,
)
+from tests.unit_tests.config_override import apply_config_overrides
class _TaskWithQueue(Protocol):
@@ -25,9 +26,12 @@ class _TaskWithQueue(Protocol):
def _configure_cloud_publish(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(task_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
- monkeypatch.setattr(task_module.dify_config, "NEW_AGENT_BETA_ACTIVITY_START_AT", datetime(2026, 8, 12, tzinfo=UTC))
- monkeypatch.setattr(task_module.dify_config, "NEW_AGENT_BETA_ACTIVITY_END_AT", datetime(2026, 8, 13, tzinfo=UTC))
+ apply_config_overrides(
+ monkeypatch,
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ NEW_AGENT_BETA_ACTIVITY_START_AT=datetime(2026, 8, 12, tzinfo=UTC),
+ NEW_AGENT_BETA_ACTIVITY_END_AT=datetime(2026, 8, 13, tzinfo=UTC),
+ )
@pytest.mark.parametrize("sqlite_session", [(AgentConfigRevision,)], indirect=True)
@@ -132,7 +136,7 @@ def test_rolled_back_workflow_publish_is_never_dispatched(
def test_non_cloud_publish_skips_revision_lookup(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(task_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
session = MagicMock()
register_new_agent_beta_publish_after_commit(
@@ -161,8 +165,11 @@ def test_publish_activity_window_is_inclusive_start_exclusive_end(
published_at: datetime,
expected: bool,
) -> None:
- monkeypatch.setattr(task_module.dify_config, "NEW_AGENT_BETA_ACTIVITY_START_AT", start)
- monkeypatch.setattr(task_module.dify_config, "NEW_AGENT_BETA_ACTIVITY_END_AT", end)
+ apply_config_overrides(
+ monkeypatch,
+ NEW_AGENT_BETA_ACTIVITY_START_AT=start,
+ NEW_AGENT_BETA_ACTIVITY_END_AT=end,
+ )
assert task_module._is_publish_in_activity_window(published_at) is expected
diff --git a/api/tests/unit_tests/tasks/test_remove_app_and_related_data_task.py b/api/tests/unit_tests/tasks/test_remove_app_and_related_data_task.py
index 125e447a10e..8774760f2c4 100644
--- a/api/tests/unit_tests/tasks/test_remove_app_and_related_data_task.py
+++ b/api/tests/unit_tests/tasks/test_remove_app_and_related_data_task.py
@@ -23,6 +23,7 @@ from tasks.remove_app_and_related_data_task import (
_delete_workflow_agent_node_bindings,
delete_draft_variables_batch,
)
+from tests.unit_tests.config_override import apply_config_overrides
def test_delete_workflow_agent_node_bindings_is_scoped_to_tenant_and_app(sqlite_session: Session) -> None:
@@ -75,7 +76,7 @@ def test_delete_workflow_agent_node_bindings_is_scoped_to_tenant_and_app(sqlite_
def test_app_cleanup_removes_agent_bindings_before_workflows(monkeypatch: pytest.MonkeyPatch) -> None:
events: list[str] = []
- monkeypatch.setattr(remove_app_task_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
other_cleanup_names = (
"_delete_app_model_configs",
"_delete_app_site",
diff --git a/api/tests/unit_tests/test_app_factory.py b/api/tests/unit_tests/test_app_factory.py
index acdeecc07c0..64f0dc230f5 100644
--- a/api/tests/unit_tests/test_app_factory.py
+++ b/api/tests/unit_tests/test_app_factory.py
@@ -10,6 +10,7 @@ from app_factory import create_flask_app_with_configs
from enums import DeploymentEdition
from libs.external_api import ExternalApi
from services.entities.feature_entities import LicenseStatus
+from tests.unit_tests.config_override import config_overrides_context
INVALID_STATUSES = [LicenseStatus.INACTIVE, LicenseStatus.EXPIRED, LicenseStatus.LOST]
VALID_STATUSES = [LicenseStatus.ACTIVE, LicenseStatus.EXPIRING]
@@ -20,11 +21,11 @@ def _license(status: LicenseStatus | None):
def _enterprise():
- return patch("app_factory.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE)
+ return config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
def _community():
- return patch("app_factory.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ return config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
@pytest.fixture
diff --git a/api/tests/unit_tests/test_config_overrides.py b/api/tests/unit_tests/test_config_overrides.py
index 39588272246..7c71518cea3 100644
--- a/api/tests/unit_tests/test_config_overrides.py
+++ b/api/tests/unit_tests/test_config_overrides.py
@@ -1,12 +1,101 @@
"""Contract tests for the shared unit-test config override fixture."""
+import ast
from collections.abc import Callable
+from pathlib import Path
+from typing import override
import pytest
from configs import dify_config
from enums import DeploymentEdition
+_UNIT_TEST_ROOT = Path(__file__).parent
+_AUTHORIZED_MUTATION_FILE = _UNIT_TEST_ROOT / "config_override.py"
+
+
+def _references_shared_config(node: ast.AST) -> bool:
+ """Return whether an expression resolves through the shared ``dify_config`` object."""
+ return any(
+ (isinstance(child, ast.Name) and child.id == "dify_config")
+ or (isinstance(child, ast.Attribute) and child.attr == "dify_config")
+ for child in ast.walk(node)
+ )
+
+
+def _attribute_chain(node: ast.AST) -> tuple[str, ...]:
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return tuple(reversed(parts))
+
+
+def _is_config_field(name: object) -> bool:
+ return isinstance(name, str) and bool(name) and name.isupper()
+
+
+class _DirectConfigMutationVisitor(ast.NodeVisitor):
+ """Find test code that bypasses the validated config override helper."""
+
+ def __init__(self) -> None:
+ self.lines: list[int] = []
+
+ @override
+ def visit_Call(self, node: ast.Call) -> None:
+ chain = _attribute_chain(node.func)
+ if chain[-2:] == ("patch", "object") and len(node.args) >= 2:
+ field = node.args[1]
+ if (
+ _references_shared_config(node.args[0])
+ and isinstance(field, ast.Constant)
+ and _is_config_field(field.value)
+ ):
+ self.lines.append(node.lineno)
+ elif chain[-1:] == ("patch",) and node.args:
+ target = node.args[0]
+ if (
+ isinstance(target, ast.Constant)
+ and isinstance(target.value, str)
+ and ".dify_config." in target.value
+ and _is_config_field(target.value.rsplit(".", 1)[-1])
+ ):
+ self.lines.append(node.lineno)
+ elif chain[-2:] == ("monkeypatch", "setattr") and node.args:
+ target = node.args[0]
+ field = node.args[1] if len(node.args) >= 2 else None
+ string_target_is_config = (
+ isinstance(target, ast.Constant) and isinstance(target.value, str) and ".dify_config." in target.value
+ )
+ object_target_is_config = (
+ field is not None
+ and _references_shared_config(target)
+ and isinstance(field, ast.Constant)
+ and _is_config_field(field.value)
+ )
+ if string_target_is_config or object_target_is_config:
+ self.lines.append(node.lineno)
+ self.generic_visit(node)
+
+ @override
+ def visit_Assign(self, node: ast.Assign) -> None:
+ for target in node.targets:
+ if (
+ isinstance(target, ast.Attribute)
+ and _is_config_field(target.attr)
+ and _references_shared_config(target)
+ ):
+ self.lines.append(node.lineno)
+ self.generic_visit(node)
+
+
+def _find_direct_config_mutations(path: Path) -> list[int]:
+ visitor = _DirectConfigMutationVisitor()
+ visitor.visit(ast.parse(path.read_text(), filename=str(path)))
+ return visitor.lines
+
def test_config_overrides_updates_shared_config(config_overrides: Callable[..., None]) -> None:
config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@@ -17,3 +106,14 @@ def test_config_overrides_updates_shared_config(config_overrides: Callable[...,
def test_config_overrides_rejects_unknown_fields(config_overrides: Callable[..., None]) -> None:
with pytest.raises(ValueError, match=r"Unknown DifyConfig fields: \['NOT_A_CONFIG_FIELD'\]"):
config_overrides(NOT_A_CONFIG_FIELD=True)
+
+
+def test_unit_tests_use_validated_config_overrides() -> None:
+ """Keep global application config mutations centralized and automatically restored."""
+ violations = {
+ str(path.relative_to(_UNIT_TEST_ROOT)): lines
+ for path in _UNIT_TEST_ROOT.rglob("*.py")
+ if path != _AUTHORIZED_MUTATION_FILE and (lines := _find_direct_config_mutations(path))
+ }
+
+ assert violations == {}, f"Use config_overrides or config_overrides_context instead: {violations}"
diff --git a/api/tests/unit_tests/test_constants.py b/api/tests/unit_tests/test_constants.py
index e40744a894a..d66cdff65db 100644
--- a/api/tests/unit_tests/test_constants.py
+++ b/api/tests/unit_tests/test_constants.py
@@ -4,6 +4,7 @@ import pytest
import constants
from configs import dify_config
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.mark.parametrize("etl_type", ["SelfHosted", "Unstructured"])
@@ -12,14 +13,16 @@ def test_document_extensions_include_odt_for_document_etl_modes(monkeypatch: pyt
original_unstructured_api_url = dify_config.UNSTRUCTURED_API_URL
try:
- monkeypatch.setattr(dify_config, "ETL_TYPE", etl_type)
- monkeypatch.setattr(dify_config, "UNSTRUCTURED_API_URL", None)
+ apply_config_overrides(monkeypatch, ETL_TYPE=etl_type, UNSTRUCTURED_API_URL=None)
reloaded_constants = importlib.reload(constants)
assert "odt" in reloaded_constants.DOCUMENT_EXTENSIONS
assert "ODT" in reloaded_constants.DOCUMENT_EXTENSIONS
finally:
- monkeypatch.setattr(dify_config, "ETL_TYPE", original_etl_type)
- monkeypatch.setattr(dify_config, "UNSTRUCTURED_API_URL", original_unstructured_api_url)
+ apply_config_overrides(
+ monkeypatch,
+ ETL_TYPE=original_etl_type,
+ UNSTRUCTURED_API_URL=original_unstructured_api_url,
+ )
importlib.reload(constants)