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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
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.pyindex 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_agfrom configs import dify_configfrom services import agent_app_sandbox_servicefrom 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.pyindex 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 Pathfrom 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_configmonkeypatch.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.pyindex 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 ModelTypefrom models import Tenantfrom models.provider import Provider, ProviderModel, ProviderTypefrom models.tools import ApiToolProvider, BuiltinToolProvider, MCPToolProvider+from tests.unit_tests.config_override import apply_config_overridesdef _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 tablethat 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.pyindex 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 pytestfrom 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)+ yielddiff --git a/api/tests/unit_tests/conftest.py b/api/tests/unit_tests/conftest.pyindex 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.fixturediff --git a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.pyindex 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_overridesdef _persist_conversation_message(@@ -864,7 +865,7 @@ def test_agent_api_access_uses_agent_id_and_returns_service_api_metadata(monkeypmonkeypatch.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.pyindex 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, RBACResourceScopefrom models import Accountfrom models.agent import Agent, AgentScope, AgentSource, AgentStatusfrom models.model import App, AppMode+from tests.unit_tests.config_override import config_overrides_contextTENANT_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.pyindex 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_overridesAPP_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.pyindex 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, AppModefrom services.app_dsl_service import ImportStatusfrom services.entities.dsl_entities import CheckDependenciesResultfrom services.entities.feature_entities import SystemFeatureModel, WebAppAuthModel+from tests.unit_tests.config_override import apply_config_overridesdef _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.pyindex 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 Accountfrom models.account import AccountStatusfrom models.enums import AppMCPServerStatusfrom models.model import App, AppMCPServer, AppMode, IconType+from tests.unit_tests.config_override import config_overrides_contextdef _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.pyindex 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_libfrom models import Tenantfrom models.account import Account, AccountStatus, TenantAccountRolefrom models.model import App, AppMode, IconType+from tests.unit_tests.config_override import apply_config_overridesdef _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.pyindex 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 LLMEnvironmentVariablefrom graphon.file import File, FileTransferMethod, FileTypefrom graphon.variables import SecretVariable, StringVariablefrom graphon.variables.variables import RAGPipelineVariable+from tests.unit_tests.config_override import apply_config_overridesdef _make_workflow(**overrides):@@ -875,7 +876,7 @@ def test_workflow_online_users_filters_inaccessible_workflow(app: Flask, monkeypaccess_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.pyindex 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_libfrom models import App, Tenant, WorkflowComment, WorkflowCommentMention, WorkflowCommentReplyfrom models.account import Account, AccountStatus, TenantAccountRolefrom models.model import AppMode, IconType+from tests.unit_tests.config_override import apply_config_overridesJAN_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.pyindex 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_libfrom models import App, Tenantfrom models.account import Account, AccountStatus, TenantAccountRolefrom models.model import AppMode, IconType+from tests.unit_tests.config_override import apply_config_overridesdef _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 modelmonkeypatch.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.pyindex 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 HumanInputRequiredfrom graphon.enums import WorkflowExecutionStatusfrom models.enums import CreatorUserRole, WorkflowRunTriggeredFromfrom 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.pyindex 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 AuthenticationFailedErrorfrom controllers.console.auth.login import LoginApifrom enums import DeploymentEditionfrom models.account import Account+from tests.unit_tests.config_override import config_overrides_contextdef 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_dbdiff --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.pyindex 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_contextdef _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.pyindex 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.pyindex 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.pyindex 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 DeploymentEditionfrom models.account import Accountfrom models.engine import dbfrom 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.pyindex 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 AccountRegisterErrorfrom 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.pyindex 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 Flaskfrom controllers.console.auth.oauth import OAuthCallback, OAuthLoginfrom libs.oauth import OAuthUserInfo, encode_oauth_statefrom models.account import Account, AccountStatus, Tenant+from tests.unit_tests.config_override import config_overrides_contextREDIRECT_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) -> Nwith (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.pyindex 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, EmailSendIpLimitErrorfrom enums import DeploymentEditionfrom models.account import Account, Tenant, TenantAccountJoinfrom services.entities.feature_entities import SystemFeatureModel+from tests.unit_tests.config_override import apply_config_overridesSQLITE_MODELS = (Account, Tenant, TenantAccountJoin)@@ -46,7 +47,7 @@ def _bind_database_session(session: Session) -> Generator[scoped_session[Sessiondef 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.pyindex 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_contextclass 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 = Nonediff --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.pyindex 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 dbfrom services.entities.knowledge_entities.rag_pipeline_entities import PipelineTemplateInfoEntityfrom services.errors.account import NoPermissionErrorfrom services.errors.rag_pipeline import RagPipelineResourceNotFoundError+from tests.unit_tests.config_override import config_overrides_contextdef _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.NORMALwith (- 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.EDITORwith (- 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.EDITORwith (- 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.pyindex 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, WorkflowTypefrom services.errors.llm import InvokeRateLimitErrorfrom services.errors.rag_pipeline import RagPipelineResourceNotFoundErrorfrom services.rag_pipeline.rag_pipeline import RagPipelineService+from tests.unit_tests.config_override import config_overrides_contextDEFAULT_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_servicsession.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_servicesession.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_enginesession.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_engsession.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.pyindex 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_contextdef 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.pyindex 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 MetadataArgsfrom services.errors.account import NoPermissionErrorfrom services.errors.metadata import MetadataResourceNotFoundErrorfrom 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.pyindex 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_contextdef 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.pyindex 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 pytestfrom flask import Flaskfrom flask.views import MethodView as FlaskMethodView+from tests.unit_tests.config_override import apply_config_overrides+_NEEDS_METHOD_VIEW_CLEANUP = Falseif 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.pyindex 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 = InvalidInitializationPasswordErrorclient = 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 = AlreadyInitializedErrorresponse = 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.pyindex 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 patchimport pytestfrom flask.views import MethodView@@ -7,6 +6,7 @@ from flask.views import MethodViewfrom configs import dify_configfrom dify_app import DifyAppfrom extensions import ext_fastopenapi+from tests.unit_tests.config_override import config_overrides_contextif 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 == 200diff --git a/api/tests/unit_tests/controllers/console/test_human_input_form.py b/api/tests/unit_tests/controllers/console/test_human_input_form.pyindex 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, WorkflowRunTriggeredFromfrom models.human_input import RecipientTypefrom models.model import App, AppModefrom 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.pyindex 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_autospecimport pytestfrom flask import Flask-from controllers.console import init_validate, wraps+from controllers.console import init_validatefrom controllers.console.error import AlreadySetupError, InitValidateFailedErrorfrom enums import DeploymentEditionfrom 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 = AlreadyInitializedErrorapp.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 = InvalidInitializationPasswordErrorapp.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.pyindex 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, patchimport pytestimport controllers.console.system as system_module+from tests.unit_tests.config_override import config_overrides_contextclass 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.pyindex 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 pytestfrom flask import Flaskfrom werkzeug.exceptions import Conflict, Forbidden, NotFound-from configs import dify_configfrom controllers.console import flask_admission, workflow_run_archivefrom 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_overridesdef _account(role: TenantAccountRole) -> Account:@@ -82,7 +82,7 @@ def test_workflow_run_archive_endpoints_reject_non_manager_when_rbac_is_disabledmethod,) -> 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_enabledmonkeypatch: 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.pyindex 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, DifySetupfrom models.account import AccountStatus, TenantAccountRolefrom models.dataset import Dataset, RateLimitLogfrom 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_contextwith (- 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.pyindex 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_contextdef 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.pyindex 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_contextVALID_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.pyindex 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_contextdef _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.pyindex 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, TenantCustomConfifrom repositories.workspace_query_repository import WorkspaceQueryRepositoryfrom services import workspace_plan_gatewayfrom 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.pyindex 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_referencefrom models import Account, Tenant+from tests.unit_tests.config_override import apply_config_overridesdef _tenant() -> Tenant:@@ -280,7 +281,7 @@ class TestPluginUploadFileRequestApi:"""Test that post() generates a signed URL and returns it"""# Arrangemock_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.idmock_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.pyindex 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_referencefrom models.account import Account, Tenantfrom services.file_request_service import DownloadFileRequestResult+from tests.unit_tests.config_override import apply_config_overridesMODULE = "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_sessionwith 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.pyindex 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, LLMResulfrom graphon.model_runtime.entities.message_entities import AssistantPromptMessage, UserPromptMessagefrom services.agent_llm_inner_service import AgentLLMInnerServiceError, PreparedAgentLLMInvocationfrom services.entities.agent_llm_inner import AgentLLMInvokeRequest+from tests.unit_tests.config_override import config_overrides_contextdef _payload() -> dict[str, object]:@@ -44,8 +45,7 @@ def _payload() -> dict[str, object]:@contextmanagerdef _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"),):yielddiff --git a/api/tests/unit_tests/controllers/inner_api/test_agent_tools.py b/api/tests/unit_tests/controllers/inner_api/test_agent_tools.pyindex 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 Flaskfrom controllers.inner_api import bp as inner_api_bpfrom services.entities.agent_tool_inner import AgentToolInvokeResponsefrom services.errors.agent_tool_inner import AgentToolInnerServiceError+from tests.unit_tests.config_override import config_overrides_contextdef _headers(api_key: str | None = "inner-key") -> dict[str, str]:@@ -48,8 +49,7 @@ def _payload() -> dict[str, object]:@contextmanagerdef _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"),):yielddiff --git a/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.py b/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.pyindex 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]:@contextmanagerdef _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"),):yielddiff --git a/api/tests/unit_tests/controllers/openapi/auth/test_composition.py b/api/tests/unit_tests/controllers/openapi/auth/test_composition.pyindex 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 DeploymentEditionfrom libs.oauth_bearer import Scope, TokenTypefrom models.account import TenantAccountRolefrom services.enterprise.enterprise_service import WebAppAccessMode+from tests.unit_tests.config_override import config_overrides_contextdef test_account_pipeline_is_auth_pipeline():@@ -163,10 +164,7 @@ def _selected_webapp_steps(*, scope, app_access_mode):features.webapp_auth.enabled = Trueselected = []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.pyindex 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 DeploymentEditionfrom libs.oauth_bearer import Scope, TokenTypefrom models.account import TenantAccountRolefrom services.enterprise.enterprise_service import WebAppAccessMode+from tests.unit_tests.config_override import config_overrides_contextdef _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 Trueassert EDITION_ENTERPRISE(_ctx()) is Falseassert EDITION_CLOUD(_ctx()) is Falsedef 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 Trueassert EDITION_COMMUNITY(_ctx()) is Falsedef 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 Truediff --git a/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.py b/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.pyindex 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 AuthDatafrom controllers.openapi.auth.pipeline import AuthPipeline, PipelineRoute, PipelineRouterfrom enums import DeploymentEditionfrom libs.oauth_bearer import Scope, TokenType+from tests.unit_tests.config_override import config_overrides_contextdef _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 = identitydiff --git a/api/tests/unit_tests/controllers/openapi/test_meta_version.py b/api/tests/unit_tests/controllers/openapi/test_meta_version.pyindex 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 annotationsimport pytestfrom enums import DeploymentEdition+from tests.unit_tests.config_override import apply_config_overridesdef 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: pytedef 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.pyindex 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 ConversationServicefrom services.errors.app import IsDraftWorkflowError, WorkflowIdFormatError, WorkflowNotFoundErrorfrom services.errors.conversation import ConversationNotExistsErrorfrom 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.pyindex 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 WorkflowNodeExecfrom repositories.entities.workflow_pause import WorkflowPauseEntityfrom services.app_generate_service import AppGenerateServicefrom services.workflow_event_snapshot_service import _build_snapshot_events+from tests.unit_tests.config_override import apply_config_overridesclass _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.pyindex 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 TenantAccountRolefrom models.dataset import Dataset, RateLimitLogfrom models.enums import ApiTokenTypefrom models.model import ApiToken, App, AppMode, IconType+from tests.unit_tests.config_override import config_overrides_contextdef _configure_current_app_mock(mock_current_app):@@ -346,7 +347,7 @@ class TestCloudEditionBillingResourceCheck:# Actwith (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.pyindex 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"] = Trueapp.config["RESTX_INCLUDE_ALL_MODELS"] = True@@ -684,12 +681,9 @@ def test_console_billing_routes_document_error_responses(monkeypatch: pytest.Monassert 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"] = Trueapp.config["RESTX_INCLUDE_ALL_MODELS"] = Truediff --git a/api/tests/unit_tests/controllers/web/test_web_forgot_password.py b/api/tests/unit_tests/controllers/web/test_web_forgot_password.pyindex 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 DeploymentEditionfrom models.account import Accountfrom models.engine import dbfrom 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),):yielddiff --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.pyindex 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 testfrom core.app.app_config.common import parameters_mapping+from tests.unit_tests.config_override import apply_config_overridesclass 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.fixturedef 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.pyindex 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 TraceQueueManagerfrom libs.datetime_utils import naive_utc_nowfrom models.enums import MessageStatusfrom models.model import AppMode+from tests.unit_tests.config_override import apply_config_overridesclass 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.pyindex 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 AgentChatAppGeneratorfrom core.app.apps.exc import GenerateTaskStoppedErrorfrom core.app.entities.app_invoke_entities import InvokeFromfrom graphon.model_runtime.errors.invoke import InvokeAuthorizationError+from tests.unit_tests.config_override import apply_config_overridesclass 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.pyindex 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 pytestfrom core.app.workflow.layers.observability import ObservabilityLayerfrom graphon.enums import BuiltinNodeTypes+from tests.unit_tests.config_override import apply_config_overridesclass 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.textdef 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.pyindex 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 MockerFixtureimport core.callback_handler.agent_tool_callback_handler as modulefrom 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.fixturediff --git a/api/tests/unit_tests/core/ops/test_ops_trace_manager.py b/api/tests/unit_tests/core/ops/test_ops_trace_manager.pyindex 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 Enginefrom sqlalchemy.orm import Session, sessionmakerimport core.ops.ops_trace_manager as module-from configs import dify_configfrom core.ops.ops_trace_manager import OpsTraceManager, TraceQueueManager, TraceTask, TraceTaskNamefrom core.rag.models.document import Document as RetrievalDocumentfrom 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, TraceAppConfigfrom models.workflow import WorkflowAppLog, WorkflowAppLogCreatedFrom, WorkflowRun, WorkflowTypefrom repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository+from tests.unit_tests.config_override import apply_config_overridesclass DummyConfig:@@ -155,7 +155,7 @@ def database(sqlite_engine: Engine, sqlite_session: Session) -> Iterator[Sessiondef 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 DummyTraceInstancediff --git a/api/tests/unit_tests/core/prompt/test_advanced_prompt_transform.py b/api/tests/unit_tests/core/prompt/test_advanced_prompt_transform.pyindex 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, patchimport pytest-from configs import dify_configfrom core.app.app_config.entities import ModelConfigEntityfrom core.memory.token_buffer_memory import TokenBufferMemoryfrom 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_overridesdef 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.pyindex 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 Keywordfrom core.rag.datasource.keyword.keyword_type import KeyWordTypefrom core.rag.models.document import Documentfrom models.dataset import Dataset+from tests.unit_tests.config_override import apply_config_overridesdef 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.pyindex 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_modulefrom core.rag.extractor.excel_extractor import ExcelExtractorfrom models.base import TypeBasefrom 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 savesdiff --git a/api/tests/unit_tests/core/rag/extractor/test_notion_extractor.py b/api/tests/unit_tests/core/rag/extractor/test_notion_extractor.pyindex 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 IndexStructureTypefrom models.base import TypeBasefrom models.dataset import Document as DocumentModelfrom 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.pyindex 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, Documentfrom models.dataset import ChildChunk, Dataset, DatasetProcessRule, DocumentCreatedFrom, DocumentSegmentfrom models.dataset import Document as DatasetDocumentfrom models.enums import DataSourceType+from tests.unit_tests.config_override import config_overrides_contextclass 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.pyindex 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 StorageTypefrom models.enums import CreatorUserRolefrom models.model import UploadFilefrom models.tools import ToolFile+from tests.unit_tests.config_override import config_overrides_contextdef _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.pyindex 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_contextdef _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.pyindex 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 pytestfrom core.tools.utils import system_encryption as encryptionfrom core.tools.utils.system_encryption import EncryptionError, SystemEncrypter+from tests.unit_tests.config_override import apply_config_overridesdef 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.pyindex 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 BuiltinNodeTypesfrom graphon.runtime import VariablePoolfrom graphon.variables.variables import StringVariablefrom models.workflow import Workflow, WorkflowType+from tests.unit_tests.config_override import config_overrides_contextdef _build_typed_node_config(node_type: NodeType):@@ -99,8 +100,7 @@ class TestWorkflowEntryInit:observability_layer = sentinel.observability_layerwith (- 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.pyindex 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 pytestfrom events.event_handlers import queue_default_plugin_install_when_tenant_created as handler_modulefrom models.account import Tenant+from tests.unit_tests.config_override import apply_config_overridesdef _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.pyindex 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 MagicMockfrom core.app.entities.app_invoke_entities import InvokeFromfrom extensions.otel.decorators.handlers.generate_handler import AppGenerateHandlerfrom extensions.otel.semconv import DifySpanAttributes, GenAIAttributes+from tests.unit_tests.config_override import config_overrides_contextclass 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.pyindex 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 WorkflowAppRunnerHandlerfrom extensions.otel.semconv import DifySpanAttributes, GenAIAttributes+from tests.unit_tests.config_override import config_overrides_contextclass 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.pyindex 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 TracerProviderfrom core.logging.context import clear_request_contextfrom models import Account+from tests.unit_tests.config_override import config_overrides_contextdef _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.pyindex 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 WorkflowRunArchifrom services.tag_application_service import TagApplicationServicefrom services.webapp_access_query_service import WebAppAccessUnavailableErrorfrom 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.pyindex 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 Iteratorimport pytestfrom flask import Blueprint-from configs import dify_configfrom dify_app import DifyAppfrom 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.pyindex 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 MagicMockimport pytestfrom flask import Flask, Response-from configs import dify_configfrom extensions import ext_request_loggingfrom extensions.ext_request_logging import _is_content_type_json, _log_request_finished, init_app+from tests.unit_tests.config_override import apply_config_overridesdef test_is_content_type_json():@@ -59,7 +59,7 @@ def mock_response_receiver(monkeypatch: pytest.MonkeyPatch) -> mock.Mock:@pytest.fixturedef 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.pyindex 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_configfrom extensions import ext_redisfrom libs.broadcast_channel.redis.pubsub_channel import BroadcastChannel as RedisBroadcastChannelfrom libs.broadcast_channel.redis.sharded_channel import ShardedRedisBroadcastChannel+from tests.unit_tests.config_override import apply_config_overridesdef 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.Mondef 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.pyindex 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 pytestfrom flask import Flaskfrom extensions import ext_set_secretkey+from tests.unit_tests.config_override import apply_config_overridesclass 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.pyindex 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_overridesBUCKET_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.pyindex 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_modulefrom extensions.ext_login import DifyLoginManagerfrom libs.login import current_userfrom 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.pyindex 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 DeploymentEditionfrom libs import oauth_bearerfrom libs.oauth_bearer import AuthContext, Scope, SubjectType, TokenType, require_workspace_memberfrom models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole+from tests.unit_tests.config_override import apply_config_overridespytestmark = pytest.mark.usefixtures("community_edition")@@ -47,7 +48,7 @@ def database(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) -> Iterat@pytest.fixturedef 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.ACTdef 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.pyindex 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_overridesdef _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",+ )# Actattachments = 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.pyindex 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 pytestfrom dify_agent.client import DifyAgentHTTPError, DifyAgentNotFoundError, DifyAgentTimeoutErrorfrom sqlalchemy.orm import Session-from configs import dify_configfrom 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_bindingfrom services.agent.workspace_service import AgentWorkspaceService+from tests.unit_tests.config_override import apply_config_overridesdef _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.pyindex 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 pytestfrom sqlalchemy import selectfrom sqlalchemy.orm import Session-from configs import dify_configfrom 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_overridesdef _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.pyindex 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, MigrationImportServicefrom 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.pyindex 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 Sessionfrom services.rag_pipeline.pipeline_template.database.database_retrieval import DatabasePipelineTemplateRetrievalfrom services.rag_pipeline.pipeline_template.pipeline_template_type import PipelineTemplateTypefrom 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) -> Nassert 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.pyindex 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 UploadFilefrom services.entities.knowledge_entities.rag_pipeline_entities import KnowledgeConfigurationfrom services.errors.rag_pipeline import RagPipelineResourceNotFoundErrorfrom services.rag_pipeline.rag_pipeline_transform_service import RagPipelineTransformService+from tests.unit_tests.config_override import apply_config_overridesdef _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_valueinstaller.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_valueinstaller.list_plugins.return_value = []migration = mocker.patch("services.rag_pipeline.rag_pipeline_transform_service.PluginMigration").return_valuediff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.pyindex 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_contexttype _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(email="[email protected]",@@ -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 Nonemock_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.pyindex 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, PendingDatafrom services.entities.dsl_entities import ImportStatusfrom services.errors.account import NoPermissionErrorfrom 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 Falsecheck = 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.pyindex 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 MessageBasedAppGeneratorfrom core.app.apps.message_generator import MessageGeneratorfrom models.model import AppModefrom 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 MessageGeneratormonkeypatch.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.pyindex 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_overridesTOKEN = "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.pyindex 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 expecteddiff --git a/api/tests/unit_tests/services/test_recommended_app_catalog_gateway.py b/api/tests/unit_tests/services/test_recommended_app_catalog_gateway.pyindex 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_overridesdef _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")yieldgateway_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_pageremote.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_pagebuiltin.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.pyindex 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_overridesTENANT = "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.pyindex 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 TypeBasefrom models.model import App, AppMode, IconTypefrom repositories.workflow_collaboration_repository import WorkflowCollaborationRepositoryfrom 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.pyindex 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.pyindex 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_resapp_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.pyindex 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_overridesclass _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 expecteddiff --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.pyindex 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_overridesdef 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.pyindex 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_configsfrom enums import DeploymentEditionfrom libs.external_api import ExternalApifrom services.entities.feature_entities import LicenseStatus+from tests.unit_tests.config_override import config_overrides_contextINVALID_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.fixturediff --git a/api/tests/unit_tests/test_config_overrides.py b/api/tests/unit_tests/test_config_overrides.pyindex 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 astfrom collections.abc import Callable+from pathlib import Path+from typing import overrideimport pytestfrom configs import dify_configfrom 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.pyindex e40744a894a..d66cdff65db 100644--- a/api/tests/unit_tests/test_constants.py+++ b/api/tests/unit_tests/test_constants.py@@ -4,6 +4,7 @@ import pytestimport constantsfrom 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: pytoriginal_unstructured_api_url = dify_config.UNSTRUCTURED_API_URLtry:- 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_EXTENSIONSassert "ODT" in reloaded_constants.DOCUMENT_EXTENSIONSfinally:- 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)