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
refactor(api): enable strict typing for services workflow tests (#43927)
Eddy ZHANGe1045952ff4d
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.tomlindex d108e8db337..fddb712cdc8 100644--- a/api/tests/unit_tests/pyrefly.toml+++ b/api/tests/unit_tests/pyrefly.toml@@ -732,10 +732,7 @@ project-excludes = ["services/tools/test_tools_manage_service.py","services/tools/test_tools_transform_service.py","services/workflow/test_draft_var_loader_simple.py",- "services/workflow/test_inspector_events.py","services/workflow/test_node_output_inspector_service.py",- "services/workflow/test_queue_dispatcher.py",- "services/workflow/test_scheduler.py","services/workflow/test_workflow_converter_additional.py","services/workflow/test_workflow_draft_variable_service.py","services/workflow/test_workflow_event_snapshot_service.py",diff --git a/api/tests/unit_tests/services/workflow/test_inspector_events.py b/api/tests/unit_tests/services/workflow/test_inspector_events.pyindex 8e1992861f2..32451654e1f 100644--- a/api/tests/unit_tests/services/workflow/test_inspector_events.py+++ b/api/tests/unit_tests/services/workflow/test_inspector_events.py@@ -14,7 +14,7 @@ The publisher and subscriber both touch redis, so we mock it out at thefrom __future__ import annotationsimport json-from collections.abc import Iterator+from collections.abc import Generator, Iteratorfrom typing import Anyfrom unittest.mock import MagicMock, patch@@ -26,42 +26,42 @@ from services.workflow.inspector_events import InspectorMessage# ──────────────────────────────────────────────────────────────────────────────-def test_channel_for_returns_namespaced_key():+def test_channel_for_returns_namespaced_key() -> None:assert inspector_events.channel_for("run-42") == "dify:inspector:workflow_run:run-42"-def test_inspector_message_to_json_round_trip():+def test_inspector_message_to_json_round_trip() -> None:msg = InspectorMessage(kind="node_changed", workflow_run_id="r1", node_id="agent-1", status="succeeded")parsed = json.loads(msg.to_json())assert parsed == {"kind": "node_changed", "workflow_run_id": "r1", "node_id": "agent-1", "status": "succeeded"}-def test_inspector_message_from_json_rejects_bad_kind():+def test_inspector_message_from_json_rejects_bad_kind() -> None:blob = json.dumps({"kind": "something_else", "workflow_run_id": "r1"})assert InspectorMessage.from_json(blob) is None-def test_inspector_message_from_json_rejects_bad_workflow_run_id():+def test_inspector_message_from_json_rejects_bad_workflow_run_id() -> None:blob = json.dumps({"kind": "node_changed", "workflow_run_id": ""})assert InspectorMessage.from_json(blob) is None-def test_inspector_message_from_json_rejects_non_string_node_id():+def test_inspector_message_from_json_rejects_non_string_node_id() -> None:blob = json.dumps({"kind": "node_changed", "workflow_run_id": "r1", "node_id": 42})assert InspectorMessage.from_json(blob) is None-def test_inspector_message_from_json_returns_none_for_invalid_json():+def test_inspector_message_from_json_returns_none_for_invalid_json() -> None:assert InspectorMessage.from_json("{not json") is None-def test_inspector_message_from_json_rejects_non_dict_payload():+def test_inspector_message_from_json_rejects_non_dict_payload() -> None:"""Defensive: a JSON array or scalar is not an InspectorMessage."""assert InspectorMessage.from_json("[1, 2, 3]") is Noneassert InspectorMessage.from_json('"plain string"') is None-def test_inspector_message_from_json_rejects_non_string_status():+def test_inspector_message_from_json_rejects_non_string_status() -> None:"""Status field, if present, must be a string."""blob = json.dumps({"kind": "workflow_completed", "workflow_run_id": "r1", "status": 42})assert InspectorMessage.from_json(blob) is None@@ -72,7 +72,7 @@ def test_inspector_message_from_json_rejects_non_string_status():# ──────────────────────────────────────────────────────────────────────────────-def test_publish_node_changed_writes_to_run_channel():+def test_publish_node_changed_writes_to_run_channel() -> None:fake_redis = MagicMock()with patch.object(inspector_events, "redis_client", fake_redis):inspector_events.publish_node_changed(workflow_run_id="run-1", node_id="agent-1", status="running")@@ -87,7 +87,7 @@ def test_publish_node_changed_writes_to_run_channel():assert msg.status == "running"-def test_publish_workflow_completed_emits_terminal_message():+def test_publish_workflow_completed_emits_terminal_message() -> None:fake_redis = MagicMock()with patch.object(inspector_events, "redis_client", fake_redis):inspector_events.publish_workflow_completed(workflow_run_id="run-1", status="succeeded")@@ -100,7 +100,7 @@ def test_publish_workflow_completed_emits_terminal_message():assert msg.status == "succeeded"-def test_publish_swallows_redis_errors():+def test_publish_swallows_redis_errors() -> None:"""Persistence must not crash if redis blows up — we publish best-effort."""class _BrokenRedis:@@ -125,7 +125,7 @@ def _make_fake_pubsub(messages: list[dict[str, Any] | None]) -> MagicMock:return pubsub-def test_subscribe_yields_heartbeat_then_real_message():+def test_subscribe_yields_heartbeat_then_real_message() -> None:"""Idle ticks (``get_message`` returns None) surface as a sentinel; realpayloads decode to ``InspectorMessage`` instances."""payload = json.dumps(@@ -156,7 +156,7 @@ def test_subscribe_yields_heartbeat_then_real_message():assert third.node_id is None-def test_subscribe_skips_malformed_payloads():+def test_subscribe_skips_malformed_payloads() -> None:fake_redis = MagicMock()fake_redis.pubsub.return_value = _make_fake_pubsub([@@ -171,19 +171,20 @@ def test_subscribe_skips_malformed_payloads():assert msg.node_id is None-def test_subscribe_unsubscribes_on_teardown():+def test_subscribe_unsubscribes_on_teardown() -> None:fake_pubsub = _make_fake_pubsub([None])fake_redis = MagicMock()fake_redis.pubsub.return_value = fake_pubsubwith patch.object(inspector_events, "redis_client", fake_redis):gen = inspector_events.subscribe("run-1", timeout_seconds=0.0)next(gen)+ assert isinstance(gen, Generator)gen.close()fake_pubsub.unsubscribe.assert_called_once_with("dify:inspector:workflow_run:run-1")fake_pubsub.close.assert_called_once()-def test_subscribe_swallows_teardown_errors():+def test_subscribe_swallows_teardown_errors() -> None:"""``unsubscribe`` / ``close`` failures must not propagate out of thegenerator — they're best-effort cleanup."""fake_pubsub = MagicMock()@@ -195,12 +196,13 @@ def test_subscribe_swallows_teardown_errors():with patch.object(inspector_events, "redis_client", fake_redis):gen = inspector_events.subscribe("run-1", timeout_seconds=0.0)next(gen)+ assert isinstance(gen, Generator)# The teardown path runs in ``finally``; closing the generator# exercises it. No exception should escape.gen.close()-def test_subscribe_skips_non_string_data_payloads():+def test_subscribe_skips_non_string_data_payloads() -> None:"""``raw["data"]`` can be ``None`` / int / bytes — only str is decodableand the rest are silently skipped."""fake_pubsub = MagicMock()diff --git a/api/tests/unit_tests/services/workflow/test_queue_dispatcher.py b/api/tests/unit_tests/services/workflow/test_queue_dispatcher.pyindex fef92191bba..6831a3f0e2a 100644--- a/api/tests/unit_tests/services/workflow/test_queue_dispatcher.py+++ b/api/tests/unit_tests/services/workflow/test_queue_dispatcher.py@@ -1,4 +1,5 @@-from unittest.mock import patch+from collections.abc import Callable+from unittest.mock import MagicMock, patchimport pytest@@ -13,24 +14,24 @@ from services.workflow.queue_dispatcher import (class TestQueuePriority:- def test_priority_values(self):+ def test_priority_values(self) -> None:assert QueuePriority.PROFESSIONAL == "workflow_professional"assert QueuePriority.TEAM == "workflow_team"assert QueuePriority.SANDBOX == "workflow_sandbox"class TestDispatchers:- def test_professional_dispatcher(self):+ def test_professional_dispatcher(self) -> None:d = ProfessionalQueueDispatcher()assert d.get_queue_name() == QueuePriority.PROFESSIONALassert d.get_priority() == 100- def test_team_dispatcher(self):+ def test_team_dispatcher(self) -> None:d = TeamQueueDispatcher()assert d.get_queue_name() == QueuePriority.TEAMassert d.get_priority() == 50- def test_sandbox_dispatcher(self):+ def test_sandbox_dispatcher(self) -> None:d = SandboxQueueDispatcher()assert d.get_queue_name() == QueuePriority.SANDBOXassert d.get_priority() == 10@@ -38,11 +39,11 @@ class TestDispatchers:class TestQueueDispatcherManager:@pytest.fixture(autouse=True)- def _cloud_edition(self, config_overrides) -> None:+ def _cloud_edition(self, config_overrides: Callable[..., None]) -> None:config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)@patch("services.workflow.queue_dispatcher.BillingService")- def test_cloud_edition_professional_plan(self, mock_billing):+ def test_cloud_edition_professional_plan(self, mock_billing: MagicMock) -> None:mock_billing.get_info.return_value = {"subscription": {"plan": "professional"}}dispatcher = QueueDispatcherManager.get_dispatcher("tenant-1")@@ -50,7 +51,7 @@ class TestQueueDispatcherManager:assert isinstance(dispatcher, ProfessionalQueueDispatcher)@patch("services.workflow.queue_dispatcher.BillingService")- def test_cloud_edition_team_plan(self, mock_billing):+ def test_cloud_edition_team_plan(self, mock_billing: MagicMock) -> None:mock_billing.get_info.return_value = {"subscription": {"plan": "team"}}dispatcher = QueueDispatcherManager.get_dispatcher("tenant-1")@@ -58,7 +59,7 @@ class TestQueueDispatcherManager:assert isinstance(dispatcher, TeamQueueDispatcher)@patch("services.workflow.queue_dispatcher.BillingService")- def test_cloud_edition_sandbox_plan(self, mock_billing):+ def test_cloud_edition_sandbox_plan(self, mock_billing: MagicMock) -> None:mock_billing.get_info.return_value = {"subscription": {"plan": "sandbox"}}dispatcher = QueueDispatcherManager.get_dispatcher("tenant-1")@@ -66,7 +67,7 @@ class TestQueueDispatcherManager:assert isinstance(dispatcher, SandboxQueueDispatcher)@patch("services.workflow.queue_dispatcher.BillingService")- def test_cloud_edition_unknown_plan_defaults_to_sandbox(self, mock_billing):+ def test_cloud_edition_unknown_plan_defaults_to_sandbox(self, mock_billing: MagicMock) -> None:mock_billing.get_info.return_value = {"subscription": {"plan": "enterprise"}}dispatcher = QueueDispatcherManager.get_dispatcher("tenant-1")@@ -74,14 +75,14 @@ class TestQueueDispatcherManager:assert isinstance(dispatcher, SandboxQueueDispatcher)@patch("services.workflow.queue_dispatcher.BillingService")- def test_cloud_edition_billing_failure_defaults_to_sandbox(self, mock_billing):+ def test_cloud_edition_billing_failure_defaults_to_sandbox(self, mock_billing: MagicMock) -> None:mock_billing.get_info.side_effect = Exception("billing unavailable")dispatcher = QueueDispatcherManager.get_dispatcher("tenant-1")assert isinstance(dispatcher, SandboxQueueDispatcher)- def test_non_cloud_edition_defaults_to_team(self, config_overrides):+ def test_non_cloud_edition_defaults_to_team(self, config_overrides: Callable[..., None]) -> None:config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)dispatcher = QueueDispatcherManager.get_dispatcher("tenant-1")@@ -89,8 +90,8 @@ class TestQueueDispatcherManager:assert isinstance(dispatcher, TeamQueueDispatcher)@patch("services.workflow.queue_dispatcher.BillingService")- def test_missing_subscription_key_defaults_to_sandbox(self, mock_billing):- mock_billing.get_info.return_value = {}+ def test_missing_subscription_key_defaults_to_sandbox(self, mock_billing: MagicMock) -> None:+ mock_billing.get_info.return_value = dict[str, object]()dispatcher = QueueDispatcherManager.get_dispatcher("tenant-1")diff --git a/api/tests/unit_tests/services/workflow/test_scheduler.py b/api/tests/unit_tests/services/workflow/test_scheduler.pyindex 3b44884161b..403bf933042 100644--- a/api/tests/unit_tests/services/workflow/test_scheduler.py+++ b/api/tests/unit_tests/services/workflow/test_scheduler.py@@ -5,24 +5,24 @@ from services.workflow.scheduler import CFSPlanScheduler, SchedulerCommandclass TestSchedulerCommand:- def test_enum_values(self):+ def test_enum_values(self) -> None:assert SchedulerCommand.RESOURCE_LIMIT_REACHED == "resource_limit_reached"assert SchedulerCommand.NONE == "none"- def test_enum_is_str(self):+ def test_enum_is_str(self) -> None:for member in SchedulerCommand:assert isinstance(member, str)class TestCFSPlanScheduler:- def test_stores_plan(self):+ def test_stores_plan(self) -> None:plan = WorkflowScheduleCFSPlanEntity(schedule_strategy=WorkflowScheduleCFSPlanEntity.Strategy.Nop,granularity=-1,)- class ConcretePlanScheduler(CFSPlanScheduler):- def can_schedule(self):+ class ConcretePlanScheduler(CFSPlanScheduler[WorkflowScheduleCFSPlanEntity]):+ def can_schedule(self) -> SchedulerCommand:return SchedulerCommand.NONEscheduler = ConcretePlanScheduler(plan)@@ -31,7 +31,7 @@ class TestCFSPlanScheduler:assert scheduler.plan.schedule_strategy == WorkflowScheduleCFSPlanEntity.Strategy.Nopassert scheduler.plan.granularity == -1- def test_cannot_instantiate_abstract(self):+ def test_cannot_instantiate_abstract(self) -> None:plan = WorkflowScheduleCFSPlanEntity(schedule_strategy=WorkflowScheduleCFSPlanEntity.Strategy.TimeSlice,granularity=10,@@ -39,14 +39,14 @@ class TestCFSPlanScheduler:with pytest.raises(TypeError):CFSPlanScheduler(plan) # type: ignore- def test_concrete_subclass_can_schedule(self):+ def test_concrete_subclass_can_schedule(self) -> None:plan = WorkflowScheduleCFSPlanEntity(schedule_strategy=WorkflowScheduleCFSPlanEntity.Strategy.TimeSlice,granularity=5,)- class TimedScheduler(CFSPlanScheduler):- def can_schedule(self):+ class TimedScheduler(CFSPlanScheduler[WorkflowScheduleCFSPlanEntity]):+ def can_schedule(self) -> SchedulerCommand:if self.plan.granularity > 0:return SchedulerCommand.NONEreturn SchedulerCommand.RESOURCE_LIMIT_REACHED@@ -54,14 +54,14 @@ class TestCFSPlanScheduler:scheduler = TimedScheduler(plan)assert scheduler.can_schedule() == SchedulerCommand.NONE- def test_concrete_subclass_resource_limit(self):+ def test_concrete_subclass_resource_limit(self) -> None:plan = WorkflowScheduleCFSPlanEntity(schedule_strategy=WorkflowScheduleCFSPlanEntity.Strategy.TimeSlice,granularity=-1,)- class TimedScheduler(CFSPlanScheduler):- def can_schedule(self):+ class TimedScheduler(CFSPlanScheduler[WorkflowScheduleCFSPlanEntity]):+ def can_schedule(self) -> SchedulerCommand:if self.plan.granularity > 0:return SchedulerCommand.NONEreturn SchedulerCommand.RESOURCE_LIMIT_REACHED@@ -71,17 +71,17 @@ class TestCFSPlanScheduler:class TestWorkflowScheduleCFSPlanEntity:- def test_strategy_values(self):+ def test_strategy_values(self) -> None:assert WorkflowScheduleCFSPlanEntity.Strategy.TimeSlice == "time-slice"assert WorkflowScheduleCFSPlanEntity.Strategy.Nop == "nop"- def test_default_granularity(self):+ def test_default_granularity(self) -> None:plan = WorkflowScheduleCFSPlanEntity(schedule_strategy=WorkflowScheduleCFSPlanEntity.Strategy.Nop,)assert plan.granularity == -1- def test_explicit_granularity(self):+ def test_explicit_granularity(self) -> None:plan = WorkflowScheduleCFSPlanEntity(schedule_strategy=WorkflowScheduleCFSPlanEntity.Strategy.TimeSlice,granularity=100,