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: scope plugin and datasource config overrides (#40854)

Asuka Minato3bcd97b643e7
diff --git a/api/tests/unit_tests/core/datasource/entities/test_datasource_entities.py b/api/tests/unit_tests/core/datasource/entities/test_datasource_entities.py
index a8c8d31537c..14693c8a64d 100644
--- a/api/tests/unit_tests/core/datasource/entities/test_datasource_entities.py
+++ b/api/tests/unit_tests/core/datasource/entities/test_datasource_entities.py
@@ -1,5 +1,3 @@
-from unittest.mock import patch
-
import pytest
from core.datasource.entities.datasource_entities import (
@@ -110,7 +108,7 @@ def test_datasource_entity():
assert entity_with_params.parameters == [param]
-def test_datasource_provider_identity():
+def test_datasource_provider_identity(config_overrides):
label = I18nObject(en_US="label", zh_Hans="标签")
description = I18nObject(en_US="desc", zh_Hans="描述")
identity = DatasourceProviderIdentity(
@@ -125,12 +123,11 @@ def test_datasource_provider_identity():
assert identity.tags == [ToolLabelEnum.SEARCH]
# Test generate_datasource_icon_url
- with patch("core.datasource.entities.datasource_entities.dify_config") as mock_config:
- mock_config.CONSOLE_API_URL = "http://api.example.com"
- url = identity.generate_datasource_icon_url("tenant123")
- assert "http://api.example.com/console/api/workspaces/current/plugin/icon" in url
- assert "tenant_id=tenant123" in url
- assert "filename=icon.png" in url
+ config_overrides(CONSOLE_API_URL="http://api.example.com")
+ url = identity.generate_datasource_icon_url("tenant123")
+ assert "http://api.example.com/console/api/workspaces/current/plugin/icon" in url
+ assert "tenant_id=tenant123" in url
+ assert "filename=icon.png" in url
# Test hardcoded icon
identity.icon = "https://assets.dify.ai/images/File%20Upload.svg"
@@ -138,10 +135,9 @@ def test_datasource_provider_identity():
# Test with empty CONSOLE_API_URL
identity.icon = "test.png"
- with patch("core.datasource.entities.datasource_entities.dify_config") as mock_config:
- mock_config.CONSOLE_API_URL = None
- url = identity.generate_datasource_icon_url("tenant123")
- assert url.startswith("/console/api/workspaces/current/plugin/icon")
+ config_overrides(CONSOLE_API_URL=None)
+ url = identity.generate_datasource_icon_url("tenant123")
+ assert url.startswith("/console/api/workspaces/current/plugin/icon")
def test_datasource_provider_entity():
diff --git a/api/tests/unit_tests/core/datasource/test_datasource_file_manager.py b/api/tests/unit_tests/core/datasource/test_datasource_file_manager.py
index 3bbc8db1b66..c61b170eb0d 100644
--- a/api/tests/unit_tests/core/datasource/test_datasource_file_manager.py
+++ b/api/tests/unit_tests/core/datasource/test_datasource_file_manager.py
@@ -58,13 +58,18 @@ def _message_file(id: str, *, url: str | None) -> MessageFile:
class TestDatasourceFileManager:
+ @pytest.fixture(autouse=True)
+ def _file_config(self, config_overrides) -> None:
+ config_overrides(
+ FILES_URL="http://localhost:5001",
+ SECRET_KEY="test_secret",
+ STORAGE_TYPE="local",
+ )
+
@patch("core.datasource.datasource_file_manager.time.time")
@patch("core.datasource.datasource_file_manager.os.urandom")
- @patch("core.datasource.datasource_file_manager.dify_config")
- def test_sign_file(self, mock_config, mock_urandom, mock_time):
+ def test_sign_file(self, mock_urandom, mock_time):
# Setup
- mock_config.FILES_URL = "http://localhost:5001"
- mock_config.SECRET_KEY = "test_secret"
mock_time.return_value = 1700000000
mock_urandom.return_value = b"1234567890abcdef" # 16 bytes
@@ -82,11 +87,9 @@ class TestDatasourceFileManager:
@patch("core.datasource.datasource_file_manager.storage")
@patch("core.datasource.datasource_file_manager.uuid4")
- @patch("core.datasource.datasource_file_manager.dify_config")
- def test_create_file_by_raw(self, mock_config, mock_uuid, mock_storage, sqlite_session: Session):
+ def test_create_file_by_raw(self, mock_uuid, mock_storage, sqlite_session: Session):
# Setup
mock_uuid.return_value = MagicMock(hex="unique_hex")
- mock_config.STORAGE_TYPE = "local"
user_id = "user_123"
tenant_id = "tenant_456"
@@ -117,11 +120,9 @@ class TestDatasourceFileManager:
@patch("core.datasource.datasource_file_manager.storage")
@patch("core.datasource.datasource_file_manager.uuid4")
- @patch("core.datasource.datasource_file_manager.dify_config")
- def test_create_file_by_raw_filename_no_extension(self, mock_config, mock_uuid, mock_storage):
+ def test_create_file_by_raw_filename_no_extension(self, mock_uuid, mock_storage):
# Setup
mock_uuid.return_value = MagicMock(hex="unique_hex")
- mock_config.STORAGE_TYPE = "local"
user_id = "user_123"
tenant_id = "tenant_456"
@@ -143,13 +144,11 @@ class TestDatasourceFileManager:
@patch("core.datasource.datasource_file_manager.storage")
@patch("core.datasource.datasource_file_manager.uuid4")
- @patch("core.datasource.datasource_file_manager.dify_config")
@patch("core.datasource.datasource_file_manager.guess_extension")
- def test_create_file_by_raw_unknown_extension(self, mock_guess_ext, mock_config, mock_uuid, mock_storage):
+ def test_create_file_by_raw_unknown_extension(self, mock_guess_ext, mock_uuid, mock_storage):
# Setup
mock_guess_ext.return_value = None # Cannot guess
mock_uuid.return_value = MagicMock(hex="unique_hex")
- mock_config.STORAGE_TYPE = "local"
# Execute
upload_file = DatasourceFileManager.create_file_by_raw(
@@ -166,11 +165,9 @@ class TestDatasourceFileManager:
@patch("core.datasource.datasource_file_manager.storage")
@patch("core.datasource.datasource_file_manager.uuid4")
- @patch("core.datasource.datasource_file_manager.dify_config")
- def test_create_file_by_raw_no_filename(self, mock_config, mock_uuid, mock_storage):
+ def test_create_file_by_raw_no_filename(self, mock_uuid, mock_storage):
# Setup
mock_uuid.return_value = MagicMock(hex="unique_hex")
- mock_config.STORAGE_TYPE = "local"
# Execute
upload_file = DatasourceFileManager.create_file_by_raw(
diff --git a/api/tests/unit_tests/core/datasource/test_notion_provider.py b/api/tests/unit_tests/core/datasource/test_notion_provider.py
index d68187cfb34..1e4c5bbb355 100644
--- a/api/tests/unit_tests/core/datasource/test_notion_provider.py
+++ b/api/tests/unit_tests/core/datasource/test_notion_provider.py
@@ -137,13 +137,12 @@ class TestNotionExtractorAuthentication:
plugin_id="langgenius/notion_datasource",
)
- @patch("core.rag.extractor.notion_extractor.dify_config")
@patch("core.rag.extractor.notion_extractor.NotionExtractor._get_access_token")
- def test_init_with_integration_token_fallback(self, mock_get_token, mock_config, mock_document_model):
+ def test_init_with_integration_token_fallback(self, mock_get_token, mock_document_model, config_overrides):
"""Test NotionExtractor falls back to integration token when credential not found."""
# Arrange
mock_get_token.side_effect = Exception("No credential id found")
- mock_config.NOTION_INTEGRATION_TOKEN = "integration-token-fallback"
+ config_overrides(NOTION_INTEGRATION_TOKEN="integration-token-fallback")
# Act
extractor = NotionExtractor(
@@ -158,13 +157,12 @@ class TestNotionExtractorAuthentication:
# Assert
assert extractor._notion_access_token == "integration-token-fallback"
- @patch("core.rag.extractor.notion_extractor.dify_config")
@patch("core.rag.extractor.notion_extractor.NotionExtractor._get_access_token")
- def test_init_missing_credentials_raises_error(self, mock_get_token, mock_config, mock_document_model):
+ def test_init_missing_credentials_raises_error(self, mock_get_token, mock_document_model, config_overrides):
"""Test NotionExtractor raises error when no credentials available."""
# Arrange
mock_get_token.side_effect = Exception("No credential id found")
- mock_config.NOTION_INTEGRATION_TOKEN = None
+ config_overrides(NOTION_INTEGRATION_TOKEN=None)
# Act & Assert
with pytest.raises(ValueError) as exc_info:
diff --git a/api/tests/unit_tests/core/helper/test_creators.py b/api/tests/unit_tests/core/helper/test_creators.py
index bb0f4d8ec07..6ac97240454 100644
--- a/api/tests/unit_tests/core/helper/test_creators.py
+++ b/api/tests/unit_tests/core/helper/test_creators.py
@@ -85,10 +85,11 @@ class TestUploadDSL:
class TestGetRedirectUrl:
- @patch("core.helper.creators.dify_config")
- def test_without_oauth_client_id(self, mock_config):
- mock_config.CREATORS_PLATFORM_API_URL = "https://creators.example.com"
- mock_config.CREATORS_PLATFORM_OAUTH_CLIENT_ID = ""
+ def test_without_oauth_client_id(self, config_overrides):
+ config_overrides(
+ CREATORS_PLATFORM_API_URL="https://creators.example.com",
+ CREATORS_PLATFORM_OAUTH_CLIENT_ID="",
+ )
from core.helper.creators import get_redirect_url
@@ -98,10 +99,11 @@ class TestGetRedirectUrl:
assert "oauth_code" not in url
assert url.startswith("https://creators.example.com")
- @patch("core.helper.creators.dify_config")
- def test_with_oauth_client_id(self, mock_config):
- mock_config.CREATORS_PLATFORM_API_URL = "https://creators.example.com"
- mock_config.CREATORS_PLATFORM_OAUTH_CLIENT_ID = "client-xyz"
+ def test_with_oauth_client_id(self, config_overrides):
+ config_overrides(
+ CREATORS_PLATFORM_API_URL="https://creators.example.com",
+ CREATORS_PLATFORM_OAUTH_CLIENT_ID="client-xyz",
+ )
with patch(
"services.oauth_server.OAuthServerService.sign_oauth_authorization_code",
@@ -115,10 +117,11 @@ class TestGetRedirectUrl:
assert "dsl_claim_code=claim-abc" in url
assert "oauth_code=oauth-code-123" in url
- @patch("core.helper.creators.dify_config")
- def test_strips_trailing_slash(self, mock_config):
- mock_config.CREATORS_PLATFORM_API_URL = "https://creators.example.com/"
- mock_config.CREATORS_PLATFORM_OAUTH_CLIENT_ID = ""
+ def test_strips_trailing_slash(self, config_overrides):
+ config_overrides(
+ CREATORS_PLATFORM_API_URL="https://creators.example.com/",
+ CREATORS_PLATFORM_OAUTH_CLIENT_ID="",
+ )
from core.helper.creators import get_redirect_url
diff --git a/api/tests/unit_tests/core/mcp/server/test_streamable_http.py b/api/tests/unit_tests/core/mcp/server/test_streamable_http.py
index 75b01a1397b..42a9df3538a 100644
--- a/api/tests/unit_tests/core/mcp/server/test_streamable_http.py
+++ b/api/tests/unit_tests/core/mcp/server/test_streamable_http.py
@@ -260,9 +260,7 @@ class TestIndividualHandlers:
def test_handle_initialize_echoes_supported_version(self):
"""A supported requested version is echoed back unchanged."""
- with patch("core.mcp.server.streamable_http.dify_config") as mock_config:
- mock_config.project.version = "1.0.0"
- result = handle_initialize("Test server", "2024-11-05")
+ result = handle_initialize("Test server", "2024-11-05")
assert isinstance(result, types.InitializeResult)
assert result.protocolVersion == "2024-11-05"
@@ -270,34 +268,26 @@ class TestIndividualHandlers:
def test_handle_initialize_echoes_intermediate_version(self):
"""The intermediate supported version (2025-03-26) is echoed back."""
- with patch("core.mcp.server.streamable_http.dify_config") as mock_config:
- mock_config.project.version = "1.0.0"
- result = handle_initialize("Test server", "2025-03-26")
+ result = handle_initialize("Test server", "2025-03-26")
assert result.protocolVersion == "2025-03-26"
def test_handle_initialize_negotiates_latest_for_modern_client(self):
"""A 2025-06-18 client gets 2025-06-18 back."""
- with patch("core.mcp.server.streamable_http.dify_config") as mock_config:
- mock_config.project.version = "1.0.0"
- result = handle_initialize("Test server", "2025-06-18")
+ result = handle_initialize("Test server", "2025-06-18")
assert result.protocolVersion == "2025-06-18"
def test_handle_initialize_falls_back_for_unknown_version(self):
"""An unsupported requested version falls back to the server latest."""
- with patch("core.mcp.server.streamable_http.dify_config") as mock_config:
- mock_config.project.version = "1.0.0"
- result = handle_initialize("Test server", "1999-01-01")
+ result = handle_initialize("Test server", "1999-01-01")
assert result.protocolVersion == types.SERVER_LATEST_PROTOCOL_VERSION
assert result.protocolVersion == "2025-06-18"
def test_handle_initialize_non_string_version_falls_back(self):
"""A malformed (non-string) requested version falls back to the server latest."""
- with patch("core.mcp.server.streamable_http.dify_config") as mock_config:
- mock_config.project.version = "1.0.0"
- result = handle_initialize("Test server", 20250618)
+ result = handle_initialize("Test server", 20250618)
assert result.protocolVersion == types.SERVER_LATEST_PROTOCOL_VERSION
diff --git a/api/tests/unit_tests/core/mcp/test_utils.py b/api/tests/unit_tests/core/mcp/test_utils.py
index 9a313c3744b..34eb3be0a38 100644
--- a/api/tests/unit_tests/core/mcp/test_utils.py
+++ b/api/tests/unit_tests/core/mcp/test_utils.py
@@ -16,6 +16,20 @@ from core.mcp.utils import (
)
[email protected](autouse=True)
+def _mcp_config(config_overrides) -> None:
+ config_overrides(
+ SSRF_PROXY_ALL_URL=None,
+ SSRF_PROXY_HTTP_URL=None,
+ SSRF_PROXY_HTTPS_URL=None,
+ HTTP_REQUEST_NODE_SSL_VERIFY=True,
+ SSRF_DEFAULT_TIME_OUT=30.0,
+ SSRF_DEFAULT_CONNECT_TIME_OUT=10.0,
+ SSRF_DEFAULT_READ_TIME_OUT=60.0,
+ SSRF_DEFAULT_WRITE_TIME_OUT=30.0,
+ )
+
+
class TestConstants:
"""Test module constants."""
@@ -32,11 +46,9 @@ class TestConstants:
class TestCreateSSRFProxyMCPHTTPClient:
"""Test create_ssrf_proxy_mcp_http_client function."""
- @patch("core.mcp.utils.dify_config")
- def test_create_client_with_all_url_proxy(self, mock_config):
+ def test_create_client_with_all_url_proxy(self, config_overrides):
"""Test client creation with SSRF_PROXY_ALL_URL configured."""
- mock_config.SSRF_PROXY_ALL_URL = "http://proxy.example.com:8080"
- mock_config.HTTP_REQUEST_NODE_SSL_VERIFY = True
+ config_overrides(SSRF_PROXY_ALL_URL="http://proxy.example.com:8080")
client = create_ssrf_proxy_mcp_http_client(
headers={"Authorization": "Bearer token"}, timeout=httpx.Timeout(30.0)
@@ -50,13 +62,13 @@ class TestCreateSSRFProxyMCPHTTPClient:
# Clean up
client.close()
- @patch("core.mcp.utils.dify_config")
- def test_create_client_with_http_https_proxies(self, mock_config):
+ def test_create_client_with_http_https_proxies(self, config_overrides):
"""Test client creation with separate HTTP/HTTPS proxies."""
- mock_config.SSRF_PROXY_ALL_URL = None
- mock_config.SSRF_PROXY_HTTP_URL = "http://http-proxy.example.com:8080"
- mock_config.SSRF_PROXY_HTTPS_URL = "http://https-proxy.example.com:8443"
- mock_config.HTTP_REQUEST_NODE_SSL_VERIFY = False
+ config_overrides(
+ SSRF_PROXY_HTTP_URL="http://http-proxy.example.com:8080",
+ SSRF_PROXY_HTTPS_URL="http://https-proxy.example.com:8443",
+ HTTP_REQUEST_NODE_SSL_VERIFY=False,
+ )
client = create_ssrf_proxy_mcp_http_client()
@@ -66,13 +78,8 @@ class TestCreateSSRFProxyMCPHTTPClient:
# Clean up
client.close()
- @patch("core.mcp.utils.dify_config")
- def test_create_client_without_proxy(self, mock_config):
+ def test_create_client_without_proxy(self):
"""Test client creation without proxy configuration."""
- mock_config.SSRF_PROXY_ALL_URL = None
- mock_config.SSRF_PROXY_HTTP_URL = None
- mock_config.SSRF_PROXY_HTTPS_URL = None
- mock_config.HTTP_REQUEST_NODE_SSL_VERIFY = True
headers = {"X-Custom-Header": "value"}
timeout = httpx.Timeout(timeout=30.0, connect=5.0, read=10.0, write=30.0)
@@ -88,13 +95,8 @@ class TestCreateSSRFProxyMCPHTTPClient:
# Clean up
client.close()
- @patch("core.mcp.utils.dify_config")
- def test_create_client_default_params(self, mock_config):
+ def test_create_client_default_params(self):
"""Test client creation with default parameters."""
- mock_config.SSRF_PROXY_ALL_URL = None
- mock_config.SSRF_PROXY_HTTP_URL = None
- mock_config.SSRF_PROXY_HTTPS_URL = None
- mock_config.HTTP_REQUEST_NODE_SSL_VERIFY = True
client = create_ssrf_proxy_mcp_http_client()
@@ -140,15 +142,8 @@ class TestSSRFProxySSEConnect:
@patch("core.mcp.utils.connect_sse", autospec=True)
@patch("core.mcp.utils.create_ssrf_proxy_mcp_http_client", autospec=True)
- @patch("core.mcp.utils.dify_config")
- def test_sse_connect_without_client(self, mock_config, mock_create_client, mock_connect_sse):
+ def test_sse_connect_without_client(self, mock_create_client, mock_connect_sse):
"""Test SSE connection without pre-configured client."""
- # Setup config
- mock_config.SSRF_DEFAULT_TIME_OUT = 30.0
- mock_config.SSRF_DEFAULT_CONNECT_TIME_OUT = 10.0
- mock_config.SSRF_DEFAULT_READ_TIME_OUT = 60.0
- mock_config.SSRF_DEFAULT_WRITE_TIME_OUT = 30.0
-
# Setup mocks
mock_client = Mock(spec=httpx.Client)
mock_create_client.return_value = mock_client
diff --git a/api/tests/unit_tests/core/rag/embedding/test_cached_embedding.py b/api/tests/unit_tests/core/rag/embedding/test_cached_embedding.py
index 97b1327bc88..b52cf81e3ea 100644
--- a/api/tests/unit_tests/core/rag/embedding/test_cached_embedding.py
+++ b/api/tests/unit_tests/core/rag/embedding/test_cached_embedding.py
@@ -452,8 +452,9 @@ class TestCacheEmbeddingMultimodalQuery:
assert "Normalized embedding is nan" in str(exc_info.value)
- def test_embed_multimodal_query_api_error(self, mock_model_instance):
+ def test_embed_multimodal_query_api_error(self, mock_model_instance, config_overrides):
"""Test handling of API errors during multimodal query embedding."""
+ config_overrides(DEBUG=False)
cache_embedding = CacheEmbedding(mock_model_instance)
document = {"file_id": "file123"}
@@ -461,16 +462,14 @@ class TestCacheEmbeddingMultimodalQuery:
mock_redis.get.return_value = None
mock_model_instance.invoke_multimodal_embedding.side_effect = Exception("API Error")
- with patch("core.rag.embedding.cached_embedding.dify_config") as mock_config:
- mock_config.DEBUG = False
-
- with pytest.raises(Exception) as exc_info:
- cache_embedding.embed_multimodal_query(document)
+ with pytest.raises(Exception) as exc_info:
+ cache_embedding.embed_multimodal_query(document)
- assert "API Error" in str(exc_info.value)
+ assert "API Error" in str(exc_info.value)
- def test_embed_multimodal_query_redis_set_error(self, mock_model_instance):
+ def test_embed_multimodal_query_redis_set_error(self, mock_model_instance, config_overrides):
"""Test handling of Redis set errors during multimodal query embedding."""
+ config_overrides(DEBUG=True)
cache_embedding = CacheEmbedding(mock_model_instance)
document = {"file_id": "file123"}
@@ -498,11 +497,8 @@ class TestCacheEmbeddingMultimodalQuery:
mock_model_instance.invoke_multimodal_embedding.return_value = embedding_result
mock_redis.setex.side_effect = RuntimeError("Redis Error")
- with patch("core.rag.embedding.cached_embedding.dify_config") as mock_config:
- mock_config.DEBUG = True
-
- with pytest.raises(RuntimeError):
- cache_embedding.embed_multimodal_query(document)
+ with pytest.raises(RuntimeError):
+ cache_embedding.embed_multimodal_query(document)
class TestCacheEmbeddingQueryErrors:
@@ -518,8 +514,11 @@ class TestCacheEmbeddingQueryErrors:
model_instance.credentials = {"api_key": "test-key"}
return model_instance
- def test_embed_query_api_error_debug_mode(self, mock_model_instance, caplog: pytest.LogCaptureFixture):
+ def test_embed_query_api_error_debug_mode(
+ self, mock_model_instance, caplog: pytest.LogCaptureFixture, config_overrides
+ ):
"""Test handling of API errors in debug mode."""
+ config_overrides(DEBUG=True)
cache_embedding = CacheEmbedding(mock_model_instance)
query = "test query"
@@ -527,18 +526,18 @@ class TestCacheEmbeddingQueryErrors:
mock_redis.get.return_value = None
mock_model_instance.invoke_text_embedding.side_effect = RuntimeError("API Error")
- with patch("core.rag.embedding.cached_embedding.dify_config") as mock_config:
- mock_config.DEBUG = True
-
- with caplog.at_level(logging.ERROR, logger="core.rag.embedding.cached_embedding"):
- with pytest.raises(RuntimeError) as exc_info:
- cache_embedding.embed_query(query)
+ with caplog.at_level(logging.ERROR, logger="core.rag.embedding.cached_embedding"):
+ with pytest.raises(RuntimeError) as exc_info:
+ cache_embedding.embed_query(query)
- assert "API Error" in str(exc_info.value)
- assert any(record.levelno == logging.ERROR for record in caplog.records)
+ assert "API Error" in str(exc_info.value)
+ assert any(record.levelno == logging.ERROR for record in caplog.records)
- def test_embed_query_redis_set_error_debug_mode(self, mock_model_instance, caplog: pytest.LogCaptureFixture):
+ def test_embed_query_redis_set_error_debug_mode(
+ self, mock_model_instance, caplog: pytest.LogCaptureFixture, config_overrides
+ ):
"""Test handling of Redis set errors in debug mode."""
+ config_overrides(DEBUG=True)
cache_embedding = CacheEmbedding(mock_model_instance)
query = "test query"
@@ -566,14 +565,11 @@ class TestCacheEmbeddingQueryErrors:
mock_model_instance.invoke_text_embedding.return_value = embedding_result
mock_redis.setex.side_effect = RuntimeError("Redis Error")
- with patch("core.rag.embedding.cached_embedding.dify_config") as mock_config:
- mock_config.DEBUG = True
-
- with caplog.at_level(logging.ERROR, logger="core.rag.embedding.cached_embedding"):
- with pytest.raises(RuntimeError):
- cache_embedding.embed_query(query)
+ with caplog.at_level(logging.ERROR, logger="core.rag.embedding.cached_embedding"):
+ with pytest.raises(RuntimeError):
+ cache_embedding.embed_query(query)
- assert any(record.levelno == logging.ERROR for record in caplog.records)
+ assert any(record.levelno == logging.ERROR for record in caplog.records)
class TestCacheEmbeddingInitialization:
diff --git a/api/tests/unit_tests/core/rag/indexing/test_indexing_runner.py b/api/tests/unit_tests/core/rag/indexing/test_indexing_runner.py
index 460a8491125..926fe1baf1e 100644
--- a/api/tests/unit_tests/core/rag/indexing/test_indexing_runner.py
+++ b/api/tests/unit_tests/core/rag/indexing/test_indexing_runner.py
@@ -1580,21 +1580,17 @@ class TestIndexingRunnerSplitter:
embedding_model_instance=mock_embedding_instance,
)
- def test_get_splitter_validates_max_tokens_too_large(self, mock_embedding_instance):
+ def test_get_splitter_validates_max_tokens_too_large(self, mock_embedding_instance, config_overrides):
"""Test splitter validation rejects max_tokens above maximum."""
- # Arrange
- with patch("core.indexing_runner.dify_config") as mock_config:
- mock_config.INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH = 5000
-
- # Act & Assert
- with pytest.raises(ValueError, match="Custom segment length should be between"):
- IndexingRunner._get_splitter(
- processing_rule_mode="custom",
- max_tokens=10000, # Above maximum
- chunk_overlap=100,
- separator="\\n",
- embedding_model_instance=mock_embedding_instance,
- )
+ config_overrides(INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH=5000)
+ with pytest.raises(ValueError, match="Custom segment length should be between"):
+ IndexingRunner._get_splitter(
+ processing_rule_mode="custom",
+ max_tokens=10000, # Above maximum
+ chunk_overlap=100,
+ separator="\\n",
+ embedding_model_instance=mock_embedding_instance,
+ )
class TestIndexingRunnerLoadSegments:
@@ -1782,30 +1778,29 @@ class TestIndexingRunnerEstimate:
"factory": mock_factory,
}
- def test_indexing_estimate_respects_batch_limit(self, mock_dependencies):
+ def test_indexing_estimate_respects_batch_limit(self, mock_dependencies, config_overrides):
"""Test indexing estimate enforces batch upload limit."""
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, BATCH_UPLOAD_LIMIT=10)
# Arrange
runner = IndexingRunner()
tenant_id = str(uuid.uuid4())
- # Create too many extract settings
- with patch("core.indexing_runner.dify_config") as mock_config:
- mock_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD
- mock_config.BATCH_UPLOAD_LIMIT = 10
- extract_settings = [MagicMock() for _ in range(15)]
+ extract_settings = [MagicMock() for _ in range(15)]
- # Act & Assert
- with pytest.raises(ValueError, match="batch upload limit"):
- runner.indexing_estimate(
- tenant_id=tenant_id,
- extract_settings=extract_settings,
- tmp_processing_rule={"mode": "automatic", "rules": {}},
- doc_form=IndexStructureType.PARAGRAPH_INDEX,
- session=mock_dependencies["session"],
- )
+ with pytest.raises(ValueError, match="batch upload limit"):
+ runner.indexing_estimate(
+ tenant_id=tenant_id,
+ extract_settings=extract_settings,
+ tmp_processing_rule={"mode": "automatic", "rules": {}},
+ doc_form=IndexStructureType.PARAGRAPH_INDEX,
+ session=mock_dependencies["session"],
+ )
- def test_indexing_estimate_commits_preview_cleanup_before_summary_workers(self, mock_dependencies):
+ def test_indexing_estimate_commits_preview_cleanup_before_summary_workers(
+ self, mock_dependencies, config_overrides
+ ):
"""Test preview cleanup is visible before summary workers use independent sessions."""
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
runner = IndexingRunner()
tenant_id = str(uuid.uuid4())
mock_processor = MagicMock()
@@ -1845,10 +1840,7 @@ class TestIndexingRunnerEstimate:
with (
patch("core.indexing_runner.get_image_upload_file_ids", return_value=["image-1"]),
patch("core.indexing_runner.storage") as mock_storage,
- patch("core.indexing_runner.dify_config") as mock_config,
):
- mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY
-
result = runner.indexing_estimate(
tenant_id=tenant_id,
extract_settings=[MagicMock()],
diff --git a/api/tests/unit_tests/core/tools/test_mcp_tool.py b/api/tests/unit_tests/core/tools/test_mcp_tool.py
index 0c6ab408a37..d5a8be5e58d 100644
--- a/api/tests/unit_tests/core/tools/test_mcp_tool.py
+++ b/api/tests/unit_tests/core/tools/test_mcp_tool.py
@@ -257,41 +257,39 @@ def test_inject_forwarded_identity_sends_account_type_for_debugger():
assert issue.call_args.kwargs["user_type"] == "account"
-def test_invoke_remote_mcp_tool_fails_closed_when_user_id_missing():
+def test_invoke_remote_mcp_tool_fails_closed_when_user_id_missing(config_overrides):
"""When forwarding is enabled AND the deployment is enterprise, missing
user_id must raise — never silently invoke as the static identity."""
tool = _build_forwarding_tool()
- with patch("core.tools.mcp_tool.tool.dify_config") as cfg:
- cfg.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISE
- with pytest.raises(ToolInvokeError, match="no end-user context"):
- tool.invoke_remote_mcp_tool({}, user_id=None, app_id=None)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
+ with pytest.raises(ToolInvokeError, match="no end-user context"):
+ tool.invoke_remote_mcp_tool({}, user_id=None, app_id=None)
-def test_invoke_skips_forwarding_outside_enterprise_edition():
+def test_invoke_skips_forwarding_outside_enterprise_edition(config_overrides):
"""Non-enterprise deployments treat the DB selector as a no-op: a stale
`identity_mode="idp_token"` row must NOT raise (fail-closed) AND must
NOT call the enterprise inner API. The runtime falls through to the
legacy provider-identity path."""
tool = _build_forwarding_tool()
- with patch("core.tools.mcp_tool.tool.dify_config") as cfg:
- cfg.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY
- # The fail-closed branch must NOT fire (no enterprise → no forwarding).
- # The function will still try the legacy DB-load path; we patch that
- # to keep the test unit-scoped.
- with patch("core.tools.mcp_tool.tool.MCPClientWithAuthRetry") as client_cls:
- client_cls.return_value.__enter__.return_value.invoke_tool.return_value = CallToolResult(
- content=[],
- _meta=None,
- )
- with patch.object(tool, "_inject_forwarded_identity") as inject:
- with patch("services.tools.mcp_tools_manage_service.MCPToolManageService"):
- with patch("core.entities.mcp_provider.MCPProviderEntity.decrypt_server_url", return_value="u"):
- with patch("core.entities.mcp_provider.MCPProviderEntity.decrypt_headers", return_value={}):
- # Should not raise; should not call enterprise.
- try:
- tool.invoke_remote_mcp_tool({}, user_id=None, app_id=None)
- except Exception:
- pass
- inject.assert_not_called()
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
+ # The fail-closed branch must NOT fire (no enterprise → no forwarding).
+ # The function will still try the legacy DB-load path; we patch that
+ # to keep the test unit-scoped.
+ with patch("core.tools.mcp_tool.tool.MCPClientWithAuthRetry") as client_cls:
+ client_cls.return_value.__enter__.return_value.invoke_tool.return_value = CallToolResult(
+ content=[],
+ _meta=None,
+ )
+ with patch.object(tool, "_inject_forwarded_identity") as inject:
+ with patch("services.tools.mcp_tools_manage_service.MCPToolManageService"):
+ with patch("core.entities.mcp_provider.MCPProviderEntity.decrypt_server_url", return_value="u"):
+ with patch("core.entities.mcp_provider.MCPProviderEntity.decrypt_headers", return_value={}):
+ # Should not raise; should not call enterprise.
+ try:
+ tool.invoke_remote_mcp_tool({}, user_id=None, app_id=None)
+ except Exception:
+ pass
+ inject.assert_not_called()
diff --git a/api/tests/unit_tests/libs/broadcast_channel/redis/test_channel_unit_tests.py b/api/tests/unit_tests/libs/broadcast_channel/redis/test_channel_unit_tests.py
index b323e4c950f..2a9bc002607 100644
--- a/api/tests/unit_tests/libs/broadcast_channel/redis/test_channel_unit_tests.py
+++ b/api/tests/unit_tests/libs/broadcast_channel/redis/test_channel_unit_tests.py
@@ -137,25 +137,21 @@ class TestTopic:
mock_redis_client.publish.assert_called_once_with("test-topic", payload)
- def test_publish_prefixes_regular_topic(self, mock_redis_client: MagicMock):
- with patch("extensions.redis_names.dify_config") as mock_config:
- mock_config.REDIS_KEY_PREFIX = "enterprise-a"
- topic = Topic(mock_redis_client, "test-topic")
-
- topic.publish(b"test message")
+ def test_publish_prefixes_regular_topic(self, mock_redis_client: MagicMock, config_overrides):
+ config_overrides(REDIS_KEY_PREFIX="enterprise-a")
+ topic = Topic(mock_redis_client, "test-topic")
+ topic.publish(b"test message")
mock_redis_client.publish.assert_called_once_with("enterprise-a:test-topic", b"test message")
- def test_subscribe_prefixes_regular_topic(self, mock_redis_client: MagicMock):
- with patch("extensions.redis_names.dify_config") as mock_config:
- mock_config.REDIS_KEY_PREFIX = "enterprise-a"
- topic = Topic(mock_redis_client, "test-topic")
-
- subscription = topic.subscribe()
- try:
- subscription._start_if_needed()
- finally:
- subscription.close()
+ def test_subscribe_prefixes_regular_topic(self, mock_redis_client: MagicMock, config_overrides):
+ config_overrides(REDIS_KEY_PREFIX="enterprise-a")
+ topic = Topic(mock_redis_client, "test-topic")
+ subscription = topic.subscribe()
+ try:
+ subscription._start_if_needed()
+ finally:
+ subscription.close()
mock_redis_client.pubsub.return_value.subscribe.assert_called_once_with("enterprise-a:test-topic")
@@ -196,12 +192,10 @@ class TestShardedTopic:
mock_redis_client.spublish.assert_called_once_with("test-sharded-topic", payload)
- def test_publish_prefixes_sharded_topic(self, mock_redis_client: MagicMock):
- with patch("extensions.redis_names.dify_config") as mock_config:
- mock_config.REDIS_KEY_PREFIX = "enterprise-a"
- sharded_topic = ShardedTopic(mock_redis_client, "test-sharded-topic")
-
- sharded_topic.publish(b"test sharded message")
+ def test_publish_prefixes_sharded_topic(self, mock_redis_client: MagicMock, config_overrides):
+ config_overrides(REDIS_KEY_PREFIX="enterprise-a")
+ sharded_topic = ShardedTopic(mock_redis_client, "test-sharded-topic")
+ sharded_topic.publish(b"test sharded message")
mock_redis_client.spublish.assert_called_once_with("enterprise-a:test-sharded-topic", b"test sharded message")
@@ -214,16 +208,14 @@ class TestShardedTopic:
assert subscription._pubsub is mock_redis_client.pubsub.return_value
assert subscription._topic == "test-sharded-topic"
- def test_subscribe_prefixes_sharded_topic(self, mock_redis_client: MagicMock):
- with patch("extensions.redis_names.dify_config") as mock_config:
- mock_config.REDIS_KEY_PREFIX = "enterprise-a"
- sharded_topic = ShardedTopic(mock_redis_client, "test-sharded-topic")
-
- subscription = sharded_topic.subscribe()
- try:
- subscription._start_if_needed()
- finally:
- subscription.close()
+ def test_subscribe_prefixes_sharded_topic(self, mock_redis_client: MagicMock, config_overrides):
+ config_overrides(REDIS_KEY_PREFIX="enterprise-a")
+ sharded_topic = ShardedTopic(mock_redis_client, "test-sharded-topic")
+ subscription = sharded_topic.subscribe()
+ try:
+ subscription._start_if_needed()
+ finally:
+ subscription.close()
mock_redis_client.pubsub.return_value.ssubscribe.assert_called_once_with("enterprise-a:test-sharded-topic")
diff --git a/api/tests/unit_tests/libs/broadcast_channel/redis/test_streams_channel_unit_tests.py b/api/tests/unit_tests/libs/broadcast_channel/redis/test_streams_channel_unit_tests.py
index 5022f572153..73a65d3b5fc 100644
--- a/api/tests/unit_tests/libs/broadcast_channel/redis/test_streams_channel_unit_tests.py
+++ b/api/tests/unit_tests/libs/broadcast_channel/redis/test_streams_channel_unit_tests.py
@@ -2,7 +2,6 @@ import threading
import time
from dataclasses import dataclass
from typing import Any, cast
-from unittest.mock import patch
import pytest
@@ -169,21 +168,17 @@ class TestStreamsBroadcastChannel:
# Expire called after publish
assert fake_redis._expire_calls.get("stream:beta", 0) >= 1
- def test_topic_uses_prefixed_stream_key(self, fake_redis: FakeStreamsRedis):
- with patch("extensions.redis_names.dify_config") as mock_config:
- mock_config.REDIS_KEY_PREFIX = "enterprise-a"
-
- topic = StreamsBroadcastChannel(fake_redis, retention_seconds=60).topic("alpha")
+ def test_topic_uses_prefixed_stream_key(self, fake_redis: FakeStreamsRedis, config_overrides):
+ config_overrides(REDIS_KEY_PREFIX="enterprise-a")
+ topic = StreamsBroadcastChannel(fake_redis, retention_seconds=60).topic("alpha")
assert topic._topic == "alpha"
assert topic._key == "enterprise-a:stream:alpha"
- def test_publish_uses_prefixed_stream_key(self, fake_redis: FakeStreamsRedis):
- with patch("extensions.redis_names.dify_config") as mock_config:
- mock_config.REDIS_KEY_PREFIX = "enterprise-a"
- topic = StreamsBroadcastChannel(fake_redis, retention_seconds=60).topic("beta")
-
- topic.publish(b"hello")
+ def test_publish_uses_prefixed_stream_key(self, fake_redis: FakeStreamsRedis, config_overrides):
+ config_overrides(REDIS_KEY_PREFIX="enterprise-a")
+ topic = StreamsBroadcastChannel(fake_redis, retention_seconds=60).topic("beta")
+ topic.publish(b"hello")
assert fake_redis._store["enterprise-a:stream:beta"][0][1] == {b"data": b"hello"}
assert fake_redis._expire_calls.get("enterprise-a:stream:beta", 0) >= 1
diff --git a/api/tests/unit_tests/services/plugin/test_dependencies_analysis.py b/api/tests/unit_tests/services/plugin/test_dependencies_analysis.py
index 178dec1bfae..b3d21531792 100644
--- a/api/tests/unit_tests/services/plugin/test_dependencies_analysis.py
+++ b/api/tests/unit_tests/services/plugin/test_dependencies_analysis.py
@@ -150,18 +150,16 @@ class TestGenerateDependencies:
class TestGenerateLatestDependencies:
- @patch("services.plugin.dependencies_analysis.dify_config")
- def test_returns_empty_when_marketplace_disabled(self, mock_config):
- mock_config.MARKETPLACE_ENABLED = False
+ def test_returns_empty_when_marketplace_disabled(self, config_overrides):
+ config_overrides(MARKETPLACE_ENABLED=False)
result = DependenciesAnalysisService.generate_latest_dependencies(["p1"])
assert result == []
@patch("services.plugin.dependencies_analysis.marketplace")
- @patch("services.plugin.dependencies_analysis.dify_config")
- def test_returns_marketplace_deps_when_enabled(self, mock_config, mock_marketplace):
- mock_config.MARKETPLACE_ENABLED = True
+ def test_returns_marketplace_deps_when_enabled(self, mock_marketplace, config_overrides):
+ config_overrides(MARKETPLACE_ENABLED=True)
manifest = MagicMock()
manifest.latest_package_identifier = "org/plugin:2.0.0@newhash"
mock_marketplace.batch_fetch_plugin_manifests.return_value = [manifest]
diff --git a/api/tests/unit_tests/services/plugin/test_plugin_migration.py b/api/tests/unit_tests/services/plugin/test_plugin_migration.py
index 58f7d8cef16..f5462570b4e 100644
--- a/api/tests/unit_tests/services/plugin/test_plugin_migration.py
+++ b/api/tests/unit_tests/services/plugin/test_plugin_migration.py
@@ -12,8 +12,13 @@ from services.plugin.plugin_migration import PluginMigration
MIGRATION_MODULE = "services.plugin.plugin_migration"
-def test_fetch_latest_package_identifier_returns_none_when_disabled(mocker: MockerFixture) -> None:
- mocker.patch("services.plugin.plugin_migration.dify_config.MARKETPLACE_ENABLED", False)
[email protected](autouse=True)
+def _marketplace_enabled(config_overrides) -> None:
+ config_overrides(MARKETPLACE_ENABLED=True)
+
+
+def test_fetch_latest_package_identifier_returns_none_when_disabled(mocker: MockerFixture, config_overrides) -> None:
+ config_overrides(MARKETPLACE_ENABLED=False)
batch_fetch = mocker.patch("services.plugin.plugin_migration.marketplace.batch_fetch_plugin_manifests")
result = PluginMigration._fetch_latest_package_identifier("langgenius/openai")
@@ -23,7 +28,6 @@ def test_fetch_latest_package_identifier_returns_none_when_disabled(mocker: Mock
def test_fetch_latest_package_identifier_calls_marketplace_when_enabled(mocker: MockerFixture) -> None:
- mocker.patch("services.plugin.plugin_migration.dify_config.MARKETPLACE_ENABLED", True)
manifest = mocker.MagicMock()
manifest.latest_package_identifier = "langgenius/openai:1.0.0@abc"
mocker.patch(
@@ -61,21 +65,16 @@ def test_extract_app_tables_checks_agent_mode_with_its_session(mocker: MockerFix
class TestHandlePluginInstanceInstall:
- def test_raises_when_disabled_and_map_nonempty(self) -> None:
- with patch(f"{MIGRATION_MODULE}.dify_config") as mock_cfg:
- mock_cfg.MARKETPLACE_ENABLED = False
-
- with pytest.raises(ValueError, match="Marketplace disabled"):
- PluginMigration.handle_plugin_instance_install(
- "tenant1", {"langgenius/openai": "langgenius/openai:1.0.0@abc"}
- )
+ def test_raises_when_disabled_and_map_nonempty(self, config_overrides) -> None:
+ config_overrides(MARKETPLACE_ENABLED=False)
+ with pytest.raises(ValueError, match="Marketplace disabled"):
+ PluginMigration.handle_plugin_instance_install(
+ "tenant1", {"langgenius/openai": "langgenius/openai:1.0.0@abc"}
+ )
- def test_no_raise_when_disabled_and_map_empty(self) -> None:
- with (
- patch(f"{MIGRATION_MODULE}.dify_config") as mock_cfg,
- patch(f"{MIGRATION_MODULE}.PluginInstaller") as mock_installer_cls,
- ):
- mock_cfg.MARKETPLACE_ENABLED = False
+ def test_no_raise_when_disabled_and_map_empty(self, config_overrides) -> None:
+ config_overrides(MARKETPLACE_ENABLED=False)
+ with patch(f"{MIGRATION_MODULE}.PluginInstaller") as mock_installer_cls:
mock_installer = MagicMock()
mock_installer_cls.return_value = mock_installer
mock_installer.install_from_identifiers.return_value = MagicMock(all_installed=True)
@@ -86,12 +85,10 @@ class TestHandlePluginInstanceInstall:
def test_proceeds_when_enabled(self) -> None:
with (
- patch(f"{MIGRATION_MODULE}.dify_config") as mock_cfg,
patch(f"{MIGRATION_MODULE}.marketplace") as mock_marketplace,
patch(f"{MIGRATION_MODULE}.PluginInstaller") as mock_installer_cls,
patch(f"{MIGRATION_MODULE}.PluginService.invalidate_plugin_model_providers_cache") as invalidate_cache,
):
- mock_cfg.MARKETPLACE_ENABLED = True
mock_marketplace.download_plugin_pkg.return_value = b"pkg_data"
mock_installer = MagicMock()
mock_installer_cls.return_value = mock_installer
@@ -108,11 +105,9 @@ class TestHandlePluginInstanceInstall:
def test_reports_failed_plugin_ids_when_install_batch_raises(self) -> None:
with (
- patch(f"{MIGRATION_MODULE}.dify_config") as mock_cfg,
patch(f"{MIGRATION_MODULE}.marketplace") as mock_marketplace,
patch(f"{MIGRATION_MODULE}.PluginInstaller") as mock_installer_cls,
):
- mock_cfg.MARKETPLACE_ENABLED = True
mock_marketplace.download_plugin_pkg.return_value = b"pkg_data"
mock_installer = MagicMock()
mock_installer_cls.return_value = mock_installer
diff --git a/api/tests/unit_tests/services/plugin/test_plugin_service.py b/api/tests/unit_tests/services/plugin/test_plugin_service.py
index b0b727c3466..11865f67f7c 100644
--- a/api/tests/unit_tests/services/plugin/test_plugin_service.py
+++ b/api/tests/unit_tests/services/plugin/test_plugin_service.py
@@ -30,6 +30,16 @@ OTHER_TENANT_ID = "22222222-2222-2222-2222-222222222222"
USER_ID = "33333333-3333-3333-3333-333333333333"
[email protected](autouse=True)
+def _plugin_config(config_overrides) -> None:
+ config_overrides(
+ MARKETPLACE_ENABLED=True,
+ PLUGIN_MODEL_PROVIDERS_CACHE_TTL=86400,
+ PLUGIN_MODEL_PROVIDERS_CACHE_ENABLED=True,
+ DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,
+ )
+
+
def _build_provider_entity(
provider: str = "openai",
installation_source: PluginInstallationSource | None = PluginInstallationSource.Marketplace,
@@ -103,14 +113,13 @@ def _provider_generation_key(tenant_id: str) -> str:
class TestFetchLatestPluginVersion:
- def test_skips_marketplace_fetch_when_disabled(self) -> None:
+ def test_skips_marketplace_fetch_when_disabled(self, config_overrides) -> None:
"""Cache misses stay None; marketplace is never called when disabled."""
+ config_overrides(MARKETPLACE_ENABLED=False)
with (
- patch(f"{MODULE}.dify_config") as mock_cfg,
patch(f"{MODULE}.redis_client") as mock_redis,
patch(f"{MODULE}.marketplace") as mock_marketplace,
):
- mock_cfg.MARKETPLACE_ENABLED = False
mock_redis.get.return_value = None # all cache misses
from core.plugin.plugin_service import PluginService
@@ -131,11 +140,9 @@ class TestFetchLatestPluginVersion:
manifest.alternative_plugin_id = ""
with (
- patch(f"{MODULE}.dify_config") as mock_cfg,
patch(f"{MODULE}.redis_client") as mock_redis,
patch(f"{MODULE}.marketplace") as mock_marketplace,
):
- mock_cfg.MARKETPLACE_ENABLED = True
mock_redis.get.return_value = None
mock_marketplace.batch_fetch_plugin_manifests.return_value = [manifest]
@@ -157,12 +164,7 @@ class TestPluginModelProviderCache:
raw_payload = TypeAdapter(list[PluginModelProviderDeclaration]).dump_json([large_provider])
cache_key = _provider_cache_key("tenant-1", 0)
- with (
- patch(f"{MODULE}.redis_client") as redis_client,
- patch(f"{MODULE}.dify_config") as mock_config,
- ):
- mock_config.PLUGIN_MODEL_PROVIDERS_CACHE_TTL = 86400
-
+ with patch(f"{MODULE}.redis_client") as redis_client:
from core.plugin.plugin_service import PluginService
PluginService._store_cached_plugin_model_providers("tenant-1", 0, [large_provider])
@@ -254,11 +256,9 @@ class TestPluginModelProviderCache:
cache_key = _provider_cache_key("tenant-1", 0)
with (
patch(f"{MODULE}.redis_client") as redis_client,
- patch(f"{MODULE}.dify_config") as mock_config,
):
redis_client.get.side_effect = [None, None, None]
redis_client.mget.side_effect = [[legacy_payload], [None]]
- mock_config.PLUGIN_MODEL_PROVIDERS_CACHE_TTL = 86400
client = Mock()
client.fetch_model_providers.return_value = [_build_plugin_model_provider()]
@@ -277,10 +277,10 @@ class TestPluginModelProviderCache:
call([cache_key]),
]
- def test_fetch_plugin_model_providers_bypasses_redis_when_cache_disabled(self) -> None:
+ def test_fetch_plugin_model_providers_bypasses_redis_when_cache_disabled(self, config_overrides) -> None:
"""With the cache disabled the daemon is the only source, and Redis is never touched."""
- with patch(f"{MODULE}.redis_client") as redis_client, patch(f"{MODULE}.dify_config") as config:
- config.PLUGIN_MODEL_PROVIDERS_CACHE_ENABLED = False
+ config_overrides(PLUGIN_MODEL_PROVIDERS_CACHE_ENABLED=False)
+ with patch(f"{MODULE}.redis_client") as redis_client:
client = Mock()
client.fetch_model_providers.return_value = [_build_plugin_model_provider()]
@@ -298,7 +298,8 @@ class TestPluginModelProviderCache:
redis_client.setex.assert_not_called()
redis_client.lock.assert_not_called()
- def test_fetch_plugin_model_providers_resolves_missing_installation_source(self) -> None:
+ def test_fetch_plugin_model_providers_resolves_missing_installation_source(self, config_overrides) -> None:
+ config_overrides(PLUGIN_MODEL_PROVIDERS_CACHE_ENABLED=False)
provider = _build_plugin_model_provider(installation_source=None)
installation = SimpleNamespace(
plugin_unique_identifier=provider.plugin_unique_identifier,
@@ -308,12 +309,10 @@ class TestPluginModelProviderCache:
from core.plugin.plugin_service import PluginService
with (
- patch(f"{MODULE}.dify_config") as config,
patch.object(
PluginService, "list_installations_from_ids", return_value=[installation]
) as list_installations,
):
- config.PLUGIN_MODEL_PROVIDERS_CACHE_ENABLED = False
client = Mock()
client.fetch_model_providers.return_value = [provider]
@@ -1207,13 +1206,11 @@ class TestPluginModelProviderCacheInvalidation:
def test_upgrade_plugin_with_marketplace_invalidates_model_provider_cache_for_tenant(self) -> None:
"""Marketplace upgrades invalidate only the mutated tenant provider cache."""
with (
- patch(f"{MODULE}.dify_config") as mock_config,
patch(f"{MODULE}.FeatureService") as feature_service,
patch(f"{MODULE}.PluginInstaller") as installer_cls,
patch(f"{MODULE}.marketplace") as marketplace,
patch(f"{MODULE}.PluginService.invalidate_plugin_model_providers_cache") as invalidate_cache,
):
- mock_config.MARKETPLACE_ENABLED = True
feature_service.get_plugin_installation_permission.return_value = PluginInstallationPermissionModel(
restrict_to_marketplace_only=False,
plugin_installation_scope=PluginInstallationScope.ALL,
@@ -1317,13 +1314,11 @@ class TestPluginModelProviderCacheInvalidation:
def test_install_from_marketplace_pkg_invalidates_model_provider_cache_for_tenant(self) -> None:
"""Marketplace package installs invalidate only the mutated tenant provider cache."""
with (
- patch(f"{MODULE}.dify_config") as mock_config,
patch(f"{MODULE}.FeatureService") as feature_service,
patch(f"{MODULE}.PluginService._check_plugin_installation_scope"),
patch(f"{MODULE}.PluginInstaller") as installer_cls,
patch(f"{MODULE}.PluginService.invalidate_plugin_model_providers_cache") as invalidate_cache,
):
- mock_config.MARKETPLACE_ENABLED = True
feature_service.get_system_features.return_value = SimpleNamespace(
plugin_installation_permission=SimpleNamespace(restrict_to_marketplace_only=False)
)
@@ -1421,13 +1416,11 @@ class TestPluginModelProviderCacheInvalidation:
with (
patch(f"{MODULE}.db", SimpleNamespace(engine=sqlite_session.get_bind())),
- patch(f"{MODULE}.dify_config") as mock_config,
patch(f"{MODULE}.PluginInstaller") as installer_cls,
patch(f"{MODULE}.ProviderCredentialsCache") as credentials_cache,
patch(f"{MODULE}.PluginService.invalidate_plugin_model_providers_cache") as invalidate_cache,
patch("core.provider_manager.ProviderManager.invalidate_configurations_cache") as invalidate_configurations,
):
- mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY
installer = installer_cls.return_value
installer.list_plugins.return_value = [plugin]
installer.uninstall.return_value = True
diff --git a/api/tests/unit_tests/services/retention/test_messages_clean_policy.py b/api/tests/unit_tests/services/retention/test_messages_clean_policy.py
index 6179cead0cc..8809af8b15d 100644
--- a/api/tests/unit_tests/services/retention/test_messages_clean_policy.py
+++ b/api/tests/unit_tests/services/retention/test_messages_clean_policy.py
@@ -116,19 +116,15 @@ class TestBillingSandboxPolicy:
class TestCreateMessageCleanPolicy:
- def test_non_cloud_edition_returns_disabled_policy(self):
- with patch(f"{MODULE}.dify_config") as cfg:
- cfg.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY
- policy = create_message_clean_policy()
+ def test_non_cloud_edition_returns_disabled_policy(self, config_overrides):
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
+ policy = create_message_clean_policy()
assert isinstance(policy, BillingDisabledPolicy)
- def test_cloud_edition_returns_sandbox_policy(self):
- with (
- patch(f"{MODULE}.dify_config") as cfg,
- patch(f"{MODULE}.BillingService") as bs,
- ):
- cfg.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD
+ def test_cloud_edition_returns_sandbox_policy(self, config_overrides):
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
+ with patch(f"{MODULE}.BillingService") as bs:
bs.get_expired_subscription_cleanup_whitelist.return_value = ["wl1"]
bs.get_plan_bulk_with_cache = MagicMock()
policy = create_message_clean_policy(graceful_period_days=30)
diff --git a/api/tests/unit_tests/services/test_datasource_provider_service.py b/api/tests/unit_tests/services/test_datasource_provider_service.py
index 6668d9d31c0..c52e59d8a98 100644
--- a/api/tests/unit_tests/services/test_datasource_provider_service.py
+++ b/api/tests/unit_tests/services/test_datasource_provider_service.py
@@ -83,18 +83,17 @@ class TestDatasourceProviderService:
yield session
@pytest.fixture(autouse=True)
- def patch_externals(self):
+ def patch_externals(self, config_overrides):
+ config_overrides(CONSOLE_API_URL="http://localhost")
with (
patch("core.plugin.impl.base._httpx_client.request", side_effect=lambda **kw: httpx.request(**kw)),
patch("core.plugin.impl.base._httpx_client.stream", side_effect=lambda **kw: httpx.stream(**kw)),
patch("httpx.request") as mock_httpx,
- patch("services.datasource_provider_service.dify_config") as mock_cfg,
patch("services.datasource_provider_service.encrypter") as mock_enc,
patch("services.datasource_provider_service.redis_client") as mock_redis,
patch("services.datasource_provider_service.generate_incremental_name") as mock_genname,
patch("services.datasource_provider_service.OAuthHandler") as mock_oauth,
):
- mock_cfg.CONSOLE_API_URL = "http://localhost"
mock_enc.encrypt_token.return_value = "enc_tok"
mock_enc.decrypt_token.return_value = "dec_tok"
mock_enc.decrypt.return_value = {"k": "dec"}