Skip to content

armgit / dify

Public Imported from GitHub
0

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

refactor(api): enable strict typing for agent backend client tests (#43928)

Eddy ZHANG0682a1b68bc2
diff --git a/api/tests/unit_tests/clients/agent_backend/test_event_adapter.py b/api/tests/unit_tests/clients/agent_backend/test_event_adapter.py
index b4fcc34d578..b33ada2f6b3 100644
--- a/api/tests/unit_tests/clients/agent_backend/test_event_adapter.py
+++ b/api/tests/unit_tests/clients/agent_backend/test_event_adapter.py
@@ -27,7 +27,7 @@ from clients.agent_backend import (
)
-def test_event_adapter_maps_run_started():
+def test_event_adapter_maps_run_started() -> None:
adapted = AgentBackendRunEventAdapter().adapt(RunStartedEvent(id="1-0", run_id="run-1"))
assert adapted == [
@@ -38,7 +38,7 @@ def test_event_adapter_maps_run_started():
]
-def test_event_adapter_maps_pydantic_ai_stream_event():
+def test_event_adapter_maps_pydantic_ai_stream_event() -> None:
adapted = AgentBackendRunEventAdapter().adapt(
PydanticAIStreamRunEvent(
id="2-0",
@@ -52,10 +52,11 @@ def test_event_adapter_maps_pydantic_ai_stream_event():
assert isinstance(event, AgentBackendStreamInternalEvent)
assert event.type == AgentBackendInternalEventType.STREAM_EVENT
assert event.event_kind == "final_result"
+ assert isinstance(event.data, dict)
assert event.data["event_kind"] == "final_result"
-def test_event_adapter_maps_pydantic_ai_stream_event_agent_message_delta_annotation():
+def test_event_adapter_maps_pydantic_ai_stream_event_agent_message_delta_annotation() -> None:
adapted = AgentBackendRunEventAdapter().adapt(
PydanticAIStreamRunEvent(
id="2-0",
@@ -74,7 +75,7 @@ def test_event_adapter_maps_pydantic_ai_stream_event_agent_message_delta_annotat
]
-def test_event_adapter_maps_run_succeeded_to_final_output():
+def test_event_adapter_maps_run_succeeded_to_final_output() -> None:
snapshot = SessionSnapshot(layers={})
adapted = AgentBackendRunEventAdapter().adapt(
RunSucceededEvent(
@@ -126,7 +127,7 @@ def test_event_adapter_maps_run_succeeded_to_final_output():
]
-def test_event_adapter_maps_run_failed_to_failed_result():
+def test_event_adapter_maps_run_failed_to_failed_result() -> None:
adapted = AgentBackendRunEventAdapter().adapt(
RunFailedEvent(
id="4-0",
@@ -167,7 +168,7 @@ def test_event_adapter_maps_run_failed_to_failed_result():
]
-def test_event_adapter_maps_run_cancelled_to_terminal_cancelled():
+def test_event_adapter_maps_run_cancelled_to_terminal_cancelled() -> None:
adapted = AgentBackendRunEventAdapter().adapt(
RunCancelledEvent(
id="6-0",
diff --git a/api/tests/unit_tests/clients/agent_backend/test_fake_client.py b/api/tests/unit_tests/clients/agent_backend/test_fake_client.py
index 6ed717ef502..a30f0670673 100644
--- a/api/tests/unit_tests/clients/agent_backend/test_fake_client.py
+++ b/api/tests/unit_tests/clients/agent_backend/test_fake_client.py
@@ -1,4 +1,5 @@
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
+from dify_agent.protocol import CreateRunRequest
from clients.agent_backend import (
AgentBackendModelConfig,
@@ -9,7 +10,7 @@ from clients.agent_backend import (
)
-def _request():
+def _request() -> CreateRunRequest:
return AgentBackendRunRequestBuilder().build_for_workflow_node(
AgentBackendWorkflowNodeRunInput(
model=AgentBackendModelConfig(
@@ -30,7 +31,7 @@ def _request():
)
-def test_fake_client_stream_is_deterministic():
+def test_fake_client_stream_is_deterministic() -> None:
client = FakeAgentBackendRunClient()
request = _request()
@@ -45,14 +46,14 @@ def test_fake_client_stream_is_deterministic():
assert first[-1]["data"]["output"] == {"text": "hello agent"}
-def test_fake_client_stream_honors_cursor():
+def test_fake_client_stream_honors_cursor() -> None:
events = list(FakeAgentBackendRunClient().stream_events("fake-run-1", after="1-0"))
assert len(events) == 1
assert events[0].type == "run_succeeded"
-def test_fake_client_failed_scenario_returns_failed_status_and_event():
+def test_fake_client_failed_scenario_returns_failed_status_and_event() -> None:
client = FakeAgentBackendRunClient(scenario=FakeAgentBackendScenario.FAILED)
status = client.wait_run("fake-run-1")
@@ -64,14 +65,14 @@ def test_fake_client_failed_scenario_returns_failed_status_and_event():
assert events[-1].data.error == "fake failure"
-def test_fake_client_cancel_run_returns_cancelled_status():
+def test_fake_client_cancel_run_returns_cancelled_status() -> None:
cancelled = FakeAgentBackendRunClient().cancel_run("fake-run-1")
assert cancelled.run_id == "fake-run-1"
assert cancelled.status == "cancelled"
-def test_fake_client_success_wait_run_returns_succeeded_status():
+def test_fake_client_success_wait_run_returns_succeeded_status() -> None:
"""Covers the default SUCCESS branch of ``wait_run`` directly."""
status = FakeAgentBackendRunClient().wait_run("fake-run-1")
diff --git a/api/tests/unit_tests/clients/agent_backend/test_request_builder.py b/api/tests/unit_tests/clients/agent_backend/test_request_builder.py
index c1da744b4b3..4c86737cba0 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
@@ -68,7 +68,7 @@ def _run_input() -> AgentBackendWorkflowNodeRunInput:
)
-def test_request_builder_outputs_dify_agent_create_run_request():
+def test_request_builder_outputs_dify_agent_create_run_request() -> None:
request = AgentBackendRunRequestBuilder().build_for_workflow_node(_run_input())
dumped = request.model_dump(mode="json")
@@ -87,7 +87,7 @@ def test_request_builder_outputs_dify_agent_create_run_request():
assert "purpose" not in dumped
-def test_request_builder_separates_agent_soul_and_workflow_job_prompt():
+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}
@@ -99,7 +99,7 @@ def test_request_builder_separates_agent_soul_and_workflow_job_prompt():
assert dumped["composition"]["layers"][2]["config"]["user"] == "Summarize the report."
-def test_request_builder_forwards_plugin_specific_model_settings_via_extra_body():
+def test_request_builder_forwards_plugin_specific_model_settings_via_extra_body() -> None:
run_input = _run_input().model_copy(
update={
"model": AgentBackendModelConfig(
@@ -124,7 +124,7 @@ def test_request_builder_forwards_plugin_specific_model_settings_via_extra_body(
@pytest.mark.parametrize("agent_config_version_kind", ["snapshot", "draft"])
def test_agent_app_request_builder_keeps_agent_soul_prompt_for_snapshot_and_draft(
agent_config_version_kind: str,
-):
+) -> None:
original_prompt = " You are Iris. \n"
run_input = _agent_app_input().model_copy(
update={
@@ -140,7 +140,7 @@ def test_agent_app_request_builder_keeps_agent_soul_prompt_for_snapshot_and_draf
assert prompt_config.prefix == original_prompt
-def test_agent_app_request_builder_wraps_agent_soul_prompt_for_build_draft():
+def test_agent_app_request_builder_wraps_agent_soul_prompt_for_build_draft() -> None:
original_prompt = " You are Iris. \n"
run_input = _agent_app_input().model_copy(
update={
@@ -154,11 +154,12 @@ def test_agent_app_request_builder_wraps_agent_soul_prompt_for_build_draft():
prompt_config = PromptConfig.model_validate(layers[AGENT_SOUL_PROMPT_LAYER_ID].config)
assert prompt_config.prefix != original_prompt
+ assert isinstance(prompt_config.prefix, str)
assert prompt_config.prefix.startswith("You are running in build mode.")
assert "```text\nYou are Iris.\n```" in prompt_config.prefix
-def test_agent_app_request_builder_uses_longer_fence_for_build_draft_prompt_body():
+def test_agent_app_request_builder_uses_longer_fence_for_build_draft_prompt_body() -> None:
run_input = _agent_app_input().model_copy(
update={
"agent_config_version_kind": "build_draft",
@@ -174,7 +175,7 @@ def test_agent_app_request_builder_uses_longer_fence_for_build_draft_prompt_body
assert "```python" in prompt_config.prefix
-def test_request_builder_sets_model_and_output_layer_contract_ids():
+def test_request_builder_sets_model_and_output_layer_contract_ids() -> None:
request = AgentBackendRunRequestBuilder().build_for_workflow_node(_run_input())
layers = {layer.name: layer for layer in request.composition.layers}
@@ -191,7 +192,7 @@ def test_request_builder_sets_model_and_output_layer_contract_ids():
assert layers[DIFY_AGENT_MODEL_LAYER_ID].config["execution_context"] == DIFY_EXECUTION_CONTEXT_LAYER_ID
-def test_request_builder_adds_dify_plugin_tools_layer_when_configured():
+def test_request_builder_adds_dify_plugin_tools_layer_when_configured() -> None:
run_input = _run_input()
run_input.tools = DifyPluginToolsLayerConfig(
tools=[
@@ -218,7 +219,7 @@ def test_request_builder_adds_dify_plugin_tools_layer_when_configured():
assert tools_config.tools[0].tool_name == "current_time"
-def test_request_builder_adds_dify_core_tools_layer_when_configured():
+def test_request_builder_adds_dify_core_tools_layer_when_configured() -> None:
run_input = _run_input()
run_input.core_tools = DifyCoreToolsLayerConfig(
tools=[
@@ -241,7 +242,7 @@ def test_request_builder_adds_dify_core_tools_layer_when_configured():
assert layers[DIFY_CORE_TOOLS_LAYER_ID].config["execution_context"] == DIFY_EXECUTION_CONTEXT_LAYER_ID
-def test_request_builder_adds_knowledge_layer_when_configured():
+def test_request_builder_adds_knowledge_layer_when_configured() -> None:
run_input = _run_input()
run_input.knowledge = DifyKnowledgeBaseLayerConfig.model_validate(
{
@@ -266,8 +267,8 @@ def test_request_builder_adds_knowledge_layer_when_configured():
assert knowledge_config.sets[0].dataset_ids == ["dataset-1"]
-def test_request_builder_rejects_blank_prompts():
- with pytest.raises(ValidationError):
+def test_request_builder_rejects_blank_prompts() -> None:
+ with pytest.raises(ValidationError, match="prompt must not be blank"):
AgentBackendWorkflowNodeRunInput(
model=AgentBackendModelConfig(
plugin_id="langgenius/openai",
@@ -280,12 +281,13 @@ def test_request_builder_rejects_blank_prompts():
agent_mode="workflow_run",
invoke_from="debugger",
),
+ backend_binding_ref="binding-ref-1",
workflow_node_job_prompt=" ",
user_prompt="hello",
)
-def test_agent_backend_request_does_not_contain_llm_credentials():
+def test_agent_backend_request_does_not_contain_llm_credentials() -> None:
request = AgentBackendRunRequestBuilder().build_for_workflow_node(_run_input())
redacted = cast(dict[str, Any], redact_for_agent_backend_log(request))
@@ -316,12 +318,12 @@ def _agent_app_input(*, include_shell: bool = False) -> AgentBackendAgentAppRunI
)
-def test_workflow_request_builder_omits_shell_layer_by_default():
+def test_workflow_request_builder_omits_shell_layer_by_default() -> None:
request = AgentBackendRunRequestBuilder().build_for_workflow_node(_run_input())
assert DIFY_SHELL_LAYER_ID not in {layer.name for layer in request.composition.layers}
-def test_workflow_request_builder_adds_shell_layer_when_include_shell():
+def test_workflow_request_builder_adds_shell_layer_when_include_shell() -> None:
run_input = _run_input()
run_input.include_shell = True
run_input.shell_config = DifyShellLayerConfig(env=[DifyShellEnvVarConfig(name="PROJECT_NAME", value="demo")])
@@ -339,12 +341,12 @@ def test_workflow_request_builder_adds_shell_layer_when_include_shell():
assert shell_config.env[0].name == "PROJECT_NAME"
-def test_agent_app_request_builder_omits_shell_layer_by_default():
+def test_agent_app_request_builder_omits_shell_layer_by_default() -> None:
request = AgentBackendRunRequestBuilder().build_for_agent_app(_agent_app_input())
assert DIFY_SHELL_LAYER_ID not in {layer.name for layer in request.composition.layers}
-def test_agent_app_request_builder_emits_multimodal_user_prompt_layer():
+def test_agent_app_request_builder_emits_multimodal_user_prompt_layer() -> None:
run_input = _agent_app_input()
run_input.user_files = [
DifyUserPromptDownloadConfig(
@@ -372,7 +374,7 @@ def test_agent_app_request_builder_emits_multimodal_user_prompt_layer():
assert "locators" not in restored_layer.config
-def test_agent_backend_log_redacts_multimodal_file_transport():
+def test_agent_backend_log_redacts_multimodal_file_transport() -> None:
run_input = _agent_app_input()
run_input.metadata = {"source_url": "https://example.com/docs"}
run_input.user_files = [
@@ -401,7 +403,7 @@ def test_agent_backend_log_redacts_multimodal_file_transport():
assert redacted["metadata"]["source_url"] == "https://example.com/docs"
-def test_agent_app_request_builder_keeps_build_draft_prompt_when_agent_soul_prompt_is_blank():
+def test_agent_app_request_builder_keeps_build_draft_prompt_when_agent_soul_prompt_is_blank() -> None:
run_input = _agent_app_input().model_copy(
update={"agent_soul_prompt": " ", "agent_config_version_kind": "build_draft"}
)
@@ -414,7 +416,7 @@ def test_agent_app_request_builder_keeps_build_draft_prompt_when_agent_soul_prom
assert "No task prompt was provided." in prompt_config.prefix
-def test_agent_app_request_builder_adds_shell_layer_when_include_shell():
+def test_agent_app_request_builder_adds_shell_layer_when_include_shell() -> None:
run_input = _agent_app_input(include_shell=True)
run_input.shell_config = DifyShellLayerConfig(env=[DifyShellEnvVarConfig(name="APP_ENV", value="enabled")])
@@ -428,7 +430,7 @@ def test_agent_app_request_builder_adds_shell_layer_when_include_shell():
assert shell_config.env[0].name == "APP_ENV"
-def test_agent_app_request_builder_adds_knowledge_layer_when_configured():
+def test_agent_app_request_builder_adds_knowledge_layer_when_configured() -> None:
run_input = _agent_app_input()
run_input.knowledge = DifyKnowledgeBaseLayerConfig.model_validate(
{
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 005955e0f3e..d108e8db337 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -8,12 +8,6 @@ min-severity = "warn"
# Existing strict-mode debt. Remove a file when bringing it under strict checking.
project-excludes = [
- "clients/agent_backend/test_cleanup_composition_compositor_integration.py",
- "clients/agent_backend/test_client.py",
- "clients/agent_backend/test_event_adapter.py",
- "clients/agent_backend/test_fake_client.py",
- "clients/agent_backend/test_request_builder.py",
- "clients/agent_backend/test_session_cleanup.py",
"commands/test_archive_workflow_runs.py",
"commands/test_data_migration_commands.py",
"commands/test_generate_swagger_markdown_docs.py",