chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,167 @@
"""
Configuration system for mock nodes in testing.
This module provides a flexible configuration system for customizing
the behavior of mock nodes during testing.
"""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
from graphon.enums import NodeType
@dataclass
class NodeMockConfig:
"""Configuration for a specific node mock."""
node_id: str
outputs: dict[str, Any] = field(default_factory=dict)
error: str | None = None
delay: float = 0.0 # Simulated execution delay in seconds
custom_handler: Callable[..., dict[str, Any]] | None = None
@dataclass
class MockConfig:
"""
Global configuration for mock nodes in a test.
This configuration allows tests to customize the behavior of mock nodes,
including their outputs, errors, and execution characteristics.
"""
# Node-specific configurations by node ID
node_configs: dict[str, NodeMockConfig] = field(default_factory=dict)
# Default configurations by node type
default_configs: dict[NodeType, dict[str, Any]] = field(default_factory=dict)
# Global settings
enable_auto_mock: bool = True
simulate_delays: bool = False
default_llm_response: str = "This is a mocked LLM response"
default_agent_response: str = "This is a mocked agent response"
default_tool_response: dict[str, Any] = field(default_factory=lambda: {"result": "mocked tool output"})
default_retrieval_response: str = "This is mocked retrieval content"
default_http_response: dict[str, Any] = field(
default_factory=lambda: {"status_code": 200, "body": "mocked response", "headers": dict[str, str]()}
)
default_template_transform_response: str = "This is mocked template transform output"
default_code_response: dict[str, Any] = field(default_factory=lambda: {"result": "mocked code execution result"})
def get_node_config(self, node_id: str) -> NodeMockConfig | None:
"""Get configuration for a specific node."""
return self.node_configs.get(node_id)
def set_node_config(self, node_id: str, config: NodeMockConfig) -> None:
"""Set configuration for a specific node."""
self.node_configs[node_id] = config
def set_node_outputs(self, node_id: str, outputs: dict[str, Any]) -> None:
"""Set expected outputs for a specific node."""
if node_id not in self.node_configs:
self.node_configs[node_id] = NodeMockConfig(node_id=node_id)
self.node_configs[node_id].outputs = outputs
def set_node_error(self, node_id: str, error: str) -> None:
"""Set an error for a specific node to simulate failure."""
if node_id not in self.node_configs:
self.node_configs[node_id] = NodeMockConfig(node_id=node_id)
self.node_configs[node_id].error = error
def get_default_config(self, node_type: NodeType) -> dict[str, Any]:
"""Get default configuration for a node type."""
return self.default_configs.get(node_type, {})
def set_default_config(self, node_type: NodeType, config: dict[str, Any]) -> None:
"""Set default configuration for a node type."""
self.default_configs[node_type] = config
class MockConfigBuilder:
"""
Builder for creating MockConfig instances with a fluent interface.
Example:
config = (MockConfigBuilder()
.with_llm_response("Custom LLM response")
.with_node_output("node_123", {"text": "specific output"})
.with_node_error("node_456", "Simulated error")
.build())
"""
def __init__(self) -> None:
self._config = MockConfig()
def with_auto_mock(self, enabled: bool = True) -> MockConfigBuilder:
"""Enable or disable auto-mocking."""
self._config.enable_auto_mock = enabled
return self
def with_delays(self, enabled: bool = True) -> MockConfigBuilder:
"""Enable or disable simulated execution delays."""
self._config.simulate_delays = enabled
return self
def with_llm_response(self, response: str) -> MockConfigBuilder:
"""Set default LLM response."""
self._config.default_llm_response = response
return self
def with_agent_response(self, response: str) -> MockConfigBuilder:
"""Set default agent response."""
self._config.default_agent_response = response
return self
def with_tool_response(self, response: dict[str, Any]) -> MockConfigBuilder:
"""Set default tool response."""
self._config.default_tool_response = response
return self
def with_retrieval_response(self, response: str) -> MockConfigBuilder:
"""Set default retrieval response."""
self._config.default_retrieval_response = response
return self
def with_http_response(self, response: dict[str, Any]) -> MockConfigBuilder:
"""Set default HTTP response."""
self._config.default_http_response = response
return self
def with_template_transform_response(self, response: str) -> MockConfigBuilder:
"""Set default template transform response."""
self._config.default_template_transform_response = response
return self
def with_code_response(self, response: dict[str, Any]) -> MockConfigBuilder:
"""Set default code execution response."""
self._config.default_code_response = response
return self
def with_node_output(self, node_id: str, outputs: dict[str, Any]) -> MockConfigBuilder:
"""Set outputs for a specific node."""
self._config.set_node_outputs(node_id, outputs)
return self
def with_node_error(self, node_id: str, error: str) -> MockConfigBuilder:
"""Set error for a specific node."""
self._config.set_node_error(node_id, error)
return self
def with_node_config(self, config: NodeMockConfig) -> MockConfigBuilder:
"""Add a node-specific configuration."""
self._config.set_node_config(config.node_id, config)
return self
def with_default_config(self, node_type: NodeType, config: dict[str, Any]) -> MockConfigBuilder:
"""Set default configuration for a node type."""
self._config.set_default_config(node_type, config)
return self
def build(self) -> MockConfig:
"""Build and return the MockConfig instance."""
return self._config
@@ -0,0 +1,194 @@
"""Mock node factory for third-party-service workflow tests.
The factory follows the same config adaptation path as production
`DifyNodeFactory.create_node()`, but swaps selected node classes for mock
implementations before instantiation.
"""
from typing import TYPE_CHECKING, Any, override
from core.workflow.human_input_adapter import adapt_node_config_for_graph
from core.workflow.node_factory import DifyNodeFactory
from graphon.entities.base_node_data import BaseNodeData
from graphon.entities.graph_config import NodeConfigDict, NodeConfigDictAdapter
from graphon.enums import BuiltinNodeTypes, NodeType
from graphon.nodes.base.node import Node
from tests.helpers.workflow.mock_nodes import (
MockAgentNode,
MockCodeNode,
MockDocumentExtractorNode,
MockHttpRequestNode,
MockIterationNode,
MockKnowledgeRetrievalNode,
MockLLMNode,
MockLoopNode,
MockParameterExtractorNode,
MockQuestionClassifierNode,
MockTemplateTransformNode,
MockToolNode,
)
if TYPE_CHECKING:
from graphon.runtime import InitParams, RuntimeState
from tests.helpers.workflow.mock_config import MockConfig
class MockNodeFactory(DifyNodeFactory):
"""
A factory that creates mock nodes for testing purposes.
This factory intercepts node creation and returns mock implementations
for nodes that require third-party services, allowing tests to run
without external dependencies.
"""
def __init__(
self,
init_params: "InitParams",
runtime_state: "RuntimeState",
mock_config: "MockConfig | None" = None,
) -> None:
"""
Initialize the mock node factory.
:param init_params: Graph initialization parameters
:param runtime_state: Graph runtime state
:param mock_config: Optional mock configuration for customizing mock behavior
"""
super().__init__(init_params, runtime_state)
self.mock_config = mock_config
# Map of node types that should be mocked
self._mock_node_types = {
BuiltinNodeTypes.LLM: MockLLMNode,
BuiltinNodeTypes.AGENT: MockAgentNode,
BuiltinNodeTypes.TOOL: MockToolNode,
BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL: MockKnowledgeRetrievalNode,
BuiltinNodeTypes.HTTP_REQUEST: MockHttpRequestNode,
BuiltinNodeTypes.QUESTION_CLASSIFIER: MockQuestionClassifierNode,
BuiltinNodeTypes.PARAMETER_EXTRACTOR: MockParameterExtractorNode,
BuiltinNodeTypes.DOCUMENT_EXTRACTOR: MockDocumentExtractorNode,
BuiltinNodeTypes.ITERATION: MockIterationNode,
BuiltinNodeTypes.LOOP: MockLoopNode,
BuiltinNodeTypes.TEMPLATE_TRANSFORM: MockTemplateTransformNode,
BuiltinNodeTypes.CODE: MockCodeNode,
}
@override
def with_runtime_state(self, runtime_state: "RuntimeState") -> "MockNodeFactory":
return MockNodeFactory(
init_params=self.init_params,
runtime_state=runtime_state,
mock_config=self.mock_config,
)
@override
def _resolve_node_class_for_factory(
self,
*,
node_type: NodeType,
node_version: str,
node_data: BaseNodeData,
) -> type[Node]:
mock_class = self._mock_node_types.get(node_type)
if mock_class is not None:
return mock_class
return super()._resolve_node_class_for_factory(
node_type=node_type,
node_version=node_version,
node_data=node_data,
)
def create_node(self, node_config: dict[str, Any] | NodeConfigDict) -> Node:
"""
Create a node instance, using mock implementations for third-party service nodes.
:param node_config: Node configuration dictionary
:return: Node instance (real or mocked)
"""
typed_node_config = NodeConfigDictAdapter.validate_python(adapt_node_config_for_graph(node_config))
node_id = typed_node_config["id"]
node_data = typed_node_config["data"]
node_type = node_data.type
# Check if this node type should be mocked
if node_type in self._mock_node_types:
# Create mock node instance
mock_class = self._mock_node_types[node_type]
resolved_node_data = self._validate_resolved_node_data(mock_class, node_data)
if node_type == BuiltinNodeTypes.CODE:
mock_instance = mock_class(
node_id=node_id,
data=resolved_node_data,
init_params=self.init_params,
runtime_state=self.runtime_state,
mock_config=self.mock_config,
code_executor=self._code_executor,
code_limits=self._code_limits,
)
elif node_type == BuiltinNodeTypes.HTTP_REQUEST:
mock_instance = mock_class(
node_id=node_id,
data=resolved_node_data,
init_params=self.init_params,
runtime_state=self.runtime_state,
mock_config=self.mock_config,
http_request_config=self._http_request_config,
http_client=self._http_request_http_client,
tool_file_manager_factory=self._bound_tool_file_manager_factory,
file_manager=self._http_request_file_manager,
)
elif node_type in {
BuiltinNodeTypes.LLM,
BuiltinNodeTypes.QUESTION_CLASSIFIER,
BuiltinNodeTypes.PARAMETER_EXTRACTOR,
}:
mock_instance = mock_class(
node_id=node_id,
data=resolved_node_data,
init_params=self.init_params,
runtime_state=self.runtime_state,
mock_config=self.mock_config,
credentials_provider=self._llm_credentials_provider,
model_factory=self._llm_model_factory,
)
else:
mock_instance = mock_class(
node_id=node_id,
data=resolved_node_data,
init_params=self.init_params,
runtime_state=self.runtime_state,
mock_config=self.mock_config,
)
return mock_instance
# For non-mocked node types, use parent implementation
return super().create_node(node_config)
def should_mock_node(self, node_type: NodeType) -> bool:
"""
Check if a node type should be mocked.
:param node_type: The node type to check
:return: True if the node should be mocked, False otherwise
"""
return node_type in self._mock_node_types
def register_mock_node_type(self, node_type: NodeType, mock_class: type[Node]) -> None:
"""
Register a custom mock implementation for a node type.
:param node_type: The node type to mock
:param mock_class: The mock class to use for this node type
"""
self._mock_node_types[node_type] = mock_class
def unregister_mock_node_type(self, node_type: NodeType) -> None:
"""
Remove a mock implementation for a node type.
:param node_type: The node type to stop mocking
"""
if node_type in self._mock_node_types:
del self._mock_node_types[node_type]
@@ -0,0 +1,773 @@
"""
Mock node implementations for testing.
This module provides mock implementations of nodes that require third-party services,
allowing tests to run without external dependencies.
"""
import time
from collections.abc import Generator, Mapping
from typing import TYPE_CHECKING, Any, Optional
from unittest.mock import MagicMock
from core.app.llm.model_access import DifyCredentialsProvider, DifyModelFactory
from core.helper.ssrf_proxy import graphon_ssrf_proxy
from core.workflow.node_runtime import (
DifyFileReferenceFactory,
DifyPreparedLLM,
DifyPromptMessageSerializer,
DifyToolFileManager,
DifyToolNodeRuntime,
build_dify_llm_file_saver,
resolve_dify_run_context,
)
from core.workflow.nodes.agent import AgentNode
from core.workflow.nodes.knowledge_retrieval.knowledge_retrieval_node import KnowledgeRetrievalNode
from graphon.enums import WorkflowNodeExecutionMetadataKey, WorkflowNodeExecutionStatus
from graphon.model_runtime.entities.llm_entities import LLMUsage
from graphon.node_events import NodeRunResult, StreamChunkEvent, StreamCompletedEvent
from graphon.nodes.code import CodeNode
from graphon.nodes.document_extractor import DocumentExtractorNode
from graphon.nodes.http_request import HttpRequestNode
from graphon.nodes.iteration import IterationNode
from graphon.nodes.llm import LLMNode
from graphon.nodes.loop import LoopNode
from graphon.nodes.parameter_extractor import ParameterExtractorNode
from graphon.nodes.question_classifier import QuestionClassifierNode
from graphon.nodes.template_transform import TemplateTransformNode
from graphon.nodes.tool import ToolNode
from graphon.template_rendering import Jinja2TemplateRenderer, TemplateRenderError
from tests.helpers.unit.core.model_fixtures import make_model_instance
if TYPE_CHECKING:
from graphon.runtime import InitParams, RuntimeState
from tests.helpers.workflow.mock_config import MockConfig
class _TestJinja2Renderer(Jinja2TemplateRenderer):
"""Simple Jinja2 renderer for tests (avoids code executor)."""
def render_template(self, template: str, variables: Mapping[str, Any]) -> str:
from jinja2 import Template as _Jinja2Template
try:
return _Jinja2Template(template).render(**variables)
except Exception as exc: # pragma: no cover - pass through as contract error
raise TemplateRenderError(str(exc)) from exc
class MockNodeMixin:
"""Mixin providing common mock functionality."""
def __init__(
self,
node_id: str,
data: Any,
*,
init_params: "InitParams",
runtime_state: "RuntimeState",
mock_config: Optional["MockConfig"] = None,
**kwargs: Any,
) -> None:
run_context = resolve_dify_run_context(init_params.run_context)
if isinstance(self, (LLMNode, QuestionClassifierNode, ParameterExtractorNode)):
kwargs.setdefault("credentials_provider", DifyCredentialsProvider(run_context=run_context))
kwargs.setdefault("model_factory", DifyModelFactory(run_context=run_context))
kwargs.setdefault(
"model_instance", DifyPreparedLLM(make_model_instance(provider="openai", model="gpt-3.5-turbo"))
)
kwargs.setdefault("prompt_message_serializer", DifyPromptMessageSerializer())
# These nodes override _run; their real runtime dependencies remain unused.
kwargs.setdefault("http_client", graphon_ssrf_proxy)
if isinstance(self, (LLMNode, QuestionClassifierNode)):
kwargs.setdefault(
"llm_file_saver", build_dify_llm_file_saver(run_context=run_context, http_client=graphon_ssrf_proxy)
)
if isinstance(self, HttpRequestNode):
kwargs.setdefault("file_reference_factory", DifyFileReferenceFactory(run_context))
# Ensure TemplateTransformNode receives a renderer now required by constructor
if isinstance(self, TemplateTransformNode):
kwargs.setdefault("jinja2_template_renderer", _TestJinja2Renderer())
# Provide default tool_file_manager for ToolNode subclasses
from graphon.nodes.tool import ToolNode as _ToolNode # local import to avoid cycles
if isinstance(self, _ToolNode):
kwargs.setdefault("tool_file_manager", DifyToolFileManager(run_context))
kwargs.setdefault("runtime", DifyToolNodeRuntime(init_params.run_context))
if isinstance(self, AgentNode):
presentation_provider = MagicMock()
presentation_provider.get_icon.return_value = None
kwargs.setdefault("strategy_resolver", MagicMock())
kwargs.setdefault("presentation_provider", presentation_provider)
kwargs.setdefault("runtime_support", MagicMock())
kwargs.setdefault("message_transformer", MagicMock())
super().__init__(
node_id=node_id,
data=data,
init_params=init_params,
runtime_state=runtime_state,
**kwargs,
)
self.mock_config = mock_config
def _get_mock_outputs(self, default_outputs: dict[str, Any]) -> dict[str, Any]:
"""Get mock outputs for this node."""
if not self.mock_config:
return default_outputs
# Check for node-specific configuration
node_config = self.mock_config.get_node_config(self._node_id)
if node_config and node_config.outputs:
return node_config.outputs
# Check for custom handler
if node_config and node_config.custom_handler:
return node_config.custom_handler(self)
return default_outputs
def _should_simulate_error(self) -> str | None:
"""Check if this node should simulate an error."""
if not self.mock_config:
return None
node_config = self.mock_config.get_node_config(self._node_id)
if node_config:
return node_config.error
return None
def _simulate_delay(self) -> None:
"""Simulate execution delay if configured."""
if not self.mock_config or not self.mock_config.simulate_delays:
return
node_config = self.mock_config.get_node_config(self._node_id)
if node_config and node_config.delay > 0:
time.sleep(node_config.delay)
class MockLLMNode(MockNodeMixin, LLMNode):
"""Mock implementation of LLMNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> Generator:
"""Execute mock LLM node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
process_data={},
error_type="MockError",
)
)
return
# Get mock response
default_response = self.mock_config.default_llm_response if self.mock_config else "Mocked LLM response"
outputs = self._get_mock_outputs(
{
"text": default_response,
"usage": {
"prompt_tokens": 10,
"completion_tokens": 5,
"total_tokens": 15,
},
"finish_reason": "stop",
}
)
# Simulate streaming if text output exists
if "text" in outputs:
text = str(outputs["text"])
# Split text into words and stream with spaces between them
# To match test expectation of text.count(" ") + 2 chunks
words = text.split(" ")
for i, word in enumerate(words):
# Add space before word (except for first word) to reconstruct text properly
chunk = " " + word if i > 0 else word
yield StreamChunkEvent(
selector=[self._node_id, "text"],
chunk=chunk,
is_final=False,
)
# Send final chunk
yield StreamChunkEvent(
selector=[self._node_id, "text"],
chunk="",
is_final=True,
)
# Create mock usage with all required fields
usage = LLMUsage.empty_usage()
usage.prompt_tokens = outputs.get("usage", {}).get("prompt_tokens", 10)
usage.completion_tokens = outputs.get("usage", {}).get("completion_tokens", 5)
usage.total_tokens = outputs.get("usage", {}).get("total_tokens", 15)
# Send completion event
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs={"mock": "inputs"},
process_data={
"model_mode": "chat",
"prompts": [],
"usage": outputs.get("usage", {}),
"finish_reason": outputs.get("finish_reason", "stop"),
"model_provider": "mock_provider",
"model_name": "mock_model",
},
outputs=outputs,
metadata={
WorkflowNodeExecutionMetadataKey.TOTAL_TOKENS: usage.total_tokens,
WorkflowNodeExecutionMetadataKey.TOTAL_PRICE: 0.0,
WorkflowNodeExecutionMetadataKey.CURRENCY: "USD",
},
llm_usage=usage,
)
)
class MockAgentNode(MockNodeMixin, AgentNode):
"""Mock implementation of AgentNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> Generator:
"""Execute mock agent node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
process_data={},
error_type="MockError",
)
)
return
# Get mock response
default_response = self.mock_config.default_agent_response if self.mock_config else "Mocked agent response"
outputs = self._get_mock_outputs(
{
"output": default_response,
"files": [],
}
)
# Send completion event
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs={"mock": "inputs"},
process_data={
"agent_log": "Mock agent executed successfully",
},
outputs=outputs,
metadata={
WorkflowNodeExecutionMetadataKey.AGENT_LOG: "Mock agent log",
},
)
)
class MockToolNode(MockNodeMixin, ToolNode):
"""Mock implementation of ToolNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> Generator:
"""Execute mock tool node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
process_data={},
error_type="MockError",
)
)
return
# Get mock response
default_response = (
self.mock_config.default_tool_response if self.mock_config else {"result": "mocked tool output"}
)
outputs = self._get_mock_outputs(default_response)
# Send completion event
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs={"mock": "inputs"},
process_data={
"tool_name": "mock_tool",
"tool_parameters": {},
},
outputs=outputs,
metadata={
WorkflowNodeExecutionMetadataKey.TOOL_INFO: {
"tool_name": "mock_tool",
"tool_label": "Mock Tool",
},
},
)
)
class MockKnowledgeRetrievalNode(MockNodeMixin, KnowledgeRetrievalNode):
"""Mock implementation of KnowledgeRetrievalNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> Generator:
"""Execute mock knowledge retrieval node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
process_data={},
error_type="MockError",
)
)
return
# Get mock response
default_response = (
self.mock_config.default_retrieval_response if self.mock_config else "Mocked retrieval content"
)
outputs = self._get_mock_outputs(
{
"result": [
{
"content": default_response,
"score": 0.95,
"metadata": {"source": "mock_source"},
}
],
}
)
# Send completion event
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs={"query": "mock query"},
process_data={
"retrieval_method": "mock",
"documents_count": 1,
},
outputs=outputs,
)
)
class MockHttpRequestNode(MockNodeMixin, HttpRequestNode):
"""Mock implementation of HttpRequestNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> Generator:
"""Execute mock HTTP request node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
process_data={},
error_type="MockError",
)
)
return
# Get mock response
default_response = (
self.mock_config.default_http_response
if self.mock_config
else {
"status_code": 200,
"body": "mocked response",
"headers": {},
}
)
outputs = self._get_mock_outputs(default_response)
# Send completion event
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs={"url": "http://mock.url", "method": "GET"},
process_data={
"request_url": "http://mock.url",
"request_method": "GET",
},
outputs=outputs,
)
)
class MockQuestionClassifierNode(MockNodeMixin, QuestionClassifierNode):
"""Mock implementation of QuestionClassifierNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> Generator:
"""Execute mock question classifier node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
process_data={},
error_type="MockError",
)
)
return
# Get mock response - default to first class
outputs = self._get_mock_outputs(
{
"class_name": "class_1",
}
)
# Send completion event
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs={"query": "mock query"},
process_data={
"classification": outputs.get("class_name", "class_1"),
},
outputs=outputs,
edge_source_handle=outputs.get("class_name", "class_1"), # Branch based on classification
)
)
class MockParameterExtractorNode(MockNodeMixin, ParameterExtractorNode):
"""Mock implementation of ParameterExtractorNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> Generator:
"""Execute mock parameter extractor node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
process_data={},
error_type="MockError",
)
)
return
# Get mock response
outputs = self._get_mock_outputs(
{
"parameters": {
"param1": "value1",
"param2": "value2",
},
}
)
# Send completion event
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs={"text": "mock text"},
process_data={
"extracted_parameters": outputs.get("parameters", {}),
},
outputs=outputs,
)
)
class MockDocumentExtractorNode(MockNodeMixin, DocumentExtractorNode):
"""Mock implementation of DocumentExtractorNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> Generator:
"""Execute mock document extractor node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
process_data={},
error_type="MockError",
)
)
return
# Get mock response
outputs = self._get_mock_outputs(
{
"text": "Mocked extracted document content",
"metadata": {
"pages": 1,
"format": "mock",
},
}
)
# Send completion event
yield StreamCompletedEvent(
node_run_result=NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs={"file": "mock_file.pdf"},
process_data={
"extraction_method": "mock",
},
outputs=outputs,
)
)
class MockIterationNode(MockNodeMixin, IterationNode):
"""Mock implementation of IterationNode that preserves mock configuration."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
class MockLoopNode(MockNodeMixin, LoopNode):
"""Mock implementation of LoopNode that preserves mock configuration."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
class MockTemplateTransformNode(MockNodeMixin, TemplateTransformNode):
"""Mock implementation of TemplateTransformNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> NodeRunResult:
"""Execute mock template transform node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
return NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
error_type="MockError",
)
# Get variables from the node data
variables: dict[str, Any] = {}
if hasattr(self._node_data, "variables"):
for variable_selector in self._node_data.variables:
variable_name = variable_selector.variable
value = self.runtime_state.variable_pool.get(variable_selector.value_selector)
variables[variable_name] = value.to_object() if value else None
# Check if we have custom mock outputs configured
if self.mock_config:
node_config = self.mock_config.get_node_config(self._node_id)
if node_config and node_config.outputs:
return NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs=variables,
outputs=node_config.outputs,
)
# Try to actually process the template using Jinja2 directly
try:
if hasattr(self._node_data, "template"):
# Import jinja2 here to avoid dependency issues
from jinja2 import Template
template = Template(self._node_data.template)
result_text = template.render(**variables)
return NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED, inputs=variables, outputs={"output": result_text}
)
except Exception:
# If direct Jinja2 fails, try CodeExecutor as fallback
try:
from core.helper.code_executor.code_executor import CodeExecutor, CodeLanguage
if hasattr(self._node_data, "template"):
result = CodeExecutor.execute_workflow_code_template(
language=CodeLanguage.JINJA2, code=self._node_data.template, inputs=variables
)
return NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs=variables,
outputs={"output": result["result"]},
)
except Exception:
# Both methods failed, fall back to default mock output
pass
# Fall back to default mock output
default_response = (
self.mock_config.default_template_transform_response if self.mock_config else "mocked template output"
)
default_outputs = {"output": default_response}
outputs = self._get_mock_outputs(default_outputs)
# Return result
return NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs=variables,
outputs=outputs,
)
class MockCodeNode(MockNodeMixin, CodeNode):
"""Mock implementation of CodeNode for testing."""
@classmethod
def version(cls) -> str:
"""Return the version of this mock node."""
return "1"
def _run(self) -> NodeRunResult:
"""Execute mock code node."""
# Simulate delay if configured
self._simulate_delay()
# Check for simulated error
error = self._should_simulate_error()
if error:
return NodeRunResult(
status=WorkflowNodeExecutionStatus.FAILED,
error=error,
inputs={},
error_type="MockError",
)
# Get mock outputs - use configured outputs or default based on output schema
default_outputs = {}
if hasattr(self._node_data, "outputs") and self._node_data.outputs:
# Generate default outputs based on schema
for output_name, output_config in self._node_data.outputs.items():
if output_config.type == "string":
default_outputs[output_name] = f"mocked_{output_name}"
elif output_config.type == "number":
default_outputs[output_name] = 42
elif output_config.type == "object":
default_outputs[output_name] = {"key": "value"}
elif output_config.type == "array[string]":
default_outputs[output_name] = ["item1", "item2"]
elif output_config.type == "array[number]":
default_outputs[output_name] = [1, 2, 3]
elif output_config.type == "array[object]":
default_outputs[output_name] = [{"key": "value1"}, {"key": "value2"}]
else:
# Default output when no schema is defined
default_outputs = (
self.mock_config.default_code_response
if self.mock_config
else {"result": "mocked code execution result"}
)
outputs = self._get_mock_outputs(default_outputs)
# Return result
return NodeRunResult(
status=WorkflowNodeExecutionStatus.SUCCEEDED,
inputs={},
outputs=outputs,
)
@@ -0,0 +1,661 @@
"""
Table-driven test framework for Engine workflows.
This module provides a robust table-driven testing framework with support for:
- Parallel test execution
- Property-based testing with Hypothesis
- Event sequence validation
- Mock configuration
- Performance metrics
- Detailed error reporting
"""
import logging
import time
from collections.abc import Callable, Sequence
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from functools import lru_cache
from pathlib import Path
from typing import Any
from core.app.entities.app_invoke_entities import DIFY_RUN_CONTEXT_KEY, InvokeFrom, UserFrom
from core.tools.utils.yaml_utils import _load_yaml_file
from core.workflow.node_factory import DifyNodeFactory, get_default_root_node_id
from core.workflow.system_variables import build_bootstrap_variables, build_system_variables
from core.workflow.variable_pool_initializer import add_node_inputs_to_pool, add_variables_to_pool
from core.workflow.workflow_entry import iter_dify_graph_engine_events
from graphon.engine import Engine
from graphon.engine.command import InMemoryChannel
from graphon.engine_events import (
EngineEvent,
GraphRunStartedEvent,
GraphRunSucceededEvent,
)
from graphon.graph import Graph
from graphon.runtime import InitParams, RuntimeState, VariablePool
from graphon.variables import (
ArrayNumberVariable,
ArrayObjectVariable,
ArrayStringVariable,
FloatVariable,
IntegerVariable,
ObjectVariable,
StringVariable,
)
from tests.helpers.workflow.mock_config import MockConfig
from tests.helpers.workflow.mock_factory import MockNodeFactory
logger = logging.getLogger(__name__)
@dataclass
class WorkflowTestCase:
"""Represents a single test case for table-driven testing."""
fixture_path: str = ""
expected_outputs: dict[str, Any] = field(default_factory=dict)
inputs: dict[str, Any] = field(default_factory=dict)
query: str = ""
description: str = ""
timeout: float = 30.0
mock_config: MockConfig | None = None
use_auto_mock: bool = False
expected_event_sequence: Sequence[type[EngineEvent]] | None = None
graph_factory: Callable[[], tuple[Graph, RuntimeState]] | None = None
@dataclass
class WorkflowTestResult:
"""Result of executing a single test case."""
test_case: WorkflowTestCase
success: bool
error: Exception | None = None
actual_outputs: dict[str, Any] | None = None
execution_time: float = 0.0
event_sequence_match: bool | None = None
event_mismatch_details: str | None = None
events: list[EngineEvent] = field(default_factory=list)
graph: Graph | None = None
graph_runtime_state: RuntimeState | None = None
validation_details: str | None = None
@dataclass
class TestSuiteResult:
"""Aggregated results for a test suite."""
total_tests: int
passed_tests: int
failed_tests: int
total_execution_time: float
results: list[WorkflowTestResult]
@property
def success_rate(self) -> float:
"""Calculate the success rate of the test suite."""
if self.total_tests == 0:
return 0.0
return (self.passed_tests / self.total_tests) * 100
def get_failed_results(self) -> list[WorkflowTestResult]:
"""Get all failed test results."""
return [r for r in self.results if not r.success]
class WorkflowRunner:
"""Core workflow execution engine for tests."""
def __init__(self, fixtures_dir: Path | None = None):
"""Initialize the workflow runner."""
if fixtures_dir is None:
# Use the new central fixtures location
# Navigate from current file to api/tests directory
current_file = Path(__file__).resolve()
# Find the 'api' directory by traversing up
for parent in current_file.parents:
if parent.name == "api" and (parent / "tests").exists():
fixtures_dir = parent / "tests" / "fixtures" / "workflow"
break
else:
# Fallback if structure is not as expected
raise ValueError("Could not locate api/tests/fixtures/workflow directory")
self.fixtures_dir = Path(fixtures_dir)
if not self.fixtures_dir.exists():
raise ValueError(f"Fixtures directory does not exist: {self.fixtures_dir}")
def load_fixture(self, fixture_name: str) -> dict[str, Any]:
"""Load a YAML fixture file with caching to avoid repeated parsing."""
if not fixture_name.endswith(".yml") and not fixture_name.endswith(".yaml"):
fixture_name = f"{fixture_name}.yml"
fixture_path = self.fixtures_dir / fixture_name
return _load_fixture(fixture_path, fixture_name)
def create_graph_from_fixture(
self,
fixture_data: dict[str, Any],
query: str = "",
inputs: dict[str, Any] | None = None,
use_mock_factory: bool = False,
mock_config: MockConfig | None = None,
) -> tuple[Graph, RuntimeState]:
"""Create a Graph instance from fixture data."""
workflow_config = fixture_data.get("workflow", {})
graph_config = workflow_config.get("graph", {})
if not graph_config:
raise ValueError("Fixture missing workflow.graph configuration")
graph_init_params = InitParams(
workflow_id="test_workflow",
graph_config=graph_config,
run_context={
DIFY_RUN_CONTEXT_KEY: {
"tenant_id": "test_tenant",
"app_id": "test_app",
"user_id": "test_user",
"user_from": UserFrom.ACCOUNT,
"invoke_from": InvokeFrom.DEBUGGER, # Set to debugger to avoid conversation_id requirement
}
},
call_depth=0,
)
system_variables = build_system_variables(
user_id="test_user",
app_id="test_app",
workflow_id=graph_init_params.workflow_id,
files=[],
query=query,
)
root_node_inputs = dict(inputs or {})
root_node_inputs.setdefault("query", query)
# Extract conversation variables from workflow config
conversation_variables = []
conversation_var_configs = workflow_config.get("conversation_variables", [])
# Mapping from value_type to Variable class
variable_type_mapping = {
"string": StringVariable,
"number": FloatVariable,
"integer": IntegerVariable,
"object": ObjectVariable,
"array[string]": ArrayStringVariable,
"array[number]": ArrayNumberVariable,
"array[object]": ArrayObjectVariable,
}
for var_config in conversation_var_configs:
value_type = var_config.get("value_type", "string")
variable_class = variable_type_mapping.get(value_type, StringVariable)
# Create the appropriate Variable type based on value_type
var = variable_class(
selector=tuple(var_config.get("selector", [])),
name=var_config.get("name", ""),
value=var_config.get("value", ""),
)
conversation_variables.append(var)
root_node_id = get_default_root_node_id(graph_config)
variable_pool = VariablePool()
add_variables_to_pool(
variable_pool,
build_bootstrap_variables(
system_variables=system_variables,
conversation_variables=conversation_variables,
),
)
add_node_inputs_to_pool(variable_pool, node_id=root_node_id, inputs=root_node_inputs)
graph_runtime_state = RuntimeState(
workflow_id="test-workflow", variable_pool=variable_pool, start_at=time.perf_counter()
)
if use_mock_factory:
node_factory = MockNodeFactory(
init_params=graph_init_params, runtime_state=graph_runtime_state, mock_config=mock_config
)
else:
node_factory = DifyNodeFactory(init_params=graph_init_params, runtime_state=graph_runtime_state)
graph = Graph.init(
graph_config=graph_config,
node_factory=node_factory,
root_node_id=root_node_id,
)
return graph, graph_runtime_state
class TableTestRunner:
"""
Advanced table-driven test runner for workflow testing.
Features:
- Parallel test execution
- Retry mechanism for flaky tests
- Custom validators
- Performance profiling
- Detailed error reporting
- Tag-based filtering
"""
def __init__(
self,
fixtures_dir: Path | None = None,
max_workers: int = 4,
enable_logging: bool = False,
log_level: str = "INFO",
graph_engine_max_workers: int = 1,
):
"""
Initialize the table test runner.
Args:
fixtures_dir: Directory containing fixture files
max_workers: Maximum number of parallel workers for test execution
enable_logging: Enable detailed logging
log_level: Logging level (DEBUG, INFO, WARNING, ERROR)
graph_engine_max_workers: Maximum workers for Engine (default: 1)
"""
self.workflow_runner = WorkflowRunner(fixtures_dir)
self.max_workers = max_workers
self.graph_engine_max_workers = graph_engine_max_workers
if enable_logging:
logging.basicConfig(
level=getattr(logging, log_level), format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
self.logger = logger
def run_test_case(self, test_case: WorkflowTestCase) -> WorkflowTestResult:
"""
Execute a single test case with retry support.
Args:
test_case: The test case to execute
Returns:
WorkflowTestResult with execution details
"""
start_time = time.perf_counter()
try:
result = self._execute_test_case(test_case)
if result.success:
self.logger.info("Test passed: %s", test_case.description)
else:
self.logger.error("Test failed: %s", test_case.description)
return result
except Exception as exc:
self.logger.exception("Error executing test case: %s", test_case.description)
return WorkflowTestResult(
test_case=test_case,
success=False,
error=exc,
execution_time=time.perf_counter() - start_time,
)
def _execute_test_case(self, test_case: WorkflowTestCase) -> WorkflowTestResult:
"""Internal method to execute a single test case."""
start_time = time.perf_counter()
try:
graph, graph_runtime_state = self._create_graph_runtime_state(test_case)
# Create and run the engine with configured worker settings
engine = Engine(
graph=graph,
runtime_state=graph_runtime_state,
command_channel=InMemoryChannel(),
workers=self.graph_engine_max_workers,
)
# Execute and collect events
events: list[EngineEvent] = []
for event in iter_dify_graph_engine_events(engine):
events.append(event)
# Check execution success
has_start = any(isinstance(e, GraphRunStartedEvent) for e in events)
success_events = [e for e in events if isinstance(e, GraphRunSucceededEvent)]
has_success = len(success_events) > 0
# Validate event sequence if provided (even for failed workflows)
event_sequence_match = None
event_mismatch_details = None
if test_case.expected_event_sequence is not None:
event_sequence_match, event_mismatch_details = self._validate_event_sequence(
test_case.expected_event_sequence, events
)
if not (has_start and has_success):
# Workflow didn't complete, but we may still want to validate events
success = False
if test_case.expected_event_sequence is not None:
# If event sequence was provided, use that for success determination
success = event_sequence_match if event_sequence_match is not None else False
return WorkflowTestResult(
test_case=test_case,
success=success,
error=Exception("Workflow did not complete successfully"),
execution_time=time.perf_counter() - start_time,
events=events,
event_sequence_match=event_sequence_match,
event_mismatch_details=event_mismatch_details,
graph=graph,
graph_runtime_state=graph_runtime_state,
)
# Get actual outputs
success_event = success_events[-1]
actual_outputs = success_event.outputs or {}
# Validate outputs
output_success, validation_details = self._validate_outputs(test_case.expected_outputs, actual_outputs)
# Overall success requires both output and event sequence validation
success = output_success and (event_sequence_match if event_sequence_match is not None else True)
return WorkflowTestResult(
test_case=test_case,
success=success,
actual_outputs=actual_outputs,
execution_time=time.perf_counter() - start_time,
event_sequence_match=event_sequence_match,
event_mismatch_details=event_mismatch_details,
events=events,
validation_details=validation_details,
error=None if success else Exception(validation_details or event_mismatch_details or "Test failed"),
graph=graph,
graph_runtime_state=graph_runtime_state,
)
except Exception as e:
self.logger.exception("Error executing test case: %s", test_case.description)
return WorkflowTestResult(
test_case=test_case,
success=False,
error=e,
execution_time=time.perf_counter() - start_time,
graph=graph if "graph" in locals() else None,
graph_runtime_state=graph_runtime_state if "graph_runtime_state" in locals() else None,
)
def _create_graph_runtime_state(self, test_case: WorkflowTestCase) -> tuple[Graph, RuntimeState]:
"""Create or retrieve graph/runtime state according to test configuration."""
if test_case.graph_factory is not None:
return test_case.graph_factory()
if not test_case.fixture_path:
raise ValueError("fixture_path must be provided when graph_factory is not specified")
fixture_data = self.workflow_runner.load_fixture(test_case.fixture_path)
return self.workflow_runner.create_graph_from_fixture(
fixture_data=fixture_data,
inputs=test_case.inputs,
query=test_case.query,
use_mock_factory=test_case.use_auto_mock,
mock_config=test_case.mock_config,
)
def _validate_outputs(
self,
expected_outputs: dict[str, Any],
actual_outputs: dict[str, Any],
) -> tuple[bool, str | None]:
"""
Validate actual outputs against expected outputs.
Returns:
tuple: (is_valid, validation_details)
"""
validation_errors = []
# Check expected outputs
for key, expected_value in expected_outputs.items():
if key not in actual_outputs:
validation_errors.append(f"Missing expected key: {key}")
continue
actual_value = actual_outputs[key]
if actual_value != expected_value:
# Format multiline strings for better readability
if isinstance(expected_value, str) and "\n" in expected_value:
expected_lines = expected_value.splitlines()
actual_lines = (
actual_value.splitlines() if isinstance(actual_value, str) else str(actual_value).splitlines()
)
validation_errors.append(
f"Value mismatch for key '{key}':\n"
f" Expected ({len(expected_lines)} lines):\n " + "\n ".join(expected_lines) + "\n"
f" Actual ({len(actual_lines)} lines):\n " + "\n ".join(actual_lines)
)
else:
validation_errors.append(
f"Value mismatch for key '{key}':\n Expected: {expected_value}\n Actual: {actual_value}"
)
if validation_errors:
return False, "\n".join(validation_errors)
return True, None
def _validate_event_sequence(
self, expected_sequence: list[type[EngineEvent]], actual_events: list[EngineEvent]
) -> tuple[bool, str | None]:
"""
Validate that actual events match the expected event sequence.
Returns:
tuple: (is_valid, error_message)
"""
actual_event_types = [type(event) for event in actual_events]
if len(expected_sequence) != len(actual_event_types):
return False, (
f"Event count mismatch. Expected {len(expected_sequence)} events, "
f"got {len(actual_event_types)} events.\n"
f"Expected: {[e.__name__ for e in expected_sequence]}\n"
f"Actual: {[e.__name__ for e in actual_event_types]}"
)
for i, (expected_type, actual_type) in enumerate(zip(expected_sequence, actual_event_types, strict=False)):
if expected_type != actual_type:
return False, (
f"Event mismatch at position {i}. "
f"Expected {expected_type.__name__}, got {actual_type.__name__}\n"
f"Full expected sequence: {[e.__name__ for e in expected_sequence]}\n"
f"Full actual sequence: {[e.__name__ for e in actual_event_types]}"
)
return True, None
def run_table_tests(
self,
test_cases: list[WorkflowTestCase],
parallel: bool = False,
fail_fast: bool = False,
) -> TestSuiteResult:
"""
Run multiple test cases as a table test suite.
Args:
test_cases: List of test cases to execute
parallel: Run tests in parallel
fail_fast: Stop execution on first failure
Returns:
TestSuiteResult with aggregated results
"""
if not test_cases:
return TestSuiteResult(
total_tests=0,
passed_tests=0,
failed_tests=0,
total_execution_time=0.0,
results=[],
)
start_time = time.perf_counter()
results = []
if parallel and self.max_workers > 1:
results = self._run_parallel(test_cases, fail_fast)
else:
results = self._run_sequential(test_cases, fail_fast)
# Calculate statistics
total_tests = len(results)
passed_tests = sum(1 for r in results if r.success)
failed_tests = total_tests - passed_tests
total_execution_time = time.perf_counter() - start_time
return TestSuiteResult(
total_tests=total_tests,
passed_tests=passed_tests,
failed_tests=failed_tests,
total_execution_time=total_execution_time,
results=results,
)
def _run_sequential(self, test_cases: list[WorkflowTestCase], fail_fast: bool) -> list[WorkflowTestResult]:
"""Run tests sequentially."""
results = []
for test_case in test_cases:
result = self.run_test_case(test_case)
results.append(result)
if fail_fast and not result.success:
self.logger.info("Fail-fast enabled: stopping execution")
break
return results
def _run_parallel(self, test_cases: list[WorkflowTestCase], fail_fast: bool) -> list[WorkflowTestResult]:
"""Run tests in parallel."""
results = []
flask_app: Any = None
try:
from flask import current_app
flask_app = current_app._get_current_object() # type: ignore[attr-defined]
except RuntimeError:
flask_app = None
def _run_test_case_with_context(test_case: WorkflowTestCase) -> WorkflowTestResult:
if flask_app is None:
return self.run_test_case(test_case)
with flask_app.app_context():
return self.run_test_case(test_case)
with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
future_to_test = {executor.submit(_run_test_case_with_context, tc): tc for tc in test_cases}
for future in as_completed(future_to_test):
test_case = future_to_test[future]
try:
result = future.result()
results.append(result)
if fail_fast and not result.success:
self.logger.info("Fail-fast enabled: cancelling remaining tests")
for remaining_future in future_to_test:
if not remaining_future.done():
remaining_future.cancel()
break
except Exception as e:
self.logger.exception("Error in parallel execution for test: %s", test_case.description)
results.append(
WorkflowTestResult(
test_case=test_case,
success=False,
error=e,
)
)
if fail_fast:
for remaining_future in future_to_test:
if not remaining_future.done():
remaining_future.cancel()
break
return results
def generate_report(self, suite_result: TestSuiteResult) -> str:
"""
Generate a detailed test report.
Args:
suite_result: Test suite results
Returns:
Formatted report string
"""
report = []
report.extend(
[
"=" * 80,
"TEST SUITE REPORT",
"=" * 80,
"",
# Summary
"SUMMARY:",
f" Total Tests: {suite_result.total_tests}",
f" Passed: {suite_result.passed_tests}",
f" Failed: {suite_result.failed_tests}",
f" Success Rate: {suite_result.success_rate:.1f}%",
f" Total Time: {suite_result.total_execution_time:.2f}s",
"",
]
)
# Failed tests details
failed_results = suite_result.get_failed_results()
if failed_results:
report.append("FAILED TESTS:")
for result in failed_results:
report.append(f" - {result.test_case.description}")
if result.error:
report.append(f" Error: {str(result.error)}")
if result.validation_details:
report.append(f" Validation: {result.validation_details}")
if result.event_mismatch_details:
report.append(f" Events: {result.event_mismatch_details}")
report.append("")
# Performance metrics
report.append("PERFORMANCE:")
sorted_results = sorted(suite_result.results, key=lambda r: r.execution_time, reverse=True)[:5]
report.append(" Slowest Tests:")
for result in sorted_results:
report.append(f" - {result.test_case.description}: {result.execution_time:.2f}s")
report.append("=" * 80)
return "\n".join(report)
@lru_cache(maxsize=32)
def _load_fixture(fixture_path: Path, fixture_name: str) -> dict[str, Any]:
"""Load a YAML fixture file with caching to avoid repeated parsing."""
if not fixture_path.exists():
raise FileNotFoundError(f"Fixture file not found: {fixture_path}")
return _load_yaml_file(file_path=str(fixture_path))
Whitespace-only changes.