Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
ci: enable Ruff F841 (#44115)
Asuka Minato96202aa544c4
diff --git a/api/.ruff.toml b/api/.ruff.tomlindex 54a92ef94c8..eb35811b01d 100644--- a/api/.ruff.toml+++ b/api/.ruff.toml@@ -58,7 +58,6 @@ select = []ignore = [- "F841", # unused-variable"B901", # allow return in yield"B904", # raise-without-from-inside-except"N815", # mixed-case-variable-in-class-scopediff --git a/api/controllers/console/app/audio.py b/api/controllers/console/app/audio.pyindex 65c14b57ed3..bab5dd06a26 100644--- a/api/controllers/console/app/audio.py+++ b/api/controllers/console/app/audio.py@@ -440,7 +440,7 @@ def _get_text_to_speech_voices(*, tenant_id: str, language: str):raise CompletionRequestError(e.description)except ValueError as e:raise e- except Exception as e:+ except Exception:logger.exception("Failed to handle get request to TextModesApi")raise InternalServerError()diff --git a/api/controllers/console/app/completion.py b/api/controllers/console/app/completion.pyindex 640fd3dd38f..9c315b1e6e4 100644--- a/api/controllers/console/app/completion.py+++ b/api/controllers/console/app/completion.py@@ -205,7 +205,7 @@ class CompletionMessageApi(Resource):raise CompletionRequestError(e.description)except ValueError as e:raise e- except Exception as e:+ except Exception:logger.exception("internal server error.")raise InternalServerError()@@ -588,7 +588,7 @@ def _generate_chat_message(raise CompletionRequestError(e.description)except ValueError as e:raise e- except Exception as e:+ except Exception:logger.exception("internal server error.")raise InternalServerError()diff --git a/api/controllers/console/app/workflow.py b/api/controllers/console/app/workflow.pyindex fd4a65f38ce..259247fb8e6 100644--- a/api/controllers/console/app/workflow.py+++ b/api/controllers/console/app/workflow.py@@ -1867,7 +1867,7 @@ class DraftWorkflowTriggerNodeApi(Resource):files=files,)return jsonable_encoder(node_execution)- except Exception as e:+ except Exception:logger.exception("Error running draft workflow trigger node")return jsonable_encoder({"status": "error", "error": "An unexpected error occurred while running the node."}diff --git a/api/controllers/service_api/app/audio.py b/api/controllers/service_api/app/audio.pyindex 427598ead2a..e3d29c91fdf 100644--- a/api/controllers/service_api/app/audio.py+++ b/api/controllers/service_api/app/audio.py@@ -152,7 +152,7 @@ class AudioApi(Resource):raise CompletionRequestError(e.description)except ValueError as e:raise e- except Exception as e:+ except Exception:logger.exception("internal server error.")raise InternalServerError()@@ -244,6 +244,6 @@ class TextApi(Resource):raise CompletionRequestError(e.description)except ValueError as e:raise e- except Exception as e:+ except Exception:logger.exception("internal server error.")raise InternalServerError()diff --git a/api/controllers/trigger/webhook.py b/api/controllers/trigger/webhook.pyindex 4b5e4cfc9b8..d011975bb92 100644--- a/api/controllers/trigger/webhook.py+++ b/api/controllers/trigger/webhook.py@@ -164,6 +164,6 @@ def handle_webhook_debug(webhook_id: str):raise NotFound(str(e))except RequestEntityTooLarge:raise- except Exception as e:+ except Exception:logger.exception("Webhook debug processing failed for %s", webhook_id)return jsonify({"error": "Internal server error", "message": "An internal error has occurred."}), 500diff --git a/api/controllers/web/audio.py b/api/controllers/web/audio.pyindex 183d35603f2..5fc45514ada 100644--- a/api/controllers/web/audio.py+++ b/api/controllers/web/audio.py@@ -124,7 +124,7 @@ class AudioApi(WebApiResource):raise CompletionRequestError(e.description)except ValueError as e:raise e- except Exception as e:+ except Exception:logger.exception("Failed to handle post request to AudioApi")raise InternalServerError()@@ -188,6 +188,6 @@ class TextApi(WebApiResource):raise CompletionRequestError(e.description)except ValueError as e:raise e- except Exception as e:+ except Exception:logger.exception("Failed to handle post request to TextApi")raise InternalServerError()diff --git a/api/controllers/web/completion.py b/api/controllers/web/completion.pyindex a7bfe9c166d..b3efcffaa65 100644--- a/api/controllers/web/completion.py+++ b/api/controllers/web/completion.py@@ -161,7 +161,7 @@ class CompletionApi(WebApiResource):raise CompletionRequestError(e.description)except ValueError as e:raise e- except Exception as e:+ except Exception:logger.exception("internal server error.")raise InternalServerError()@@ -275,7 +275,7 @@ class ChatApi(WebApiResource):raise CompletionRequestError(e.description)except ValueError as e:raise e- except Exception as e:+ except Exception:logger.exception("internal server error.")raise InternalServerError()diff --git a/api/core/tools/utils/model_invocation_utils.py b/api/core/tools/utils/model_invocation_utils.pyindex 901ce24f966..4723b1ef5c9 100644--- a/api/core/tools/utils/model_invocation_utils.py+++ b/api/core/tools/utils/model_invocation_utils.py@@ -154,7 +154,7 @@ class ModelInvocationUtils:raise InvokeModelError(f"Invoke bad request error: {e}")except InvokeConnectionError as e:raise InvokeModelError(f"Invoke connection error: {e}")- except InvokeAuthorizationError as e:+ except InvokeAuthorizationError:raise InvokeModelError("Invoke authorization error")except InvokeServerUnavailableError as e:raise InvokeModelError(f"Invoke server unavailable error: {e}")diff --git a/api/providers/trace/trace-weave/tests/unit_tests/weave_trace/test_weave_trace.py b/api/providers/trace/trace-weave/tests/unit_tests/weave_trace/test_weave_trace.pyindex da2202fb0a9..4c0abbc8e4c 100644--- a/api/providers/trace/trace-weave/tests/unit_tests/weave_trace/test_weave_trace.py+++ b/api/providers/trace/trace-weave/tests/unit_tests/weave_trace/test_weave_trace.py@@ -265,7 +265,7 @@ class TestInit:"""Test __init__ initializes weave without entity prefix when entity is None."""mock_w, weave_client = mock_weaveconfig = _make_weave_config(entity=None)- instance = WeaveDataTrace(config)+ WeaveDataTrace(config)mock_w.init.assert_called_once_with(project_name="my-project")@@ -318,7 +318,6 @@ class TestGetProjectUrl:monkeypatch.setattr(trace_instance, "project_name", None)# Force an error by making string formatting fail# Simulate exception via property- original_entity = trace_instance.entitytrace_instance.entity = Nonetrace_instance.project_name = Noneurl = trace_instance.get_project_url()diff --git a/api/providers/vdb/vdb-alibabacloud-mysql/tests/unit_tests/test_alibabacloud_mysql_vector.py b/api/providers/vdb/vdb-alibabacloud-mysql/tests/unit_tests/test_alibabacloud_mysql_vector.pyindex e07c12e64d9..de170fedd59 100644--- a/api/providers/vdb/vdb-alibabacloud-mysql/tests/unit_tests/test_alibabacloud_mysql_vector.py+++ b/api/providers/vdb/vdb-alibabacloud-mysql/tests/unit_tests/test_alibabacloud_mysql_vector.py@@ -468,7 +468,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):vector_store = AlibabaCloudMySQLVector(self.collection_name, self.config)query_vector = [0.1, 0.2, 0.3, 0.4]- docs = vector_store.search_by_vector(query_vector, top_k=5, document_ids_filter=["dataset1"])+ vector_store.search_by_vector(query_vector, top_k=5, document_ids_filter=["dataset1"])# Verify the SQL contains the WHERE clause for filteringexecute_calls = mock_cursor.execute.call_args_list@@ -578,7 +578,7 @@ class TestAlibabaCloudMySQLVector(unittest.TestCase):mock_cursor.__iter__ = lambda self: iter([])vector_store = AlibabaCloudMySQLVector(self.collection_name, self.config)- docs = vector_store.search_by_full_text("machine learning", top_k=5, document_ids_filter=["dataset1"])+ vector_store.search_by_full_text("machine learning", top_k=5, document_ids_filter=["dataset1"])# Verify the SQL contains the AND clause for filteringexecute_calls = mock_cursor.execute.call_args_listdiff --git a/api/providers/vdb/vdb-baidu/src/dify_vdb_baidu/baidu_vector.py b/api/providers/vdb/vdb-baidu/src/dify_vdb_baidu/baidu_vector.pyindex f3c955adb06..6ef8f0cd9f4 100644--- a/api/providers/vdb/vdb-baidu/src/dify_vdb_baidu/baidu_vector.py+++ b/api/providers/vdb/vdb-baidu/src/dify_vdb_baidu/baidu_vector.py@@ -239,7 +239,7 @@ class BaiduVector(BaseVector):def _table_existed(self) -> bool:try:- table = self._db.table(self._collection_name)+ self._db.table(self._collection_name)except ServerError as e:if e.code == ServerErrCode.TABLE_NOT_EXIST:return Falsediff --git a/api/providers/vdb/vdb-clickzetta/src/dify_vdb_clickzetta/clickzetta_vector.py b/api/providers/vdb/vdb-clickzetta/src/dify_vdb_clickzetta/clickzetta_vector.pyindex c4caf7672ed..42d835a4e34 100644--- a/api/providers/vdb/vdb-clickzetta/src/dify_vdb_clickzetta/clickzetta_vector.py+++ b/api/providers/vdb/vdb-clickzetta/src/dify_vdb_clickzetta/clickzetta_vector.py@@ -421,7 +421,7 @@ class ClickzettaVector(BaseVector):breakexcept queue.Empty:continue- except (RuntimeError, ValueError, TypeError, ConnectionError) as e:+ except (RuntimeError, ValueError, TypeError, ConnectionError):logger.exception("Write worker error")def _execute_write(self, func, *args, **kwargs):diff --git a/api/providers/vdb/vdb-opengauss/tests/integration_tests/test_opengauss.py b/api/providers/vdb/vdb-opengauss/tests/integration_tests/test_opengauss.pyindex 8b444527d7a..b957e518906 100644--- a/api/providers/vdb/vdb-opengauss/tests/integration_tests/test_opengauss.py+++ b/api/providers/vdb/vdb-opengauss/tests/integration_tests/test_opengauss.py@@ -26,7 +26,7 @@ class OpenGaussTest(AbstractVectorTest):max_connection=5,)break- except psycopg2.OperationalError as e:+ except psycopg2.OperationalError:retry_count += 1if retry_count < max_retries:time.sleep(retry_delay)diff --git a/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py b/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.pyindex 74c5991bcd7..327bafd1498 100644--- a/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py+++ b/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py@@ -287,7 +287,7 @@ class WeaviateVector(BaseVector):self._ensure_properties()redis_client.set(cache_key, 1, ex=3600)- except Exception as e:+ except Exception:logger.exception("Error creating collection %s", self._collection_name)raisediff --git a/api/repositories/knowledge/dataset_read_repository.py b/api/repositories/knowledge/dataset_read_repository.pyindex 6a0b837bcb7..81a072790fa 100644--- a/api/repositories/knowledge/dataset_read_repository.py+++ b/api/repositories/knowledge/dataset_read_repository.py@@ -605,7 +605,6 @@ def build_dataset_detail_prefetch(datasets: Sequence[Dataset], *, session: Sessiif not dataset_ids:return DatasetDetailPrefetch()- tenant_ids = {dataset.tenant_id for dataset in datasets}dataset_owners = [(dataset.tenant_id, dataset.id) for dataset in datasets]app_counts = dict(diff --git a/api/services/web_app_runtime_query_service.py b/api/services/web_app_runtime_query_service.pyindex a8bf2ce3b68..ad730200d1b 100644--- a/api/services/web_app_runtime_query_service.py+++ b/api/services/web_app_runtime_query_service.py@@ -77,7 +77,7 @@ class WebAppRuntimeQueryService:if record.site.icon_type == "image" and record.site.iconelse None)- except FileNotExistsError as exc:+ except FileNotExistsError:logger.warning("Web app site icon is unavailable: app_id=%s tenant_id=%s file_id=%s",record.app_id,diff --git a/api/tasks/ops_trace_task.py b/api/tasks/ops_trace_task.pyindex 49fe68ad7ed..acfa59df3f2 100644--- a/api/tasks/ops_trace_task.py+++ b/api/tasks/ops_trace_task.py@@ -124,7 +124,7 @@ def process_trace_tasks(self, file_info):logger.exception("Failed to schedule trace dispatch retry, app_id: %s", app_id)failed_key = f"{OPS_TRACE_FAILED_KEY}_{app_id}"redis_client.incr(failed_key)- except Exception as e:+ except Exception:logger.exception("Processing trace tasks failed, app_id: %s", app_id)failed_key = f"{OPS_TRACE_FAILED_KEY}_{app_id}"redis_client.incr(failed_key)diff --git a/api/tests/integration_tests/tasks/test_remove_app_and_related_data_task.py b/api/tests/integration_tests/tasks/test_remove_app_and_related_data_task.pyindex 4f444598b12..d9aafbea543 100644--- a/api/tests/integration_tests/tasks/test_remove_app_and_related_data_task.py+++ b/api/tests/integration_tests/tasks/test_remove_app_and_related_data_task.py@@ -19,7 +19,6 @@ from tasks.remove_app_and_related_data_task import (@pytest.fixturedef app_and_tenant(flask_req_ctx):- tenant_id = uuid.uuid4()with session_factory.create_session() as session:tenant = Tenant(name="test_tenant")session.add(tenant)diff --git a/api/tests/integration_tests/workflow/nodes/test_http.py b/api/tests/integration_tests/workflow/nodes/test_http.pyindex 86b0cd0fd71..d580388e5e4 100644--- a/api/tests/integration_tests/workflow/nodes/test_http.py+++ b/api/tests/integration_tests/workflow/nodes/test_http.py@@ -72,7 +72,7 @@ def init_http_node(config: dict):graph_runtime_state=graph_runtime_state,)- graph = Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")+ Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")node = HttpRequestNode(node_id=str(uuid.uuid4()),@@ -719,7 +719,7 @@ def test_nested_object_variable_selector(setup_http_mock):graph_runtime_state=graph_runtime_state,)- graph = Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")+ Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")node = HttpRequestNode(node_id=str(uuid.uuid4()),diff --git a/api/tests/test_containers_integration_tests/commands/test_legacy_model_type_migration.py b/api/tests/test_containers_integration_tests/commands/test_legacy_model_type_migration.pyindex 3229ab05685..69ffc70dbda 100644--- a/api/tests/test_containers_integration_tests/commands/test_legacy_model_type_migration.py+++ b/api/tests/test_containers_integration_tests/commands/test_legacy_model_type_migration.py@@ -141,7 +141,7 @@ def _insert_load_balancing_model_config(def migration_module():try:return importlib.import_module("services.legacy_model_type_migration")- except ModuleNotFoundError as exc: # pragma: no cover - explicit TDD failure path+ except ModuleNotFoundError: # pragma: no cover - explicit TDD failure pathpytest.fail("services.legacy_model_type_migration is missing. ""Implement LegacyModelTypeMigrationService before running these tests."diff --git a/api/tests/test_containers_integration_tests/services/test_advanced_prompt_template_service.py b/api/tests/test_containers_integration_tests/services/test_advanced_prompt_template_service.pyindex 144cba280f4..2c80269e6e6 100644--- a/api/tests/test_containers_integration_tests/services/test_advanced_prompt_template_service.py+++ b/api/tests/test_containers_integration_tests/services/test_advanced_prompt_template_service.py@@ -1,7 +1,6 @@import copyimport pytest-from faker import Fakerfrom sqlalchemy.orm import Sessionfrom core.prompt.prompt_templates.advanced_prompt_templates import (@@ -33,7 +32,6 @@ class TestAdvancedPromptTemplateService:- Proper prompt generation- Appropriate prompt template selection"""- fake = Faker()args = {"app_mode": AppMode.CHAT,@@ -68,7 +66,6 @@ class TestAdvancedPromptTemplateService:- Proper context integration- Template structure validation"""- fake = Faker()# Act: Execute the method under testresult = AdvancedPromptTemplateService.get_prompt(@@ -101,7 +98,6 @@ class TestAdvancedPromptTemplateService:- Proper context integration- Template structure validation"""- fake = Faker()# Act: Execute the method under testresult = AdvancedPromptTemplateService.get_prompt(app_mode=AppMode.CHAT, model_mode="chat", has_context="true")@@ -130,7 +126,6 @@ class TestAdvancedPromptTemplateService:- Proper context integration- Template structure validation"""- fake = Faker()# Act: Execute the method under testresult = AdvancedPromptTemplateService.get_prompt(@@ -160,7 +155,6 @@ class TestAdvancedPromptTemplateService:- Proper context integration- Template structure validation"""- fake = Faker()# Act: Execute the method under testresult = AdvancedPromptTemplateService.get_prompt(@@ -189,7 +183,6 @@ class TestAdvancedPromptTemplateService:- Context is not included in prompt- Template structure remains intact"""- fake = Faker()# Act: Execute the method under testresult = AdvancedPromptTemplateService.get_prompt(@@ -219,7 +212,6 @@ class TestAdvancedPromptTemplateService:- Proper handling of unsupported app modes- Default empty dict return"""- fake = Faker()# Act: Execute the method under testresult = AdvancedPromptTemplateService.get_prompt(@@ -239,7 +231,6 @@ class TestAdvancedPromptTemplateService:- Proper handling of unsupported model modes- Default empty dict return"""- fake = Faker()# Act: Execute the method under testresult = AdvancedPromptTemplateService.get_prompt(@@ -260,7 +251,6 @@ class TestAdvancedPromptTemplateService:- Template structure preservation- Context placement at the beginning"""- fake = Faker()# Create test prompt templateprompt_template = copy.deepcopy(CHAT_APP_COMPLETION_PROMPT_CONFIG)@@ -291,7 +281,6 @@ class TestAdvancedPromptTemplateService:- Original template is preserved when no context- No modification to prompt text"""- fake = Faker()# Create test prompt templateprompt_template = copy.deepcopy(CHAT_APP_COMPLETION_PROMPT_CONFIG)@@ -322,7 +311,6 @@ class TestAdvancedPromptTemplateService:- Template structure preservation- Context placement at the beginning of first message"""- fake = Faker()# Create test prompt templateprompt_template = copy.deepcopy(CHAT_APP_CHAT_PROMPT_CONFIG)@@ -354,7 +342,6 @@ class TestAdvancedPromptTemplateService:- Original template is preserved when no context- No modification to prompt text"""- fake = Faker()# Create test prompt templateprompt_template = copy.deepcopy(CHAT_APP_CHAT_PROMPT_CONFIG)@@ -383,7 +370,6 @@ class TestAdvancedPromptTemplateService:- All app modes work correctly- Proper template selection for each combination"""- fake = Faker()# Test all app modesapp_modes = [AppMode.CHAT, AppMode.COMPLETION]@@ -413,7 +399,6 @@ class TestAdvancedPromptTemplateService:- Proper error handling- Consistent behavior with unusual inputs"""- fake = Faker()# Test edge casesedge_cases = [@@ -443,7 +428,6 @@ class TestAdvancedPromptTemplateService:- Deep copy is used properly- Template immutability is maintained"""- fake = Faker()# Store original templatesoriginal_chat_completion = copy.deepcopy(CHAT_APP_COMPLETION_PROMPT_CONFIG)@@ -459,7 +443,7 @@ class TestAdvancedPromptTemplateService:}# Act: Execute the method under test- result = AdvancedPromptTemplateService.get_prompt(**args)+ AdvancedPromptTemplateService.get_prompt(**args)# Assert: Verify original templates are unchangedassert original_chat_completion == CHAT_APP_COMPLETION_PROMPT_CONFIG@@ -478,7 +462,6 @@ class TestAdvancedPromptTemplateService:- Context integration is consistent across different templates- No context duplication or corruption"""- fake = Faker()# Test different scenariostest_scenarios = [diff --git a/api/tests/test_containers_integration_tests/services/test_agent_service.py b/api/tests/test_containers_integration_tests/services/test_agent_service.pyindex ab7c658be08..42e040f0154 100644--- a/api/tests/test_containers_integration_tests/services/test_agent_service.py+++ b/api/tests/test_containers_integration_tests/services/test_agent_service.py@@ -224,7 +224,6 @@ class TestAgentService:Returns:list: Created agent thoughts"""- fake = Faker()agent_thoughts = []@@ -288,12 +287,11 @@ class TestAgentService:"""Test successful retrieval of agent logs with complete data."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)conversation, message = self._create_test_conversation_and_message(db_session_with_containers, app, account)- agent_thoughts = self._create_test_agent_thoughts(db_session_with_containers, message)+ self._create_test_agent_thoughts(db_session_with_containers, message)# Execute the method under testresult = AgentService.get_agent_logs(app, conversation.id, message.id, db_session_with_containers)@@ -537,7 +535,6 @@ class TestAgentService:"""Test agent logs retrieval with tool errors."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -587,7 +584,6 @@ class TestAgentService:"""Test agent logs retrieval when message has no agent thoughts."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -664,7 +660,6 @@ class TestAgentService:"""Test error handling when agent config is not found."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -683,7 +678,6 @@ class TestAgentService:"""Test successful listing of agent providers."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -704,7 +698,6 @@ class TestAgentService:"""Test successful retrieval of specific agent provider."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -728,7 +721,6 @@ class TestAgentService:"""Test error handling when plugin daemon client raises an error."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -750,7 +742,6 @@ class TestAgentService:"""Test agent logs retrieval with complex tool data and multiple tools."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -837,7 +828,6 @@ class TestAgentService:"""Test agent logs retrieval with message files and agent thought files."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -917,7 +907,6 @@ class TestAgentService:"""Test agent logs retrieval with different timezone settings."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -944,7 +933,6 @@ class TestAgentService:"""Test agent logs retrieval with empty tool data."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)@@ -985,7 +973,6 @@ class TestAgentService:"""Test agent logs retrieval with malformed JSON data in tool fields."""- fake = Faker()# Create test dataapp, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)diff --git a/api/tests/test_containers_integration_tests/services/test_annotation_service.py b/api/tests/test_containers_integration_tests/services/test_annotation_service.pyindex c0a5d213fac..93e49764f81 100644--- a/api/tests/test_containers_integration_tests/services/test_annotation_service.py+++ b/api/tests/test_containers_integration_tests/services/test_annotation_service.py@@ -497,7 +497,7 @@ class TestAnnotationService:- Search treats special characters as literal characters, not wildcards- SQL injection via LIKE wildcards is prevented"""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create annotations with special characters in content@@ -657,7 +657,7 @@ class TestAnnotationService:"""Test successful enabling of app annotation."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Setup enable arguments@@ -685,7 +685,7 @@ class TestAnnotationService:"""Test successful disabling of app annotation."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Disable annotation@@ -887,7 +887,7 @@ class TestAnnotationService:"""Test successful batch import of app annotations."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create CSV content@@ -929,7 +929,7 @@ class TestAnnotationService:"""Test batch import with empty CSV file."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create empty CSV content@@ -965,7 +965,7 @@ class TestAnnotationService:"""Test batch import when quota is exceeded."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create CSV content@@ -1055,7 +1055,7 @@ class TestAnnotationService:"""Test getting disabled app annotation setting by app ID."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Get annotation setting (no setting exists)diff --git a/api/tests/test_containers_integration_tests/services/test_app_generate_service.py b/api/tests/test_containers_integration_tests/services/test_app_generate_service.pyindex 879335d27fc..1f8825ed3a1 100644--- a/api/tests/test_containers_integration_tests/services/test_app_generate_service.py+++ b/api/tests/test_containers_integration_tests/services/test_app_generate_service.py@@ -983,7 +983,7 @@ class TestAppGenerateService:"""Test getting max active requests with app-specific limit."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies, mode="completion")@@ -1003,7 +1003,7 @@ class TestAppGenerateService:"""Test getting max active requests with config limit being smaller."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies, mode="completion")@@ -1024,7 +1024,7 @@ class TestAppGenerateService:"""Test getting max active requests with zero limits (infinite)."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies, mode="completion")diff --git a/api/tests/test_containers_integration_tests/services/test_app_service.py b/api/tests/test_containers_integration_tests/services/test_app_service.pyindex 9fa1170e70e..eaa6c999979 100644--- a/api/tests/test_containers_integration_tests/services/test_app_service.py+++ b/api/tests/test_containers_integration_tests/services/test_app_service.py@@ -497,10 +497,8 @@ class TestAppService:icon_background="#4ECDC4",)- chat_app = app_service.create_app(tenant.id, chat_app_params, account, session=db_session_with_containers)- completion_app = app_service.create_app(- tenant.id, completion_app_params, account, session=db_session_with_containers- )+ app_service.create_app(tenant.id, chat_app_params, account, session=db_session_with_containers)+ app_service.create_app(tenant.id, completion_app_params, account, session=db_session_with_containers)# Test filter by modechat_apps = app_service.get_paginate_apps(@@ -682,11 +680,6 @@ class TestAppService:app = app_service.create_app(tenant.id, app_params, account, session=db_session_with_containers)# Store original values- original_name = app.name- original_description = app.description- original_icon = app.icon- original_icon_background = app.icon_background- original_use_icon_as_answer_icon = app.use_icon_as_answer_icon# Update appupdate_args = {@@ -862,7 +855,6 @@ class TestAppService:app = app_service.create_app(tenant.id, app_args, account, session=db_session_with_containers)# Store original API status- original_api_status = app.enable_api# Update API status to disabledmock_current_user = create_autospec(Account, instance=True)@@ -1057,7 +1049,7 @@ class TestAppService:app_service = AppService()# Create apps with special characters in names- app_with_percent = app_service.create_app(+ app_service.create_app(tenant.id,CreateAppParams(name="App with 50% discount",@@ -1073,7 +1065,7 @@ class TestAppService:session=db_session_with_containers,)- app_with_underscore = app_service.create_app(+ app_service.create_app(tenant.id,CreateAppParams(name="test_data_app",@@ -1089,7 +1081,7 @@ class TestAppService:session=db_session_with_containers,)- app_with_backslash = app_service.create_app(+ app_service.create_app(tenant.id,CreateAppParams(name="path\\to\\app",@@ -1106,7 +1098,7 @@ class TestAppService:)# Create app that should NOT match- app_no_match = app_service.create_app(+ app_service.create_app(tenant.id,CreateAppParams(name="100% different",diff --git a/api/tests/test_containers_integration_tests/services/test_conversation_service.py b/api/tests/test_containers_integration_tests/services/test_conversation_service.pyindex 69407cb039b..33cc75edac7 100644--- a/api/tests/test_containers_integration_tests/services/test_conversation_service.py+++ b/api/tests/test_containers_integration_tests/services/test_conversation_service.py@@ -552,7 +552,7 @@ class TestConversationServiceSummarization:mock_llm_generator.return_value = generated_name# Act- result = ConversationService.auto_generate_name(app_model, conversation, session=db_session_with_containers)+ ConversationService.auto_generate_name(app_model, conversation, session=db_session_with_containers)# Assertassert conversation.name == generated_name # Name updated on conversation object@@ -609,7 +609,7 @@ class TestConversationServiceSummarization:mock_llm_generator.side_effect = Exception("LLM service unavailable")# Act- result = ConversationService.auto_generate_name(app_model, conversation, session=db_session_with_containers)+ ConversationService.auto_generate_name(app_model, conversation, session=db_session_with_containers)# Assertassert conversation.name == original_name # Name remains unchanged@@ -636,7 +636,7 @@ class TestConversationServiceSummarization:mock_naive_utc_now.return_value = mock_time# Act- result = ConversationService.rename(+ ConversationService.rename(app_model=app_model,conversation_id=conversation.id,user=user,diff --git a/api/tests/test_containers_integration_tests/services/test_end_user_service.py b/api/tests/test_containers_integration_tests/services/test_end_user_service.pyindex 2864f135ca1..b82a0a227e2 100644--- a/api/tests/test_containers_integration_tests/services/test_end_user_service.py+++ b/api/tests/test_containers_integration_tests/services/test_end_user_service.py@@ -421,7 +421,6 @@ class TestEndUserServiceCreateBatch:"""Create multiple apps under the same tenant."""first_app = factory.create_app_and_account(db_session_with_containers)tenant_id = first_app.tenant_id- apps = [first_app]for _ in range(count - 1):app = App(tenant_id=tenant_id,diff --git a/api/tests/test_containers_integration_tests/services/test_feature_service.py b/api/tests/test_containers_integration_tests/services/test_feature_service.pyindex bc939bbab9f..a5796361e8d 100644--- a/api/tests/test_containers_integration_tests/services/test_feature_service.py+++ b/api/tests/test_containers_integration_tests/services/test_feature_service.py@@ -260,7 +260,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Setup test data with proper config- tenant_id = self._create_test_tenant_id()+ self._create_test_tenant_id()with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEdiff --git a/api/tests/test_containers_integration_tests/services/test_file_service.py b/api/tests/test_containers_integration_tests/services/test_file_service.pyindex dc91e29085f..0f3016ba81c 100644--- a/api/tests/test_containers_integration_tests/services/test_file_service.py+++ b/api/tests/test_containers_integration_tests/services/test_file_service.py@@ -163,7 +163,7 @@ class TestFileService:"""Test successful file upload with valid parameters."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)filename = "test_document.pdf"@@ -198,7 +198,7 @@ class TestFileService:"""Test file upload with end user instead of account."""- fake = Faker()+end_user = self._create_test_end_user(db_session_with_containers, mock_external_service_dependencies)filename = "test_image.jpg"@@ -222,7 +222,7 @@ class TestFileService:"""Test file upload with datasets source parameter."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)filename = "test_document.pdf"@@ -247,7 +247,7 @@ class TestFileService:"""Test file upload with invalid filename characters."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)filename = "test/file<name>.txt"@@ -289,7 +289,7 @@ class TestFileService:"""Test file upload with filename that exceeds length limit."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)# Create a filename longer than 200 characters@@ -319,7 +319,7 @@ class TestFileService:"""Test file upload for datasets with unsupported file type."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)filename = "test_image.jpg"@@ -341,7 +341,7 @@ class TestFileService:"""Test file upload with file size exceeding limit."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)filename = "large_image.jpg"@@ -501,7 +501,7 @@ class TestFileService:"""Test successful file preview generation."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)upload_file = self._create_test_upload_file(db_session_with_containers, mock_external_service_dependencies, account@@ -535,7 +535,7 @@ class TestFileService:"""Test file preview with unsupported file type."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)upload_file = self._create_test_upload_file(db_session_with_containers, mock_external_service_dependencies, account@@ -555,7 +555,7 @@ class TestFileService:"""Test file preview with text that exceeds preview limit."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)upload_file = self._create_test_upload_file(db_session_with_containers, mock_external_service_dependencies, account@@ -582,7 +582,7 @@ class TestFileService:"""Test file upload with empty content."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)filename = "empty.txt"@@ -605,7 +605,7 @@ class TestFileService:"""Test file upload with special characters in filename (but valid ones)."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)filename = "test-file_with_underscores_and.dots.txt"@@ -628,7 +628,7 @@ class TestFileService:"""Test file upload with different case extensions."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)filename = "test.PDF"@@ -698,7 +698,7 @@ class TestFileService:"""Test file upload with source URL that gets overridden by signed URL."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)filename = "test.pdf"@@ -737,7 +737,7 @@ class TestFileService:"""Test file upload with blocked extension."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)# Mock blacklist configuration by patching the inner field@@ -760,7 +760,7 @@ class TestFileService:"""Test file upload with blocked extension (case insensitive)."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)# Mock blacklist configuration by patching the inner field@@ -784,7 +784,7 @@ class TestFileService:"""Test file upload with extension not in blacklist."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)# Mock blacklist configuration by patching the inner field@@ -810,7 +810,7 @@ class TestFileService:"""Test file upload with empty blacklist (default behavior)."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)# Mock empty blacklist configuration by patching the inner field@@ -836,7 +836,7 @@ class TestFileService:"""Test file upload with multiple blocked extensions."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)# Mock blacklist with multiple extensions by patching the inner field@@ -861,7 +861,7 @@ class TestFileService:"""Test file upload with no extension when blacklist is configured."""- fake = Faker()+account = self._create_test_account(db_session_with_containers, mock_external_service_dependencies)# Mock blacklist configuration by patching the inner fielddiff --git a/api/tests/test_containers_integration_tests/services/test_message_service.py b/api/tests/test_containers_integration_tests/services/test_message_service.pyindex d26ee1c530f..cc4d8bc641b 100644--- a/api/tests/test_containers_integration_tests/services/test_message_service.py+++ b/api/tests/test_containers_integration_tests/services/test_message_service.py@@ -260,7 +260,7 @@ class TestMessageService:"""Test pagination by first ID when no conversation ID is provided."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Test pagination with no conversation ID@@ -376,7 +376,7 @@ class TestMessageService:"""Test pagination by last ID when no user is provided."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Test pagination with no user,diff --git a/api/tests/test_containers_integration_tests/services/test_metadata_service.py b/api/tests/test_containers_integration_tests/services/test_metadata_service.pyindex 6caa5fd757d..6db0af70616 100644--- a/api/tests/test_containers_integration_tests/services/test_metadata_service.py+++ b/api/tests/test_containers_integration_tests/services/test_metadata_service.py@@ -234,7 +234,7 @@ class TestMetadataService:)db_session_with_containers.expire_all()second_metadata_args = MetadataArgs(type="number", name="second_metadata")- second_metadata = _metadata_service(db_session_with_containers).create_metadata(+ _metadata_service(db_session_with_containers).create_metadata(DatasetRef(tenant.id, dataset.id), second_metadata_args, actor_id=account.id)db_session_with_containers.expire_all()@@ -408,7 +408,7 @@ class TestMetadataService:"""account, tenant = self._create_test_account_and_tenant(db_session_with_containers)dataset = self._create_test_dataset(db_session_with_containers, account, tenant)- document = self._create_test_document(db_session_with_containers, dataset, account)+ self._create_test_document(db_session_with_containers, dataset, account)assert dataset.built_in_field_enabled is False_metadata_service(db_session_with_containers).enable_built_in_field(DatasetRef(dataset.tenant_id, dataset.id))db_session_with_containers.expire_all()@@ -660,7 +660,7 @@ class TestMetadataService:db_session_with_containers.add(dataset)db_session_with_containers.commit()metadata_args = MetadataArgs(type="string", name="test_metadata")- metadata = _metadata_service(db_session_with_containers).create_metadata(+ _metadata_service(db_session_with_containers).create_metadata(DatasetRef(tenant.id, dataset.id), metadata_args, actor_id=account.id)db_session_with_containers.expire_all()diff --git a/api/tests/test_containers_integration_tests/services/test_model_load_balancing_service.py b/api/tests/test_containers_integration_tests/services/test_model_load_balancing_service.pyindex d5d058195a2..5666969bc13 100644--- a/api/tests/test_containers_integration_tests/services/test_model_load_balancing_service.py+++ b/api/tests/test_containers_integration_tests/services/test_model_load_balancing_service.py@@ -124,7 +124,6 @@ class TestModelLoadBalancingService:Returns:tuple: (provider, provider_model_setting) - Created provider and setting instances"""- fake = Faker()# Create providerprovider = Provider(@@ -162,7 +161,7 @@ class TestModelLoadBalancingService:- Correct method calls to provider configuration"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -205,7 +204,7 @@ class TestModelLoadBalancingService:- Correct method calls to provider configuration"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -248,7 +247,7 @@ class TestModelLoadBalancingService:- No database state changes"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -284,7 +283,7 @@ class TestModelLoadBalancingService:- Correct return format and data structure"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -371,7 +370,7 @@ class TestModelLoadBalancingService:- No database state changes"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -411,7 +410,7 @@ class TestModelLoadBalancingService:- Inherit config initialization when needed"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)diff --git a/api/tests/test_containers_integration_tests/services/test_model_provider_service.py b/api/tests/test_containers_integration_tests/services/test_model_provider_service.pyindex 356bf77dbd2..7f5391c6dd0 100644--- a/api/tests/test_containers_integration_tests/services/test_model_provider_service.py+++ b/api/tests/test_containers_integration_tests/services/test_model_provider_service.py@@ -100,7 +100,6 @@ class TestModelProviderService:Returns:Provider: Created provider instance"""- fake = Faker()provider = Provider(tenant_id=tenant_id,@@ -140,7 +139,6 @@ class TestModelProviderService:Returns:ProviderModel: Created provider model instance"""- fake = Faker()provider_model = ProviderModel(tenant_id=tenant_id,@@ -178,7 +176,6 @@ class TestModelProviderService:Returns:ProviderModelSetting: Created provider model setting instance"""- fake = Faker()provider_model_setting = ProviderModelSetting(tenant_id=tenant_id,@@ -205,15 +202,13 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -283,7 +278,7 @@ class TestModelProviderService:- Correct handling of unsupported model types"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -383,21 +378,19 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider and models- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")- provider_model_1 = self._create_test_provider_model(+ self._create_test_provider_model(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai", "gpt-3.5-turbo", "llm")- provider_model_2 = self._create_test_provider_model(+ self._create_test_provider_model(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai", "gpt-4", "llm")@@ -496,15 +489,13 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -555,15 +546,13 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -597,7 +586,7 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -629,15 +618,13 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic default modelmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -685,15 +672,13 @@ class TestModelProviderService:- Database state management"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -719,15 +704,13 @@ class TestModelProviderService:- Mock interactions with ModelProviderFactory"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ModelProviderFactory to return realistic icon datamock_model_provider_factory = mock_external_service_dependencies["model_provider_factory"].return_value@@ -758,15 +741,13 @@ class TestModelProviderService:- Provider configuration management"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -794,15 +775,13 @@ class TestModelProviderService:- Model configuration management"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -832,15 +811,13 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -891,15 +868,13 @@ class TestModelProviderService:- Model credential validation process"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -935,15 +910,13 @@ class TestModelProviderService:- Model credential management"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -978,15 +951,13 @@ class TestModelProviderService:- Model credential cleanup"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -1018,15 +989,13 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -1097,15 +1066,13 @@ class TestModelProviderService:- Model schema handling"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -1165,15 +1132,13 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)# Create test provider- provider = self._create_test_provider(- db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai"- )+ self._create_test_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, "openai")# Mock ProviderManager to return realistic configurationmock_provider_manager = mock_external_service_dependencies["provider_manager"].return_value@@ -1209,7 +1174,7 @@ class TestModelProviderService:- Mock interactions with ProviderManager"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)diff --git a/api/tests/test_containers_integration_tests/services/test_trigger_provider_service.py b/api/tests/test_containers_integration_tests/services/test_trigger_provider_service.pyindex 93e23dcd268..f6a90934a92 100644--- a/api/tests/test_containers_integration_tests/services/test_trigger_provider_service.py+++ b/api/tests/test_containers_integration_tests/services/test_trigger_provider_service.py@@ -163,7 +163,7 @@ class TestTriggerProviderService:- Merged credentials are used for subscribe and update- Database state is correctly updated"""- fake = Faker()+account, tenant = self._create_test_account_and_tenant(mock_external_service_dependencies, db_session_with_containers)@@ -263,7 +263,7 @@ class TestTriggerProviderService:- All new credentials are used when no HIDDEN_VALUE is present- Merged credentials contain only new values"""- fake = Faker()+account, tenant = self._create_test_account_and_tenant(mock_external_service_dependencies, db_session_with_containers)@@ -323,7 +323,7 @@ class TestTriggerProviderService:- All HIDDEN_VALUE credentials are replaced with existing values- Original credentials are preserved"""- fake = Faker()+account, tenant = self._create_test_account_and_tenant(mock_external_service_dependencies, db_session_with_containers)@@ -381,7 +381,7 @@ class TestTriggerProviderService:This test verifies:- UNKNOWN_VALUE is used when HIDDEN_VALUE key doesn't exist in original credentials"""- fake = Faker()+account, tenant = self._create_test_account_and_tenant(mock_external_service_dependencies, db_session_with_containers)@@ -441,7 +441,7 @@ class TestTriggerProviderService:- Database transaction is rolled back when an error occurs- Original subscription state is preserved"""- fake = Faker()+account, tenant = self._create_test_account_and_tenant(mock_external_service_dependencies, db_session_with_containers)@@ -519,7 +519,7 @@ class TestTriggerProviderService:This test verifies:- Error is raised when new name conflicts with existing subscription"""- fake = Faker()+account, tenant = self._create_test_account_and_tenant(mock_external_service_dependencies, db_session_with_containers)diff --git a/api/tests/test_containers_integration_tests/services/test_web_conversation_service.py b/api/tests/test_containers_integration_tests/services/test_web_conversation_service.pyindex 76dc411451a..f231661e725 100644--- a/api/tests/test_containers_integration_tests/services/test_web_conversation_service.py+++ b/api/tests/test_containers_integration_tests/services/test_web_conversation_service.py@@ -480,7 +480,7 @@ class TestWebConversationService:"""Test that pagination_by_last_id raises ValueError when user is None."""- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Test with None userdiff --git a/api/tests/test_containers_integration_tests/services/test_workflow_app_service.py b/api/tests/test_containers_integration_tests/services/test_workflow_app_service.pyindex 0ed46ad66d4..654db34b817 100644--- a/api/tests/test_containers_integration_tests/services/test_workflow_app_service.py+++ b/api/tests/test_containers_integration_tests/services/test_workflow_app_service.py@@ -201,7 +201,6 @@ class TestWorkflowAppLogQueryService:Returns:tuple: (workflow, workflow_run, workflow_app_log) - Created workflow entities"""- fake = Faker()# Create workflowworkflow = Workflow(@@ -266,7 +265,7 @@ class TestWorkflowAppLogQueryService:Test successful pagination of workflow app logs with basic parameters."""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)workflow, workflow_run, workflow_app_log = self._create_test_workflow_data(db_session_with_containers, app, account@@ -304,7 +303,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with keyword search functionality."""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)workflow, workflow_run, workflow_app_log = self._create_test_workflow_data(db_session_with_containers, app, account@@ -351,7 +350,7 @@ class TestWorkflowAppLogQueryService:- SQL injection via LIKE wildcards is prevented"""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)workflow, _, _ = self._create_test_workflow_data(db_session_with_containers, app, account)@@ -494,7 +493,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with status filtering."""# Arrange: Create test data with different statuses- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow@@ -593,7 +592,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with time-based filtering."""# Arrange: Create test data with different timestamps- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow@@ -705,7 +704,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with different page sizes and limits."""# Arrange: Create test data with multiple logs- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow@@ -819,7 +818,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with user role and session filtering."""# Arrange: Create test data with different user roles- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow@@ -1013,7 +1012,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with UUID keyword search functionality."""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow@@ -1102,7 +1101,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with edge cases and boundary conditions."""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow@@ -1200,7 +1199,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with empty results and no data scenarios."""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Act & Assert: Test empty results@@ -1267,7 +1266,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with complex query combinations."""# Arrange: Create test data with various combinations- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)workflow, _, _ = self._create_test_workflow_data(db_session_with_containers, app, account)@@ -1367,7 +1366,7 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with large dataset for performance validation."""# Arrange: Create a larger dataset- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)workflow, _, _ = self._create_test_workflow_data(db_session_with_containers, app, account)@@ -1459,7 +1458,6 @@ class TestWorkflowAppLogQueryService:Test workflow app logs pagination with proper tenant isolation."""# Arrange: Create multiple tenants and apps- fake = Faker()# Create first tenant and apptenant1, account1 = self._create_test_tenant_and_account(diff --git a/api/tests/test_containers_integration_tests/services/test_workflow_draft_variable_service.py b/api/tests/test_containers_integration_tests/services/test_workflow_draft_variable_service.pyindex 4cef1d30ffa..21da6f6d6d8 100644--- a/api/tests/test_containers_integration_tests/services/test_workflow_draft_variable_service.py+++ b/api/tests/test_containers_integration_tests/services/test_workflow_draft_variable_service.py@@ -245,13 +245,13 @@ class TestWorkflowDraftVariableService:var1_value = StringSegment(value=fake.word())var2_value = StringSegment(value=fake.word())var3_value = StringSegment(value=fake.word())- var1 = self._create_test_variable(+ self._create_test_variable(db_session_with_containers, app.id, CONVERSATION_VARIABLE_NODE_ID, "var1", var1_value, fake=fake)- var2 = self._create_test_variable(+ self._create_test_variable(db_session_with_containers, app.id, CONVERSATION_VARIABLE_NODE_ID, "var2", var2_value, fake=fake)- var3 = self._create_test_variable(+ self._create_test_variable(db_session_with_containers,app.id,"test_node_1",@@ -380,10 +380,10 @@ class TestWorkflowDraftVariableService:app = self._create_test_app(db_session_with_containers, mock_external_service_dependencies, fake=fake)conv_var1_value = StringSegment(value=fake.word())conv_var2_value = StringSegment(value=fake.word())- conv_var1 = self._create_test_variable(+ self._create_test_variable(db_session_with_containers, app.id, CONVERSATION_VARIABLE_NODE_ID, "conv_var1", conv_var1_value, fake=fake)- conv_var2 = self._create_test_variable(+ self._create_test_variable(db_session_with_containers, app.id, CONVERSATION_VARIABLE_NODE_ID, "conv_var2", conv_var2_value, fake=fake)sys_var_value = StringSegment(value=fake.word())@@ -828,7 +828,7 @@ class TestWorkflowDraftVariableService:app = self._create_test_app(db_session_with_containers, mock_external_service_dependencies, fake=fake)sys_var1_value = StringSegment(value=fake.word())sys_var2_value = StringSegment(value=fake.word())- sys_var1 = self._create_test_variable(+ self._create_test_variable(db_session_with_containers,app.id,SYSTEM_VARIABLE_NODE_ID,@@ -837,7 +837,7 @@ class TestWorkflowDraftVariableService:variable_type=DraftVariableType.SYS,fake=fake,)- sys_var2 = self._create_test_variable(+ self._create_test_variable(db_session_with_containers,app.id,SYSTEM_VARIABLE_NODE_ID,@@ -876,10 +876,10 @@ class TestWorkflowDraftVariableService:fake = Faker()app = self._create_test_app(db_session_with_containers, mock_external_service_dependencies, fake=fake)test_value = StringSegment(value=fake.word())- conv_var = self._create_test_variable(+ self._create_test_variable(db_session_with_containers, app.id, CONVERSATION_VARIABLE_NODE_ID, "test_conv_var", test_value, fake=fake)- sys_var = self._create_test_variable(+ self._create_test_variable(db_session_with_containers,app.id,SYSTEM_VARIABLE_NODE_ID,@@ -888,7 +888,7 @@ class TestWorkflowDraftVariableService:variable_type=DraftVariableType.SYS,fake=fake,)- node_var = self._create_test_variable(+ self._create_test_variable(db_session_with_containers,app.id,"test_node",diff --git a/api/tests/test_containers_integration_tests/services/test_workflow_run_service.py b/api/tests/test_containers_integration_tests/services/test_workflow_run_service.pyindex 18d204998c5..b37b1a558ea 100644--- a/api/tests/test_containers_integration_tests/services/test_workflow_run_service.py+++ b/api/tests/test_containers_integration_tests/services/test_workflow_run_service.py@@ -135,7 +135,6 @@ class TestWorkflowRunService:Returns:WorkflowRun: Created workflow run instance"""- fake = Faker()# Create workflow run with offset timestampbase_time = datetime.now(UTC)@@ -237,7 +236,7 @@ class TestWorkflowRunService:- Repository method calls"""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create multiple workflow runs@@ -284,7 +283,7 @@ class TestWorkflowRunService:- Repository method calls with proper parameters"""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create multiple workflow runs with different timestamps@@ -333,11 +332,11 @@ class TestWorkflowRunService:- Repository method calls with default values"""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow runs- workflow_run = self._create_test_workflow_run(db_session_with_containers, app, account, "debugging")+ self._create_test_workflow_run(db_session_with_containers, app, account, "debugging")# Act: Execute the method under test without limitargs = {} # No limit specified@@ -378,7 +377,7 @@ class TestWorkflowRunService:- WorkflowWithMessage wrapper functionality"""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow runs with messages@@ -387,7 +386,7 @@ class TestWorkflowRunService:workflow_run = self._create_test_workflow_run(db_session_with_containers, app, account, "debugging", offset_minutes=i)- message = self._create_test_message(db_session_with_containers, app, account, workflow_run)+ self._create_test_message(db_session_with_containers, app, account, workflow_run)workflow_runs.append(workflow_run)# Act: Execute the method under test@@ -429,7 +428,7 @@ class TestWorkflowRunService:- Repository method calls with proper parameters"""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow run@@ -467,7 +466,7 @@ class TestWorkflowRunService:- Return value for missing records"""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Use a non-existent UUID@@ -499,7 +498,7 @@ class TestWorkflowRunService:- Context setup for plugin tool providers"""# Arrange: Create test data- fake = Faker()+app, account = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)# Create workflow rundiff --git a/api/tests/test_containers_integration_tests/services/test_workflow_service.py b/api/tests/test_containers_integration_tests/services/test_workflow_service.pyindex 8582a2d546c..b200504f907 100644--- a/api/tests/test_containers_integration_tests/services/test_workflow_service.py+++ b/api/tests/test_containers_integration_tests/services/test_workflow_service.py@@ -234,7 +234,7 @@ class TestWorkflowService:fake = Faker()account = self._create_test_account(db_session_with_containers, fake)app = self._create_test_app(db_session_with_containers, fake)- workflow = self._create_test_workflow(db_session_with_containers, app, account, fake)+ self._create_test_workflow(db_session_with_containers, app, account, fake)workflow_service = WorkflowService()@@ -820,9 +820,8 @@ class TestWorkflowService:app = self._create_test_app(db_session_with_containers, fake)# Create existing draft workflow- existing_workflow = self._create_test_workflow(db_session_with_containers, app, account, fake)+ self._create_test_workflow(db_session_with_containers, app, account, fake)# Get the actual hash that was generated- original_hash = existing_workflow.unique_hashnew_graph = {"nodes": [@@ -1391,7 +1390,6 @@ class TestWorkflowService:account = self._create_test_account(db_session_with_containers, fake)app = self._create_test_app(db_session_with_containers, fake)workflow = self._create_test_workflow(db_session_with_containers, app, account, fake)- original_name = workflow.marked_namedb_session_with_containers.commit()diff --git a/api/tests/test_containers_integration_tests/services/tools/test_api_tools_manage_service.py b/api/tests/test_containers_integration_tests/services/tools/test_api_tools_manage_service.pyindex 87c3c750ed4..7ca307c009f 100644--- a/api/tests/test_containers_integration_tests/services/tools/test_api_tools_manage_service.py+++ b/api/tests/test_containers_integration_tests/services/tools/test_api_tools_manage_service.py@@ -458,14 +458,9 @@ class TestApiToolManageService:db_session_with_containers, mock_external_service_dependencies)- provider_name = fake.company()- icon = {"content": "🔧", "background": "#FFF"}- credentials = {"auth_type": "none"}+ fake.company()schema_type = "invalid_type"- schema = self._create_test_openapi_schema()- privacy_policy = "https://example.com/privacy"- custom_disclaimer = "Custom disclaimer text"- labels = ["test"]+ self._create_test_openapi_schema()# Act & Assert: Try to create provider with invalid schema typewith pytest.raises(ValidationError) as exc_info:@@ -631,7 +626,7 @@ class TestApiToolManageService:self, db_session_with_containers: Session, mock_external_service_dependencies: MockDependencies) -> None:"""Test deletion raises ValueError when provider not found."""- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -645,8 +640,6 @@ class TestApiToolManageService:db_session_with_containers: Session,mock_external_service_dependencies: MockDependencies,) -> None:- fake = Faker()-# Firmware fix for cache.delete() in update flowmock_encrypter = mock_external_service_dependencies["encrypter"]mock_cache = MagicMock()@@ -885,7 +878,7 @@ class TestApiToolManageService:self, db_session_with_containers: Session, mock_external_service_dependencies: MockDependencies) -> None:"""Test listing tools raises ValueError when provider not found."""- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -897,7 +890,7 @@ class TestApiToolManageService:self, db_session_with_containers: Session, mock_external_service_dependencies: MockDependencies) -> None:"""Test preview raises ValueError for invalid schema type."""- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)diff --git a/api/tests/test_containers_integration_tests/services/tools/test_mcp_tools_manage_service.py b/api/tests/test_containers_integration_tests/services/tools/test_mcp_tools_manage_service.pyindex ba2ae62a053..a32127b9d9c 100644--- a/api/tests/test_containers_integration_tests/services/tools/test_mcp_tools_manage_service.py+++ b/api/tests/test_containers_integration_tests/services/tools/test_mcp_tools_manage_service.py@@ -140,7 +140,7 @@ class TestMCPToolManageService:- Proper error handling for non-existent providers"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -203,7 +203,7 @@ class TestMCPToolManageService:- Security boundaries are maintained"""# Arrange: Create test data for two tenants- fake = Faker()+account1, tenant1 = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -235,7 +235,7 @@ class TestMCPToolManageService:- Proper error handling for non-existent server identifiers"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -300,7 +300,7 @@ class TestMCPToolManageService:- Security boundaries are maintained"""# Arrange: Create test data for two tenants- fake = Faker()+account1, tenant1 = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -334,7 +334,7 @@ class TestMCPToolManageService:- Return value correctness"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -415,7 +415,7 @@ class TestMCPToolManageService:- Database integrity constraints"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -468,7 +468,7 @@ class TestMCPToolManageService:- URL hash uniqueness enforcement"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -521,7 +521,7 @@ class TestMCPToolManageService:- Server identifier uniqueness enforcement"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -573,7 +573,7 @@ class TestMCPToolManageService:- Empty list handling for tenants with no providers"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -667,7 +667,7 @@ class TestMCPToolManageService:- No transformation service calls for empty lists"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -699,7 +699,7 @@ class TestMCPToolManageService:- Security boundaries are maintained"""# Arrange: Create test data for two tenants- fake = Faker()+account1, tenant1 = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -772,7 +772,7 @@ class TestMCPToolManageService:- Return value correctness"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -843,7 +843,7 @@ class TestMCPToolManageService:- Database state remains unchanged"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -895,7 +895,7 @@ class TestMCPToolManageService:- Database state remains unchanged"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -945,7 +945,7 @@ class TestMCPToolManageService:- Database state after deletion"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -1003,7 +1003,7 @@ class TestMCPToolManageService:- Security boundaries are maintained"""# Arrange: Create test data for two tenants- fake = Faker()+account1, tenant1 = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -1038,7 +1038,7 @@ class TestMCPToolManageService:- External service integration"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -1047,8 +1047,6 @@ class TestMCPToolManageService:mcp_provider = self._create_test_mcp_provider(db_session_with_containers, mock_external_service_dependencies, tenant.id, account.id)- original_name = mcp_provider.name- original_icon = mcp_provider.icondb_session_with_containers.commit()@@ -1098,7 +1096,7 @@ class TestMCPToolManageService:- Database integrity constraints"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -1149,7 +1147,7 @@ class TestMCPToolManageService:- External service integration"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -1210,7 +1208,7 @@ class TestMCPToolManageService:- Credentials are still updated"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -1265,7 +1263,7 @@ class TestMCPToolManageService:- Proper error handling for authentication errors"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -1328,7 +1326,7 @@ class TestMCPToolManageService:- Tools list is cleared"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -1370,7 +1368,7 @@ class TestMCPToolManageService:- Correct exception type and message"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)diff --git a/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py b/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.pyindex 7397b5bb4b7..27b32207b82 100644--- a/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py+++ b/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py@@ -1042,7 +1042,7 @@ class TestWorkflowToolManageService:# Verify the tool was NOT created in database# This is the expected behavior (no pollution)- tool_count = (+ (db_session_with_containers.query(WorkflowToolProvider).where(WorkflowToolProvider.tenant_id == account.current_tenant.id,@@ -1097,7 +1097,7 @@ class TestWorkflowToolManageService:self, db_session_with_containers: Session, mock_external_service_dependencies):"""Test listing workflow tools when none exist returns empty list."""- fake = Faker()+app, account, workflow = self._create_test_app_and_account(db_session_with_containers, mock_external_service_dependencies)diff --git a/api/tests/test_containers_integration_tests/services/workflow/test_workflow_converter.py b/api/tests/test_containers_integration_tests/services/workflow/test_workflow_converter.pyindex dfddf26ddf6..63e2b94d830 100644--- a/api/tests/test_containers_integration_tests/services/workflow/test_workflow_converter.py+++ b/api/tests/test_containers_integration_tests/services/workflow/test_workflow_converter.py@@ -202,7 +202,7 @@ class TestWorkflowConverter:- Workflow creation with correct configuration"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -315,7 +315,7 @@ class TestWorkflowConverter:- Database state management"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -429,7 +429,7 @@ class TestWorkflowConverter:- External data variable mapping"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)@@ -508,7 +508,7 @@ class TestWorkflowConverter:- Query variable selector setup"""# Arrange: Create test data- fake = Faker()+account, tenant = self._create_test_account_and_tenant(db_session_with_containers, mock_external_service_dependencies)diff --git a/api/tests/test_containers_integration_tests/tasks/test_batch_clean_document_task.py b/api/tests/test_containers_integration_tests/tasks/test_batch_clean_document_task.pyindex 9476bd9a0c0..d325867a391 100644--- a/api/tests/test_containers_integration_tests/tasks/test_batch_clean_document_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_batch_clean_document_task.py@@ -590,7 +590,7 @@ class TestBatchCleanDocumentTask:)assert deleted_segment is None- except Exception as e:+ except Exception:# If the task fails due to external service issues (e.g., plugin daemon),# we should still verify that the database state is consistent# This is a common scenario in test environments where external services may not be availablediff --git a/api/tests/test_containers_integration_tests/tasks/test_clean_dataset_task.py b/api/tests/test_containers_integration_tests/tasks/test_clean_dataset_task.pyindex 6584ad5bfbb..d6cdd01c0b9 100644--- a/api/tests/test_containers_integration_tests/tasks/test_clean_dataset_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_clean_dataset_task.py@@ -480,7 +480,7 @@ class TestCleanDatasetTask:# Create a document and segmentdocument = self._create_test_document(db_session_with_containers, account, tenant, dataset)- segment = self._create_test_segment(db_session_with_containers, account, tenant, dataset, document)+ self._create_test_segment(db_session_with_containers, account, tenant, dataset, document)# Execute the task with invalid doc_form valuestest_cases = [None, "", " ", "\t\n"]@@ -516,7 +516,7 @@ class TestCleanDatasetTask:# Recreate data for next test casedocument = self._create_test_document(db_session_with_containers, account, tenant, dataset)- segment = self._create_test_segment(db_session_with_containers, account, tenant, dataset, document)+ self._create_test_segment(db_session_with_containers, account, tenant, dataset, document)# Verify that IndexProcessorFactory was called with default typemock_factory = mock_external_service_dependencies["index_processor_factory"]@@ -540,7 +540,7 @@ class TestCleanDatasetTask:account, tenant = self._create_test_account_and_tenant(db_session_with_containers)dataset = self._create_test_dataset(db_session_with_containers, account, tenant)document = self._create_test_document(db_session_with_containers, account, tenant, dataset)- segment = self._create_test_segment(db_session_with_containers, account, tenant, dataset, document)+ self._create_test_segment(db_session_with_containers, account, tenant, dataset, document)# Mock IndexProcessorFactory to raise an exceptionmock_index_processor = mock_external_service_dependencies["index_processor"]@@ -826,7 +826,7 @@ class TestCleanDatasetTask:account, tenant = self._create_test_account_and_tenant(db_session_with_containers)dataset = self._create_test_dataset(db_session_with_containers, account, tenant)document = self._create_test_document(db_session_with_containers, account, tenant, dataset)- segment = self._create_test_segment(db_session_with_containers, account, tenant, dataset, document)+ self._create_test_segment(db_session_with_containers, account, tenant, dataset, document)upload_file = self._create_test_upload_file(db_session_with_containers, account, tenant)# Update document with file referencediff --git a/api/tests/test_containers_integration_tests/tasks/test_clean_notion_document_task.py b/api/tests/test_containers_integration_tests/tasks/test_clean_notion_document_task.pyindex bcd57495825..ac43b65acdf 100644--- a/api/tests/test_containers_integration_tests/tasks/test_clean_notion_document_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_clean_notion_document_task.py@@ -167,7 +167,7 @@ class TestCleanNotionDocumentTask:This test verifies that the task properly handles the case wherethe specified dataset does not exist in the database."""- fake = Faker()+non_existent_dataset_id = str(uuid.uuid4())document_ids = [str(uuid.uuid4()), str(uuid.uuid4())]@@ -475,7 +475,7 @@ class TestCleanNotionDocumentTask:# Clean up only first 3 documentsdocuments_to_clean = [doc.id for doc in documents[:3]]segments_to_clean = [seg for seg in all_segments if seg.document_id in documents_to_clean]- index_node_ids_to_clean = [seg.index_node_id for seg in segments_to_clean]+ [seg.index_node_id for seg in segments_to_clean]clean_notion_document_task(documents_to_clean, dataset.id)@@ -885,7 +885,7 @@ class TestCleanNotionDocumentTask:target_dataset = datasets[0]target_document = all_documents[0]target_segments = [seg for seg in all_segments if seg.dataset_id == target_dataset.id]- target_index_node_ids = [seg.index_node_id for seg in target_segments]+ [seg.index_node_id for seg in target_segments]clean_notion_document_task([target_document.id], target_dataset.id)diff --git a/api/tests/test_containers_integration_tests/tasks/test_dataset_indexing_task.py b/api/tests/test_containers_integration_tests/tasks/test_dataset_indexing_task.pyindex 0e18308b391..fa5496ee03c 100644--- a/api/tests/test_containers_integration_tests/tasks/test_dataset_indexing_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_dataset_indexing_task.py@@ -602,7 +602,7 @@ class TestDatasetIndexingTaskIntegration:db_session_with_containers,document_ids=large_document_ids,)- features = patched_external_dependencies["features"]+ patched_external_dependencies["features"]# Act_document_indexing(dataset.id, large_document_ids)diff --git a/api/tests/test_containers_integration_tests/tasks/test_delete_segment_from_index_task.py b/api/tests/test_containers_integration_tests/tasks/test_delete_segment_from_index_task.pyindex edd23ca2b68..9ab88957de0 100644--- a/api/tests/test_containers_integration_tests/tasks/test_delete_segment_from_index_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_delete_segment_from_index_task.py@@ -210,7 +210,7 @@ class TestDeleteSegmentFromIndexTask:segments = []for i in range(count):- created_at = fake.date_time_this_year()+ fake.date_time_this_year()segment = DocumentSegment(tenant_id=document.tenant_id,dataset_id=document.dataset_id,diff --git a/api/tests/test_containers_integration_tests/tasks/test_document_indexing_task.py b/api/tests/test_containers_integration_tests/tasks/test_document_indexing_task.pyindex 613bb04e012..c48929bb83c 100644--- a/api/tests/test_containers_integration_tests/tasks/test_document_indexing_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_document_indexing_task.py@@ -881,9 +881,8 @@ class TestDocumentIndexingTasks:tenant1_id = dataset1.tenant_idtenant2_id = dataset2.tenant_iddataset1_id = dataset1.id- dataset2_id = dataset2.iddocument_ids1 = [doc.id for doc in documents1]- document_ids2 = [doc.id for doc in documents2]+ [doc.id for doc in documents2]# Mock the task functionfrom unittest.mock import MagicMockdiff --git a/api/tests/test_containers_integration_tests/tasks/test_mail_change_mail_task.py b/api/tests/test_containers_integration_tests/tasks/test_mail_change_mail_task.pyindex a697878bb60..4fdf367d716 100644--- a/api/tests/test_containers_integration_tests/tasks/test_mail_change_mail_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_mail_change_mail_task.py@@ -115,7 +115,7 @@ class TestMailChangeMailTask:- Successful task completion"""# Arrange: Create test data- account = self._create_test_account(db_session_with_containers)+ self._create_test_account(db_session_with_containers)test_language = "zh-Hans"test_email = "[email protected]"test_code = "789012"diff --git a/api/tests/test_containers_integration_tests/tasks/test_mail_email_code_login_task.py b/api/tests/test_containers_integration_tests/tasks/test_mail_email_code_login_task.pyindex 567bd44b930..dfbfd467bfe 100644--- a/api/tests/test_containers_integration_tests/tasks/test_mail_email_code_login_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_mail_email_code_login_task.py@@ -403,7 +403,7 @@ class TestSendEmailCodeLoginMailTask:4. Process extreme language codes"""# Arrange: Setup test data- fake = Faker()+test_language = "en-US"# Edge case test datadiff --git a/api/tests/test_containers_integration_tests/tasks/test_rag_pipeline_run_tasks.py b/api/tests/test_containers_integration_tests/tasks/test_rag_pipeline_run_tasks.pyindex 8311ce96736..545391e4e7a 100644--- a/api/tests/test_containers_integration_tests/tasks/test_rag_pipeline_run_tasks.py+++ b/api/tests/test_containers_integration_tests/tasks/test_rag_pipeline_run_tasks.py@@ -613,7 +613,7 @@ class TestRagPipelineRunTasks:# Mock file servicefile_id1 = str(uuid.uuid4())- file_id2 = str(uuid.uuid4())+ str(uuid.uuid4())mock_file_service["get_content"].side_effect = [file_content1, file_content2]# Use real Redis for TenantIsolatedTaskQueue@@ -680,7 +680,7 @@ class TestRagPipelineRunTasks:# Mock file servicefile_id1 = str(uuid.uuid4())- file_id2 = str(uuid.uuid4())+ str(uuid.uuid4())mock_file_service["get_content"].side_effect = [file_content1, file_content2]# Use real Redis for TenantIsolatedTaskQueue@@ -772,7 +772,7 @@ class TestRagPipelineRunTasks:- Function raises ValueError for missing entities"""# Arrange: Create entity data with valid UUIDs but non-existent entities- fake = Faker()+invalid_entity_data = {"pipeline_id": str(uuid.uuid4()),"application_generate_entity": {@@ -817,7 +817,7 @@ class TestRagPipelineRunTasks:- Function raises ValueError for missing entities"""# Arrange: Create test data with non-existent IDs- fake = Faker()+entity_data = {"pipeline_id": str(uuid.uuid4()),"application_generate_entity": {diff --git a/api/tests/test_containers_integration_tests/test_workflow_pause_integration.py b/api/tests/test_containers_integration_tests/test_workflow_pause_integration.pyindex d9bbf54150c..6e4ac8c0aef 100644--- a/api/tests/test_containers_integration_tests/test_workflow_pause_integration.py+++ b/api/tests/test_containers_integration_tests/test_workflow_pause_integration.py@@ -858,7 +858,7 @@ class TestWorkflowPauseIntegration:assert deleted_pause is Nonetry:- content = storage.load(file_key).decode()+ storage.load(file_key).decode()pytest.fail("File should be deleted from storage after pause deletion")except FileNotFoundError:# This is expected - file should be deleted from storagediff --git a/api/tests/unit_tests/clients/agent_backend/test_request_builder.py b/api/tests/unit_tests/clients/agent_backend/test_request_builder.pyindex 4c86737cba0..c6f2b7724a3 100644--- a/api/tests/unit_tests/clients/agent_backend/test_request_builder.py+++ b/api/tests/unit_tests/clients/agent_backend/test_request_builder.py@@ -89,7 +89,7 @@ def test_request_builder_outputs_dify_agent_create_run_request() -> None:def test_request_builder_separates_agent_soul_and_workflow_job_prompt() -> None:request = AgentBackendRunRequestBuilder().build_for_workflow_node(_run_input())- layers = {layer.name: layer for layer in request.composition.layers}+ {layer.name: layer for layer in request.composition.layers}dumped = request.model_dump(mode="json")assert dumped["composition"]["layers"][0]["config"]["prefix"] == "You are a careful reviewer."diff --git a/api/tests/unit_tests/commands/test_legacy_model_type_migration.py b/api/tests/unit_tests/commands/test_legacy_model_type_migration.pyindex 6ebac69bcba..70e5774d92d 100644--- a/api/tests/unit_tests/commands/test_legacy_model_type_migration.py+++ b/api/tests/unit_tests/commands/test_legacy_model_type_migration.py@@ -63,7 +63,7 @@ def dirty_fixture(sqlite_engine: sa.Engine) -> DirtyDataFixture:def command_module() -> ModuleType:try:return importlib.import_module("commands.data_migration")- except ModuleNotFoundError as exc: # pragma: no cover - explicit TDD failure path+ except ModuleNotFoundError: # pragma: no cover - explicit TDD failure pathpytest.fail("commands.data_migration is missing. ""Implement the `flask data-migrate legacy-model-types` command group before running these tests."diff --git a/api/tests/unit_tests/controllers/console/app/test_annotation_security.py b/api/tests/unit_tests/controllers/console/app/test_annotation_security.pyindex 2cfa372a388..715a90e0f75 100644--- a/api/tests/unit_tests/controllers/console/app/test_annotation_security.py+++ b/api/tests/unit_tests/controllers/console/app/test_annotation_security.py@@ -208,21 +208,21 @@ class TestAnnotationImportFileValidation:max_size = dify_config.ANNOTATION_IMPORT_FILE_SIZE_LIMIT * 1024 * 1024large_content = b"x" * (max_size + 1024) # Exceed by 1KB- file = FileStorage(stream=io.BytesIO(large_content), filename="test.csv", content_type="text/csv")+ FileStorage(stream=io.BytesIO(large_content), filename="test.csv", content_type="text/csv")# Should be rejected in controller# This would be tested in integration tests with actual endpointdef test_empty_file_rejected(self):"""Test that empty files are rejected."""- file = FileStorage(stream=io.BytesIO(b""), filename="test.csv", content_type="text/csv")+ FileStorage(stream=io.BytesIO(b""), filename="test.csv", content_type="text/csv")# Should be rejected# This would be tested in integration testsdef test_non_csv_file_rejected(self):"""Test that non-CSV files are rejected."""- file = FileStorage(stream=io.BytesIO(b"test"), filename="test.txt", content_type="text/plain")+ FileStorage(stream=io.BytesIO(b"test"), filename="test.txt", content_type="text/plain")# Should be rejected based on extension# This would be tested in integration tests@@ -248,7 +248,7 @@ class TestAnnotationImportServiceValidation:with patch("services.annotation_service.current_account_with_tenant") as mock_auth:mock_auth.return_value = (_account(), "tenant_id")- with patch("services.annotation_service.FeatureService") as mock_features:+ with patch("services.annotation_service.FeatureService"):result = AppAnnotationService.batch_import_app_annotations("app_id", file, sqlite_session)# Should return error about too many records@@ -305,8 +305,8 @@ class TestAnnotationImportServiceValidation:with patch("services.annotation_service.current_account_with_tenant") as mock_auth:mock_auth.return_value = (_account(), "tenant_id")- with patch("services.annotation_service.FeatureService") as mock_features:- with patch("services.annotation_service.batch_import_annotations_task") as mock_task:+ with patch("services.annotation_service.FeatureService"):+ with patch("services.annotation_service.batch_import_annotations_task"):with patch("services.annotation_service.redis_client"):result = AppAnnotationService.batch_import_app_annotations("app_id", file, sqlite_session)diff --git a/api/tests/unit_tests/controllers/console/app/test_generator_api.py b/api/tests/unit_tests/controllers/console/app/test_generator_api.pyindex 4e20e384f44..338cc8ef6a0 100644--- a/api/tests/unit_tests/controllers/console/app/test_generator_api.py+++ b/api/tests/unit_tests/controllers/console/app/test_generator_api.py@@ -135,7 +135,7 @@ def test_instruction_generate_workflow_not_found(api = generator_module.InstructionGenerateApi()method = unwrap(api.post)- app_model = _persist_app(sqlite_session)+ _persist_app(sqlite_session)_install_workflow_service(monkeypatch, workflow=None)with app.test_request_context(@@ -163,7 +163,7 @@ def test_instruction_generate_node_missing(api = generator_module.InstructionGenerateApi()method = unwrap(api.post)- app_model = _persist_app(sqlite_session)+ _persist_app(sqlite_session)workflow = _workflow({"nodes": []})_install_workflow_service(monkeypatch, workflow=workflow)diff --git a/api/tests/unit_tests/controllers/console/app/workflow_draft_variables_test.py b/api/tests/unit_tests/controllers/console/app/workflow_draft_variables_test.pyindex 709ae1e72a4..0c62e2b4c00 100644--- a/api/tests/unit_tests/controllers/console/app/workflow_draft_variables_test.py+++ b/api/tests/unit_tests/controllers/console/app/workflow_draft_variables_test.py@@ -74,7 +74,7 @@ class TestWorkflowDraftVariableFields:draft_var.file_id = str(uuid.uuid4())draft_var.variable_file = Nonewith pytest.raises(AssertionError):- result = _serialize_full_content(draft_var)+ _serialize_full_content(draft_var)def test_conversation_variable(self):conv_var = WorkflowDraftVariable.new_conversation_variable(diff --git a/api/tests/unit_tests/controllers/service_api/app/test_audio.py b/api/tests/unit_tests/controllers/service_api/app/test_audio.pyindex ece7d3381b5..250a5f754c0 100644--- a/api/tests/unit_tests/controllers/service_api/app/test_audio.py+++ b/api/tests/unit_tests/controllers/service_api/app/test_audio.py@@ -10,7 +10,7 @@ Tests coverage for:import ioimport uuidfrom inspect import unwrap-from unittest.mock import Mock, patch+from unittest.mock import patchimport pytestfrom flask import Flask, request@@ -170,11 +170,8 @@ class TestAudioServiceMockedBehavior:@pytest.fixturedef mock_file(self):- """Create mock file upload."""- mock = Mock()- mock.filename = "test_audio.mp3"- mock.content_type = "audio/mpeg"- return mock+ """Create a file upload."""+ return FileStorage(stream=io.BytesIO(b"audio"), filename="test_audio.mp3", content_type="audio/mpeg")@patch.object(AudioService, "transcript_asr")def test_transcript_asr_returns_response(self, mock_asr, mock_app, mock_file, sqlite_session: Session):@@ -323,10 +320,25 @@ class TestTextApi:assert calls["message_ref"] == MessageRef(AppRef("tenant-1", "a1"), "message-1", end_user_id="end-user-1")assert calls["session"] is sqlite_session- def test_error_mapping(self, app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:- monkeypatch.setattr(- AudioService, "transcript_tts", lambda **_kwargs: (_ for _ in ()).throw(QuotaExceededError())- )+ @pytest.mark.parametrize(+ ("exc", "expected"),+ [+ (QuotaExceededError(), ProviderQuotaExceededError),+ (RuntimeError("internal provider failure"), InternalServerError),+ ],+ )+ def test_error_mapping(+ self,+ app: Flask,+ monkeypatch: pytest.MonkeyPatch,+ sqlite_session: Session,+ exc: Exception,+ expected: type[Exception],+ ) -> None:+ def raise_error(**_kwargs: object) -> None:+ raise exc++ monkeypatch.setattr(AudioService, "transcript_tts", raise_error)api = TextApi()handler = unwrap(api.post)@@ -335,5 +347,5 @@ class TestTextApi:with app.test_request_context("/text-to-audio", method="POST", json={"text": "hello"}):payload = TextToAudioPayload.model_validate(request.get_json() or {})- with pytest.raises(ProviderQuotaExceededError):+ with pytest.raises(expected):handler(api, payload, sqlite_session, app_model=app_model, end_user=end_user)diff --git a/api/tests/unit_tests/controllers/service_api/app/test_completion.py b/api/tests/unit_tests/controllers/service_api/app/test_completion.pyindex c5fc2f92999..7f51489398a 100644--- a/api/tests/unit_tests/controllers/service_api/app/test_completion.py+++ b/api/tests/unit_tests/controllers/service_api/app/test_completion.py@@ -598,7 +598,7 @@ class TestChatApiController:def test_rejects_sandbox_plan_workflow_version(self, app: Flask, monkeypatch: pytest.MonkeyPatch, orm_session: Session) -> None:- completion_module = sys.modules["controllers.service_api.app.completion"]+ sys.modules["controllers.service_api.app.completion"]apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)billing_get_info = Mock(return_value={"subscription": {"plan": CloudPlan.SANDBOX}})diff --git a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py b/api/tests/unit_tests/controllers/service_api/app/test_workflow.pyindex 1f8e56a348f..c0bb353fa4f 100644--- a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py+++ b/api/tests/unit_tests/controllers/service_api/app/test_workflow.py@@ -523,7 +523,7 @@ class TestWorkflowRunApi:config_overrides: Callable[..., None],) -> None:config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)- workflow_module = sys.modules["controllers.service_api.app.workflow"]+ sys.modules["controllers.service_api.app.workflow"]billing_get_info = Mock(return_value={"subscription": {"plan": CloudPlan.SANDBOX}})generate = Mock(return_value={"result": "ok"})@@ -582,7 +582,7 @@ class TestWorkflowRunByIdApi:config_overrides: Callable[..., None],) -> None:config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)- workflow_module = sys.modules["controllers.service_api.app.workflow"]+ sys.modules["controllers.service_api.app.workflow"]billing_get_info = Mock(return_value={"subscription": {"plan": CloudPlan.SANDBOX}})generate = Mock()@@ -669,7 +669,7 @@ class TestWorkflowRunByIdApi:config_overrides: Callable[..., None],) -> None:config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- workflow_module = sys.modules["controllers.service_api.app.workflow"]+ sys.modules["controllers.service_api.app.workflow"]monkeypatch.setattr(AppGenerateService,"generate",@@ -694,7 +694,7 @@ class TestWorkflowRunByIdApi:config_overrides: Callable[..., None],) -> None:config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- workflow_module = sys.modules["controllers.service_api.app.workflow"]+ sys.modules["controllers.service_api.app.workflow"]monkeypatch.setattr(AppGenerateService,"generate",diff --git a/api/tests/unit_tests/controllers/web/test_audio.py b/api/tests/unit_tests/controllers/web/test_audio.pyindex 79c7ecc8589..3163c106836 100644--- a/api/tests/unit_tests/controllers/web/test_audio.py+++ b/api/tests/unit_tests/controllers/web/test_audio.py@@ -8,6 +8,7 @@ from io import BytesIOimport pytestfrom flask import Flask, Responsefrom sqlalchemy.orm import Session+from werkzeug.exceptions import InternalServerErrorfrom controllers.web.audio import AudioApi, TextApi, TextToAudioPayloadfrom controllers.web.error import (@@ -132,6 +133,7 @@ class TestAudioApi:(ProviderTokenNotInitError(description="no token"), ProviderNotInitializeError),(QuotaExceededError(), ProviderQuotaExceededError),(ModelCurrentlyNotSupportError(), ProviderModelCurrentlyNotSupportError),+ (RuntimeError("internal provider failure"), InternalServerError),],)def test_provider_failure_mapping(@@ -241,8 +243,22 @@ class TestTextApi:if owner != "current":assert audio_runtime.resolutions == []- def test_invoke_error_mapped(self, app: Flask, web_app: App, audio_runtime: AudioRuntimeObservations) -> None:- audio_runtime.lookup_error = InvokeError(description="invoke failed")+ @pytest.mark.parametrize(+ ("provider_error", "expected_error"),+ [+ (InvokeError(description="invoke failed"), CompletionRequestError),+ (RuntimeError("internal provider failure"), InternalServerError),+ ],+ )+ def test_provider_failure_mapping(+ self,+ provider_error: Exception,+ expected_error: type[Exception],+ app: Flask,+ web_app: App,+ audio_runtime: AudioRuntimeObservations,+ ) -> None:+ audio_runtime.lookup_error = provider_errorwith app.test_request_context("/text-to-audio", method="POST", json={"text": "hello"}):- with pytest.raises(CompletionRequestError):+ with pytest.raises(expected_error):TextApi().post(web_app, _end_user())diff --git a/api/tests/unit_tests/controllers/web/test_completion.py b/api/tests/unit_tests/controllers/web/test_completion.pyindex 73f2ce6d20c..a9e8c595ea3 100644--- a/api/tests/unit_tests/controllers/web/test_completion.py+++ b/api/tests/unit_tests/controllers/web/test_completion.py@@ -9,6 +9,7 @@ from unittest.mock import MagicMock, patchimport pytestfrom flask import Flaskfrom sqlalchemy.orm import Session+from werkzeug.exceptions import InternalServerErrorfrom controllers.web.completion import ChatApi, ChatStopApi, CompletionApi, CompletionStopApifrom controllers.web.error import (@@ -43,6 +44,32 @@ def _end_user() -> EndUser:return make_end_user(end_user_id="eu-1", app_id="app-1", name="Web User")+ ("resource", "mode", "path"),+ [+ (CompletionApi, AppMode.COMPLETION, "/completion-messages"),+ (ChatApi, AppMode.CHAT, "/chat-messages"),+ ],+)+def test_unexpected_generation_error_hides_internal_details(+ app: Flask,+ resource: type[CompletionApi | ChatApi],+ mode: AppMode,+ path: str,+) -> None:+ error = RuntimeError("internal provider failure")+ with (+ patch("controllers.web.completion.AppGenerateService.generate", side_effect=error),+ app.test_request_context(path, method="POST", json={"inputs": {}, "query": "hello"}),+ pytest.raises(InternalServerError) as exc_info,+ ):+ resource().post(_app(mode), _end_user())++ assert exc_info.value.code == 500+ assert "internal provider failure" not in str(exc_info.value)+ assert exc_info.value.__context__ is error++# ---------------------------------------------------------------------------# CompletionApi# ---------------------------------------------------------------------------diff --git a/api/tests/unit_tests/core/app/apps/pipeline/test_pipeline_generator.py b/api/tests/unit_tests/core/app/apps/pipeline/test_pipeline_generator.pyindex f702e0ed626..587e8da9424 100644--- a/api/tests/unit_tests/core/app/apps/pipeline/test_pipeline_generator.py+++ b/api/tests/unit_tests/core/app/apps/pipeline/test_pipeline_generator.py@@ -628,7 +628,7 @@ def test_single_loop_generate_success(def test_handle_response_value_error_triggers_generate_task_stopped(generator, mocker: MockerFixture):- pipeline = _build_pipeline()+ _build_pipeline()workflow = _build_workflow()app_entity = FakeRagPipelineGenerateEntity(task_id="t")diff --git a/api/tests/unit_tests/core/app/features/rate_limiting/test_rate_limit.py b/api/tests/unit_tests/core/app/features/rate_limiting/test_rate_limit.pyindex 097fe7a28ed..499bd3ff37a 100644--- a/api/tests/unit_tests/core/app/features/rate_limiting/test_rate_limit.py+++ b/api/tests/unit_tests/core/app/features/rate_limiting/test_rate_limit.py@@ -131,7 +131,7 @@ class TestRateLimit:})- rate_limit = RateLimit("test_client", 5)+ RateLimit("test_client", 5)expected_max_key = "dify:rate_limit:test_client:max_active_requests"redis_patch.setex.assert_called_with(expected_max_key, timedelta(days=1), 5)@@ -565,7 +565,6 @@ class TestRateLimitConcurrency:import threadinglock = threading.Lock()- data = {}hashes = {}def mock_hlen(key):diff --git a/api/tests/unit_tests/core/callback_handler/test_index_tool_callback_handler.py b/api/tests/unit_tests/core/callback_handler/test_index_tool_callback_handler.pyindex 4c40841fd98..76b0af1fdfa 100644--- a/api/tests/unit_tests/core/callback_handler/test_index_tool_callback_handler.py+++ b/api/tests/unit_tests/core/callback_handler/test_index_tool_callback_handler.py@@ -264,7 +264,7 @@ class TestOnToolEnd:class TestReturnRetrieverResourceInfo:def test_publish_called(self, handler: DatasetIndexToolCallbackHandler, mock_queue_manager, mocker: MockerFixture):- mock_event = mocker.patch("core.callback_handler.index_tool_callback_handler.QueueRetrieverResourcesEvent")+ mocker.patch("core.callback_handler.index_tool_callback_handler.QueueRetrieverResourcesEvent")resources = [mocker.Mock()]handler.return_retriever_resource_info(resources)diff --git a/api/tests/unit_tests/core/datasource/test_file_upload.py b/api/tests/unit_tests/core/datasource/test_file_upload.pyindex 130036b249e..1dd5ddd5680 100644--- a/api/tests/unit_tests/core/datasource/test_file_upload.py+++ b/api/tests/unit_tests/core/datasource/test_file_upload.py@@ -359,7 +359,6 @@ class TestVirusScanningIntegration:# When virus scanning is added, this test should be updated# Arrange- content = b"This could be any content"# Act - No virus scanning function exists yet# This is a placeholder for future implementationdiff --git a/api/tests/unit_tests/core/datasource/test_notion_provider.py b/api/tests/unit_tests/core/datasource/test_notion_provider.pyindex bbbb24906d2..acb4a61300a 100644--- a/api/tests/unit_tests/core/datasource/test_notion_provider.py+++ b/api/tests/unit_tests/core/datasource/test_notion_provider.py@@ -1122,7 +1122,7 @@ class TestNotionExtractorReadBlock:mock_request.return_value = httpx.Response(200, json=mock_data)# Act- result = extractor._read_block("block-parent")+ extractor._read_block("block-parent")# Assert# Should only be called once (no recursion for child_page)diff --git a/api/tests/unit_tests/core/datasource/test_website_crawl.py b/api/tests/unit_tests/core/datasource/test_website_crawl.pyindex ed99d489673..20b8fd32089 100644--- a/api/tests/unit_tests/core/datasource/test_website_crawl.py+++ b/api/tests/unit_tests/core/datasource/test_website_crawl.py@@ -195,7 +195,7 @@ class TestWebsiteCrawlDatasourcePlugin:datasource_params = {"url": "https://example.com", "max_depth": 2}- result = plugin.get_website_crawl(+ plugin.get_website_crawl(user_id="test_user", datasource_parameters=datasource_params, provider_type="watercrawl")@@ -576,7 +576,7 @@ class TestWebsiteService:}mock_response = httpx.Response(200, json={"code": 200, "data": {"taskId": "task-789"}})- mock_httpx_post = mocker.patch(+ mocker.patch("services.data_source.website_service._adaptive_http_client.post",return_value=mock_response,)@@ -724,7 +724,6 @@ class TestRobotsTxtRespect:This test verifies the provider is initialized correctly."""mock_client = mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")- mock_instance = mock_client.return_valueprovider = WaterCrawlProvider(api_key="test_key", base_url="https://app.watercrawl.dev/")@@ -779,7 +778,7 @@ class TestContentExtraction:def test_structure_data_with_metadata(self, mocker: MockerFixture) -> None:"""Test that content is properly structured with metadata."""- mock_client = mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")+ mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")provider = WaterCrawlProvider(api_key="test_key")@@ -804,7 +803,7 @@ class TestContentExtraction:def test_structure_data_fallback_title(self, mocker: MockerFixture) -> None:"""Test that fallback title is used when og:title is not available."""- mock_client = mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")+ mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")provider = WaterCrawlProvider(api_key="test_key")@@ -819,7 +818,7 @@ class TestContentExtraction:def test_structure_data_invalid_result(self, mocker: MockerFixture) -> None:"""Test that ValueError is raised for invalid result objects."""- mock_client = mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")+ mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")provider = WaterCrawlProvider(api_key="test_key")@@ -903,10 +902,9 @@ class TestErrorHandling:"""Test that missing API key is handled properly at the httpx client level."""# Mock the client to avoid actual httpx initializationmock_client = mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")- mock_instance = mock_client.return_value# Create provider with mocked client - should work with mock- provider = WaterCrawlProvider(api_key="test_key")+ WaterCrawlProvider(api_key="test_key")# Verify the client was initialized with the API keymock_client.assert_called_once_with("test_key", None)@@ -1462,7 +1460,7 @@ class TestProviderSpecificFeatures:mock_client = mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")# Create provider without specifying base_url- provider = WaterCrawlProvider(api_key="test_key")+ WaterCrawlProvider(api_key="test_key")# Verify default base URL is usedmock_client.assert_called_once_with("test_key", None)@@ -1734,7 +1732,7 @@ class TestEdgeCasesAndBoundaries:Not all pages have complete metadata, so extraction shouldhandle missing fields gracefully."""- mock_client = mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")+ mocker.patch("core.rag.extractor.watercrawl.provider.WaterCrawlAPIClient")provider = WaterCrawlProvider(api_key="test_key")diff --git a/api/tests/unit_tests/core/external_data_tool/test_factory.py b/api/tests/unit_tests/core/external_data_tool/test_factory.pyindex 6bb384b0ac9..273a4e75d39 100644--- a/api/tests/unit_tests/core/external_data_tool/test_factory.py+++ b/api/tests/unit_tests/core/external_data_tool/test_factory.py@@ -15,7 +15,7 @@ def test_external_data_tool_factory_init():variable = "var_v"config = {"key": "value"}- factory = ExternalDataToolFactory(name, tenant_id, app_id, variable, config)+ ExternalDataToolFactory(name, tenant_id, app_id, variable, config)mock_code_based_extension.extension_class.assert_called_once_with(ExtensionModule.EXTERNAL_DATA_TOOL, name)mock_extension_class.assert_called_once_with(diff --git a/api/tests/unit_tests/core/mcp/client/test_streamable_http.py b/api/tests/unit_tests/core/mcp/client/test_streamable_http.pyindex 6dfc2c7c1fe..c8c22fd17fe 100644--- a/api/tests/unit_tests/core/mcp/client/test_streamable_http.py+++ b/api/tests/unit_tests/core/mcp/client/test_streamable_http.py@@ -206,17 +206,13 @@ def test_streamablehttp_client_queue_cleanup():"""Test that StreamableHTTP client properly cleans up queues on exit."""test_url = "http://test.example/mcp"- read_queue = None- write_queue = None-with patch("core.mcp.client.streamable_client.create_ssrf_proxy_mcp_http_client") as mock_client_factory:# Mock connection that raises an exceptionmock_client_factory.side_effect = Exception("Connection failed")try:with streamablehttp_client(test_url) as (rq, wq, get_session_id):- read_queue = rq- write_queue = wq+ passexcept Exception:pass # Expected to fail@@ -252,7 +248,7 @@ def test_streamablehttp_client_headers_propagation(monkeypatch: pytest.MonkeyPatdef test_streamablehttp_client_concurrent_access():"""Test StreamableHTTP client behavior with concurrent queue access."""test_read_queue: queue.Queue = queue.Queue()- test_write_queue: queue.Queue = queue.Queue()+ queue.Queue()# Simulate concurrent producers and consumersdef producer():diff --git a/api/tests/unit_tests/core/mcp/session/test_base_session.py b/api/tests/unit_tests/core/mcp/session/test_base_session.pyindex c4f57e60e99..bf1d85d93a7 100644--- a/api/tests/unit_tests/core/mcp/session/test_base_session.py+++ b/api/tests/unit_tests/core/mcp/session/test_base_session.py@@ -295,8 +295,7 @@ def test_send_request_http_status_auth_error(streams):def mock_error():try:- msg = write_stream.get(timeout=2)- req_id = msg.message.root.id+ write_stream.get(timeout=2)response = Response(status_code=401, request=Request("GET", "http://test"))error = HTTPStatusError("Unauthorized", request=response.request, response=response)read_stream.put(error)diff --git a/api/tests/unit_tests/core/repositories/test_human_input_repository.py b/api/tests/unit_tests/core/repositories/test_human_input_repository.pyindex 6aaa0596152..c53b5b88fac 100644--- a/api/tests/unit_tests/core/repositories/test_human_input_repository.py+++ b/api/tests/unit_tests/core/repositories/test_human_input_repository.py@@ -361,7 +361,7 @@ def test_get_form_returns_entity_and_none_when_missing(repository_session: Sessiform = _persist_form(repository_session, form_id="f1")_persist_form(repository_session, form_id="other-tenant-form", tenant_id="other-tenant")- recipient = _persist_recipient(repository_session, form_id=form.id, recipient_id="r1", access_token="tok")+ _persist_recipient(repository_session, form_id=form.id, recipient_id="r1", access_token="tok")repo = HumanInputFormRepositoryImpl(tenant_id="tenant", workflow_execution_id="run")entity = repo.get_form("node")assert entity is not None@@ -462,7 +462,7 @@ def test_submission_repository_init_no_args() -> None:def test_submission_get_by_token_and_get_by_form_id_success_paths(repository_session: Session) -> None:form = _persist_form(repository_session, form_id="f1", workflow_run_id=None)- recipient = _persist_recipient(repository_session, form_id=form.id, recipient_id="r1", access_token="tok")+ _persist_recipient(repository_session, form_id=form.id, recipient_id="r1", access_token="tok")repo = HumanInputFormSubmissionRepository()record = repo.get_by_token("tok")assert record is not Nonediff --git a/api/tests/unit_tests/core/schemas/test_resolver.py b/api/tests/unit_tests/core/schemas/test_resolver.pyindex ed819457798..a642d5fe480 100644--- a/api/tests/unit_tests/core/schemas/test_resolver.py+++ b/api/tests/unit_tests/core/schemas/test_resolver.py@@ -559,7 +559,7 @@ class TestSchemaResolverClass:for _ in range(10):SchemaResolver.clear_cache()start = time.perf_counter()- result_slow = resolve_dify_schema_refs(with_refs_schema, max_depth=50)+ resolve_dify_schema_refs(with_refs_schema, max_depth=50)elapsed = time.perf_counter() - startslow_times.append(elapsed)diff --git a/api/tests/unit_tests/core/tools/test_signature.py b/api/tests/unit_tests/core/tools/test_signature.pyindex 1214d8a4caf..f568b867ee6 100644--- a/api/tests/unit_tests/core/tools/test_signature.py+++ b/api/tests/unit_tests/core/tools/test_signature.py@@ -107,7 +107,7 @@ def test_verify_tool_file_signature_rejects_invalid_sign(query = parse_qs(parsed.query)timestamp = query["timestamp"][0]nonce = query["nonce"][0]- sign = query["sign"][0]+ query["sign"][0]assert verify_tool_file_signature("tool-file-id", timestamp, nonce, "bad-signature") is Falsediff --git a/api/tests/unit_tests/core/workflow/generator/test_runner_missing.py b/api/tests/unit_tests/core/workflow/generator/test_runner_missing.pyindex 147678e198f..57d9a324511 100644--- a/api/tests/unit_tests/core/workflow/generator/test_runner_missing.py+++ b/api/tests/unit_tests/core/workflow/generator/test_runner_missing.py@@ -74,7 +74,6 @@ def test_collect_container_errors():nodes = [{"id": "n1", "data": {"type": "llm"}},]- edges = []# Test would go here but we need to see what _validate_structure calls@@ -174,5 +173,5 @@ def test_missing_terminal_mode_auto():graph = {"nodes": [{"id": "n1", "data": {"type": "start"}}], "edges": []}# Missing terminal check happens inside _validate_structure- errors = WorkflowGenerator._validate_structure(graph=graph, mode="workflow", installed_tools=set())+ WorkflowGenerator._validate_structure(graph=graph, mode="workflow", installed_tools=set())# Mocking this deeply is hard, but we can verify it doesn't faildiff --git a/api/tests/unit_tests/core/workflow/graph_engine/test_mock_nodes.py b/api/tests/unit_tests/core/workflow/graph_engine/test_mock_nodes.pyindex a4a6f57a237..542411c5656 100644--- a/api/tests/unit_tests/core/workflow/graph_engine/test_mock_nodes.py+++ b/api/tests/unit_tests/core/workflow/graph_engine/test_mock_nodes.py@@ -684,7 +684,7 @@ class MockTemplateTransformNode(MockNodeMixin, TemplateTransformNode):return NodeRunResult(status=WorkflowNodeExecutionStatus.SUCCEEDED, inputs=variables, outputs={"output": result_text})- except Exception as e:+ except Exception:# If direct Jinja2 fails, try CodeExecutor as fallbacktry:from core.helper.code_executor.code_executor import CodeExecutor, CodeLanguagediff --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.pyindex 2678610cb80..afaeadd5e3d 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@@ -1251,7 +1251,7 @@ def test_stale_previous_node_refs_are_ignored_when_workflow_prompt_has_no_frontedef test_previous_node_file_array_uses_agent_stub_download_mappings_in_workflow_context():first_reference = build_file_reference(record_id="tool-file-1")- second_reference = build_file_reference(record_id="tool-file-2")+ build_file_reference(record_id="tool-file-2")class FileArrayVariablePool(FakeVariablePool):def get(self, selector):diff --git a/api/tests/unit_tests/core/workflow/nodes/human_input/test_entities.py b/api/tests/unit_tests/core/workflow/nodes/human_input/test_entities.pyindex feb04a4a38a..a3d555c0d60 100644--- a/api/tests/unit_tests/core/workflow/nodes/human_input/test_entities.py+++ b/api/tests/unit_tests/core/workflow/nodes/human_input/test_entities.py@@ -596,7 +596,7 @@ class TestHumanInputNodeVariableResolution:workflow_execution_id_getter=lambda: "exec-2",)repository = runtime.build_form_repository()- create = mocker.spy(repository, "create_form")+ mocker.spy(repository, "create_form")runtime = runtime.with_form_repository(repository)node = _build_human_input_node(node_id=config["id"],diff --git a/api/tests/unit_tests/core/workflow/nodes/test_base_node.py b/api/tests/unit_tests/core/workflow/nodes/test_base_node.pyindex d9630f69676..45aa7470618 100644--- a/api/tests/unit_tests/core/workflow/nodes/test_base_node.py+++ b/api/tests/unit_tests/core/workflow/nodes/test_base_node.py@@ -108,8 +108,6 @@ def test_node_accepts_invoke_from_enum():def test_missing_generic_argument_raises_type_error():- graph_config: dict[str, object] = {}-with pytest.raises(TypeError):class _InvalidNode(Node): # type: ignore[type-abstract]diff --git a/api/tests/unit_tests/core/workflow/nodes/test_if_else.py b/api/tests/unit_tests/core/workflow/nodes/test_if_else.pyindex 38d1e94bbc9..20d4e40cf23 100644--- a/api/tests/unit_tests/core/workflow/nodes/test_if_else.py+++ b/api/tests/unit_tests/core/workflow/nodes/test_if_else.py@@ -75,7 +75,7 @@ def test_execute_if_else_result_true():graph_init_params=init_params,graph_runtime_state=graph_runtime_state,)- graph = Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")+ Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")node = _build_if_else_node(node_data={@@ -160,7 +160,7 @@ def test_execute_if_else_result_false():graph_init_params=init_params,graph_runtime_state=graph_runtime_state,)- graph = Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")+ Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")node = _build_if_else_node(node_data={@@ -314,7 +314,7 @@ def test_execute_if_else_boolean_conditions(condition: Condition):graph_init_params=init_params,graph_runtime_state=graph_runtime_state,)- graph = Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")+ Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")node_data = {"title": "Boolean Test",@@ -364,7 +364,7 @@ def test_execute_if_else_boolean_false_conditions():graph_init_params=init_params,graph_runtime_state=graph_runtime_state,)- graph = Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")+ Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")node_data = {"title": "Boolean False Test",@@ -425,7 +425,7 @@ def test_execute_if_else_boolean_cases_structure():graph_init_params=init_params,graph_runtime_state=graph_runtime_state,)- graph = Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")+ Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")node_data = {"title": "Boolean Cases Test",diff --git a/api/tests/unit_tests/core/workflow/nodes/tool/test_tool_node_invocation_behavior.py b/api/tests/unit_tests/core/workflow/nodes/tool/test_tool_node_invocation_behavior.pyindex 911bfd7fa00..987ef88696d 100644--- a/api/tests/unit_tests/core/workflow/nodes/tool/test_tool_node_invocation_behavior.py+++ b/api/tests/unit_tests/core/workflow/nodes/tool/test_tool_node_invocation_behavior.py@@ -57,7 +57,7 @@ def init_tool_node(config: dict[str, object]) -> ToolNode:graph_runtime_state=graph_runtime_state,)- graph = Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")+ Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id="start")tool_file_manager = DifyToolFileManager(init_params.run_context)diff --git a/api/tests/unit_tests/core/workflow/test_variable_pool.py b/api/tests/unit_tests/core/workflow/test_variable_pool.pyindex 215933b021b..4fbc87a7e68 100644--- a/api/tests/unit_tests/core/workflow/test_variable_pool.py+++ b/api/tests/unit_tests/core/workflow/test_variable_pool.py@@ -270,12 +270,6 @@ class TestVariablePoolSerialization:]# Create comprehensive user inputs- user_inputs = {- "string_input": "test_value",- "number_input": 42,- "object_input": {"nested": {"key": "value"}},- "array_input": ["item1", "item2", "item3"],- }# Create VariablePoolpool = VariablePool()diff --git a/api/tests/unit_tests/core/workflow/test_workflow_entry_redis_channel.py b/api/tests/unit_tests/core/workflow/test_workflow_entry_redis_channel.pyindex 4e8140c144d..5df526d1750 100644--- a/api/tests/unit_tests/core/workflow/test_workflow_entry_redis_channel.py+++ b/api/tests/unit_tests/core/workflow/test_workflow_entry_redis_channel.py@@ -25,7 +25,7 @@ class TestWorkflowEntryRedisChannel:# Patch GraphEngine to verify it receives the Redis channelwith patch("core.workflow.workflow_entry.GraphEngine", autospec=True) as mock_graph_engine_type:- mock_graph_engine = mock_graph_engine_type.return_value # Create WorkflowEntry with Redis channel+ # Create WorkflowEntry with Redis channelworkflow_entry = WorkflowEntry(tenant_id="test-tenant",app_id="test-app",@@ -60,10 +60,8 @@ class TestWorkflowEntryRedisChannel:patch("core.workflow.workflow_entry.GraphEngine", autospec=True) as mock_graph_engine_type,patch("core.workflow.workflow_entry.InMemoryChannel", autospec=True) as mock_in_memory_channel,):- mock_graph_engine = mock_graph_engine_type.return_value- mock_inmemory_channel = (- mock_in_memory_channel.return_value- ) # Create WorkflowEntry without providing a channel+ mock_inmemory_channel = mock_in_memory_channel.return_value+ # Create WorkflowEntry without providing a channelworkflow_entry = WorkflowEntry(tenant_id="test-tenant",app_id="test-app",diff --git a/api/tests/unit_tests/enterprise/telemetry/test_enterprise_trace.py b/api/tests/unit_tests/enterprise/telemetry/test_enterprise_trace.pyindex 5b7fb4acc1e..2181738b181 100644--- a/api/tests/unit_tests/enterprise/telemetry/test_enterprise_trace.py+++ b/api/tests/unit_tests/enterprise/telemetry/test_enterprise_trace.py@@ -453,7 +453,7 @@ class TestTraceDispatcher:class TestWorkflowTrace:def test_emits_correct_span_attributes(self, trace_handler: EnterpriseOtelTrace, mock_exporter):- with patch("enterprise.telemetry.enterprise_trace.emit_telemetry_log") as mock_log:+ with patch("enterprise.telemetry.enterprise_trace.emit_telemetry_log"):info = make_workflow_info()trace_handler._workflow_trace(info)diff --git a/api/tests/unit_tests/enterprise/telemetry/test_id_generator.py b/api/tests/unit_tests/enterprise/telemetry/test_id_generator.pyindex dc2be14ebf3..9bf51736934 100644--- a/api/tests/unit_tests/enterprise/telemetry/test_id_generator.py+++ b/api/tests/unit_tests/enterprise/telemetry/test_id_generator.py@@ -177,7 +177,7 @@ class TestCorrelationIdGeneratorGenerateSpanId:set_span_id_source("not-a-uuid")gen = CorrelationIdGenerator()- with patch("enterprise.telemetry.id_generator.random.getrandbits", return_value=7) as mock_rng:+ with patch("enterprise.telemetry.id_generator.random.getrandbits", return_value=7):span_id = gen.generate_span_id()assert span_id == 7diff --git a/api/tests/unit_tests/libs/test_time_parser.py b/api/tests/unit_tests/libs/test_time_parser.pyindex 83ff251272a..8319cb1cc67 100644--- a/api/tests/unit_tests/libs/test_time_parser.py+++ b/api/tests/unit_tests/libs/test_time_parser.py@@ -62,7 +62,6 @@ class TestGetTimeThreshold:"""Test getting threshold for days."""before = datetime.now(UTC)result = get_time_threshold("7d")- after = datetime.now(UTC)assert result is not None# Result should be approximately 7 days ago@@ -74,7 +73,6 @@ class TestGetTimeThreshold:"""Test getting threshold for hours."""before = datetime.now(UTC)result = get_time_threshold("4h")- after = datetime.now(UTC)assert result is not Noneexpected = before - timedelta(hours=4)diff --git a/api/tests/unit_tests/models/test_account_models.py b/api/tests/unit_tests/models/test_account_models.pyindex 14677e13c71..61987cad94a 100644--- a/api/tests/unit_tests/models/test_account_models.py+++ b/api/tests/unit_tests/models/test_account_models.py@@ -648,7 +648,6 @@ class TestTenantModel:"""Test custom_config_dict property getter."""# Arrangetenant = Tenant(name="Test Workspace")- config = {"feature1": True, "feature2": "value"}tenant.custom_config = '{"feature1": true, "feature2": "value"}'# Actdiff --git a/api/tests/unit_tests/models/test_workflow.py b/api/tests/unit_tests/models/test_workflow.pyindex a7f5cf5bf9f..111be8880a9 100644--- a/api/tests/unit_tests/models/test_workflow.py+++ b/api/tests/unit_tests/models/test_workflow.py@@ -308,8 +308,6 @@ class TestWorkflowDraftVariableGetValue:name: strvalue: Segment- tenant_id = "test_tenant_id"-test_file = File(file_type=FileType.IMAGE,transfer_method=FileTransferMethod.REMOTE_URL,@@ -378,7 +376,6 @@ class TestWorkflowDraftVariableGetValue:def test_file_variable_preserves_all_fields(self):"""Test that File type variables preserve all fields during encoding/decoding."""- tenant_id = "test_tenant_id"# Create a File with specific field valuestest_file = File(diff --git a/api/tests/unit_tests/services/controller_api.py b/api/tests/unit_tests/services/controller_api.pyindex 3ef2a15c3ca..a8fb6ad4c54 100644--- a/api/tests/unit_tests/services/controller_api.py+++ b/api/tests/unit_tests/services/controller_api.py@@ -355,9 +355,7 @@ class TestDatasetListApi:for i in range(3)]- paginated_response = ControllerApiTestDataFactory.create_paginated_response(- items=datasets, total=3, page=1, per_page=20- )+ ControllerApiTestDataFactory.create_paginated_response(items=datasets, total=3, page=1, per_page=20)with patch("controllers.console.datasets.datasets.DatasetService.get_datasets") as mock_get_datasets:mock_get_datasets.return_value = (datasets, 3)@@ -546,7 +544,7 @@ class TestDatasetApiGet:with (patch("controllers.console.datasets.datasets.DatasetService.get_dataset") as mock_get_dataset,- patch("controllers.console.datasets.datasets.DatasetService.check_dataset_permission") as mock_check_perm,+ patch("controllers.console.datasets.datasets.DatasetService.check_dataset_permission"),):mock_get_dataset.return_value = None # Dataset not founddiff --git a/api/tests/unit_tests/services/data_migration/test_import_service.py b/api/tests/unit_tests/services/data_migration/test_import_service.pyindex 512d2f10e66..28e9d81d19a 100644--- a/api/tests/unit_tests/services/data_migration/test_import_service.py+++ b/api/tests/unit_tests/services/data_migration/test_import_service.py@@ -602,7 +602,7 @@ def test_workflow_tool_skip_records_id_mapping(database: Database):def test_api_tool_existing_provider_records_id_mapping(monkeypatch: pytest.MonkeyPatch, database: Database, conflict_strategy: ConflictStrategy):- target_provider = _persist_api_provider(database.session, provider_id="target-api-provider-id")+ _persist_api_provider(database.session, provider_id="target-api-provider-id")_persist_api_provider(database.session, provider_id="other-tenant-provider-id", tenant_id="tenant-2")id_mapping = {}id_mapping_details = []@@ -731,7 +731,7 @@ def test_mcp_tool_import_restores_exported_tool_list(monkeypatch: pytest.MonkeyPdef test_mcp_tool_existing_provider_records_id_mapping(monkeypatch: pytest.MonkeyPatch, database: Database, conflict_strategy: ConflictStrategy):- provider = _persist_mcp_provider(database.session, provider_id="target-mcp-provider-id")+ _persist_mcp_provider(database.session, provider_id="target-mcp-provider-id")_persist_mcp_provider(database.session,provider_id="other-mcp-provider-id",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.pyindex 939b54b1559..84970c38c1e 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@@ -204,7 +204,7 @@ def test_generate_rejects_original_document_outside_pipeline_dataset_before_dispsqlite_session.add_all([dataset, pipeline, outside_document])sqlite_session.commit()mocker.patch.object(PipelineGenerateService, "_get_workflow", return_value=_make_workflow())- generator_cls = mocker.patch("services.rag_pipeline.pipeline_generate_service.PipelineGenerator")+ mocker.patch("services.rag_pipeline.pipeline_generate_service.PipelineGenerator")with pytest.raises(ValueError, match="Pipeline document not found"):PipelineGenerateService.generate(diff --git a/api/tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.py b/api/tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.pyindex 8d30ca231c7..4dbc7bc0bd7 100644--- a/api/tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.py+++ b/api/tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.py@@ -636,7 +636,7 @@ class TestRestoreFromRun:run = WorkflowRunRestoreTestDataFactory.create_workflow_run()- with patch("services.retention.workflow_run.restore_archived_workflow_run.click") as mock_click:+ with patch("services.retention.workflow_run.restore_archived_workflow_run.click"):result = restore._restore_from_run(run, session_maker=database.session_maker)assert result.success is False@@ -653,7 +653,7 @@ class TestRestoreFromRun:run = WorkflowRunRestoreTestDataFactory.create_workflow_run()- with patch("services.retention.workflow_run.restore_archived_workflow_run.click") as mock_click:+ with patch("services.retention.workflow_run.restore_archived_workflow_run.click"):result = restore._restore_from_run(run, session_maker=database.session_maker)assert result.success is False@@ -702,7 +702,7 @@ class TestRestoreFromRun:)mock_get_repo.return_value = mock_repo- with patch("services.retention.workflow_run.restore_archived_workflow_run.click") as mock_click:+ with patch("services.retention.workflow_run.restore_archived_workflow_run.click"):result = restore._restore_from_run(run, session_maker=database.session_maker)assert result.success is True@@ -750,7 +750,7 @@ class TestRestoreFromRun:run = WorkflowRunRestoreTestDataFactory.create_workflow_run()- with patch("services.retention.workflow_run.restore_archived_workflow_run.click") as mock_click:+ with patch("services.retention.workflow_run.restore_archived_workflow_run.click"):result = restore._restore_from_run(run, session_maker=database.session_maker)assert result.success is False@@ -825,7 +825,7 @@ class TestRestoreBatch:with patch.object(restore, "_get_workflow_run_repo", return_value=mock_repo):with patch.object(restore, "_restore_from_run", side_effect=[result1, result2]):- with patch("services.retention.workflow_run.restore_archived_workflow_run.click") as mock_click:+ with patch("services.retention.workflow_run.restore_archived_workflow_run.click"):results = restore.restore_batch(tenant_ids=["tenant-1"],start_date=datetime(2024, 1, 1),@@ -858,7 +858,7 @@ class TestRestoreBatch:with patch.object(restore, "_get_workflow_run_repo", return_value=mock_repo):with patch.object(restore, "_restore_from_run", return_value=result):- with patch("services.retention.workflow_run.restore_archived_workflow_run.click") as mock_click:+ with patch("services.retention.workflow_run.restore_archived_workflow_run.click"):results = restore.restore_batch(tenant_ids=["tenant-1"],start_date=datetime(2024, 1, 1),@@ -885,7 +885,7 @@ class TestRestoreByRunId:mock_repo.get_archived_log_by_run_id.return_value = Nonewith patch.object(restore, "_get_workflow_run_repo", return_value=mock_repo):- with patch("services.retention.workflow_run.restore_archived_workflow_run.click") as mock_click:+ with patch("services.retention.workflow_run.restore_archived_workflow_run.click"):result = restore.restore_by_run_id("nonexistent-run")assert result.success is False@@ -906,7 +906,7 @@ class TestRestoreByRunId:with patch.object(restore, "_get_workflow_run_repo", return_value=mock_repo):with patch.object(restore, "_restore_from_run", return_value=result):- with patch("services.retention.workflow_run.restore_archived_workflow_run.click") as mock_click:+ with patch("services.retention.workflow_run.restore_archived_workflow_run.click"):actual_result = restore.restore_by_run_id("run-1")assert actual_result.success is True@@ -926,7 +926,7 @@ class TestRestoreByRunId:with patch.object(restore, "_get_workflow_run_repo", return_value=mock_repo):with patch.object(restore, "_restore_from_run", return_value=result):- with patch("services.retention.workflow_run.restore_archived_workflow_run.click") as mock_click:+ with patch("services.retention.workflow_run.restore_archived_workflow_run.click"):actual_result = restore.restore_by_run_id("run-1")assert actual_result.success is Truediff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.pyindex df4b5e11c85..287ef0709d1 100644--- a/api/tests/unit_tests/services/test_app_dsl_service.py+++ b/api/tests/unit_tests/services/test_app_dsl_service.py@@ -1242,7 +1242,7 @@ def test_import_creation_marker_tracks_persisted_app(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch, confirmed: bool, overwrite: bool) -> None:account = _account(account_id=_CALLER_ID, tenant_id=_TENANT_ID)- target = _persist_overwrite_target(sqlite_session) if overwrite else None+ _persist_overwrite_target(sqlite_session) if overwrite else Nonedata = yaml.safe_dump({"version": CURRENT_APP_DSL_VERSION,diff --git a/api/tests/unit_tests/services/test_app_generate_service.py b/api/tests/unit_tests/services/test_app_generate_service.pyindex 5b20675c9c8..55fa8da4f60 100644--- a/api/tests/unit_tests/services/test_app_generate_service.py+++ b/api/tests/unit_tests/services/test_app_generate_service.py@@ -485,7 +485,7 @@ class TestGenerate(_RealSessionTest):return_value=gen_instance,)- result = AppGenerateService.generate(+ AppGenerateService.generate(app_model=_make_app(AppMode.ADVANCED_CHAT),user=_make_user(),args={"workflow_id": None, "query": "hi", "inputs": {}},@@ -625,7 +625,7 @@ class TestGenerate(_RealSessionTest):side_effect=lambda x: x,)- result = AppGenerateService.generate(+ AppGenerateService.generate(app_model=_make_app(AppMode.WORKFLOW),user=_make_user(),args={"inputs": {}},@@ -938,7 +938,7 @@ class TestGenerateSingleIteration(_RealSessionTest):def test_advanced_chat_mode(self, mocker: MockerFixture):workflow = _make_workflow()mocker.patch.object(AppGenerateService, "_get_workflow", return_value=workflow)- gen_spy = mocker.patch(+ mocker.patch("services.app_generate_service.AdvancedChatAppGenerator.convert_to_event_stream",side_effect=lambda x: x,)@@ -1091,7 +1091,7 @@ class TestGetResponseGenerator:return_value=gen_instance,)- result = AppGenerateService.get_response_generator(app_model=app, workflow_run=workflow_run)+ AppGenerateService.get_response_generator(app_model=app, workflow_run=workflow_run)gen_instance.retrieve_events.assert_called_once()def test_ended_workflow_run_still_returns_generator(self, mocker: MockerFixture):@@ -1107,6 +1107,6 @@ class TestGetResponseGenerator:return_value=gen_instance,)- result = AppGenerateService.get_response_generator(app_model=app, workflow_run=workflow_run)+ AppGenerateService.get_response_generator(app_model=app, workflow_run=workflow_run)# current impl falls through the TODO and still creates a generatorgen_instance.retrieve_events.assert_called_once()diff --git a/api/tests/unit_tests/services/test_variable_truncator.py b/api/tests/unit_tests/services/test_variable_truncator.pyindex 8af859dc357..7cb31751b82 100644--- a/api/tests/unit_tests/services/test_variable_truncator.py+++ b/api/tests/unit_tests/services/test_variable_truncator.py@@ -493,13 +493,13 @@ class TestEdgeCases:"""Test truncator behavior with zero or very small limits."""# Zero string limitwith pytest.raises(ValueError, match="string_length_limit should be greater than 3\\."):- truncator = VariableTruncator(string_length_limit=3)+ VariableTruncator(string_length_limit=3)with pytest.raises(ValueError, match="array_element_limit should be greater than 0\\."):- truncator = VariableTruncator(array_element_limit=0)+ VariableTruncator(array_element_limit=0)with pytest.raises(ValueError, match="max_size_bytes should be greater than 0\\."):- truncator = VariableTruncator(max_size_bytes=0)+ VariableTruncator(max_size_bytes=0)def test_unicode_and_special_characters(self):"""Test truncator with unicode and special characters."""diff --git a/api/tests/unit_tests/services/test_workflow_service.py b/api/tests/unit_tests/services/test_workflow_service.pyindex 9fc63e780e6..89b27a2c634 100644--- a/api/tests/unit_tests/services/test_workflow_service.py+++ b/api/tests/unit_tests/services/test_workflow_service.py@@ -3256,7 +3256,7 @@ class TestWorkflowServiceDraftExecution:with (patch("services.workflow_service.db", SimpleNamespace(engine=sqlite_engine)),patch("services.workflow_service.WorkflowDraftVariableService"),- patch("services.workflow_service.StartNodeData") as mock_start_data,+ patch("services.workflow_service.StartNodeData"),patch("services.workflow_service._rebuild_file_for_user_inputs_in_start_node",side_effect=lambda **kwargs: kwargs["user_inputs"],diff --git a/api/tests/unit_tests/tasks/test_dataset_indexing_task.py b/api/tests/unit_tests/tasks/test_dataset_indexing_task.pyindex 3b9b5103947..51c61f45e9d 100644--- a/api/tests/unit_tests/tasks/test_dataset_indexing_task.py+++ b/api/tests/unit_tests/tasks/test_dataset_indexing_task.py@@ -183,7 +183,7 @@ class TestTaskEnqueuing:self, tenant_id: str, dataset_id: str, document_ids: list[str], mock_redis: MagicMock) -> None:with (- patch.object(DocumentIndexingTaskProxy, "features") as features,+ patch.object(DocumentIndexingTaskProxy, "features"),patch.object(DocumentIndexingTaskProxy, "PRIORITY_TASK_FUNC", Mock()) as task,):DocumentIndexingTaskProxy(tenant_id, dataset_id, document_ids).delay()diff --git a/api/tests/unit_tests/tasks/test_segment_index_cleanup_tasks.py b/api/tests/unit_tests/tasks/test_segment_index_cleanup_tasks.pyindex 910cf8abf34..1c680bdfb47 100644--- a/api/tests/unit_tests/tasks/test_segment_index_cleanup_tasks.py+++ b/api/tests/unit_tests/tasks/test_segment_index_cleanup_tasks.py@@ -190,7 +190,7 @@ def test_delete_segment_removes_attachment_blobs_from_storage(binding_id = binding.idwith (- patch("tasks.delete_segment_from_index_task.IndexProcessorFactory") as processor_factory,+ patch("tasks.delete_segment_from_index_task.IndexProcessorFactory"),patch("tasks.delete_segment_from_index_task.storage.delete") as storage_delete,):delete_segment_from_index_task.run(["node-1"], dataset.id, document.id, [segment.id])@@ -305,7 +305,7 @@ def test_delete_segment_keeps_database_cleanup_when_attachment_storage_delete_fabinding_id = binding.idwith (- patch("tasks.delete_segment_from_index_task.IndexProcessorFactory") as processor_factory,+ patch("tasks.delete_segment_from_index_task.IndexProcessorFactory"),patch("tasks.delete_segment_from_index_task.storage.delete",side_effect=RuntimeError("storage unavailable"),