Skip to content

armgit / dify

Public Imported from GitHub
0

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

test: centralize controller and storage config overrides (#40867)

Asuka Minato92110e1982b3
diff --git a/api/tests/unit_tests/controllers/console/datasets/test_datasets.py b/api/tests/unit_tests/controllers/console/datasets/test_datasets.py
index c4e8e7569f7..ada7de0ce20 100644
--- a/api/tests/unit_tests/controllers/console/datasets/test_datasets.py
+++ b/api/tests/unit_tests/controllers/console/datasets/test_datasets.py
@@ -1,5 +1,6 @@
import datetime
import json
+from collections.abc import Callable
from contextlib import ExitStack
from inspect import unwrap
from types import SimpleNamespace
@@ -255,7 +256,10 @@ class TestDatasetList:
assert status == 200
assert resp["data"][0]["permission_keys"] == ["dataset.acl.readonly", "dataset.acl.edit"]
- def test_get_restricted_whitelist_blocks_own_dataset_fallback(self, app: Flask):
+ def test_get_restricted_whitelist_blocks_own_dataset_fallback(
+ self, app: Flask, config_overrides: Callable[..., None]
+ ):
+ config_overrides(RBAC_ENABLED=True)
api = DatasetListApi()
method = unwrap(api.get)
current_user = self._mock_user()
@@ -266,7 +270,6 @@ class TestDatasetList:
)
with app.test_request_context("/datasets"):
with (
- patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),
patch.object(DatasetService, "get_datasets", return_value=([], 0)) as get_datasets,
patch(
"controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",
@@ -282,7 +285,10 @@ class TestDatasetList:
assert get_datasets.call_args.kwargs["accessible_dataset_ids"] == []
assert get_datasets.call_args.kwargs["include_own_datasets"] is False
- def test_get_default_read_is_unrestricted_when_whitelist_unrestricted(self, app: Flask):
+ def test_get_default_read_is_unrestricted_when_whitelist_unrestricted(
+ self, app: Flask, config_overrides: Callable[..., None]
+ ):
+ config_overrides(RBAC_ENABLED=True)
api = DatasetListApi()
method = unwrap(api.get)
current_user = self._mock_user()
@@ -291,7 +297,6 @@ class TestDatasetList:
)
with app.test_request_context("/datasets"):
with (
- patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),
patch.object(DatasetService, "get_datasets", return_value=([], 0)) as get_datasets,
patch(
"controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",
@@ -306,7 +311,10 @@ class TestDatasetList:
method(api, MagicMock(), "tenant-1", current_user)
assert get_datasets.call_args.kwargs["accessible_dataset_ids"] is None
- def test_get_restricted_whitelist_overrides_default_read_permission(self, app: Flask):
+ def test_get_restricted_whitelist_overrides_default_read_permission(
+ self, app: Flask, config_overrides: Callable[..., None]
+ ):
+ config_overrides(RBAC_ENABLED=True)
api = DatasetListApi()
method = unwrap(api.get)
current_user = self._mock_user()
@@ -315,7 +323,6 @@ class TestDatasetList:
)
with app.test_request_context("/datasets"):
with (
- patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),
patch.object(DatasetService, "get_datasets", return_value=([], 0)) as get_datasets,
patch(
"controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",
@@ -331,7 +338,10 @@ class TestDatasetList:
assert get_datasets.call_args.kwargs["accessible_dataset_ids"] == ["dataset-whitelist-only"]
assert get_datasets.call_args.kwargs["include_own_datasets"] is False
- def test_get_restricted_whitelist_ignores_dataset_read_overrides(self, app: Flask):
+ def test_get_restricted_whitelist_ignores_dataset_read_overrides(
+ self, app: Flask, config_overrides: Callable[..., None]
+ ):
+ config_overrides(RBAC_ENABLED=True)
api = DatasetListApi()
method = unwrap(api.get)
current_user = self._mock_user()
@@ -353,7 +363,6 @@ class TestDatasetList:
)
with app.test_request_context("/datasets"):
with (
- patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),
patch.object(DatasetService, "get_datasets", return_value=([], 0)) as get_datasets,
patch(
"controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",
@@ -371,14 +380,14 @@ class TestDatasetList:
]
assert get_datasets.call_args.kwargs["include_own_datasets"] is False
- def test_get_with_ids_applies_dataset_visibility(self, app: Flask):
+ def test_get_with_ids_applies_dataset_visibility(self, app: Flask, config_overrides: Callable[..., None]):
+ config_overrides(RBAC_ENABLED=True)
api = DatasetListApi()
method = unwrap(api.get)
current_user = self._mock_user()
permissions = enterprise_rbac_service.MyPermissionsResponse()
with app.test_request_context("/datasets?ids=dataset-1"):
with (
- patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),
patch.object(DatasetService, "get_datasets_by_ids", return_value=([], 0)) as get_datasets_by_ids,
patch(
"controllers.console.datasets.datasets.enterprise_rbac_service.RBACService.MyPermissions.get",
@@ -583,7 +592,8 @@ class TestDatasetApiGet:
assert status == 200
assert data["embedding_available"] is True
- def test_get_attaches_permission_keys_when_rbac_enabled(self, app: Flask):
+ def test_get_attaches_permission_keys_when_rbac_enabled(self, app: Flask, config_overrides: Callable[..., None]):
+ config_overrides(RBAC_ENABLED=True)
api = DatasetApi()
method = unwrap(api.get)
dataset_id = "123e4567-e89b-12d3-a456-426614174000"
@@ -592,7 +602,6 @@ class TestDatasetApiGet:
dataset = make_dataset(id=dataset_id)
with (
app.test_request_context(f"/datasets/{dataset_id}"),
- patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),
patch.object(DatasetService, "get_dataset", return_value=dataset),
patch.object(DatasetService, "check_dataset_permission", return_value=None),
patch(
@@ -853,14 +862,14 @@ class TestDatasetUseCheckApi:
check_permission.assert_called_once_with(dataset, current_user, session)
dataset_use_check.assert_called_once_with(DatasetRef("tenant-1", dataset_id), session)
- def test_get_use_check_relies_on_rbac_in_rbac_mode(self, app: Flask):
+ def test_get_use_check_relies_on_rbac_in_rbac_mode(self, app: Flask, config_overrides: Callable[..., None]):
+ config_overrides(RBAC_ENABLED=True)
api = DatasetUseCheckApi()
method = unwrap(api.get)
dataset = make_dataset(id="dataset-id")
session = MagicMock()
with (
app.test_request_context("/datasets/dataset-id/use-check"),
- patch("controllers.console.datasets.datasets.dify_config.RBAC_ENABLED", True),
patch.object(DatasetService, "get_dataset_for_tenant", return_value=dataset),
patch.object(DatasetService, "check_dataset_permission") as check_permission,
patch.object(DatasetService, "dataset_use_check", return_value=False),
@@ -1510,44 +1519,44 @@ class TestDatasetEnableApiApi:
class TestDatasetApiBaseUrlApi:
- def test_get_api_base_url_from_config(self, app: Flask):
+ def test_get_api_base_url_from_config(self, app: Flask, config_overrides: Callable[..., None]):
+ config_overrides(SERVICE_API_URL="https://example.com")
api = DatasetApiBaseUrlApi()
method = unwrap(api.get)
with (
app.test_request_context("/"),
- patch("controllers.console.datasets.datasets.dify_config.SERVICE_API_URL", "https://example.com"),
):
response = method(api)
assert response["api_base_url"] == "https://example.com/v1"
- def test_get_api_base_url_from_request(self, app: Flask):
+ def test_get_api_base_url_from_request(self, app: Flask, config_overrides: Callable[..., None]):
+ config_overrides(SERVICE_API_URL=None)
api = DatasetApiBaseUrlApi()
method = unwrap(api.get)
with (
app.test_request_context("http://localhost:5000/"),
- patch("controllers.console.datasets.datasets.dify_config.SERVICE_API_URL", None),
):
response = method(api)
assert response["api_base_url"] == "http://localhost:5000/v1"
- def test_get_api_base_url_no_double_v1(self, app: Flask):
+ def test_get_api_base_url_no_double_v1(self, app: Flask, config_overrides: Callable[..., None]):
+ config_overrides(SERVICE_API_URL="https://example.com/v1")
api = DatasetApiBaseUrlApi()
method = unwrap(api.get)
with (
app.test_request_context("/"),
- patch("controllers.console.datasets.datasets.dify_config.SERVICE_API_URL", "https://example.com/v1"),
):
response = method(api)
assert response["api_base_url"] == "https://example.com/v1"
class TestDatasetRetrievalSettingApi:
- def test_get_success(self, app: Flask):
+ def test_get_success(self, app: Flask, config_overrides: Callable[..., None]):
+ config_overrides(VECTOR_STORE="qdrant")
api = DatasetRetrievalSettingApi()
method = unwrap(api.get)
with (
app.test_request_context("/"),
- patch("controllers.console.datasets.datasets.dify_config.VECTOR_STORE", "qdrant"),
patch(
"controllers.console.datasets.datasets._get_retrieval_methods_by_vector_type",
return_value={"retrieval_method": ["semantic", "hybrid"]},
@@ -1556,21 +1565,15 @@ class TestDatasetRetrievalSettingApi:
response = method(api)
assert "retrieval_method" in response
- def test_tidb_vector_returns_semantic_only_when_fulltext_disabled(self):
- with patch(
- "controllers.console.datasets.datasets.dify_config.TIDB_VECTOR_ENABLE_FULLTEXT_SEARCH",
- False,
- ):
- response = _get_retrieval_methods_by_vector_type(VectorType.TIDB_VECTOR)
+ def test_tidb_vector_returns_semantic_only_when_fulltext_disabled(self, config_overrides: Callable[..., None]):
+ config_overrides(TIDB_VECTOR_ENABLE_FULLTEXT_SEARCH=False)
+ response = _get_retrieval_methods_by_vector_type(VectorType.TIDB_VECTOR)
assert response["retrieval_method"] == [RetrievalMethod.SEMANTIC_SEARCH.value]
- def test_tidb_vector_returns_full_methods_when_fulltext_enabled(self):
- with patch(
- "controllers.console.datasets.datasets.dify_config.TIDB_VECTOR_ENABLE_FULLTEXT_SEARCH",
- True,
- ):
- response = _get_retrieval_methods_by_vector_type(VectorType.TIDB_VECTOR)
+ def test_tidb_vector_returns_full_methods_when_fulltext_enabled(self, config_overrides: Callable[..., None]):
+ config_overrides(TIDB_VECTOR_ENABLE_FULLTEXT_SEARCH=True)
+ response = _get_retrieval_methods_by_vector_type(VectorType.TIDB_VECTOR)
assert response["retrieval_method"] == [
RetrievalMethod.SEMANTIC_SEARCH.value,
diff --git a/api/tests/unit_tests/controllers/console/test_apikey.py b/api/tests/unit_tests/controllers/console/test_apikey.py
index 06965e67021..5013ea58ffd 100644
--- a/api/tests/unit_tests/controllers/console/test_apikey.py
+++ b/api/tests/unit_tests/controllers/console/test_apikey.py
@@ -12,7 +12,6 @@ from sqlalchemy import event, select
from sqlalchemy.orm import Session
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
-from configs import dify_config
from controllers.console.agent.roster import AgentApiKeyListApi
from controllers.console.apikey import (
AppApiKeyListResource,
@@ -249,7 +248,12 @@ def test_delete_api_key_rejects_foreign_tenant_token(sqlite_session: Session) ->
assert session.get(ApiToken, "key-1") is api_key
-def test_api_key_lists_require_matching_rbac_permission() -> None:
+def test_api_key_lists_require_matching_rbac_permission(config_overrides: Callable[..., None]) -> None:
+ config_overrides(
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ LOGIN_DISABLED=True,
+ RBAC_ENABLED=True,
+ )
app = Flask(__name__)
account = _make_account(TenantAccountRole.OWNER)
api_id = UUID("00000000-0000-0000-0000-000000000001")
@@ -277,9 +281,6 @@ def test_api_key_lists_require_matching_rbac_permission() -> None:
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", True),
patch("controllers.console.wraps.current_account_with_tenant", return_value=(account, "tenant-1")),
patch("controllers.common.wraps.current_account_with_tenant", return_value=(account, "tenant-1")),
patch.object(BaseApiKeyListResource, "_get_api_key_list") as get_api_key_list,
@@ -300,7 +301,12 @@ def test_api_key_lists_require_matching_rbac_permission() -> None:
get_api_key_list.assert_not_called()
-def test_api_key_lists_reject_legacy_read_only_members() -> None:
+def test_api_key_lists_reject_legacy_read_only_members(config_overrides: Callable[..., None]) -> None:
+ config_overrides(
+ DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
+ LOGIN_DISABLED=True,
+ RBAC_ENABLED=False,
+ )
app = Flask(__name__)
account = _make_account(TenantAccountRole.NORMAL)
api_id = UUID("00000000-0000-0000-0000-000000000001")
@@ -310,9 +316,6 @@ def test_api_key_lists_reject_legacy_read_only_members() -> None:
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),
patch("libs.login.current_user", current_user),
patch("controllers.console.wraps.current_account_with_tenant", return_value=(account, "tenant-1")),
patch.object(BaseApiKeyListResource, "_get_api_key_list") as get_api_key_list,
diff --git a/api/tests/unit_tests/controllers/console/test_fastopenapi_setup.py b/api/tests/unit_tests/controllers/console/test_fastopenapi_setup.py
index 8018ed3c115..19fa4f47089 100644
--- a/api/tests/unit_tests/controllers/console/test_fastopenapi_setup.py
+++ b/api/tests/unit_tests/controllers/console/test_fastopenapi_setup.py
@@ -1,4 +1,5 @@
import builtins
+from collections.abc import Callable
from datetime import datetime
from types import SimpleNamespace
from unittest.mock import Mock, create_autospec
@@ -7,7 +8,6 @@ import pytest
from flask.views import MethodView
from controllers.console import setup as setup_controller
-from controllers.console import wraps
from controllers.console.error import AlreadySetupError, NotInitValidateError
from dify_app import DifyApp
from enums import DeploymentEdition
@@ -78,8 +78,9 @@ def test_console_setup_fastopenapi_post_success(
setup_service: Mock,
monkeypatch: pytest.MonkeyPatch,
deployment_edition: DeploymentEdition,
+ config_overrides: Callable[..., None],
) -> None:
- monkeypatch.setattr(wraps.dify_config, "DEPLOYMENT_EDITION", deployment_edition)
+ config_overrides(DEPLOYMENT_EDITION=deployment_edition)
monkeypatch.setattr(setup_controller, "is_init_validated", lambda: True)
mark_setup_completed = Mock()
monkeypatch.setattr(setup_controller, "mark_setup_completed", mark_setup_completed)
@@ -114,9 +115,9 @@ def test_console_setup_fastopenapi_post_success(
def test_console_setup_fastopenapi_post_rejects_cloud_edition(
app: DifyApp,
setup_service: Mock,
- monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
) -> None:
- monkeypatch.setattr(wraps.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
response = app.test_client().post(
"/console/api/setup",
@@ -167,10 +168,10 @@ def test_console_setup_fastopenapi_post_rejects_cloud_edition(
def test_console_setup_fastopenapi_post_rejects_invalid_payload_before_service_call(
app: DifyApp,
setup_service: Mock,
- monkeypatch: pytest.MonkeyPatch,
payload: dict[str, str],
+ config_overrides: Callable[..., None],
) -> None:
- monkeypatch.setattr(wraps.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
response = app.test_client().post("/console/api/setup", json=payload)
@@ -195,8 +196,9 @@ def test_console_setup_translates_service_errors_to_controller_errors(
monkeypatch: pytest.MonkeyPatch,
service_error: Exception,
expected_controller_error: type[Exception],
+ config_overrides: Callable[..., None],
) -> None:
- monkeypatch.setattr(wraps.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
monkeypatch.setattr(setup_controller, "is_init_validated", lambda: False)
mark_setup_completed = Mock()
monkeypatch.setattr(setup_controller, "mark_setup_completed", mark_setup_completed)
@@ -226,8 +228,9 @@ def test_console_setup_fastopenapi_does_not_mark_setup_completed_when_service_fa
app: DifyApp,
setup_service: Mock,
monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
) -> None:
- monkeypatch.setattr(wraps.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
monkeypatch.setattr(setup_controller, "is_init_validated", lambda: True)
mark_setup_completed = Mock()
monkeypatch.setattr(setup_controller, "mark_setup_completed", mark_setup_completed)
diff --git a/api/tests/unit_tests/controllers/console/test_knowledge_fs_proxy.py b/api/tests/unit_tests/controllers/console/test_knowledge_fs_proxy.py
index 1a00bb7a508..1bcb8f7182a 100644
--- a/api/tests/unit_tests/controllers/console/test_knowledge_fs_proxy.py
+++ b/api/tests/unit_tests/controllers/console/test_knowledge_fs_proxy.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import gzip
+from collections.abc import Callable
from inspect import unwrap
from unittest.mock import MagicMock
@@ -44,8 +45,8 @@ from services.knowledge_fs_proxy import (
@pytest.fixture(autouse=True)
-def enable_knowledge_fs(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr("controllers.console.knowledge_fs_proxy.dify_config.KNOWLEDGE_FS_ENABLED", True)
+def enable_knowledge_fs(config_overrides: Callable[..., None]) -> None:
+ config_overrides(KNOWLEDGE_FS_ENABLED=True)
def _upstream(
@@ -148,9 +149,9 @@ def test_proxy_options_does_not_require_an_authenticated_account(app: Flask) ->
def test_proxy_options_is_hidden_when_knowledge_fs_is_disabled(
app: Flask,
- monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
) -> None:
- monkeypatch.setattr("controllers.console.knowledge_fs_proxy.dify_config.KNOWLEDGE_FS_ENABLED", False)
+ config_overrides(KNOWLEDGE_FS_ENABLED=False)
with app.test_request_context(
"/console/api/knowledge-fs/knowledge-spaces",
@@ -186,8 +187,8 @@ def test_proxy_options_hides_unregistered_operations(
assert response.status_code == 404
-def test_proxy_is_hidden_when_knowledge_fs_is_disabled(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr("controllers.console.knowledge_fs_proxy.dify_config.KNOWLEDGE_FS_ENABLED", False)
+def test_proxy_is_hidden_when_knowledge_fs_is_disabled(app: Flask, config_overrides: Callable[..., None]) -> None:
+ config_overrides(KNOWLEDGE_FS_ENABLED=False)
with app.test_request_context("/console/api/knowledge-fs/knowledge-spaces", method="GET"):
with pytest.raises(NotFound):
@@ -204,10 +205,11 @@ def test_proxy_is_hidden_when_knowledge_fs_is_disabled(app: Flask, monkeypatch:
def test_proxy_routes_are_hidden_before_downstream_work_when_disabled(
app: Flask,
monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
route,
method: KnowledgeFSMethod,
) -> None:
- monkeypatch.setattr("controllers.console.knowledge_fs_proxy.dify_config.KNOWLEDGE_FS_ENABLED", False)
+ config_overrides(KNOWLEDGE_FS_ENABLED=False)
proxy_request = MagicMock()
proxy_non_get = MagicMock()
monkeypatch.setattr("controllers.console.knowledge_fs_proxy._proxy_request", proxy_request)
@@ -290,8 +292,9 @@ def test_generic_routes_delegate_to_the_authorized_service_use_case(
def test_read_post_applies_knowledge_rate_limit_once(
app: Flask,
monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
) -> None:
- monkeypatch.setattr("controllers.common.wraps.dify_config.RBAC_ENABLED", False)
+ config_overrides(RBAC_ENABLED=False)
account = Account(name="Knowledge User", email="[email protected]")
account.id = "account-1"
account.role = TenantAccountRole.DATASET_OPERATOR
@@ -469,7 +472,12 @@ def test_generic_write_forwards_path_raw_body_and_current_tenant(
def test_generic_write_forwards_through_the_authorized_production_path(
app: Flask,
monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
) -> None:
+ config_overrides(
+ KNOWLEDGE_FS_BASE_URL="http://knowledge-fs.test",
+ KNOWLEDGE_FS_JWT_SECRET=SecretStr("production-secret-with-at-least-32-bytes"),
+ )
account = Account(name="Knowledge User", email="[email protected]")
account.id = "account-1"
account.role = TenantAccountRole.DATASET_OPERATOR
@@ -485,16 +493,6 @@ def test_generic_write_forwards_through_the_authorized_production_path(
"controllers.console.wraps.FeatureService.get_knowledge_rate_limit",
MagicMock(return_value=MagicMock(enabled=False)),
)
- monkeypatch.setattr(
- "services.knowledge_fs_proxy.dify_config.KNOWLEDGE_FS_BASE_URL",
- "http://knowledge-fs.test",
- raising=False,
- )
- monkeypatch.setattr(
- "services.knowledge_fs_proxy.dify_config.KNOWLEDGE_FS_JWT_SECRET",
- SecretStr("production-secret-with-at-least-32-bytes"),
- raising=False,
- )
upstream_request = MagicMock(
return_value=httpx.Response(
201,
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py b/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py
index bc963f7065d..c205f931cc6 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import builtins
import importlib
+from collections.abc import Callable
from contextlib import ExitStack, contextmanager
from inspect import unwrap
from types import ModuleType
@@ -40,7 +41,7 @@ def app() -> Flask:
@pytest.fixture
-def controller_module(monkeypatch: pytest.MonkeyPatch):
+def controller_module(monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]):
"""
Import the controller with auth decorators neutralized only during import.
@@ -74,8 +75,7 @@ def controller_module(monkeypatch: pytest.MonkeyPatch):
global _WRAPS_MODULE
wraps_module = importlib.import_module("controllers.console.wraps")
_WRAPS_MODULE = wraps_module
- monkeypatch.setattr(module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
- monkeypatch.setattr(wraps_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
login_module = importlib.import_module("libs.login")
monkeypatch.setattr(login_module, "check_csrf_token", lambda *args, **kwargs: None)
@@ -718,20 +718,24 @@ def test_tool_labels_list(app: Flask, controller_module, monkeypatch: pytest.Mon
# --- _resolve_identity_mode: gating + None-resolution (PR #36839 review) ---
-def test_resolve_identity_mode_none_keeps_current_when_enterprise(controller_module, monkeypatch: pytest.MonkeyPatch):
+def test_resolve_identity_mode_none_keeps_current_when_enterprise(
+ controller_module, config_overrides: Callable[..., None]
+):
"""None means 'leave unchanged' — fall back to the stored mode (update path)."""
identity_mode = importlib.import_module("core.entities.mcp_provider").IdentityMode
- monkeypatch.setattr(controller_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
resolved = controller_module._resolve_identity_mode(None, current=identity_mode.IDP_TOKEN)
assert resolved == identity_mode.IDP_TOKEN
-def test_resolve_identity_mode_explicit_value_overrides_current(controller_module, monkeypatch: pytest.MonkeyPatch):
+def test_resolve_identity_mode_explicit_value_overrides_current(
+ controller_module, config_overrides: Callable[..., None]
+):
"""An explicit value wins over the stored mode."""
identity_mode = importlib.import_module("core.entities.mcp_provider").IdentityMode
- monkeypatch.setattr(controller_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
resolved = controller_module._resolve_identity_mode(identity_mode.OFF, current=identity_mode.IDP_TOKEN)
@@ -739,12 +743,12 @@ def test_resolve_identity_mode_explicit_value_overrides_current(controller_modul
def test_resolve_identity_mode_coerces_non_off_to_off_when_not_enterprise(
- controller_module, monkeypatch: pytest.MonkeyPatch
+ controller_module, config_overrides: Callable[..., None]
):
"""Gate: a non-EE deployment must never persist a non-OFF mode — the
runtime won't forward, so the stored row must not imply it does."""
identity_mode = importlib.import_module("core.entities.mcp_provider").IdentityMode
- monkeypatch.setattr(controller_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
# Both an explicit idp_token request AND an inherited non-OFF current
# must collapse to OFF.
@@ -756,11 +760,11 @@ def test_resolve_identity_mode_coerces_non_off_to_off_when_not_enterprise(
def test_resolve_identity_mode_off_is_passthrough_when_not_enterprise(
- controller_module, monkeypatch: pytest.MonkeyPatch
+ controller_module, config_overrides: Callable[..., None]
):
"""OFF is always fine — the gate only neutralizes non-OFF values."""
identity_mode = importlib.import_module("core.entities.mcp_provider").IdentityMode
- monkeypatch.setattr(controller_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
assert controller_module._resolve_identity_mode(None, current=identity_mode.OFF) == identity_mode.OFF
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py b/api/tests/unit_tests/controllers/service_api/app/test_workflow.py
index c1cf3539477..f91a9ca35f2 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_workflow.py
@@ -16,6 +16,7 @@ Focus on:
import json
import sys
import uuid
+from collections.abc import Callable
from datetime import UTC, datetime
from inspect import unwrap
from types import SimpleNamespace
@@ -582,10 +583,14 @@ class TestWorkflowRunApi:
handler(api, session=sqlite_session, app_model=app_model, end_user=end_user)
def test_sandbox_billing_does_not_gate_default_workflow_run(
- self, app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
+ self,
+ app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ sqlite_session: Session,
+ config_overrides: Callable[..., None],
) -> None:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
workflow_module = sys.modules["controllers.service_api.app.workflow"]
- monkeypatch.setattr(workflow_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
billing_get_info = Mock(return_value={"enabled": True, "subscription": {"plan": CloudPlan.SANDBOX}})
generate = Mock(return_value={"result": "ok"})
@@ -610,10 +615,14 @@ class TestWorkflowRunApi:
class TestWorkflowRunByIdApi:
def test_rejects_sandbox_plan_with_upgrade_error(
- self, app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
+ self,
+ app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ sqlite_session: Session,
+ config_overrides: Callable[..., None],
) -> None:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
workflow_module = sys.modules["controllers.service_api.app.workflow"]
- monkeypatch.setattr(workflow_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
billing_get_info = Mock(return_value={"enabled": True, "subscription": {"plan": CloudPlan.SANDBOX}})
generate = Mock()
@@ -664,9 +673,9 @@ class TestWorkflowRunByIdApi:
billing_enabled: bool,
plan: CloudPlan,
sqlite_session: Session,
+ config_overrides: Callable[..., None],
) -> None:
- workflow_module = sys.modules["controllers.service_api.app.workflow"]
- monkeypatch.setattr(workflow_module.dify_config, "DEPLOYMENT_EDITION", deployment_edition)
+ config_overrides(DEPLOYMENT_EDITION=deployment_edition)
billing_get_info = Mock(return_value={"enabled": billing_enabled, "subscription": {"plan": plan}})
generate = Mock(return_value={"result": "ok"})
@@ -694,9 +703,15 @@ class TestWorkflowRunByIdApi:
billing_get_info.assert_not_called()
@pytest.mark.parametrize("sqlite_session", [()], indirect=True)
- def test_not_found(self, app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
+ def test_not_found(
+ self,
+ app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ sqlite_session: Session,
+ config_overrides: Callable[..., None],
+ ) -> None:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
workflow_module = sys.modules["controllers.service_api.app.workflow"]
- monkeypatch.setattr(workflow_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
monkeypatch.setattr(
AppGenerateService,
"generate",
@@ -713,9 +728,15 @@ class TestWorkflowRunByIdApi:
handler(api, session=sqlite_session, app_model=app_model, end_user=end_user, workflow_id="w1")
@pytest.mark.parametrize("sqlite_session", [()], indirect=True)
- def test_draft_workflow(self, app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
+ def test_draft_workflow(
+ self,
+ app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ sqlite_session: Session,
+ config_overrides: Callable[..., None],
+ ) -> None:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
workflow_module = sys.modules["controllers.service_api.app.workflow"]
- monkeypatch.setattr(workflow_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
monkeypatch.setattr(
AppGenerateService,
"generate",
diff --git a/api/tests/unit_tests/core/plugin/test_model_runtime_adapter.py b/api/tests/unit_tests/core/plugin/test_model_runtime_adapter.py
index a436116f838..0a2646a7c7a 100644
--- a/api/tests/unit_tests/core/plugin/test_model_runtime_adapter.py
+++ b/api/tests/unit_tests/core/plugin/test_model_runtime_adapter.py
@@ -2,6 +2,7 @@
import datetime
import uuid
+from collections.abc import Callable
from types import SimpleNamespace
from unittest.mock import MagicMock, Mock, patch, sentinel
@@ -484,7 +485,9 @@ class TestPluginModelRuntime:
voice="alloy",
)
- def test_fetch_model_providers_does_not_keep_bound_runtime_cache(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ def test_fetch_model_providers_does_not_keep_bound_runtime_cache(
+ self, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+ ) -> None:
client = Mock(spec=PluginModelClient)
client.fetch_model_providers.return_value = []
from core.plugin import plugin_service as plugin_service_module
@@ -500,7 +503,7 @@ class TestPluginModelRuntime:
lock=Mock(return_value=MagicMock()),
),
)
- monkeypatch.setattr(plugin_service_module.dify_config, "PLUGIN_MODEL_PROVIDERS_CACHE_TTL", 0)
+ config_overrides(PLUGIN_MODEL_PROVIDERS_CACHE_TTL=0)
runtime = PluginModelRuntime(tenant_id="tenant", user_id="user", client=client, plugin_service=PluginService)
runtime.fetch_model_providers()
@@ -509,13 +512,13 @@ class TestPluginModelRuntime:
assert client.fetch_model_providers.call_count == 2
def test_fetch_model_providers_uses_tenant_ttl_cache_across_runtime_instances(
- self, monkeypatch: pytest.MonkeyPatch
+ self, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
) -> None:
+ config_overrides(PLUGIN_MODEL_PROVIDERS_CACHE_TTL=300)
redis = _FakeRedis()
from core.plugin import plugin_service as plugin_service_module
monkeypatch.setattr(plugin_service_module, "redis_client", redis)
- monkeypatch.setattr(plugin_service_module.dify_config, "PLUGIN_MODEL_PROVIDERS_CACHE_TTL", 300)
first_client = Mock(spec=PluginModelClient)
first_client.fetch_model_providers.return_value = [_build_plugin_model_provider(tenant_id="tenant")]
second_client = Mock(spec=PluginModelClient)
@@ -535,12 +538,14 @@ class TestPluginModelRuntime:
second_client.fetch_model_providers.assert_not_called()
assert redis.setex_calls[0][1] == 300
- def test_fetch_model_providers_cache_is_tenant_isolated(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ def test_fetch_model_providers_cache_is_tenant_isolated(
+ self, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+ ) -> None:
+ config_overrides(PLUGIN_MODEL_PROVIDERS_CACHE_TTL=300)
redis = _FakeRedis()
from core.plugin import plugin_service as plugin_service_module
monkeypatch.setattr(plugin_service_module, "redis_client", redis)
- monkeypatch.setattr(plugin_service_module.dify_config, "PLUGIN_MODEL_PROVIDERS_CACHE_TTL", 300)
first_client = Mock(spec=PluginModelClient)
first_client.fetch_model_providers.return_value = [_build_plugin_model_provider(tenant_id="tenant-a")]
second_client = Mock(spec=PluginModelClient)
@@ -758,7 +763,10 @@ def test_invoke_llm_with_structured_output_raises_when_model_schema_is_missing()
)
-def test_get_model_schema_deletes_invalid_cache_and_refetches(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_get_model_schema_deletes_invalid_cache_and_refetches(
+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+) -> None:
+ config_overrides(PLUGIN_MODEL_SCHEMA_CACHE_TTL=300)
client = Mock(spec=PluginModelClient)
schema = _build_model_schema()
delete = Mock()
@@ -772,7 +780,6 @@ def test_get_model_schema_deletes_invalid_cache_and_refetches(monkeypatch: pytes
setex=setex,
),
)
- monkeypatch.setattr(model_runtime_module.dify_config, "PLUGIN_MODEL_SCHEMA_CACHE_TTL", 300)
client.get_model_schema.return_value = schema
runtime = PluginModelRuntime(tenant_id="tenant", user_id="user", client=client, plugin_service=PluginService)
@@ -797,9 +804,11 @@ def test_get_model_schema_deletes_invalid_cache_and_refetches(monkeypatch: pytes
setex.assert_called_once()
-def test_get_llm_num_tokens_returns_zero_when_plugin_counting_is_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_get_llm_num_tokens_returns_zero_when_plugin_counting_is_disabled(
+ config_overrides: Callable[..., None],
+) -> None:
client = Mock(spec=PluginModelClient)
- monkeypatch.setattr(model_runtime_module.dify_config, "PLUGIN_BASED_TOKEN_COUNTING_ENABLED", False)
+ config_overrides(PLUGIN_BASED_TOKEN_COUNTING_ENABLED=False)
runtime = PluginModelRuntime(tenant_id="tenant", user_id="user", client=client, plugin_service=PluginService)
assert (
diff --git a/api/tests/unit_tests/extensions/otel/decorators/test_base.py b/api/tests/unit_tests/extensions/otel/decorators/test_base.py
index a42f861bb7a..5d8c8620ebd 100644
--- a/api/tests/unit_tests/extensions/otel/decorators/test_base.py
+++ b/api/tests/unit_tests/extensions/otel/decorators/test_base.py
@@ -8,7 +8,7 @@ Test coverage:
- Integration with OpenTelemetry SDK
"""
-from unittest.mock import patch
+from collections.abc import Callable
import pytest
from opentelemetry.trace import StatusCode
@@ -16,10 +16,14 @@ from opentelemetry.trace import StatusCode
from extensions.otel.decorators.base import trace_span
[email protected](autouse=True)
+def _otel_enabled(config_overrides: Callable[..., None]) -> None:
+ config_overrides(ENABLE_OTEL=True)
+
+
class TestTraceSpanDecorator:
"""Test trace_span decorator basic functionality."""
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_decorated_function_executes_normally(self, tracer_provider_with_memory_exporter):
"""Test that decorated function executes and returns correct value."""
@@ -30,7 +34,6 @@ class TestTraceSpanDecorator:
result = test_func(2, 3)
assert result == 5
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_decorator_with_args_and_kwargs(self, tracer_provider_with_memory_exporter):
"""Test that decorator correctly handles args and kwargs."""
@@ -45,7 +48,6 @@ class TestTraceSpanDecorator:
class TestTraceSpanWithMemoryExporter:
"""Test trace_span with MemorySpanExporter to verify span creation."""
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_span_is_created_and_exported(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that span is created and exported to memory exporter."""
@@ -58,7 +60,6 @@ class TestTraceSpanWithMemoryExporter:
spans = memory_span_exporter.get_finished_spans()
assert len(spans) == 1
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_span_name_matches_function(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that span name matches the decorated function."""
@@ -72,7 +73,6 @@ class TestTraceSpanWithMemoryExporter:
assert len(spans) == 1
assert "my_test_function" in spans[0].name
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_span_status_is_ok_on_success(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that span status is OK when function succeeds."""
@@ -86,7 +86,6 @@ class TestTraceSpanWithMemoryExporter:
assert len(spans) == 1
assert spans[0].status.status_code == StatusCode.OK
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_span_status_is_error_on_exception(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that span status is ERROR when function raises exception."""
@@ -101,7 +100,6 @@ class TestTraceSpanWithMemoryExporter:
assert len(spans) == 1
assert spans[0].status.status_code == StatusCode.ERROR
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_exception_is_recorded_in_span(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that exception details are recorded in span events."""
diff --git a/api/tests/unit_tests/extensions/otel/decorators/test_handler.py b/api/tests/unit_tests/extensions/otel/decorators/test_handler.py
index bf861e3ef7b..e59f71deb9a 100644
--- a/api/tests/unit_tests/extensions/otel/decorators/test_handler.py
+++ b/api/tests/unit_tests/extensions/otel/decorators/test_handler.py
@@ -8,7 +8,7 @@ Test coverage:
- Signature caching
"""
-from unittest.mock import patch
+from collections.abc import Callable
import pytest
from opentelemetry.trace import StatusCode
@@ -16,6 +16,11 @@ from opentelemetry.trace import StatusCode
from extensions.otel.decorators.handler import SpanHandler
[email protected](autouse=True)
+def _otel_enabled(config_overrides: Callable[..., None]) -> None:
+ config_overrides(ENABLE_OTEL=True)
+
+
class TestSpanHandlerExtractArguments:
"""Test SpanHandler._extract_arguments method."""
@@ -133,7 +138,6 @@ class TestSpanHandlerExtractArguments:
class TestSpanHandlerWrapper:
"""Test SpanHandler.wrapper default implementation."""
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_wrapper_creates_span(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that wrapper creates a span."""
handler = SpanHandler()
@@ -148,7 +152,6 @@ class TestSpanHandlerWrapper:
spans = memory_span_exporter.get_finished_spans()
assert len(spans) == 1
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_wrapper_sets_span_kind_internal(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that wrapper sets SpanKind to INTERNAL."""
from opentelemetry.trace import SpanKind
@@ -165,7 +168,6 @@ class TestSpanHandlerWrapper:
assert len(spans) == 1
assert spans[0].kind == SpanKind.INTERNAL
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_wrapper_sets_status_ok_on_success(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that wrapper sets status to OK when function succeeds."""
handler = SpanHandler()
@@ -180,7 +182,6 @@ class TestSpanHandlerWrapper:
assert len(spans) == 1
assert spans[0].status.status_code == StatusCode.OK
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_wrapper_records_exception_on_error(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that wrapper records exception when function raises."""
handler = SpanHandler()
@@ -198,7 +199,6 @@ class TestSpanHandlerWrapper:
assert len(events) > 0
assert any("exception" in event.name.lower() for event in events)
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_wrapper_sets_status_error_on_exception(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that wrapper sets status to ERROR when function raises exception."""
handler = SpanHandler()
@@ -215,7 +215,6 @@ class TestSpanHandlerWrapper:
assert spans[0].status.status_code == StatusCode.ERROR
assert "test error" in spans[0].status.description
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_wrapper_re_raises_exception(self, tracer_provider_with_memory_exporter):
"""Test that wrapper re-raises exception after recording it."""
handler = SpanHandler()
@@ -227,7 +226,6 @@ class TestSpanHandlerWrapper:
with pytest.raises(ValueError, match="test error"):
handler.wrapper(tracer, test_func)
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_wrapper_passes_arguments_correctly(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test that wrapper correctly passes arguments to wrapped function."""
handler = SpanHandler()
@@ -240,7 +238,6 @@ class TestSpanHandlerWrapper:
assert result == 6
- @patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True)
def test_wrapper_with_memory_exporter(self, tracer_provider_with_memory_exporter, memory_span_exporter):
"""Test wrapper end-to-end with memory exporter."""
handler = SpanHandler()
diff --git a/api/tests/unit_tests/extensions/otel/test_retrieval_tracing.py b/api/tests/unit_tests/extensions/otel/test_retrieval_tracing.py
index 824028316fe..09f0d9dc4ff 100644
--- a/api/tests/unit_tests/extensions/otel/test_retrieval_tracing.py
+++ b/api/tests/unit_tests/extensions/otel/test_retrieval_tracing.py
@@ -1,7 +1,9 @@
import threading
+from collections.abc import Callable
from unittest.mock import MagicMock, patch
from uuid import uuid4
+import pytest
from opentelemetry.trace import StatusCode, get_current_span, get_tracer
from core.rag.rerank.rerank_type import RerankMode
@@ -10,6 +12,11 @@ from core.workflow.nodes.knowledge_retrieval.retrieval import KnowledgeRetrieval
from models.dataset import Dataset
[email protected](autouse=True)
+def _otel_enabled(config_overrides: Callable[..., None]) -> None:
+ config_overrides(ENABLE_OTEL=True)
+
+
def test_knowledge_retrieval_creates_a_child_otel_span(
memory_span_exporter,
tracer_provider_with_memory_exporter,
@@ -27,7 +34,6 @@ def test_knowledge_retrieval_creates_a_child_otel_span(
retrieval = DatasetRetrieval()
with (
- patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True),
patch.object(retrieval, "_check_knowledge_rate_limit"),
patch.object(retrieval, "_get_available_datasets", return_value=[]),
get_tracer(__name__).start_as_current_span("knowledge-retrieval-node") as node_span,
@@ -64,7 +70,6 @@ def test_multiple_retrieve_preserves_otel_context_in_dataset_thread(
with (
app.app_context(),
- patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True),
patch.object(retrieval, "_multiple_retrieve_thread", side_effect=record_active_trace),
patch.object(retrieval, "_on_query"),
get_tracer(__name__).start_as_current_span("knowledge-retrieval-node") as node_span,
@@ -96,7 +101,6 @@ def test_retriever_thread_exception_sets_error_span_and_is_collected(
expected_error = RuntimeError("retrieval failed")
with (
- patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True),
patch("core.rag.retrieval.dataset_retrieval.session_factory.create_session"),
patch.object(retrieval, "_retriever", side_effect=expected_error),
):
@@ -135,7 +139,6 @@ def test_retriever_thread_exception_emits_skip_event_when_requested(
dataset_id = str(uuid4())
with (
- patch("extensions.otel.decorators.base.dify_config.ENABLE_OTEL", True),
patch("core.rag.retrieval.dataset_retrieval.session_factory.create_session"),
patch.object(retrieval, "_retriever", side_effect=expected_error),
get_tracer(__name__).start_as_current_span("dataset-retrieval-parent") as parent_span,
diff --git a/api/tests/unit_tests/extensions/test_ext_login.py b/api/tests/unit_tests/extensions/test_ext_login.py
index d58e7f52e56..1125d2311ad 100644
--- a/api/tests/unit_tests/extensions/test_ext_login.py
+++ b/api/tests/unit_tests/extensions/test_ext_login.py
@@ -1,4 +1,5 @@
import json
+from collections.abc import Callable
from typing import cast
from unittest import mock
@@ -89,7 +90,7 @@ def test_on_user_logged_in_logs_unsupported_user_type(caplog: pytest.LogCaptureF
def test_admin_api_key_header_takes_precedence_over_console_cookie(
- monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
+ sqlite_session: Session, config_overrides: Callable[..., None]
) -> None:
app = Flask(__name__)
tenant = ext_login.Tenant(name="Test Tenant")
@@ -104,11 +105,13 @@ def test_admin_api_key_header_takes_precedence_over_console_cookie(
)
sqlite_session.add(tenant_account_join)
sqlite_session.commit()
- monkeypatch.setattr(ext_login.dify_config, "ADMIN_API_KEY_ENABLE", True)
- monkeypatch.setattr(ext_login.dify_config, "ADMIN_API_KEY", "admin-key")
- monkeypatch.setattr(ext_login.dify_config, "CONSOLE_WEB_URL", "http://console.example.com")
- monkeypatch.setattr(ext_login.dify_config, "CONSOLE_API_URL", "http://api.example.com")
- monkeypatch.setattr(ext_login.dify_config, "COOKIE_DOMAIN", "")
+ config_overrides(
+ ADMIN_API_KEY_ENABLE=True,
+ ADMIN_API_KEY="admin-key",
+ CONSOLE_WEB_URL="http://console.example.com",
+ CONSOLE_API_URL="http://api.example.com",
+ COOKIE_DOMAIN="",
+ )
with app.test_request_context(
"/console/api/test",
diff --git a/api/tests/unit_tests/extensions/test_ext_socketio.py b/api/tests/unit_tests/extensions/test_ext_socketio.py
index a5851b80932..d61d520fb6f 100644
--- a/api/tests/unit_tests/extensions/test_ext_socketio.py
+++ b/api/tests/unit_tests/extensions/test_ext_socketio.py
@@ -1,6 +1,6 @@
import ssl
+from collections.abc import Callable
-import pytest
import socketio
from configs import dify_config
@@ -11,9 +11,10 @@ def test_socketio_server_uses_redis_manager() -> None:
assert isinstance(ext_socketio.sio.manager, socketio.RedisManager)
-def test_create_socketio_client_manager_uses_pubsub_url_and_prefixed_channel(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(ext_socketio.dify_config, "PUBSUB_REDIS_URL", "redis://redis.example.com:6380/3")
- monkeypatch.setattr(ext_socketio.dify_config, "REDIS_KEY_PREFIX", "tenant-a")
+def test_create_socketio_client_manager_uses_pubsub_url_and_prefixed_channel(
+ config_overrides: Callable[..., None],
+) -> None:
+ config_overrides(PUBSUB_REDIS_URL="redis://redis.example.com:6380/3", REDIS_KEY_PREFIX="tenant-a")
manager = ext_socketio.create_socketio_client_manager()
@@ -21,11 +22,13 @@ def test_create_socketio_client_manager_uses_pubsub_url_and_prefixed_channel(mon
assert manager.channel == "tenant-a:socketio"
-def test_build_redis_options_includes_tls_options_for_rediss(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(ext_socketio.dify_config, "REDIS_SSL_CERT_REQS", "CERT_REQUIRED")
- monkeypatch.setattr(ext_socketio.dify_config, "REDIS_SSL_CA_CERTS", "/ca.pem")
- monkeypatch.setattr(ext_socketio.dify_config, "REDIS_SSL_CERTFILE", "/cert.pem")
- monkeypatch.setattr(ext_socketio.dify_config, "REDIS_SSL_KEYFILE", "/key.pem")
+def test_build_redis_options_includes_tls_options_for_rediss(config_overrides: Callable[..., None]) -> None:
+ config_overrides(
+ REDIS_SSL_CERT_REQS="CERT_REQUIRED",
+ REDIS_SSL_CA_CERTS="/ca.pem",
+ REDIS_SSL_CERTFILE="/cert.pem",
+ REDIS_SSL_KEYFILE="/key.pem",
+ )
options = ext_socketio._build_redis_options("rediss://redis.example.com:6380/3")
@@ -35,11 +38,11 @@ def test_build_redis_options_includes_tls_options_for_rediss(monkeypatch: pytest
assert options["ssl_keyfile"] == "/key.pem"
-def test_build_redis_options_omits_socket_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_build_redis_options_omits_socket_timeout(config_overrides: Callable[..., None]) -> None:
# socket_timeout must not be passed to RedisManager because the pub/sub
# listen loop blocks indefinitely between messages; a read timeout there
# triggers an infinite reconnect storm (issue #39423).
- monkeypatch.setattr(ext_socketio.dify_config, "REDIS_SOCKET_TIMEOUT", 5.0)
+ config_overrides(REDIS_SOCKET_TIMEOUT=5.0)
options = ext_socketio._build_redis_options("redis://redis.example.com:6380/3")
diff --git a/api/tests/unit_tests/libs/key_providers/test_azure_keyvault_key_provider.py b/api/tests/unit_tests/libs/key_providers/test_azure_keyvault_key_provider.py
index 748785371f7..cd8962e5b4f 100644
--- a/api/tests/unit_tests/libs/key_providers/test_azure_keyvault_key_provider.py
+++ b/api/tests/unit_tests/libs/key_providers/test_azure_keyvault_key_provider.py
@@ -8,6 +8,7 @@ decryption of tokens encrypted before the rotation.
import datetime
import json
+from collections.abc import Callable
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -15,7 +16,6 @@ import pytest
from azure.core.exceptions import HttpResponseError
from azure.keyvault.keys import KeyRotationPolicy
-from configs import dify_config
from libs.key_providers.azure_keyvault_key_provider import AzureKeyVaultKeyProvider
@@ -120,15 +120,17 @@ def fake_key_client(monkeypatch: pytest.MonkeyPatch) -> FakeKeyClient:
@pytest.fixture(autouse=True)
-def azure_keyvault_config(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(dify_config, "AZURE_KEYVAULT_VAULT_URL", "https://fake-vault.vault.azure.net")
- monkeypatch.setattr(dify_config, "AZURE_KEYVAULT_KEY_SIZE", 2048)
- monkeypatch.setattr(dify_config, "AZURE_KEYVAULT_ROTATION_INTERVAL_DAYS", None)
+def azure_keyvault_config(config_overrides: Callable[..., None]) -> None:
+ config_overrides(
+ AZURE_KEYVAULT_VAULT_URL="https://fake-vault.vault.azure.net",
+ AZURE_KEYVAULT_KEY_SIZE=2048,
+ AZURE_KEYVAULT_ROTATION_INTERVAL_DAYS=None,
+ )
@pytest.mark.usefixtures("fake_key_client")
-def test_missing_vault_url_raises(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(dify_config, "AZURE_KEYVAULT_VAULT_URL", None)
+def test_missing_vault_url_raises(config_overrides: Callable[..., None]) -> None:
+ config_overrides(AZURE_KEYVAULT_VAULT_URL=None)
with pytest.raises(ValueError, match="AZURE_KEYVAULT_VAULT_URL"):
AzureKeyVaultKeyProvider()
@@ -182,9 +184,9 @@ def test_generate_key_pair_without_rotation_interval_does_not_set_policy(fake_ke
def test_generate_key_pair_with_rotation_interval_sets_time_after_create_only(
- monkeypatch: pytest.MonkeyPatch, fake_key_client: FakeKeyClient
+ config_overrides: Callable[..., None], fake_key_client: FakeKeyClient
) -> None:
- monkeypatch.setattr(dify_config, "AZURE_KEYVAULT_ROTATION_INTERVAL_DAYS", 30)
+ config_overrides(AZURE_KEYVAULT_ROTATION_INTERVAL_DAYS=30)
provider = AzureKeyVaultKeyProvider()
provider.generate_key_pair("tenant-1")
diff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.py
index 9b76c0938c4..18c16d5bfc1 100644
--- a/api/tests/unit_tests/services/test_app_dsl_service.py
+++ b/api/tests/unit_tests/services/test_app_dsl_service.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from types import SimpleNamespace
from typing import cast
from unittest.mock import Mock
@@ -528,8 +529,10 @@ def test_export_dsl_loads_model_config_and_annotation_reply_with_request_session
load_annotation_reply_config.assert_called_once_with(service_session, app_id)
-def test_ensure_agent_manage_permission_noops_when_rbac_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr("services.app_dsl_service.dify_config.RBAC_ENABLED", False)
+def test_ensure_agent_manage_permission_noops_when_rbac_disabled(
+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+) -> None:
+ config_overrides(RBAC_ENABLED=False)
check = Mock()
monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", check)
@@ -538,8 +541,10 @@ def test_ensure_agent_manage_permission_noops_when_rbac_disabled(monkeypatch: py
check.assert_not_called()
-def test_ensure_agent_manage_permission_allows_agent_manager(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr("services.app_dsl_service.dify_config.RBAC_ENABLED", True)
+def test_ensure_agent_manage_permission_allows_agent_manager(
+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+) -> None:
+ config_overrides(RBAC_ENABLED=True)
check = Mock(return_value=True)
monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", check)
@@ -548,8 +553,10 @@ def test_ensure_agent_manage_permission_allows_agent_manager(monkeypatch: pytest
check.assert_called_once_with("tenant-1", "account-1", scene=RBACPermission.AGENT_MANAGE)
-def test_ensure_agent_manage_permission_rejects_without_agent_manage(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr("services.app_dsl_service.dify_config.RBAC_ENABLED", True)
+def test_ensure_agent_manage_permission_rejects_without_agent_manage(
+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+) -> None:
+ config_overrides(RBAC_ENABLED=True)
monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", Mock(return_value=False))
with pytest.raises(NoPermissionError):
@@ -557,9 +564,11 @@ def test_ensure_agent_manage_permission_rejects_without_agent_manage(monkeypatch
def test_create_or_update_app_gates_agent_mode_before_creation(
- monkeypatch: pytest.MonkeyPatch, unbound_session: Session
+ monkeypatch: pytest.MonkeyPatch,
+ unbound_session: Session,
+ config_overrides: Callable[..., None],
) -> None:
- monkeypatch.setattr("services.app_dsl_service.dify_config.RBAC_ENABLED", True)
+ config_overrides(RBAC_ENABLED=True)
monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", Mock(return_value=False))
service = AppDslService(session=unbound_session)
@@ -574,9 +583,11 @@ def test_create_or_update_app_gates_agent_mode_before_creation(
def test_import_app_reraises_permission_denial_instead_of_failed_result(
- monkeypatch: pytest.MonkeyPatch, unbound_session: Session
+ monkeypatch: pytest.MonkeyPatch,
+ unbound_session: Session,
+ config_overrides: Callable[..., None],
) -> None:
- monkeypatch.setattr("services.app_dsl_service.dify_config.RBAC_ENABLED", True)
+ config_overrides(RBAC_ENABLED=True)
monkeypatch.setattr("services.app_dsl_service.RBACService.CheckAccess.check", Mock(return_value=False))
service = AppDslService(session=unbound_session)
diff --git a/api/tests/unit_tests/services/test_dataset_service_dataset.py b/api/tests/unit_tests/services/test_dataset_service_dataset.py
index 0d855f1d6ea..f20946f4e91 100644
--- a/api/tests/unit_tests/services/test_dataset_service_dataset.py
+++ b/api/tests/unit_tests/services/test_dataset_service_dataset.py
@@ -270,7 +270,9 @@ class TestDatasetServiceRetrieval:
assert DatasetService.get_dataset_for_tenant(owned.id, "tenant-1", session=sqlite_session) is owned
assert DatasetService.get_dataset_for_tenant(foreign.id, "tenant-1", session=sqlite_session) is None
- def test_get_datasets_applies_rbac_resource_scope_and_maintainer_override(self, sqlite_session: Session) -> None:
+ def test_get_datasets_applies_rbac_resource_scope_and_maintainer_override(
+ self, config_overrides: Callable[..., None], sqlite_session: Session
+ ) -> None:
user = _account(role=TenantAccountRole.NORMAL)
accessible = _dataset(dataset_id="accessible", name="Accessible", maintainer="other")
owned = _dataset(dataset_id="owned", name="Owned", maintainer=user.id)
@@ -279,8 +281,9 @@ class TestDatasetServiceRetrieval:
sqlite_session.add_all([accessible, owned, hidden, foreign])
sqlite_session.commit()
+ config_overrides(RBAC_ENABLED=True)
+
with (
- patch("services.dataset_service.dify_config.RBAC_ENABLED", True),
patch(
"services.dataset_service.enterprise_rbac_service.RBACService.MyPermissions.get",
return_value=SimpleNamespace(workspace=SimpleNamespace(permission_keys=[])),
@@ -299,24 +302,28 @@ class TestDatasetServiceRetrieval:
assert total == 2
assert {dataset.id for dataset in datasets} == {accessible.id, owned.id}
- def test_get_datasets_without_user_keeps_only_team_visible_rows(self, sqlite_session: Session) -> None:
+ def test_get_datasets_without_user_keeps_only_team_visible_rows(
+ self, config_overrides: Callable[..., None], sqlite_session: Session
+ ) -> None:
shared = _dataset(dataset_id="shared", name="Shared", permission=DatasetPermissionEnum.ALL_TEAM)
private = _dataset(dataset_id="private", name="Private", permission=DatasetPermissionEnum.ONLY_ME)
sqlite_session.add_all([shared, private])
sqlite_session.commit()
- with patch("services.dataset_service.dify_config.RBAC_ENABLED", False):
- datasets, total = DatasetService.get_datasets(
- page=1,
- per_page=20,
- session=sqlite_session,
- tenant_id="tenant-1",
- )
+ config_overrides(RBAC_ENABLED=False)
+ datasets, total = DatasetService.get_datasets(
+ page=1,
+ per_page=20,
+ session=sqlite_session,
+ tenant_id="tenant-1",
+ )
assert total == 1
assert [dataset.id for dataset in datasets] == [shared.id]
- def test_get_datasets_by_ids_intersects_requested_and_accessible_ids(self, sqlite_session: Session) -> None:
+ def test_get_datasets_by_ids_intersects_requested_and_accessible_ids(
+ self, config_overrides: Callable[..., None], sqlite_session: Session
+ ) -> None:
user = _account(role=TenantAccountRole.NORMAL)
accessible = _dataset(dataset_id="accessible", name="Accessible", maintainer="other")
owned = _dataset(dataset_id="owned", name="Owned", maintainer=user.id)
@@ -324,35 +331,39 @@ class TestDatasetServiceRetrieval:
sqlite_session.add_all([accessible, owned, hidden])
sqlite_session.commit()
- with patch("services.dataset_service.dify_config.RBAC_ENABLED", True):
- datasets, total = DatasetService.get_datasets_by_ids(
- [accessible.id, owned.id, hidden.id],
- "tenant-1",
- user=user,
- accessible_dataset_ids=[accessible.id, "not-requested"],
- include_own_datasets=True,
- session=sqlite_session,
- )
+ config_overrides(RBAC_ENABLED=True)
+ datasets, total = DatasetService.get_datasets_by_ids(
+ [accessible.id, owned.id, hidden.id],
+ "tenant-1",
+ user=user,
+ accessible_dataset_ids=[accessible.id, "not-requested"],
+ include_own_datasets=True,
+ session=sqlite_session,
+ )
assert total == 2
assert {dataset.id for dataset in datasets} == {accessible.id, owned.id}
- def test_get_datasets_rbac_without_user_returns_no_rows(self, sqlite_session: Session) -> None:
+ def test_get_datasets_rbac_without_user_returns_no_rows(
+ self, config_overrides: Callable[..., None], sqlite_session: Session
+ ) -> None:
sqlite_session.add(_dataset())
sqlite_session.commit()
- with patch("services.dataset_service.dify_config.RBAC_ENABLED", True):
- datasets, total = DatasetService.get_datasets(
- page=1,
- per_page=20,
- session=sqlite_session,
- tenant_id="tenant-1",
- )
+ config_overrides(RBAC_ENABLED=True)
+ datasets, total = DatasetService.get_datasets(
+ page=1,
+ per_page=20,
+ session=sqlite_session,
+ tenant_id="tenant-1",
+ )
assert datasets == []
assert total == 0
- def test_get_datasets_rbac_include_all_requires_workspace_permission(self, sqlite_session: Session) -> None:
+ def test_get_datasets_rbac_include_all_requires_workspace_permission(
+ self, config_overrides: Callable[..., None], sqlite_session: Session
+ ) -> None:
user = _account(role=TenantAccountRole.NORMAL)
sqlite_session.add_all(
[
@@ -362,8 +373,8 @@ class TestDatasetServiceRetrieval:
)
sqlite_session.commit()
+ config_overrides(RBAC_ENABLED=True)
with (
- patch("services.dataset_service.dify_config.RBAC_ENABLED", True),
patch(
"services.dataset_service.enterprise_rbac_service.RBACService.MyPermissions.get",
return_value=SimpleNamespace(
diff --git a/api/tests/unit_tests/services/test_file_service.py b/api/tests/unit_tests/services/test_file_service.py
index ffd507fd06a..49367183d9c 100644
--- a/api/tests/unit_tests/services/test_file_service.py
+++ b/api/tests/unit_tests/services/test_file_service.py
@@ -1,7 +1,7 @@
import base64
import hashlib
import os
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from datetime import UTC, datetime
from unittest.mock import patch
@@ -10,7 +10,6 @@ from sqlalchemy import Engine
from sqlalchemy.orm import Session, sessionmaker
from werkzeug.exceptions import NotFound
-from configs import dify_config
from enums import DeploymentEdition
from extensions.storage.storage_type import StorageType
from models.base import TypeBase
@@ -175,12 +174,12 @@ class TestFileService:
assert result.name.endswith(".txt")
assert db_session.get(UploadFile, result.id) is not None
- def test_upload_file_blocked_extension(self, file_service):
- with patch.object(dify_config, "inner_UPLOAD_FILE_EXTENSION_BLACKLIST", "exe"):
- with pytest.raises(BlockedFileExtensionError):
- file_service.upload_file(
- filename="test.exe", content=b"", mimetype="application/octet-stream", user=_account()
- )
+ def test_upload_file_blocked_extension(self, file_service, config_overrides: Callable[..., None]):
+ config_overrides(inner_UPLOAD_FILE_EXTENSION_BLACKLIST="exe")
+ with pytest.raises(BlockedFileExtensionError):
+ file_service.upload_file(
+ filename="test.exe", content=b"", mimetype="application/octet-stream", user=_account()
+ )
def test_upload_file_unsupported_type_for_datasets(self, file_service):
with pytest.raises(UnsupportedFileTypeError):
@@ -188,12 +187,12 @@ class TestFileService:
filename="test.jpg", content=b"", mimetype="image/jpeg", user=_account(), source="datasets"
)
- def test_upload_file_too_large(self, file_service):
+ def test_upload_file_too_large(self, file_service, config_overrides: Callable[..., None]):
# 16MB file for an image with 15MB limit
content = b"a" * (16 * 1024 * 1024)
- with patch.object(dify_config, "UPLOAD_IMAGE_FILE_SIZE_LIMIT", 15):
- with pytest.raises(FileTooLargeError):
- file_service.upload_file(filename="test.jpg", content=content, mimetype="image/jpeg", user=_account())
+ config_overrides(UPLOAD_IMAGE_FILE_SIZE_LIMIT=15)
+ with pytest.raises(FileTooLargeError):
+ file_service.upload_file(filename="test.jpg", content=content, mimetype="image/jpeg", user=_account())
def test_upload_file_end_user(self, file_service: FileService, db_session: Session):
user = EndUser(
@@ -210,54 +209,54 @@ class TestFileService:
assert result.created_by_role == CreatorUserRole.END_USER
assert db_session.get(UploadFile, result.id) is not None
- def test_is_file_size_within_limit(self):
- with (
- patch.object(dify_config, "UPLOAD_IMAGE_FILE_SIZE_LIMIT", 10),
- patch.object(dify_config, "UPLOAD_VIDEO_FILE_SIZE_LIMIT", 20),
- patch.object(dify_config, "UPLOAD_AUDIO_FILE_SIZE_LIMIT", 30),
- patch.object(dify_config, "UPLOAD_FILE_SIZE_LIMIT", 5),
- ):
- # Image
- assert FileService.is_file_size_within_limit(extension="jpg", file_size=10 * 1024 * 1024) is True
- assert FileService.is_file_size_within_limit(extension="png", file_size=11 * 1024 * 1024) is False
-
- # Video
- assert FileService.is_file_size_within_limit(extension="mp4", file_size=20 * 1024 * 1024) is True
- assert FileService.is_file_size_within_limit(extension="avi", file_size=21 * 1024 * 1024) is False
-
- # Audio
- assert FileService.is_file_size_within_limit(extension="mp3", file_size=30 * 1024 * 1024) is True
- assert FileService.is_file_size_within_limit(extension="wav", file_size=31 * 1024 * 1024) is False
-
- # Default
- assert FileService.is_file_size_within_limit(extension="txt", file_size=5 * 1024 * 1024) is True
- assert FileService.is_file_size_within_limit(extension="pdf", file_size=6 * 1024 * 1024) is False
- assert (
- FileService.is_file_size_within_limit(
- extension="pdf",
- file_size=6 * 1024 * 1024,
- default_file_size_limit=7,
- )
- is True
+ def test_is_file_size_within_limit(self, config_overrides: Callable[..., None]):
+ config_overrides(
+ UPLOAD_IMAGE_FILE_SIZE_LIMIT=10,
+ UPLOAD_VIDEO_FILE_SIZE_LIMIT=20,
+ UPLOAD_AUDIO_FILE_SIZE_LIMIT=30,
+ UPLOAD_FILE_SIZE_LIMIT=5,
+ )
+ # Image
+ assert FileService.is_file_size_within_limit(extension="jpg", file_size=10 * 1024 * 1024) is True
+ assert FileService.is_file_size_within_limit(extension="png", file_size=11 * 1024 * 1024) is False
+
+ # Video
+ assert FileService.is_file_size_within_limit(extension="mp4", file_size=20 * 1024 * 1024) is True
+ assert FileService.is_file_size_within_limit(extension="avi", file_size=21 * 1024 * 1024) is False
+
+ # Audio
+ assert FileService.is_file_size_within_limit(extension="mp3", file_size=30 * 1024 * 1024) is True
+ assert FileService.is_file_size_within_limit(extension="wav", file_size=31 * 1024 * 1024) is False
+
+ # Default
+ assert FileService.is_file_size_within_limit(extension="txt", file_size=5 * 1024 * 1024) is True
+ assert FileService.is_file_size_within_limit(extension="pdf", file_size=6 * 1024 * 1024) is False
+ assert (
+ FileService.is_file_size_within_limit(
+ extension="pdf",
+ file_size=6 * 1024 * 1024,
+ default_file_size_limit=7,
)
- assert (
- FileService.is_file_size_within_limit(
- extension="pdf",
- file_size=8 * 1024 * 1024,
- default_file_size_limit=7,
- )
- is False
+ is True
+ )
+ assert (
+ FileService.is_file_size_within_limit(
+ extension="pdf",
+ file_size=8 * 1024 * 1024,
+ default_file_size_limit=7,
)
+ is False
+ )
- # Media-specific limits are not affected by the knowledge document override.
- assert (
- FileService.is_file_size_within_limit(
- extension="jpg",
- file_size=11 * 1024 * 1024,
- default_file_size_limit=100,
- )
- is False
+ # Media-specific limits are not affected by the knowledge document override.
+ assert (
+ FileService.is_file_size_within_limit(
+ extension="jpg",
+ file_size=11 * 1024 * 1024,
+ default_file_size_limit=100,
)
+ is False
+ )
def test_get_file_base64_success(self, file_service: FileService, db_session: Session):
self._persist_upload_file(db_session, key="test_key")
@@ -276,7 +275,10 @@ class TestFileService:
with pytest.raises(NotFound, match="File not found"):
file_service.get_file_base64("non_existent")
- def test_get_file_presigned_url_success(self, file_service: FileService, db_session: Session):
+ def test_get_file_presigned_url_success(
+ self, file_service: FileService, db_session: Session, config_overrides: Callable[..., None]
+ ):
+ config_overrides(FILES_ACCESS_TIMEOUT=300)
self._persist_upload_file(
db_session,
extension="png",
@@ -285,7 +287,6 @@ class TestFileService:
)
with (
- patch.object(dify_config, "FILES_ACCESS_TIMEOUT", 300),
patch("services.file_service.storage") as mock_storage,
):
mock_storage.generate_presigned_url.return_value = "https://s3.example.com/icon.png?signature=test"
@@ -303,12 +304,11 @@ class TestFileService:
with pytest.raises(NotFound, match="File not found"):
file_service.get_file_presigned_url(file_id="file_id", tenant_id="tenant_id")
- def test_get_icon_url_uses_direct_storage_url_for_cloud_s3(self, file_service: FileService):
- with (
- patch.object(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
- patch.object(dify_config, "STORAGE_TYPE", StorageType.S3),
- patch.object(file_service, "get_file_presigned_url", return_value="direct-url") as get_presigned_url,
- ):
+ def test_get_icon_url_uses_direct_storage_url_for_cloud_s3(
+ self, file_service: FileService, config_overrides: Callable[..., None]
+ ):
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, STORAGE_TYPE=StorageType.S3)
+ with patch.object(file_service, "get_file_presigned_url", return_value="direct-url") as get_presigned_url:
result = file_service.get_icon_url("file_id", "tenant_id")
assert result == "direct-url"
@@ -326,12 +326,10 @@ class TestFileService:
file_service: FileService,
deployment_edition: DeploymentEdition,
storage_type: StorageType,
+ config_overrides: Callable[..., None],
):
- with (
- patch.object(dify_config, "DEPLOYMENT_EDITION", deployment_edition),
- patch.object(dify_config, "STORAGE_TYPE", storage_type),
- patch("services.file_service.file_helpers.get_signed_file_url", return_value="preview-url") as get_url,
- ):
+ config_overrides(DEPLOYMENT_EDITION=deployment_edition, STORAGE_TYPE=storage_type)
+ with patch("services.file_service.file_helpers.get_signed_file_url", return_value="preview-url") as get_url:
result = file_service.get_icon_url("file_id", "tenant_id")
assert result == "preview-url"