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 core and service config overrides (#40868)

Asuka Minato3824323fe785
diff --git a/api/tests/unit_tests/config_override.py b/api/tests/unit_tests/config_override.py
new file mode 100644
index 00000000000..2c3175ce9ce
--- /dev/null
+++ b/api/tests/unit_tests/config_override.py
@@ -0,0 +1,15 @@
+"""Typed config override support shared by unit-test fixtures and helpers."""
+
+import pytest
+
+from configs import dify_config
+
+
+def apply_config_overrides(monkeypatch: pytest.MonkeyPatch, **values: object) -> None:
+ """Override known DifyConfig fields for the lifetime of ``monkeypatch``."""
+ unknown_fields = values.keys() - type(dify_config).model_fields.keys()
+ if unknown_fields:
+ raise ValueError(f"Unknown DifyConfig fields: {sorted(unknown_fields)}")
+
+ for name, value in values.items():
+ monkeypatch.setattr(dify_config, name, value)
diff --git a/api/tests/unit_tests/conftest.py b/api/tests/unit_tests/conftest.py
index ce90f8f380a..556e89f7780 100644
--- a/api/tests/unit_tests/conftest.py
+++ b/api/tests/unit_tests/conftest.py
@@ -41,6 +41,7 @@ import core.db.session_factory as session_factory_module
from extensions import ext_redis
from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
from models.base import TypeBase
+from tests.unit_tests.config_override import apply_config_overrides
def _patch_redis_clients_on_loaded_modules() -> None:
@@ -120,14 +121,9 @@ def config_overrides(monkeypatch: pytest.MonkeyPatch) -> Callable[..., None]:
field names keeps tests scoped without replacing that instance with an
unconstrained mock. ``monkeypatch`` restores every value after the test.
"""
- from configs import dify_config
def apply(**values: object) -> None:
- unknown_fields = values.keys() - type(dify_config).model_fields.keys()
- if unknown_fields:
- raise ValueError(f"Unknown DifyConfig fields: {sorted(unknown_fields)}")
- for name, value in values.items():
- monkeypatch.setattr(dify_config, name, value)
+ apply_config_overrides(monkeypatch, **values)
return apply
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py b/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py
index 152ada73f90..987c15d7a39 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py
@@ -27,6 +27,7 @@ from core.app.apps.agent_app.runtime_request_builder import (
)
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom
from models.agent_config_entities import AgentSoulConfig
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture(autouse=True)
@@ -403,7 +404,7 @@ class TestAgentAppRuntimeRequestBuilder:
assert exc.value.error_code == "agent_model_not_configured"
def test_build_maps_agent_soul_shell_settings_to_shell_layer(self, monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr("core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_SHELL_ENABLED", True)
+ apply_config_overrides(monkeypatch, AGENT_SHELL_ENABLED=True)
soul = AgentSoulConfig.model_validate(
{
"model": {
@@ -482,7 +483,7 @@ class TestAgentAppConfigLayer:
assert names.index(DIFY_CONFIG_LAYER_ID) == names.index(DIFY_SHELL_LAYER_ID) + 1
def test_config_layer_present_when_agent_soul_has_no_config_assets(self, monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr("core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_SHELL_ENABLED", True)
+ apply_config_overrides(monkeypatch, AGENT_SHELL_ENABLED=True)
builder = AgentAppRuntimeRequestBuilder(
dify_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
)
diff --git a/api/tests/unit_tests/core/app/apps/workflow/test_app_queue_manager.py b/api/tests/unit_tests/core/app/apps/workflow/test_app_queue_manager.py
index eeabb51c27a..fb92e098702 100644
--- a/api/tests/unit_tests/core/app/apps/workflow/test_app_queue_manager.py
+++ b/api/tests/unit_tests/core/app/apps/workflow/test_app_queue_manager.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from collections.abc import Callable
from unittest.mock import Mock, patch
from core.app.apps.base_app_queue_manager import PublishFrom
@@ -79,12 +80,12 @@ class TestWorkflowAppQueueManager:
graph_engine_manager.return_value.send_stop_command.assert_not_called()
manager._execution_coordinator.mark_terminal()
- def test_execution_timeout_aborts_graph_before_stop_event(self):
+ def test_execution_timeout_aborts_graph_before_stop_event(self, config_overrides: Callable[..., None]):
+ config_overrides(APP_MAX_EXECUTION_TIME=0)
with (
patch("core.app.apps.base_app_queue_manager.redis_client") as queue_redis,
patch("core.app.apps.execution_coordinator.redis_client") as execution_redis,
patch("core.app.apps.execution_coordinator.GraphEngineManager") as graph_engine_manager,
- patch("core.app.apps.execution_coordinator.dify_config.APP_MAX_EXECUTION_TIME", 0),
):
queue_redis.get.return_value = None
manager = WorkflowAppQueueManager(
diff --git a/api/tests/unit_tests/core/callback_handler/test_workflow_tool_callback_handler.py b/api/tests/unit_tests/core/callback_handler/test_workflow_tool_callback_handler.py
index 81ac48b2036..ea6451dc785 100644
--- a/api/tests/unit_tests/core/callback_handler/test_workflow_tool_callback_handler.py
+++ b/api/tests/unit_tests/core/callback_handler/test_workflow_tool_callback_handler.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from unittest.mock import MagicMock, call
import pytest
@@ -33,9 +34,9 @@ def mock_print_text(mocker: MockerFixture):
@pytest.fixture
-def enable_debug(mocker: MockerFixture):
+def enable_debug(config_overrides: Callable[..., None]):
"""Force DEBUG on so the handler emits its verbose stdout traces."""
- mocker.patch("core.callback_handler.workflow_tool_callback_handler.dify_config.DEBUG", True)
+ config_overrides(DEBUG=True)
class TestDifyWorkflowCallbackHandler:
@@ -112,12 +113,15 @@ class TestDifyWorkflowCallbackHandler:
mock_print_text.assert_not_called()
def test_on_tool_execution_skips_print_when_debug_disabled(
- self, handler: DifyWorkflowCallbackHandler, mock_print_text, mocker: MockerFixture
+ self,
+ handler: DifyWorkflowCallbackHandler,
+ mock_print_text,
+ config_overrides: Callable[..., None],
):
"""When DEBUG is off, outputs are still yielded but nothing is printed
and model_dump_json() is never invoked."""
# Arrange
- mocker.patch("core.callback_handler.workflow_tool_callback_handler.dify_config.DEBUG", False)
+ config_overrides(DEBUG=False)
message = MagicMock()
# Act
diff --git a/api/tests/unit_tests/core/datasource/__base/test_datasource_plugin.py b/api/tests/unit_tests/core/datasource/__base/test_datasource_plugin.py
index 5482b4db525..15f3d7e43ce 100644
--- a/api/tests/unit_tests/core/datasource/__base/test_datasource_plugin.py
+++ b/api/tests/unit_tests/core/datasource/__base/test_datasource_plugin.py
@@ -1,6 +1,6 @@
-from unittest.mock import MagicMock, patch
+from collections.abc import Callable
+from unittest.mock import MagicMock
-from configs import dify_config
from core.datasource.__base.datasource_plugin import DatasourcePlugin
from core.datasource.__base.datasource_runtime import DatasourceRuntime
from core.datasource.entities.datasource_entities import DatasourceEntity, DatasourceProviderType
@@ -69,7 +69,8 @@ class TestDatasourcePlugin:
assert new_plugin.icon == icon
mock_entity.model_copy.assert_called_once()
- def test_get_icon_url(self):
+ def test_get_icon_url(self, config_overrides: Callable[..., None]):
+ config_overrides(CONSOLE_API_URL="https://api.dify.ai")
# Arrange
entity = MagicMock(spec=DatasourceEntity)
runtime = MagicMock(spec=DatasourceRuntime)
@@ -78,13 +79,9 @@ class TestDatasourcePlugin:
plugin = ConcreteDatasourcePlugin(entity=entity, runtime=runtime, icon=icon)
- # Mocking dify_config.CONSOLE_API_URL
- with patch.object(dify_config, "CONSOLE_API_URL", "https://api.dify.ai"):
- # Act
- icon_url = plugin.get_icon_url(tenant_id)
+ icon_url = plugin.get_icon_url(tenant_id)
- # Assert
- expected_url = (
- f"https://api.dify.ai/console/api/workspaces/current/plugin/icon?tenant_id={tenant_id}&filename={icon}"
- )
- assert icon_url == expected_url
+ expected_url = (
+ f"https://api.dify.ai/console/api/workspaces/current/plugin/icon?tenant_id={tenant_id}&filename={icon}"
+ )
+ assert icon_url == expected_url
diff --git a/api/tests/unit_tests/core/entities/test_entities_mcp_provider.py b/api/tests/unit_tests/core/entities/test_entities_mcp_provider.py
index 4ebf265193d..cc48adfb5b0 100644
--- a/api/tests/unit_tests/core/entities/test_entities_mcp_provider.py
+++ b/api/tests/unit_tests/core/entities/test_entities_mcp_provider.py
@@ -3,7 +3,6 @@ from unittest.mock import Mock, patch
import pytest
-from core.entities import mcp_provider as mcp_provider_module
from core.entities.mcp_provider import (
DEFAULT_EXPIRES_IN,
DEFAULT_TOKEN_TYPE,
@@ -69,7 +68,9 @@ def test_from_db_model_maps_fields() -> None:
def test_redirect_url_uses_console_api_url(monkeypatch: pytest.MonkeyPatch) -> None:
# Arrange
entity = _build_mcp_provider_entity()
- monkeypatch.setattr(mcp_provider_module.dify_config, "CONSOLE_API_URL", "https://console.example.com")
+ from tests.unit_tests.config_override import apply_config_overrides
+
+ apply_config_overrides(monkeypatch, CONSOLE_API_URL="https://console.example.com")
# Act
redirect_url = entity.redirect_url
diff --git a/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py b/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py
index 5ecc9fc5967..a967f28b4d1 100644
--- a/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py
+++ b/api/tests/unit_tests/core/extension/test_api_based_extension_requestor.py
@@ -1,3 +1,5 @@
+from collections.abc import Callable
+
import httpx
import pytest
from pytest_mock import MockerFixture
@@ -29,10 +31,8 @@ def test_request_success(mocker: MockerFixture):
)
-def test_request_with_ssrf_proxy(mocker: MockerFixture):
- # Mock dify_config
- mocker.patch("configs.dify_config.SSRF_PROXY_HTTP_URL", "http://proxy:8080")
- mocker.patch("configs.dify_config.SSRF_PROXY_HTTPS_URL", "https://proxy:8081")
+def test_request_with_ssrf_proxy(mocker: MockerFixture, config_overrides: Callable[..., None]):
+ config_overrides(SSRF_PROXY_HTTP_URL="http://proxy:8080", SSRF_PROXY_HTTPS_URL="https://proxy:8081")
# Mock httpx.Client
mock_client = mocker.MagicMock()
@@ -60,10 +60,8 @@ def test_request_with_ssrf_proxy(mocker: MockerFixture):
assert mock_transport.call_count == 2
-def test_request_with_only_one_proxy_config(mocker: MockerFixture):
- # Mock dify_config with only one proxy
- mocker.patch("configs.dify_config.SSRF_PROXY_HTTP_URL", "http://proxy:8080")
- mocker.patch("configs.dify_config.SSRF_PROXY_HTTPS_URL", None)
+def test_request_with_only_one_proxy_config(mocker: MockerFixture, config_overrides: Callable[..., None]):
+ config_overrides(SSRF_PROXY_HTTP_URL="http://proxy:8080", SSRF_PROXY_HTTPS_URL=None)
# Mock httpx.Client
mock_client = mocker.MagicMock()
diff --git a/api/tests/unit_tests/core/helper/test_marketplace.py b/api/tests/unit_tests/core/helper/test_marketplace.py
index 6d9d37f4c93..a587584ae19 100644
--- a/api/tests/unit_tests/core/helper/test_marketplace.py
+++ b/api/tests/unit_tests/core/helper/test_marketplace.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -21,9 +22,11 @@ def test_get_plugin_pkg_url_contains_unique_identifier() -> None:
assert "unique_identifier=langgenius%2Fopenai%3A0.4.2%40checksum" in url
-def test_download_plugin_pkg_delegates_with_configured_size(mocker: MockerFixture) -> None:
+def test_download_plugin_pkg_delegates_with_configured_size(
+ mocker: MockerFixture, config_overrides: Callable[..., None]
+) -> None:
mocked_download = mocker.patch("core.helper.marketplace.download_with_size_limit", return_value=b"pkg")
- mocker.patch("core.helper.marketplace.dify_config.PLUGIN_MAX_PACKAGE_SIZE", 1234)
+ config_overrides(PLUGIN_MAX_PACKAGE_SIZE=1234)
result = download_plugin_pkg("langgenius/openai:0.4.2@checksum")
diff --git a/api/tests/unit_tests/core/helper/test_ssrf_proxy.py b/api/tests/unit_tests/core/helper/test_ssrf_proxy.py
index 458f2efd05b..824db04c56d 100644
--- a/api/tests/unit_tests/core/helper/test_ssrf_proxy.py
+++ b/api/tests/unit_tests/core/helper/test_ssrf_proxy.py
@@ -1,4 +1,5 @@
import gzip
+from collections.abc import Callable
from typing import override
from unittest.mock import ANY, MagicMock, call, patch
@@ -141,15 +142,19 @@ def test_force_list_response_returns_when_retries_disabled(mock_get_client):
mock_client.send.assert_called_once()
-def test_build_ssrf_client_passes_ssl_verify_to_proxy_mount_transports():
+def test_build_ssrf_client_passes_ssl_verify_to_proxy_mount_transports(
+ config_overrides: Callable[..., None],
+):
+ config_overrides(
+ SSRF_PROXY_ALL_URL=None,
+ SSRF_PROXY_HTTP_URL="http://proxy.example.com:8080",
+ SSRF_PROXY_HTTPS_URL="http://proxy.example.com:8443",
+ )
mock_client = MagicMock()
http_transport = MagicMock()
https_transport = MagicMock()
with (
- patch("core.helper.ssrf_proxy.dify_config.SSRF_PROXY_ALL_URL", None),
- patch("core.helper.ssrf_proxy.dify_config.SSRF_PROXY_HTTP_URL", "http://proxy.example.com:8080"),
- patch("core.helper.ssrf_proxy.dify_config.SSRF_PROXY_HTTPS_URL", "http://proxy.example.com:8443"),
patch("core.helper.ssrf_proxy.httpx.HTTPTransport", side_effect=[http_transport, https_transport]) as transport,
patch("core.helper.ssrf_proxy.httpx.Client", return_value=mock_client) as client,
):
diff --git a/api/tests/unit_tests/core/plugin/impl/test_base_client_impl.py b/api/tests/unit_tests/core/plugin/impl/test_base_client_impl.py
index 3eff5112ec3..7ba72be423f 100644
--- a/api/tests/unit_tests/core/plugin/impl/test_base_client_impl.py
+++ b/api/tests/unit_tests/core/plugin/impl/test_base_client_impl.py
@@ -1,4 +1,5 @@
import json
+from collections.abc import Callable
from urllib.parse import quote
import pytest
@@ -42,9 +43,9 @@ class _StreamContext:
class TestBasePluginClientImpl:
- def test_inject_trace_headers(self, mocker: MockerFixture):
+ def test_inject_trace_headers(self, mocker: MockerFixture, config_overrides: Callable[..., None]):
client = BasePluginClient()
- mocker.patch("core.plugin.impl.base.dify_config.ENABLE_OTEL", True)
+ config_overrides(ENABLE_OTEL=True)
trace_header = "00-abc-xyz-01"
mocker.patch("core.helper.trace_id_helper.generate_traceparent_header", return_value=trace_header)
diff --git a/api/tests/unit_tests/core/plugin/test_endpoint_client.py b/api/tests/unit_tests/core/plugin/test_endpoint_client.py
index ff9deb918af..c8042275dfa 100644
--- a/api/tests/unit_tests/core/plugin/test_endpoint_client.py
+++ b/api/tests/unit_tests/core/plugin/test_endpoint_client.py
@@ -8,6 +8,7 @@ This test module covers the endpoint client operations including:
Tests follow the Arrange-Act-Assert pattern for clarity.
"""
+from collections.abc import Callable
from unittest.mock import MagicMock, patch
import httpx
@@ -42,13 +43,9 @@ class TestPluginEndpointClientDelete:
return PluginEndpointClient()
@pytest.fixture
- def mock_config(self):
+ def mock_config(self, config_overrides: Callable[..., None]):
"""Mock plugin daemon configuration."""
- with (
- patch("core.plugin.impl.base.dify_config.PLUGIN_DAEMON_URL", "http://127.0.0.1:5002"),
- patch("core.plugin.impl.base.dify_config.PLUGIN_DAEMON_KEY", "test-api-key"),
- ):
- yield
+ config_overrides(PLUGIN_DAEMON_URL="http://127.0.0.1:5002", PLUGIN_DAEMON_KEY="test-api-key")
def test_delete_endpoint_success(self, endpoint_client, mock_config):
"""Test successful endpoint deletion.
diff --git a/api/tests/unit_tests/core/plugin/test_plugin_entities.py b/api/tests/unit_tests/core/plugin/test_plugin_entities.py
index 3875ec70c5f..cb4eaf1cd88 100644
--- a/api/tests/unit_tests/core/plugin/test_plugin_entities.py
+++ b/api/tests/unit_tests/core/plugin/test_plugin_entities.py
@@ -1,11 +1,11 @@
import binascii
import datetime
+from collections.abc import Callable
from enum import StrEnum
import pytest
from flask import Response
from pydantic import ValidationError
-from pytest_mock import MockerFixture
from core.plugin.entities.endpoint import EndpointEntityWithInstance
from core.plugin.entities.marketplace import MarketplacePluginDeclaration, MarketplacePluginSnapshot
@@ -35,8 +35,8 @@ from graphon.model_runtime.entities.message_entities import (
class TestEndpointEntity:
- def test_endpoint_entity_with_instance_renders_url(self, mocker: MockerFixture):
- mocker.patch("core.plugin.entities.endpoint.dify_config.ENDPOINT_URL_TEMPLATE", "https://dify.test/{hook_id}")
+ def test_endpoint_entity_with_instance_renders_url(self, config_overrides: Callable[..., None]):
+ config_overrides(ENDPOINT_URL_TEMPLATE="https://dify.test/{hook_id}")
now = datetime.datetime.now(datetime.UTC)
entity = EndpointEntityWithInstance.model_validate(
diff --git a/api/tests/unit_tests/core/rag/datasource/keyword/jieba/test_jieba.py b/api/tests/unit_tests/core/rag/datasource/keyword/jieba/test_jieba.py
index eb96d33989b..835e6b54e87 100644
--- a/api/tests/unit_tests/core/rag/datasource/keyword/jieba/test_jieba.py
+++ b/api/tests/unit_tests/core/rag/datasource/keyword/jieba/test_jieba.py
@@ -289,7 +289,9 @@ def test_get_dataset_keyword_table_returns_existing_table_data(patched_runtime):
def test_get_dataset_keyword_table_creates_table_when_missing(monkeypatch: pytest.MonkeyPatch, patched_runtime):
keyword = Jieba(_dataset(dataset_keyword_table=None))
- monkeypatch.setattr(jieba_module.dify_config, "KEYWORD_DATA_SOURCE_TYPE", "database")
+ from tests.unit_tests.config_override import apply_config_overrides
+
+ apply_config_overrides(monkeypatch, KEYWORD_DATA_SOURCE_TYPE="database")
result = keyword._get_dataset_keyword_table(patched_runtime.session)
assert result == {}
diff --git a/api/tests/unit_tests/core/rag/datasource/vdb/test_vector_factory.py b/api/tests/unit_tests/core/rag/datasource/vdb/test_vector_factory.py
index 47b917c86d5..dd78ae7fd14 100644
--- a/api/tests/unit_tests/core/rag/datasource/vdb/test_vector_factory.py
+++ b/api/tests/unit_tests/core/rag/datasource/vdb/test_vector_factory.py
@@ -14,6 +14,7 @@ from extensions.storage.storage_type import StorageType
from models.dataset import Whitelist
from models.enums import CreatorUserRole
from models.model import UploadFile
+from tests.unit_tests.config_override import apply_config_overrides
def _register_fake_factory_module(monkeypatch: pytest.MonkeyPatch, module_path: str, class_name: str):
@@ -268,8 +269,11 @@ def test_init_vector_uses_whitelist_override(
tenant_id = str(uuid4())
sqlite_session.add(Whitelist(tenant_id=tenant_id, category="vector_db"))
sqlite_session.commit()
- monkeypatch.setattr(vector_factory_module.dify_config, "VECTOR_STORE", vector_factory_module.VectorType.CHROMA)
- monkeypatch.setattr(vector_factory_module.dify_config, "VECTOR_STORE_WHITELIST_ENABLE", True)
+ apply_config_overrides(
+ monkeypatch,
+ VECTOR_STORE=vector_factory_module.VectorType.CHROMA,
+ VECTOR_STORE_WHITELIST_ENABLE=True,
+ )
monkeypatch.setattr(
vector_factory_module.Vector,
"get_vector_factory",
@@ -290,8 +294,7 @@ def test_init_vector_uses_whitelist_override(
def test_init_vector_raises_when_vector_store_missing(
vector_factory_module, monkeypatch: pytest.MonkeyPatch, unbound_session: Session
):
- monkeypatch.setattr(vector_factory_module.dify_config, "VECTOR_STORE", None)
- monkeypatch.setattr(vector_factory_module.dify_config, "VECTOR_STORE_WHITELIST_ENABLE", False)
+ apply_config_overrides(monkeypatch, VECTOR_STORE=None, VECTOR_STORE_WHITELIST_ENABLE=False)
vector = vector_factory_module.Vector.__new__(vector_factory_module.Vector)
vector._dataset = SimpleNamespace(index_struct_dict=None, tenant_id="tenant-1")
diff --git a/api/tests/unit_tests/core/rag/extractor/test_extract_processor.py b/api/tests/unit_tests/core/rag/extractor/test_extract_processor.py
index 369e63e57e3..49c2cce919f 100644
--- a/api/tests/unit_tests/core/rag/extractor/test_extract_processor.py
+++ b/api/tests/unit_tests/core/rag/extractor/test_extract_processor.py
@@ -12,6 +12,7 @@ from core.rag.models.document import Document
from extensions.storage.storage_type import StorageType
from models.enums import CreatorUserRole
from models.model import UploadFile
+from tests.unit_tests.config_override import apply_config_overrides
def _upload_file(*, key: str, file_id: str = "upload-file-1") -> UploadFile:
@@ -145,7 +146,7 @@ class TestExtractProcessorLoaders:
content = "a" * 100_000
response = SimpleNamespace(headers={"Content-Type": "text/plain"}, content=content.encode())
monkeypatch.setattr(processor_module.remote_fetcher, "make_request", lambda *args, **kwargs: response)
- monkeypatch.setattr(processor_module.dify_config, "ETL_TYPE", "SelfHosted")
+ apply_config_overrides(monkeypatch, ETL_TYPE="SelfHosted")
text = ExtractProcessor.load_from_url("https://example.com/response.txt", return_text=True)
@@ -155,8 +156,11 @@ class TestExtractProcessorLoaders:
class TestExtractProcessorFileRouting:
@pytest.fixture(autouse=True)
def _set_unstructured_config(self, monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr(processor_module.dify_config, "UNSTRUCTURED_API_URL", "https://unstructured")
- monkeypatch.setattr(processor_module.dify_config, "UNSTRUCTURED_API_KEY", "key")
+ apply_config_overrides(
+ monkeypatch,
+ UNSTRUCTURED_API_URL="https://unstructured",
+ UNSTRUCTURED_API_KEY="key",
+ )
def _run_extract_for_extension(
self,
@@ -167,7 +171,7 @@ class TestExtractProcessorFileRouting:
session: object | None = None,
):
factory = _patch_all_extractors(monkeypatch)
- monkeypatch.setattr(processor_module.dify_config, "ETL_TYPE", etl_type)
+ apply_config_overrides(monkeypatch, ETL_TYPE=etl_type)
def fake_download(key: str, local_path: str):
Path(local_path).write_text("content", encoding="utf-8")
diff --git a/api/tests/unit_tests/core/rag/extractor/test_pdf_extractor.py b/api/tests/unit_tests/core/rag/extractor/test_pdf_extractor.py
index 3f5cf0d37cb..bc35f5fde03 100644
--- a/api/tests/unit_tests/core/rag/extractor/test_pdf_extractor.py
+++ b/api/tests/unit_tests/core/rag/extractor/test_pdf_extractor.py
@@ -8,6 +8,7 @@ from sqlalchemy.orm import Session
import core.rag.extractor.pdf_extractor as pe
from models.model import UploadFile
+from tests.unit_tests.config_override import apply_config_overrides
TENANT_ID = str(uuid4())
USER_ID = str(uuid4())
@@ -41,9 +42,12 @@ def mock_dependencies(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session)
storage = _Storage()
monkeypatch.setattr(pe, "storage", storage)
monkeypatch.setattr(pe, "db", _DatabaseBinding(sqlite_session))
- monkeypatch.setattr(pe.dify_config, "FILES_URL", "http://files.local")
- monkeypatch.setattr(pe.dify_config, "INTERNAL_FILES_URL", None)
- monkeypatch.setattr(pe.dify_config, "STORAGE_TYPE", "local")
+ apply_config_overrides(
+ monkeypatch,
+ FILES_URL="http://files.local",
+ INTERNAL_FILES_URL=None,
+ STORAGE_TYPE="local",
+ )
return _Dependencies(storage=storage, session=sqlite_session)
diff --git a/api/tests/unit_tests/core/rag/extractor/test_word_extractor.py b/api/tests/unit_tests/core/rag/extractor/test_word_extractor.py
index 830e95c1721..211feb8dd13 100644
--- a/api/tests/unit_tests/core/rag/extractor/test_word_extractor.py
+++ b/api/tests/unit_tests/core/rag/extractor/test_word_extractor.py
@@ -21,6 +21,7 @@ from sqlalchemy.orm import Session
import core.rag.extractor.word_extractor as we
from core.rag.extractor.word_extractor import WordExtractor
from models.model import UploadFile
+from tests.unit_tests.config_override import apply_config_overrides
class _TextOxmlElement(Protocol):
@@ -131,8 +132,7 @@ def test_extract_images_from_docx(monkeypatch: pytest.MonkeyPatch, inject_sessio
monkeypatch.setattr(we, "db", db_stub)
# Patch config values used for URL composition and storage type
- monkeypatch.setattr(we.dify_config, "FILES_URL", "http://files.local", raising=False)
- monkeypatch.setattr(we.dify_config, "STORAGE_TYPE", "local", raising=False)
+ apply_config_overrides(monkeypatch, FILES_URL="http://files.local", STORAGE_TYPE="local")
# Patch external image fetcher
def fake_make_request(method: str, url: str, **kwargs):
@@ -208,8 +208,7 @@ def test_extract_images_does_not_stage_partial_files_on_storage_failure(
)
save = MagicMock(side_effect=[None, RuntimeError("storage failure")])
monkeypatch.setattr(we, "storage", SimpleNamespace(save=save))
- monkeypatch.setattr(we.dify_config, "FILES_URL", "http://files.local", raising=False)
- monkeypatch.setattr(we.dify_config, "STORAGE_TYPE", "local", raising=False)
+ apply_config_overrides(monkeypatch, FILES_URL="http://files.local", STORAGE_TYPE="local")
extractor = object.__new__(WordExtractor)
extractor.tenant_id = "00000000-0000-0000-0000-000000000001"
@@ -222,35 +221,24 @@ def test_extract_images_does_not_stage_partial_files_on_storage_failure(
assert sqlite_session.scalars(select(UploadFile)).all() == []
-def test_extract_images_from_docx_uses_internal_files_url():
+def test_extract_images_from_docx_uses_internal_files_url(monkeypatch: pytest.MonkeyPatch):
"""Test that INTERNAL_FILES_URL takes precedence over FILES_URL for plugin access."""
# Test the URL generation logic directly
from configs import dify_config
- # Mock the configuration values
- original_files_url = dify_config.FILES_URL
- original_internal_files_url = dify_config.INTERNAL_FILES_URL
-
- try:
- # Set both URLs - INTERNAL should take precedence
- dify_config.FILES_URL = "http://external.example.com"
- dify_config.INTERNAL_FILES_URL = "http://internal.docker:5001"
-
- # Test the URL generation logic (same as in word_extractor.py)
- upload_file_id = "test_file_id"
+ apply_config_overrides(
+ monkeypatch,
+ FILES_URL="http://external.example.com",
+ INTERNAL_FILES_URL="http://internal.docker:5001",
+ )
- # This is the pattern we fixed in the word extractor
- base_url = dify_config.INTERNAL_FILES_URL or dify_config.FILES_URL
- generated_url = f"{base_url}/files/{upload_file_id}/file-preview"
+ upload_file_id = "test_file_id"
- # Verify that INTERNAL_FILES_URL is used instead of FILES_URL
- assert "http://internal.docker:5001" in generated_url, f"Expected internal URL, got: {generated_url}"
- assert "http://external.example.com" not in generated_url, f"Should not use external URL, got: {generated_url}"
+ base_url = dify_config.INTERNAL_FILES_URL or dify_config.FILES_URL
+ generated_url = f"{base_url}/files/{upload_file_id}/file-preview"
- finally:
- # Restore original values
- dify_config.FILES_URL = original_files_url
- dify_config.INTERNAL_FILES_URL = original_internal_files_url
+ assert "http://internal.docker:5001" in generated_url, f"Expected internal URL, got: {generated_url}"
+ assert "http://external.example.com" not in generated_url, f"Should not use external URL, got: {generated_url}"
def test_extract_hyperlinks(monkeypatch: pytest.MonkeyPatch, unbound_session: Session):
@@ -258,8 +246,7 @@ def test_extract_hyperlinks(monkeypatch: pytest.MonkeyPatch, unbound_session: Se
monkeypatch.setattr(we, "storage", SimpleNamespace(save=lambda k, d: None))
db_stub = SimpleNamespace(session=unbound_session)
monkeypatch.setattr(we, "db", db_stub)
- monkeypatch.setattr(we.dify_config, "FILES_URL", "http://files.local", raising=False)
- monkeypatch.setattr(we.dify_config, "STORAGE_TYPE", "local", raising=False)
+ apply_config_overrides(monkeypatch, FILES_URL="http://files.local", STORAGE_TYPE="local")
doc = Document()
p = doc.add_paragraph("Visit ")
@@ -303,8 +290,7 @@ def test_extract_legacy_hyperlinks(monkeypatch: pytest.MonkeyPatch, unbound_sess
monkeypatch.setattr(we, "storage", SimpleNamespace(save=lambda k, d: None))
db_stub = SimpleNamespace(session=unbound_session)
monkeypatch.setattr(we, "db", db_stub)
- monkeypatch.setattr(we.dify_config, "FILES_URL", "http://files.local", raising=False)
- monkeypatch.setattr(we.dify_config, "STORAGE_TYPE", "local", raising=False)
+ apply_config_overrides(monkeypatch, FILES_URL="http://files.local", STORAGE_TYPE="local")
doc = Document()
p = doc.add_paragraph()
@@ -476,7 +462,7 @@ def test_extract_images_handles_invalid_external_cases(monkeypatch: pytest.Monke
db_stub = SimpleNamespace(session=sqlite_session)
monkeypatch.setattr(we, "db", db_stub)
monkeypatch.setattr(we, "storage", SimpleNamespace(save=lambda key, data: None))
- monkeypatch.setattr(we.dify_config, "FILES_URL", "http://files.local", raising=False)
+ apply_config_overrides(monkeypatch, FILES_URL="http://files.local")
extractor = object.__new__(WordExtractor)
extractor.tenant_id = "tenant"
diff --git a/api/tests/unit_tests/core/tools/test_tool_manager.py b/api/tests/unit_tests/core/tools/test_tool_manager.py
index a2947dbd94a..a299fe465dc 100644
--- a/api/tests/unit_tests/core/tools/test_tool_manager.py
+++ b/api/tests/unit_tests/core/tools/test_tool_manager.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import json
import threading
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from dataclasses import dataclass
from datetime import datetime
from types import SimpleNamespace
@@ -956,10 +956,10 @@ def test_get_mcp_provider_controller_missing_raises(monkeypatch: pytest.MonkeyPa
ToolManager.get_mcp_provider_controller("tenant-1", "mcp-1")
-def test_generate_tool_icon_urls_for_builtin_and_plugin():
- with patch("core.tools.tool_manager.dify_config.CONSOLE_API_URL", "https://console.example.com"):
- builtin_url = ToolManager.generate_builtin_tool_icon_url("time")
- plugin_url = ToolManager.generate_plugin_tool_icon_url("tenant-1", "icon.svg")
+def test_generate_tool_icon_urls_for_builtin_and_plugin(config_overrides: Callable[..., None]):
+ config_overrides(CONSOLE_API_URL="https://console.example.com")
+ builtin_url = ToolManager.generate_builtin_tool_icon_url("time")
+ plugin_url = ToolManager.generate_plugin_tool_icon_url("tenant-1", "icon.svg")
assert builtin_url.endswith("/tool-provider/builtin/time/icon")
assert "/plugin/icon" in plugin_url
diff --git a/api/tests/unit_tests/core/workflow/generator/test_runner.py b/api/tests/unit_tests/core/workflow/generator/test_runner.py
index 35ed9f1ad5a..1a067ca2089 100644
--- a/api/tests/unit_tests/core/workflow/generator/test_runner.py
+++ b/api/tests/unit_tests/core/workflow/generator/test_runner.py
@@ -17,10 +17,10 @@ from unittest.mock import MagicMock, patch
import pytest
from jinja2 import Template
-from configs import dify_config
from core.workflow.generator.runner import WorkflowGenerator, _find_planned_tool_entry
from core.workflow.generator.tool_catalogue import ToolCatalogueEntry
from core.workflow.generator.types import GraphDict
+from tests.unit_tests.config_override import apply_config_overrides
def _llm_result(text: str) -> MagicMock:
@@ -456,7 +456,7 @@ class _ParallelBuilderModel:
class TestParallelNodeBuilder:
def test_builder_concurrency_caps_at_configured_workers(self, monkeypatch):
- monkeypatch.setattr(dify_config, "WORKFLOW_GENERATOR_NODE_BUILDER_MAX_WORKERS", 2)
+ apply_config_overrides(monkeypatch, WORKFLOW_GENERATOR_NODE_BUILDER_MAX_WORKERS=2)
planner = {
"title": "URL Summarizer",
"description": "Summarize a URL.",
@@ -512,7 +512,7 @@ class TestParallelNodeBuilder:
assert [edge["source"] for edge in result["graph"]["edges"]] == ["node1", "node2"]
def test_higher_worker_config_runs_all_builders_in_one_wave(self, monkeypatch):
- monkeypatch.setattr(dify_config, "WORKFLOW_GENERATOR_NODE_BUILDER_MAX_WORKERS", 5)
+ apply_config_overrides(monkeypatch, WORKFLOW_GENERATOR_NODE_BUILDER_MAX_WORKERS=5)
planner = {
"title": "URL Summarizer",
"description": "Summarize a URL.",
@@ -561,7 +561,7 @@ class TestParallelNodeBuilder:
# One worker: node1's builder fails immediately, node2's blocks the
# worker briefly, node3 sits in the queue. The failure must cancel
# node3 before the worker frees up — no LLM call for it at all.
- monkeypatch.setattr(dify_config, "WORKFLOW_GENERATOR_NODE_BUILDER_MAX_WORKERS", 1)
+ apply_config_overrides(monkeypatch, WORKFLOW_GENERATOR_NODE_BUILDER_MAX_WORKERS=1)
planner = {
"title": "x",
"description": "x",
diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py
index 34b72677314..28cf8ab6ef4 100644
--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py
+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py
@@ -39,6 +39,7 @@ from models.agent_config_entities import (
DeclaredOutputType,
WorkflowNodeJobConfig,
)
+from tests.unit_tests.config_override import apply_config_overrides
@pytest.fixture(autouse=True)
@@ -464,7 +465,7 @@ def test_builds_workflow_run_request_with_file_output_schema_and_reserved_metada
def test_build_maps_agent_soul_shell_settings_to_shell_layer(monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr("core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_SHELL_ENABLED", True)
+ apply_config_overrides(monkeypatch, AGENT_SHELL_ENABLED=True)
context = _context()
snapshot = AgentConfigSnapshot(
id="snapshot-1",
@@ -673,7 +674,7 @@ def test_build_shell_layer_config_maps_cli_tool_inline_secret_value_to_env():
def test_builds_workflow_run_request_with_dify_plugin_tools_layer(monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr("core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_SHELL_ENABLED", True)
+ apply_config_overrides(monkeypatch, AGENT_SHELL_ENABLED=True)
context = _context()
snapshot = AgentConfigSnapshot(
id="snapshot-1",
@@ -1470,7 +1471,7 @@ def test_build_config_layer_config_returns_empty_config_for_empty_agent_soul():
def test_workflow_run_request_has_config_layer_with_empty_agent_soul(monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr("core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_SHELL_ENABLED", True)
+ apply_config_overrides(monkeypatch, AGENT_SHELL_ENABLED=True)
result = WorkflowAgentRuntimeRequestBuilder().build(_context())
diff --git a/api/tests/unit_tests/services/agent/test_agent_observability_service.py b/api/tests/unit_tests/services/agent/test_agent_observability_service.py
index 8bcf67dbf93..32a6e5a54d8 100644
--- a/api/tests/unit_tests/services/agent/test_agent_observability_service.py
+++ b/api/tests/unit_tests/services/agent/test_agent_observability_service.py
@@ -1,7 +1,6 @@
import json
from datetime import UTC, datetime
from decimal import Decimal
-from types import SimpleNamespace
import pytest
from sqlalchemy import Select, select
@@ -30,6 +29,7 @@ from models.workflow import (
)
from services.agent import observability_service as observability_service_module
from services.agent.observability_service import AgentLogQueryParams, AgentObservabilityService
+from tests.unit_tests.config_override import apply_config_overrides
def _app(*, app_id: str = "app-1", name: str = "Iris", mode: AppMode = AppMode.AGENT_CHAT) -> App:
@@ -291,7 +291,7 @@ def test_statistics_workflow_chat_context_only_uses_chat_runs() -> None:
def test_workflow_metadata_numeric_sql_supports_postgresql_and_mysql(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(observability_service_module, "dify_config", SimpleNamespace(DB_TYPE="postgresql"))
+ apply_config_overrides(monkeypatch, DB_TYPE="postgresql")
postgres_sql = AgentObservabilityService._workflow_execution_metadata_numeric_sql(
("agent_log", "agent_backend", "usage", "total_tokens"), "BIGINT"
@@ -300,7 +300,7 @@ def test_workflow_metadata_numeric_sql_supports_postgresql_and_mysql(monkeypatch
assert "CAST(wne.execution_metadata AS JSONB)" in postgres_sql
assert "#>> '{agent_log,agent_backend,usage,total_tokens}'" in postgres_sql
- monkeypatch.setattr(observability_service_module, "dify_config", SimpleNamespace(DB_TYPE="mysql"))
+ apply_config_overrides(monkeypatch, DB_TYPE="mysql")
mysql_sql = AgentObservabilityService._workflow_execution_metadata_numeric_sql(("total_tokens",), "BIGINT")
@@ -315,7 +315,7 @@ def test_workflow_statistics_include_run_without_message(
sqlite_session.add_all([workflow_app, _workflow_run(), _node_execution(), _workflow_binding()])
sqlite_session.commit()
- monkeypatch.setattr(observability_service_module, "dify_config", SimpleNamespace(DB_TYPE="mysql"))
+ apply_config_overrides(monkeypatch, DB_TYPE="mysql")
monkeypatch.setattr(observability_service_module, "convert_datetime_to_date", lambda field: f"DATE({field})")
monkeypatch.setattr(
AgentObservabilityService,
diff --git a/api/tests/unit_tests/services/agent/test_skill_package_service.py b/api/tests/unit_tests/services/agent/test_skill_package_service.py
index f634cfdda45..fa7cb7a48eb 100644
--- a/api/tests/unit_tests/services/agent/test_skill_package_service.py
+++ b/api/tests/unit_tests/services/agent/test_skill_package_service.py
@@ -221,7 +221,9 @@ def test_validate_and_normalize_rejects_archive_too_large_uncompressed(monkeypat
def test_validate_and_normalize_rejects_archive_too_large_uploaded_bytes(monkeypatch: pytest.MonkeyPatch):
- monkeypatch.setattr(skill_package_service_module.dify_config, "UPLOAD_SKILL_FILE_SIZE_LIMIT", 1)
+ from tests.unit_tests.config_override import apply_config_overrides
+
+ apply_config_overrides(monkeypatch, UPLOAD_SKILL_FILE_SIZE_LIMIT=1)
with pytest.raises(SkillPackageError) as exc_info:
SkillPackageService().validate_and_normalize(content=b"x" * (1024 * 1024 + 1), filename="skill.zip")
diff --git a/api/tests/unit_tests/services/controller_api.py b/api/tests/unit_tests/services/controller_api.py
index 4dd0019cfc0..3ef2a15c3ca 100644
--- a/api/tests/unit_tests/services/controller_api.py
+++ b/api/tests/unit_tests/services/controller_api.py
@@ -82,7 +82,7 @@ This test suite follows a comprehensive testing strategy that covers:
================================================================================
"""
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from types import SimpleNamespace
from unittest.mock import Mock, patch
from uuid import uuid4
@@ -813,7 +813,8 @@ class TestExternalDatasetApi:
)
@pytest.fixture
- def mock_current_account_context(self, app: Flask) -> Iterator[Mock]:
+ def mock_current_account_context(self, app: Flask, config_overrides: Callable[..., None]) -> Iterator[Mock]:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
"""Provide the wrapper auth context required by HTTP-client controller tests."""
mock_user = Account(
name="Test User",
@@ -830,7 +831,6 @@ class TestExternalDatasetApi:
with (
patch("controllers.console.wraps.current_account_with_tenant") as mock_get_user,
- patch("controllers.console.wraps.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
patch("libs.login.check_csrf_token", return_value=None),
):
mock_tenant_id = "tenant-123"
diff --git a/api/tests/unit_tests/services/rag_pipeline/test_pipeline_generate_service.py b/api/tests/unit_tests/services/rag_pipeline/test_pipeline_generate_service.py
index 27188816af6..fabc093c9b0 100644
--- a/api/tests/unit_tests/services/rag_pipeline/test_pipeline_generate_service.py
+++ b/api/tests/unit_tests/services/rag_pipeline/test_pipeline_generate_service.py
@@ -1,3 +1,5 @@
+from collections.abc import Callable
+
import pytest
from pytest_mock import MockerFixture
from sqlalchemy.orm import Session
@@ -76,9 +78,10 @@ def _make_document(
)
-def test_get_max_active_requests_uses_smallest_non_zero_limit(mocker: MockerFixture) -> None:
- mocker.patch("services.rag_pipeline.pipeline_generate_service.dify_config.APP_DEFAULT_ACTIVE_REQUESTS", 5)
- mocker.patch("services.rag_pipeline.pipeline_generate_service.dify_config.APP_MAX_ACTIVE_REQUESTS", 3)
+def test_get_max_active_requests_uses_smallest_non_zero_limit(
+ config_overrides: Callable[..., None],
+) -> None:
+ config_overrides(APP_DEFAULT_ACTIVE_REQUESTS=5, APP_MAX_ACTIVE_REQUESTS=3)
app_model = _make_app(max_active_requests=10)
@@ -87,9 +90,10 @@ def test_get_max_active_requests_uses_smallest_non_zero_limit(mocker: MockerFixt
assert result == 3
-def test_get_max_active_requests_returns_zero_when_all_unlimited(mocker: MockerFixture) -> None:
- mocker.patch("services.rag_pipeline.pipeline_generate_service.dify_config.APP_DEFAULT_ACTIVE_REQUESTS", 0)
- mocker.patch("services.rag_pipeline.pipeline_generate_service.dify_config.APP_MAX_ACTIVE_REQUESTS", 0)
+def test_get_max_active_requests_returns_zero_when_all_unlimited(
+ config_overrides: Callable[..., None],
+) -> None:
+ config_overrides(APP_DEFAULT_ACTIVE_REQUESTS=0, APP_MAX_ACTIVE_REQUESTS=0)
app_model = _make_app(max_active_requests=0)
diff --git a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline.py b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline.py
index 2ddb1ea4485..dcbff0dbdf3 100644
--- a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline.py
+++ b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline.py
@@ -1,3 +1,5 @@
+from collections.abc import Callable
+
from pytest_mock import MockerFixture
from services.rag_pipeline.rag_pipeline import RagPipelineService
@@ -9,8 +11,9 @@ def _make_service() -> RagPipelineService:
def test_fetch_recommended_plugin_manifests_returns_empty_when_disabled(
mocker: MockerFixture,
+ config_overrides: Callable[..., None],
) -> None:
- mocker.patch("services.rag_pipeline.rag_pipeline.dify_config.MARKETPLACE_ENABLED", False)
+ config_overrides(MARKETPLACE_ENABLED=False)
batch_fetch = mocker.patch("services.rag_pipeline.rag_pipeline.marketplace.batch_fetch_plugin_by_ids")
service = _make_service()
@@ -22,8 +25,9 @@ def test_fetch_recommended_plugin_manifests_returns_empty_when_disabled(
def test_fetch_recommended_plugin_manifests_returns_data_when_enabled(
mocker: MockerFixture,
+ config_overrides: Callable[..., None],
) -> None:
- mocker.patch("services.rag_pipeline.rag_pipeline.dify_config.MARKETPLACE_ENABLED", True)
+ config_overrides(MARKETPLACE_ENABLED=True)
expected = [{"plugin_id": "langgenius/openai", "name": "OpenAI"}]
mocker.patch(
"services.rag_pipeline.rag_pipeline.marketplace.batch_fetch_plugin_by_ids",
diff --git a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_service.py b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_service.py
index cea5bc86a02..a7194a805ef 100644
--- a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_service.py
+++ b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_service.py
@@ -1,5 +1,6 @@
import json
import time
+from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from types import SimpleNamespace
@@ -249,9 +250,9 @@ def _make_recommended_plugin(plugin_id: str) -> PipelineRecommendedPlugin:
def test_get_pipeline_templates_fallbacks_to_builtin_for_non_english_empty_result(
- mocker: MockerFixture, sqlite_session: Session
+ mocker: MockerFixture, sqlite_session: Session, config_overrides: Callable[..., None]
) -> None:
- mocker.patch("services.rag_pipeline.rag_pipeline.dify_config.HOSTED_FETCH_PIPELINE_TEMPLATES_MODE", "remote")
+ config_overrides(HOSTED_FETCH_PIPELINE_TEMPLATES_MODE="remote")
session = sqlite_session
remote_retrieval = mocker.Mock()
@@ -290,9 +291,12 @@ def test_get_pipeline_templates_customized_mode_uses_customized_factory(
@pytest.mark.parametrize("template_type", ["built-in", "customized"])
def test_get_pipeline_template_detail_uses_expected_mode(
- mocker: MockerFixture, template_type: str, sqlite_session: Session
+ mocker: MockerFixture,
+ template_type: str,
+ sqlite_session: Session,
+ config_overrides: Callable[..., None],
) -> None:
- mocker.patch("services.rag_pipeline.rag_pipeline.dify_config.HOSTED_FETCH_PIPELINE_TEMPLATES_MODE", "remote")
+ config_overrides(HOSTED_FETCH_PIPELINE_TEMPLATES_MODE="remote")
session = sqlite_session
retrieval = mocker.Mock()
retrieval.get_pipeline_template_detail.return_value = {"id": "tpl-1"}
@@ -1919,8 +1923,10 @@ def test_init_uses_default_sessionmaker_when_none(mocker: MockerFixture, sqlite_
assert exec_session_maker.kw["expire_on_commit"] is False
-def test_get_pipeline_templates_builtin_en_us_no_fallback(mocker: MockerFixture, sqlite_session: Session) -> None:
- mocker.patch("services.rag_pipeline.rag_pipeline.dify_config.HOSTED_FETCH_PIPELINE_TEMPLATES_MODE", "remote")
+def test_get_pipeline_templates_builtin_en_us_no_fallback(
+ mocker: MockerFixture, sqlite_session: Session, config_overrides: Callable[..., None]
+) -> None:
+ config_overrides(HOSTED_FETCH_PIPELINE_TEMPLATES_MODE="remote")
session = sqlite_session
retrieval = mocker.Mock()
retrieval.get_pipeline_templates.return_value = {"pipeline_templates": []}
diff --git a/api/tests/unit_tests/services/test_agent_app_sandbox_service.py b/api/tests/unit_tests/services/test_agent_app_sandbox_service.py
index c2418ecd09a..5a8fea8f4aa 100644
--- a/api/tests/unit_tests/services/test_agent_app_sandbox_service.py
+++ b/api/tests/unit_tests/services/test_agent_app_sandbox_service.py
@@ -36,6 +36,7 @@ from services.agent_app_sandbox_service import (
AgentSandboxInspectorError,
WorkflowAgentSandboxService,
)
+from tests.unit_tests.config_override import apply_config_overrides
def _add_normal_conversation(session: Session, *, binding_id: str) -> Conversation:
@@ -687,7 +688,7 @@ def test_workflow_download_resolves_only_exact_active_owner_chain(
"FileRequestService",
lambda: SimpleNamespace(request_download=request_download),
)
- monkeypatch.setattr(sandbox_module.dify_config, "FILES_URL", "https://files.example")
+ apply_config_overrides(monkeypatch, FILES_URL="https://files.example")
service = WorkflowAgentSandboxService(client_factory=lambda: nullcontext(cast(Client, client)))
result = service.download_file(
@@ -847,7 +848,7 @@ def test_workflow_download_uses_authenticated_account_and_trusted_file_request(
"services.agent_app_sandbox_service.FileRequestService",
lambda: SimpleNamespace(request_download=request_download),
)
- monkeypatch.setattr("services.agent_app_sandbox_service.dify_config.FILES_URL", "https://files.example")
+ apply_config_overrides(monkeypatch, FILES_URL="https://files.example")
result = WorkflowAgentSandboxService(client_factory=lambda: nullcontext(client)).download_file(
tenant_id="tenant-1",
@@ -904,7 +905,7 @@ def test_agent_app_download_uses_complete_account_context_after_session_exit(
"FileRequestService",
lambda: SimpleNamespace(request_download=request_download),
)
- monkeypatch.setattr(sandbox_module.dify_config, "FILES_URL", "https://files.example")
+ apply_config_overrides(monkeypatch, FILES_URL="https://files.example")
result = AgentAppSandboxService(client_factory=lambda: nullcontext(client)).download_file(
tenant_id="tenant-1",
diff --git a/api/tests/unit_tests/services/test_agent_config_service.py b/api/tests/unit_tests/services/test_agent_config_service.py
index bc2a1f84b0b..f69def8bd7c 100644
--- a/api/tests/unit_tests/services/test_agent_config_service.py
+++ b/api/tests/unit_tests/services/test_agent_config_service.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import io
import zipfile
+from collections.abc import Callable
from datetime import datetime
from types import SimpleNamespace
from unittest.mock import patch
@@ -1162,7 +1163,10 @@ def test_resolve_skill_file_member_path_requires_existing_member() -> None:
assert exc_info.value.status_code == 404
-def test_download_url_helpers_bind_shared_download_request_to_console_origin() -> None:
+def test_download_url_helpers_bind_shared_download_request_to_console_origin(
+ config_overrides: Callable[..., None],
+) -> None:
+ config_overrides(FILES_URL="https://example.com")
service = AgentConfigService()
with (
@@ -1174,7 +1178,6 @@ def test_download_url_helpers_bind_shared_download_request_to_console_origin() -
ConfigDownloadRequest("guide.txt", "text/plain", 20, "/files/guide.txt?sign=2"),
],
),
- patch(f"{MODULE}.dify_config.FILES_URL", "https://example.com"),
):
assert (
service.download_skill_url(
diff --git a/api/tests/unit_tests/services/test_app_service.py b/api/tests/unit_tests/services/test_app_service.py
index 8c71979a726..b9bf28be032 100644
--- a/api/tests/unit_tests/services/test_app_service.py
+++ b/api/tests/unit_tests/services/test_app_service.py
@@ -114,7 +114,10 @@ def _persist_agent_app(
class TestCreateAppTransactionBoundary:
- def test_commits_database_state_before_external_side_effects(self, sqlite_session: Session) -> None:
+ def test_commits_database_state_before_external_side_effects(
+ self, sqlite_session: Session, config_overrides: Callable[..., None]
+ ) -> None:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
account = _persist_account(sqlite_session)
phase_events: list[str] = []
event.listen(sqlite_session, "after_commit", lambda _session: phase_events.append("commit"))
@@ -132,7 +135,6 @@ class TestCreateAppTransactionBoundary:
"services.app_service.FeatureService.get_system_features",
return_value=SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),
),
- patch("services.app_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY),
):
app = AppService().create_app(
account.current_tenant_id,
@@ -174,7 +176,10 @@ class TestCreateAppTransactionBoundary:
assert sqlite_session.scalars(select(AppModelConfig)).all() == []
assert sqlite_session.get(Agent, existing_agent.id) is existing_agent
- def test_falls_back_when_default_model_schema_is_unavailable(self, sqlite_session: Session) -> None:
+ def test_falls_back_when_default_model_schema_is_unavailable(
+ self, sqlite_session: Session, config_overrides: Callable[..., None]
+ ) -> None:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
account = _persist_account(sqlite_session)
model_type_instance = MagicMock()
model_type_instance.get_model_schema.side_effect = ValueError("Base model unknown-model not found")
@@ -195,7 +200,6 @@ class TestCreateAppTransactionBoundary:
"services.app_service.FeatureService.get_system_features",
return_value=SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),
),
- patch("services.app_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY),
):
app = AppService().create_app(
account.current_tenant_id,
diff --git a/api/tests/unit_tests/services/test_dataset_service_document.py b/api/tests/unit_tests/services/test_dataset_service_document.py
index 1763cfab7b9..18229ac3fb1 100644
--- a/api/tests/unit_tests/services/test_dataset_service_document.py
+++ b/api/tests/unit_tests/services/test_dataset_service_document.py
@@ -1,5 +1,6 @@
"""Unit tests for DocumentService behaviors in dataset_service."""
+from collections.abc import Callable
from datetime import datetime
from sqlalchemy import event, select
@@ -1117,13 +1118,18 @@ class TestDocumentServiceSaveDocumentWithDatasetId:
check_quota.assert_not_called()
- def test_save_document_with_dataset_id_enforces_batch_upload_limit(self, account_context, unbound_session: Session):
+ def test_save_document_with_dataset_id_enforces_batch_upload_limit(
+ self,
+ account_context,
+ unbound_session: Session,
+ config_overrides: Callable[..., None],
+ ):
+ config_overrides(BATCH_UPLOAD_LIMIT=1)
dataset = _dataset_row()
knowledge_config = _make_upload_knowledge_config(file_ids=["file-1", "file-2"])
with (
patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=True)),
- patch("services.dataset_service.dify_config.BATCH_UPLOAD_LIMIT", 1),
patch.object(DocumentService, "check_documents_upload_quota") as check_quota,
):
with pytest.raises(ValueError, match="batch upload limit of 1"):
@@ -1706,8 +1712,12 @@ class TestDocumentServiceSaveWithoutDatasetBilling:
yield account
def test_save_document_without_dataset_id_counts_notion_pages_for_quota(
- self, account_context, sqlite_session: Session
+ self,
+ account_context,
+ sqlite_session: Session,
+ config_overrides: Callable[..., None],
):
+ config_overrides(BATCH_UPLOAD_LIMIT="10")
knowledge_config = KnowledgeConfig(
indexing_technique="economy",
data_source=DataSource(
@@ -1736,7 +1746,6 @@ class TestDocumentServiceSaveWithoutDatasetBilling:
with (
patch("services.dataset_service.FeatureService.get_features", return_value=features),
- patch("services.dataset_service.dify_config.BATCH_UPLOAD_LIMIT", "10"),
patch.object(DocumentService, "check_documents_upload_quota") as check_quota,
patch.object(
DocumentService,
@@ -1755,8 +1764,12 @@ class TestDocumentServiceSaveWithoutDatasetBilling:
assert sqlite_session.get(Dataset, dataset.id) is dataset
def test_save_document_without_dataset_id_enforces_batch_limit_for_website_urls(
- self, account_context, unbound_session: Session
+ self,
+ account_context,
+ unbound_session: Session,
+ config_overrides: Callable[..., None],
):
+ config_overrides(BATCH_UPLOAD_LIMIT="1")
knowledge_config = KnowledgeConfig(
indexing_technique="economy",
data_source=DataSource(
@@ -1774,7 +1787,6 @@ class TestDocumentServiceSaveWithoutDatasetBilling:
with (
patch("services.dataset_service.FeatureService.get_features", return_value=_make_features(enabled=True)),
- patch("services.dataset_service.dify_config.BATCH_UPLOAD_LIMIT", "1"),
patch.object(DocumentService, "check_documents_upload_quota") as check_quota,
):
with pytest.raises(ValueError, match="batch upload limit of 1"):
diff --git a/api/tests/unit_tests/services/test_dataset_service_segment.py b/api/tests/unit_tests/services/test_dataset_service_segment.py
index 2e2ad0aa774..5598361f977 100644
--- a/api/tests/unit_tests/services/test_dataset_service_segment.py
+++ b/api/tests/unit_tests/services/test_dataset_service_segment.py
@@ -1,5 +1,7 @@
"""Unit tests for SegmentService behaviors in dataset_service."""
+from collections.abc import Callable
+
from services.dataset_ref_service import DatasetRef, DatasetRefService, DocumentRef, SegmentRef
from .dataset_service_test_helpers import (
@@ -471,13 +473,13 @@ class TestSegmentServiceValidation:
with pytest.raises(ValueError, match="Content is empty"):
SegmentService.segment_create_args_validate({"content": " "}, document)
- def test_segment_create_args_validate_enforces_attachment_limit(self):
+ def test_segment_create_args_validate_enforces_attachment_limit(self, config_overrides: Callable[..., None]):
+ config_overrides(SINGLE_CHUNK_ATTACHMENT_LIMIT=1)
document = _make_document(doc_form=IndexStructureType.PARAGRAPH_INDEX)
args = {"content": "hello", "attachment_ids": ["a-1", "a-2"]}
- with patch("services.dataset_service.dify_config.SINGLE_CHUNK_ATTACHMENT_LIMIT", 1):
- with pytest.raises(ValueError, match="Exceeded maximum attachment limit of 1"):
- SegmentService.segment_create_args_validate(args, document)
+ with pytest.raises(ValueError, match="Exceeded maximum attachment limit of 1"):
+ SegmentService.segment_create_args_validate(args, document)
def test_segment_create_args_validate_requires_attachment_ids_list(self):
document = _make_document(doc_form=IndexStructureType.PARAGRAPH_INDEX)
diff --git a/api/tests/unit_tests/services/test_human_input_delivery_test_service.py b/api/tests/unit_tests/services/test_human_input_delivery_test_service.py
index fb9ebf6e9be..8929d49702f 100644
--- a/api/tests/unit_tests/services/test_human_input_delivery_test_service.py
+++ b/api/tests/unit_tests/services/test_human_input_delivery_test_service.py
@@ -2,7 +2,8 @@
from __future__ import annotations
-from unittest.mock import MagicMock, patch
+from collections.abc import Callable
+from unittest.mock import MagicMock
from uuid import uuid4
import pytest
@@ -10,7 +11,6 @@ from flask import Flask
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session
-from configs import dify_config
from core.workflow.human_input_adapter import (
EmailDeliveryConfig,
EmailDeliveryMethod,
@@ -45,17 +45,17 @@ def _make_valid_email_config():
)
-def test_build_form_link():
- with patch.object(dify_config, "APP_WEB_URL", "http://example.com/"):
- assert _build_form_link("token123") == "http://example.com/form/token123"
+def test_build_form_link(config_overrides: Callable[..., None]):
+ config_overrides(APP_WEB_URL="http://example.com/")
+ assert _build_form_link("token123") == "http://example.com/form/token123"
- with patch.object(dify_config, "APP_WEB_URL", "http://example.com"):
- assert _build_form_link("token123") == "http://example.com/form/token123"
+ config_overrides(APP_WEB_URL="http://example.com")
+ assert _build_form_link("token123") == "http://example.com/form/token123"
assert _build_form_link(None) is None
- with patch.object(dify_config, "APP_WEB_URL", None):
- assert _build_form_link("token123") is None
+ config_overrides(APP_WEB_URL=None)
+ assert _build_form_link("token123") is None
class TestDeliveryTestRegistry:
@@ -320,7 +320,8 @@ class TestEmailDeliveryTestHandler:
handler = EmailDeliveryTestHandler(session_factory=sqlite_engine)
assert handler._query_workspace_member_emails(tenant_id="t1", user_ids=[]) == {}
- def test_build_substitutions(self):
+ def test_build_substitutions(self, config_overrides: Callable[..., None]):
+ config_overrides(APP_WEB_URL="http://example.com")
context = DeliveryTestContext(
tenant_id="t1",
app_id="a1",
@@ -331,8 +332,7 @@ class TestEmailDeliveryTestHandler:
recipients=[DeliveryTestEmailRecipient(email="[email protected]", form_token="token123")],
)
- with patch.object(dify_config, "APP_WEB_URL", "http://example.com"):
- subs = EmailDeliveryTestHandler._build_substitutions(context=context, recipient_email="[email protected]")
+ subs = EmailDeliveryTestHandler._build_substitutions(context=context, recipient_email="[email protected]")
assert subs["node_title"] == "title"
assert subs["form_content"] == "content"
diff --git a/api/tests/unit_tests/services/test_human_input_service.py b/api/tests/unit_tests/services/test_human_input_service.py
index 8760e6cb957..5c42999ae74 100644
--- a/api/tests/unit_tests/services/test_human_input_service.py
+++ b/api/tests/unit_tests/services/test_human_input_service.py
@@ -40,6 +40,7 @@ from services.human_input_service import (
HumanInputService,
InvalidFormDataError,
)
+from tests.unit_tests.config_override import apply_config_overrides
def _make_app(mode: AppMode) -> App:
@@ -130,7 +131,7 @@ def test_ensure_form_active_respects_global_timeout(
created_at=naive_utc_now() - timedelta(hours=2),
expiration_time=naive_utc_now() + timedelta(hours=2),
)
- monkeypatch.setattr(human_input_service_module.dify_config, "HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS", 3600)
+ apply_config_overrides(monkeypatch, HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS=3600)
with pytest.raises(FormExpiredError):
service.ensure_form_active(Form(expired_record))
@@ -701,7 +702,7 @@ def test_is_globally_expired_zero_timeout(
) -> None:
service = HumanInputService(unbound_session_factory)
- monkeypatch.setattr(human_input_service_module.dify_config, "HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS", 0)
+ apply_config_overrides(monkeypatch, HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS=0)
assert service._is_globally_expired(Form(sample_form_record)) is False
diff --git a/api/tests/unit_tests/services/test_knowledge_fs_proxy.py b/api/tests/unit_tests/services/test_knowledge_fs_proxy.py
index 4d7e67f6d60..51cd56b7bfd 100644
--- a/api/tests/unit_tests/services/test_knowledge_fs_proxy.py
+++ b/api/tests/unit_tests/services/test_knowledge_fs_proxy.py
@@ -223,14 +223,15 @@ def _set_config(
timeout_seconds: float = 7.5,
jwt_secret: str | None = _JWT_SECRET,
) -> None:
+ from tests.unit_tests.config_override import apply_config_overrides
+
values = {
"KNOWLEDGE_FS_BASE_URL": base_url,
"KNOWLEDGE_FS_SSE_READ_TIMEOUT_SECONDS": sse_read_timeout_seconds,
"KNOWLEDGE_FS_TIMEOUT_SECONDS": timeout_seconds,
"KNOWLEDGE_FS_JWT_SECRET": SecretStr(jwt_secret) if jwt_secret is not None else None,
}
- for name, value in values.items():
- monkeypatch.setattr(f"services.knowledge_fs_proxy.dify_config.{name}", value, raising=False)
+ apply_config_overrides(monkeypatch, **values)
def _processing_task_events_path() -> str:
diff --git a/api/tests/unit_tests/services/test_model_provider_service.py b/api/tests/unit_tests/services/test_model_provider_service.py
index 0de7fe2c9c4..2c2f86bbf40 100644
--- a/api/tests/unit_tests/services/test_model_provider_service.py
+++ b/api/tests/unit_tests/services/test_model_provider_service.py
@@ -387,7 +387,9 @@ class TestModelProviderServiceConfiguration:
def test_preferred_provider_fallback_uses_custom_presence_not_configuration_status(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
- monkeypatch.setattr(service_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ from tests.unit_tests.config_override import apply_config_overrides
+
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
state = _ProviderSummaryState(has_custom_provider=True)
preferred_provider_type = ModelProviderService._get_preferred_provider_type(
diff --git a/api/tests/unit_tests/services/test_snippet_service.py b/api/tests/unit_tests/services/test_snippet_service.py
index caac531bdbc..10c1622ab6e 100644
--- a/api/tests/unit_tests/services/test_snippet_service.py
+++ b/api/tests/unit_tests/services/test_snippet_service.py
@@ -940,15 +940,14 @@ def test_delete_draft_variable_files_removes_storage_objects(
def test_delete_archived_workflow_run_files_removes_prefixed_objects(monkeypatch: pytest.MonkeyPatch) -> None:
- from configs import dify_config
+ from tests.unit_tests.config_override import apply_config_overrides
snippet = _snippet()
archive_storage = SimpleNamespace(
list_objects=Mock(return_value=["tenant-1/app_id=snippet-1/run.json"]),
delete_object=Mock(),
)
- monkeypatch.setattr(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
- monkeypatch.setattr(dify_config, "ARCHIVE_STORAGE_ENABLED", True)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, ARCHIVE_STORAGE_ENABLED=True)
monkeypatch.setattr("libs.archive_storage.get_archive_storage", Mock(return_value=archive_storage))
SnippetService._delete_archived_workflow_run_files(snippet=snippet)
diff --git a/api/tests/unit_tests/services/test_step_by_step_tour_service.py b/api/tests/unit_tests/services/test_step_by_step_tour_service.py
index 94203183ef6..7a99fa61444 100644
--- a/api/tests/unit_tests/services/test_step_by_step_tour_service.py
+++ b/api/tests/unit_tests/services/test_step_by_step_tour_service.py
@@ -9,8 +9,8 @@ from sqlalchemy.orm import Session, sessionmaker
from enums import DeploymentEdition
from models.account import Account, AccountStatus
from models.onboarding import AccountStepByStepTourState
-from services import step_by_step_tour_service as service_module
from services.step_by_step_tour_service import StepByStepTourService
+from tests.unit_tests.config_override import apply_config_overrides
def _account(*, initialized_at: datetime | None = None, created_at: datetime | None = None) -> Account:
@@ -39,8 +39,11 @@ def _load_state(session: Session) -> AccountStepByStepTourState | None:
def _set_tour_config(monkeypatch: pytest.MonkeyPatch, *, enabled: bool, rollout_started_at: datetime | None) -> None:
- monkeypatch.setattr(service_module.dify_config, "ENABLE_STEP_BY_STEP_TOUR", enabled)
- monkeypatch.setattr(service_module.dify_config, "STEP_BY_STEP_TOUR_ROLLOUT_STARTED_AT", rollout_started_at)
+ apply_config_overrides(
+ monkeypatch,
+ ENABLE_STEP_BY_STEP_TOUR=enabled,
+ STEP_BY_STEP_TOUR_ROLLOUT_STARTED_AT=rollout_started_at,
+ )
def test_get_state_creates_state_and_records_first_workspace_for_eligible_account(
@@ -67,7 +70,7 @@ def test_get_state_creates_state_and_records_first_workspace_for_eligible_accoun
def test_is_eligible_does_not_depend_on_cloud_edition(monkeypatch: pytest.MonkeyPatch) -> None:
_set_tour_config(monkeypatch, enabled=True, rollout_started_at=datetime(2026, 6, 1))
- monkeypatch.setattr(service_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
result = StepByStepTourService.is_eligible(_account(initialized_at=datetime(2026, 6, 28)))
diff --git a/api/tests/unit_tests/services/test_telemetry_service.py b/api/tests/unit_tests/services/test_telemetry_service.py
index 8b1f9df0558..8b11e3a2ff7 100644
--- a/api/tests/unit_tests/services/test_telemetry_service.py
+++ b/api/tests/unit_tests/services/test_telemetry_service.py
@@ -58,11 +58,16 @@ def test_reporting_without_setup_is_skipped(sqlite_session: Session, telemetry_e
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
-def test_report_install_marks_reported_at(sqlite_session: Session, telemetry_enabled, monkeypatch: pytest.MonkeyPatch):
+def test_report_install_marks_reported_at(
+ sqlite_session: Session,
+ telemetry_enabled,
+ monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
+):
setup = DifySetup(version="installed-version", instance_id="d246c3a1-350b-406c-92c7-6043df680758")
sqlite_session.add(setup)
sqlite_session.commit()
- monkeypatch.setattr(telemetry_service.dify_config.project, "version", "running-version")
+ config_overrides(project=telemetry_service.dify_config.project.model_copy(update={"version": "running-version"}))
sent_payloads: list[dict[str, str | int]] = []
@@ -190,12 +195,15 @@ def test_report_install_does_not_use_fallback_endpoint_after_http_error(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
def test_report_heartbeat_retries_pending_install_before_heartbeat(
- sqlite_session: Session, telemetry_enabled, monkeypatch: pytest.MonkeyPatch
+ sqlite_session: Session,
+ telemetry_enabled,
+ monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
):
setup = DifySetup(version="installed-version", instance_id="d246c3a1-350b-406c-92c7-6043df680758")
sqlite_session.add(setup)
sqlite_session.commit()
- monkeypatch.setattr(telemetry_service.dify_config.project, "version", "running-version")
+ config_overrides(project=telemetry_service.dify_config.project.model_copy(update={"version": "running-version"}))
sent_payloads: list[dict[str, str | int]] = []
diff --git a/api/tests/unit_tests/services/test_turnstile_service.py b/api/tests/unit_tests/services/test_turnstile_service.py
index 5c2173b5eb8..e812e30fdbc 100644
--- a/api/tests/unit_tests/services/test_turnstile_service.py
+++ b/api/tests/unit_tests/services/test_turnstile_service.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from unittest.mock import MagicMock
import httpx
@@ -13,9 +14,8 @@ from services.turnstile_service import (
@pytest.fixture(autouse=True)
-def configure_turnstile(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr("services.turnstile_service.dify_config.TURNSTILE_SECRET_KEY", SecretStr("test-secret"))
- monkeypatch.setattr("services.turnstile_service.dify_config.TURNSTILE_ALLOWED_HOSTNAMES", "dify.dev")
+def configure_turnstile(config_overrides: Callable[..., None]) -> None:
+ config_overrides(TURNSTILE_SECRET_KEY=SecretStr("test-secret"), TURNSTILE_ALLOWED_HOSTNAMES="dify.dev")
def mock_response(monkeypatch: pytest.MonkeyPatch, *, status_code: int = 200, payload: object) -> MagicMock:
@@ -125,12 +125,11 @@ def test_verify_maps_timeout_to_upstream_error(monkeypatch: pytest.MonkeyPatch)
[(None, "dify.dev"), (SecretStr("test-secret"), "")],
)
def test_verify_fails_closed_when_cloud_configuration_is_missing(
- monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
secret: SecretStr | None,
allowed_hostnames: str,
) -> None:
- monkeypatch.setattr("services.turnstile_service.dify_config.TURNSTILE_SECRET_KEY", secret)
- monkeypatch.setattr("services.turnstile_service.dify_config.TURNSTILE_ALLOWED_HOSTNAMES", allowed_hostnames)
+ config_overrides(TURNSTILE_SECRET_KEY=secret, TURNSTILE_ALLOWED_HOSTNAMES=allowed_hostnames)
with pytest.raises(TurnstileUpstreamError):
TurnstileService.verify(token="verified-token", remote_ip=None)
diff --git a/api/tests/unit_tests/services/test_variable_truncator_additional.py b/api/tests/unit_tests/services/test_variable_truncator_additional.py
index 50644d42946..7e08ca75474 100644
--- a/api/tests/unit_tests/services/test_variable_truncator_additional.py
+++ b/api/tests/unit_tests/services/test_variable_truncator_additional.py
@@ -7,13 +7,17 @@ from graphon.variables.segments import IntegerSegment, ObjectSegment, StringSegm
from graphon.variables.types import SegmentType
from services import variable_truncator as truncator_module
from services.variable_truncator import VariableTruncator
+from tests.unit_tests.config_override import apply_config_overrides
class TestVariableTruncatorAdditionalBehavior:
def test_default_should_use_dify_config_limits(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(truncator_module.dify_config, "WORKFLOW_VARIABLE_TRUNCATION_MAX_SIZE", 111)
- monkeypatch.setattr(truncator_module.dify_config, "WORKFLOW_VARIABLE_TRUNCATION_ARRAY_LENGTH", 7)
- monkeypatch.setattr(truncator_module.dify_config, "WORKFLOW_VARIABLE_TRUNCATION_STRING_LENGTH", 33)
+ apply_config_overrides(
+ monkeypatch,
+ WORKFLOW_VARIABLE_TRUNCATION_MAX_SIZE=111,
+ WORKFLOW_VARIABLE_TRUNCATION_ARRAY_LENGTH=7,
+ WORKFLOW_VARIABLE_TRUNCATION_STRING_LENGTH=33,
+ )
truncator = VariableTruncator.default()
diff --git a/api/tests/unit_tests/services/test_webhook_service_additional.py b/api/tests/unit_tests/services/test_webhook_service_additional.py
index 44c13149088..9bf7f9d50b6 100644
--- a/api/tests/unit_tests/services/test_webhook_service_additional.py
+++ b/api/tests/unit_tests/services/test_webhook_service_additional.py
@@ -62,7 +62,9 @@ class TestWebhookServiceExtractionFallbacks:
flask_app: Flask,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(service_module.dify_config, "WEBHOOK_REQUEST_BODY_MAX_SIZE", 1)
+ from tests.unit_tests.config_override import apply_config_overrides
+
+ apply_config_overrides(monkeypatch, WEBHOOK_REQUEST_BODY_MAX_SIZE=1)
with flask_app.test_request_context("/webhook", method="POST", data="ab"):
with pytest.raises(RequestEntityTooLarge):
diff --git a/api/tests/unit_tests/services/test_workflow_service.py b/api/tests/unit_tests/services/test_workflow_service.py
index 16357514227..5d4e3d92ced 100644
--- a/api/tests/unit_tests/services/test_workflow_service.py
+++ b/api/tests/unit_tests/services/test_workflow_service.py
@@ -11,6 +11,7 @@ This test suite covers:
import json
import uuid
+from collections.abc import Callable
from datetime import datetime, timedelta
from types import SimpleNamespace
from typing import Any, cast
@@ -215,6 +216,10 @@ class TestWorkflowAssociatedDataFactory:
@pytest.mark.usefixtures("sqlite_session")
class TestWorkflowService:
+ @pytest.fixture(autouse=True)
+ def _community_edition(self, config_overrides: Callable[..., None]) -> None:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
+
"""
Comprehensive unit tests for WorkflowService methods.
@@ -1272,7 +1277,6 @@ class TestWorkflowService:
with (
patch("services.workflow_service.app_published_workflow_was_updated"),
- patch("services.workflow_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY),
patch(
"services.workflow_service.register_new_agent_beta_workflow_publish_after_commit"
) as register_workflow_publish,
@@ -1306,7 +1310,6 @@ class TestWorkflowService:
with (
patch("services.workflow_service.app_published_workflow_was_updated"),
- patch("services.workflow_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY),
patch(
"services.agent.workflow_publish_service.WorkflowAgentPublishService.copy_agent_node_bindings_to_published",
return_value=True,
@@ -1346,10 +1349,6 @@ class TestWorkflowService:
with (
patch("services.workflow_service.app_published_workflow_was_updated"),
- patch(
- "services.workflow_service.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- ),
):
first = workflow_service.publish_workflow(session=sqlite_session, app_model=app, account=account)
second = workflow_service.publish_workflow(session=sqlite_session, app_model=app, account=account)
@@ -1376,10 +1375,6 @@ class TestWorkflowService:
with (
patch("services.workflow_service.app_published_workflow_was_updated"),
- patch(
- "services.workflow_service.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- ),
):
published = workflow_service.publish_workflow(session=sqlite_session, app_model=app, account=account)
sqlite_session.flush()
@@ -1415,10 +1410,6 @@ class TestWorkflowService:
with (
patch("services.workflow_service.app_published_workflow_was_updated"),
- patch(
- "services.workflow_service.dify_config.DEPLOYMENT_EDITION",
- DeploymentEdition.COMMUNITY,
- ),
):
workflow = workflow_service.publish_workflow(session=sqlite_session, app_model=app, account=account)
published.append(workflow)
@@ -1485,7 +1476,13 @@ class TestWorkflowService:
):
workflow_service.publish_workflow(session=sqlite_session, app_model=app, account=account)
- def test_publish_workflow_trigger_limit_exceeded(self, workflow_service: WorkflowService, sqlite_session: Session):
+ def test_publish_workflow_trigger_limit_exceeded(
+ self,
+ workflow_service: WorkflowService,
+ sqlite_session: Session,
+ config_overrides: Callable[..., None],
+ ):
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
"""
Test publish_workflow raises error when trigger node limit exceeded in SANDBOX plan.
@@ -1511,7 +1508,6 @@ class TestWorkflowService:
sqlite_session.commit()
with (
- patch("services.workflow_service.dify_config.DEPLOYMENT_EDITION", DeploymentEdition.CLOUD),
patch("services.workflow_service.BillingService") as MockBillingService,
):
MockBillingService.get_info.return_value = {"subscription": {"plan": "sandbox"}}
diff --git a/api/tests/unit_tests/services/tools/test_builtin_tools_manage_service.py b/api/tests/unit_tests/services/tools/test_builtin_tools_manage_service.py
index c6926a310ed..bcaabd7b815 100644
--- a/api/tests/unit_tests/services/tools/test_builtin_tools_manage_service.py
+++ b/api/tests/unit_tests/services/tools/test_builtin_tools_manage_service.py
@@ -296,7 +296,9 @@ class TestGetOauthClientSchema:
monkeypatch.setattr(BuiltinToolManageService, "is_oauth_custom_client_enabled", MagicMock(return_value=True))
monkeypatch.setattr(BuiltinToolManageService, "is_oauth_system_client_exists", MagicMock(return_value=False))
monkeypatch.setattr(BuiltinToolManageService, "get_custom_oauth_client_params", MagicMock(return_value={}))
- monkeypatch.setattr(service_module.dify_config, "CONSOLE_API_URL", "https://api.example.com")
+ from tests.unit_tests.config_override import apply_config_overrides
+
+ apply_config_overrides(monkeypatch, CONSOLE_API_URL="https://api.example.com")
result = BuiltinToolManageService.get_builtin_tool_provider_oauth_client_schema("t", "google")
diff --git a/api/tests/unit_tests/tasks/test_human_input_timeout_tasks.py b/api/tests/unit_tests/tasks/test_human_input_timeout_tasks.py
index b8cca3a1171..3b320f4a0ec 100644
--- a/api/tests/unit_tests/tasks/test_human_input_timeout_tasks.py
+++ b/api/tests/unit_tests/tasks/test_human_input_timeout_tasks.py
@@ -14,6 +14,7 @@ from core.workflow.nodes.human_input.entities import FormDefinition
from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus
from models.human_input import HumanInputForm
from tasks import human_input_timeout_tasks as task_module
+from tests.unit_tests.config_override import apply_config_overrides
class _FakeService:
@@ -103,7 +104,7 @@ def test_check_and_handle_human_input_timeouts_marks_and_routes(
):
now = datetime(2025, 1, 1, 12, 0, 0)
monkeypatch.setattr(task_module, "naive_utc_now", lambda: now)
- monkeypatch.setattr(task_module.dify_config, "HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS", 3600)
+ apply_config_overrides(monkeypatch, HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS=3600)
forms = [
_build_form(
@@ -180,7 +181,7 @@ def test_check_and_handle_human_input_timeouts_orders_by_id_before_limit(
):
now = datetime(2025, 1, 1, 12, 0, 0)
monkeypatch.setattr(task_module, "naive_utc_now", lambda: now)
- monkeypatch.setattr(task_module.dify_config, "HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS", 0)
+ apply_config_overrides(monkeypatch, HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS=0)
forms = [
_build_form(
@@ -222,7 +223,7 @@ def test_check_and_handle_human_input_timeouts_omits_global_filter_when_disabled
):
now = datetime(2025, 1, 1, 12, 0, 0)
monkeypatch.setattr(task_module, "naive_utc_now", lambda: now)
- monkeypatch.setattr(task_module.dify_config, "HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS", 0)
+ apply_config_overrides(monkeypatch, HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS=0)
old_unexpired_form = _build_form(
form_id="form-old",
@@ -263,7 +264,7 @@ def test_check_and_handle_human_input_timeouts_routes_conversation_owned_form_to
# workflow_run_id — which previously raised and was swallowed by the except.
now = datetime(2025, 1, 1, 12, 0, 0)
monkeypatch.setattr(task_module, "naive_utc_now", lambda: now)
- monkeypatch.setattr(task_module.dify_config, "HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS", 3600)
+ apply_config_overrides(monkeypatch, HUMAN_INPUT_GLOBAL_TIMEOUT_SECONDS=3600)
form = _build_form(
form_id="form-chat",
diff --git a/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py b/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py
index 54eaf46f37b..7792f5b8e8d 100644
--- a/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py
+++ b/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py
@@ -2,12 +2,13 @@ from unittest.mock import MagicMock
import pytest
+from tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_task
+from tests.unit_tests.config_override import apply_config_overrides
+
APP_RBAC_QUEUE = "app_rbac"
def test_initialize_created_app_rbac_access_task_uses_rbac_queue():
- from tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_task
-
assert initialize_created_app_rbac_access_task.queue == APP_RBAC_QUEUE
@@ -21,7 +22,7 @@ def test_initialize_created_app_rbac_access_task_batches_workspace_members(monke
import tasks.initialize_created_app_rbac_access_task as task_module
from tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_task
- monkeypatch.setattr(task_module.dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
monkeypatch.setattr(
task_module.TenantService,
"iter_member_account_id_batches",
@@ -54,7 +55,7 @@ def test_initialize_created_app_rbac_access_task_retries_on_failure(monkeypatch:
import tasks.initialize_created_app_rbac_access_task as task_module
from tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_task
- monkeypatch.setattr(task_module.dify_config, "RBAC_ENABLED", True)
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=True)
monkeypatch.setattr(
task_module.TenantService,
"iter_member_account_id_batches",
diff --git a/api/tests/unit_tests/tasks/test_install_default_plugins_task.py b/api/tests/unit_tests/tasks/test_install_default_plugins_task.py
index 3a0357c24c5..f7e44be1a50 100644
--- a/api/tests/unit_tests/tasks/test_install_default_plugins_task.py
+++ b/api/tests/unit_tests/tasks/test_install_default_plugins_task.py
@@ -5,6 +5,8 @@ from unittest.mock import MagicMock, call
import pytest
from celery.exceptions import Retry
+from tests.unit_tests.config_override import apply_config_overrides
+
def test_install_default_plugins_task_uses_plugin_queue() -> None:
from tasks.install_default_plugins_task import install_default_plugins_task
@@ -71,7 +73,7 @@ def test_install_default_plugins_task_queues_model_configuration_after_daemon_in
plugin_id = "langgenius/openai"
plugin_identifier = "langgenius/openai:1.0.0@aaa"
- monkeypatch.setattr(task_module.dify_config, "NEW_USER_DEFAULT_MODELS", "llm:provider:model")
+ apply_config_overrides(monkeypatch, NEW_USER_DEFAULT_MODELS="llm:provider:model")
monkeypatch.setattr(
task_module.marketplace,
"batch_fetch_plugin_manifests",
@@ -96,7 +98,7 @@ def test_configure_default_models_task_retries_while_plugins_are_installing(
import tasks.install_default_plugins_task as task_module
from tasks.install_default_plugins_task import configure_default_models_task
- monkeypatch.setattr(task_module.dify_config, "NEW_USER_DEFAULT_MODELS", "llm:provider:model")
+ apply_config_overrides(monkeypatch, NEW_USER_DEFAULT_MODELS="llm:provider:model")
monkeypatch.setattr(
task_module.PluginService,
"fetch_install_task",
@@ -115,10 +117,11 @@ def test_configure_default_models_task_sets_each_explicit_model(monkeypatch: pyt
import tasks.install_default_plugins_task as task_module
from tasks.install_default_plugins_task import configure_default_models_task
- monkeypatch.setattr(
- task_module.dify_config,
- "NEW_USER_DEFAULT_MODELS",
- ("llm:langgenius/openai/openai:gpt-4o-mini,text-embedding:langgenius/openai/openai:text-embedding-3-small"),
+ apply_config_overrides(
+ monkeypatch,
+ NEW_USER_DEFAULT_MODELS=(
+ "llm:langgenius/openai/openai:gpt-4o-mini,text-embedding:langgenius/openai/openai:text-embedding-3-small"
+ ),
)
fetch_install_task = MagicMock(
return_value=SimpleNamespace(