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 converter/telemetry/tools test files (#44820)

Felix Shid30615be3056
diff --git a/api/tests/unit_tests/core/app/apps/pipeline/test_generate_response_converter.py b/api/tests/unit_tests/core/app/apps/pipeline/test_generate_response_converter.py
index 0bac966bfb6..62e9125a5f4 100644
--- a/api/tests/unit_tests/core/app/apps/pipeline/test_generate_response_converter.py
+++ b/api/tests/unit_tests/core/app/apps/pipeline/test_generate_response_converter.py
@@ -13,7 +13,7 @@ from core.app.entities.task_entities import (
from graphon.enums import WorkflowExecutionStatus, WorkflowNodeExecutionStatus
-def test_convert_blocking_full_and_simple_response():
+def test_convert_blocking_full_and_simple_response() -> None:
blocking = WorkflowAppBlockingResponse(
task_id="task",
workflow_run_id="run",
@@ -35,11 +35,14 @@ def test_convert_blocking_full_and_simple_response():
simple = WorkflowAppGenerateResponseConverter.convert_blocking_simple_response(blocking)
assert full == simple
+ assert isinstance(full, dict)
assert full["workflow_run_id"] == "run"
- assert full["data"]["status"] == WorkflowExecutionStatus.SUCCEEDED
+ full_data = full["data"]
+ assert isinstance(full_data, dict)
+ assert full_data["status"] == WorkflowExecutionStatus.SUCCEEDED
-def test_convert_stream_full_response():
+def test_convert_stream_full_response() -> None:
def stream() -> Generator[AppStreamResponse]:
yield WorkflowAppStreamResponse(
stream_response=PingStreamResponse(task_id="t"),
@@ -53,11 +56,12 @@ def test_convert_stream_full_response():
result = list(WorkflowAppGenerateResponseConverter.convert_stream_full_response(stream()))
assert result[0] == "ping"
+ assert isinstance(result[1], dict)
assert result[1]["event"] == "error"
assert result[1]["code"] == "invalid_param"
-def test_convert_stream_simple_response_node_ignore_details():
+def test_convert_stream_simple_response_node_ignore_details() -> None:
node_start = NodeStartStreamResponse(
task_id="t",
workflow_run_id="run",
@@ -105,7 +109,13 @@ def test_convert_stream_simple_response_node_ignore_details():
result = list(WorkflowAppGenerateResponseConverter.convert_stream_simple_response(stream()))
+ assert isinstance(result[0], dict)
assert result[0]["event"] == "node_started"
- assert result[0]["data"]["inputs"] is None
+ start_data = result[0]["data"]
+ assert isinstance(start_data, dict)
+ assert start_data["inputs"] is None
+ assert isinstance(result[1], dict)
assert result[1]["event"] == "node_finished"
- assert result[1]["data"]["inputs"] is None
+ finish_data = result[1]["data"]
+ assert isinstance(finish_data, dict)
+ assert finish_data["inputs"] is None
diff --git a/api/tests/unit_tests/core/app/apps/test_base_app_generate_response_converter.py b/api/tests/unit_tests/core/app/apps/test_base_app_generate_response_converter.py
index 0389c3bc041..5f29e27c254 100644
--- a/api/tests/unit_tests/core/app/apps/test_base_app_generate_response_converter.py
+++ b/api/tests/unit_tests/core/app/apps/test_base_app_generate_response_converter.py
@@ -37,12 +37,16 @@ class _DummyConverter(AppGenerateResponseConverter[WorkflowAppBlockingResponse])
return {"kind": "blocking-simple", "task_id": blocking_response.task_id}
@classmethod
- def convert_stream_full_response(cls, stream_response: Generator[AppStreamResponse]) -> Generator[dict | str]:
+ def convert_stream_full_response(
+ cls, stream_response: Generator[AppStreamResponse]
+ ) -> Generator[dict[str, object] | str]:
cls.stream_full_calls.append(stream_response)
yield {"kind": "stream-full"}
@classmethod
- def convert_stream_simple_response(cls, stream_response: Generator[AppStreamResponse]) -> Generator[dict | str]:
+ def convert_stream_simple_response(
+ cls, stream_response: Generator[AppStreamResponse]
+ ) -> Generator[dict[str, object] | str]:
cls.stream_simple_calls.append(stream_response)
yield {"kind": "stream-simple"}
diff --git a/api/tests/unit_tests/core/llm_generator/output_parser/test_rule_config_generator.py b/api/tests/unit_tests/core/llm_generator/output_parser/test_rule_config_generator.py
index b2783bdf999..1167f17b94d 100644
--- a/api/tests/unit_tests/core/llm_generator/output_parser/test_rule_config_generator.py
+++ b/api/tests/unit_tests/core/llm_generator/output_parser/test_rule_config_generator.py
@@ -10,7 +10,7 @@ from core.llm_generator.prompts import (
class TestRuleConfigGeneratorOutputParser:
- def test_get_format_instructions(self):
+ def test_get_format_instructions(self) -> None:
parser = RuleConfigGeneratorOutputParser()
instructions = parser.get_format_instructions()
assert instructions == (
@@ -19,7 +19,7 @@ class TestRuleConfigGeneratorOutputParser:
RULE_CONFIG_STATEMENT_GENERATE_TEMPLATE,
)
- def test_parse_success(self):
+ def test_parse_success(self) -> None:
parser = RuleConfigGeneratorOutputParser()
text = """
```json
@@ -35,7 +35,7 @@ class TestRuleConfigGeneratorOutputParser:
assert result["variables"] == ["var1", "var2"]
assert result["opening_statement"] == "Hello!"
- def test_parse_invalid_json(self):
+ def test_parse_invalid_json(self) -> None:
parser = RuleConfigGeneratorOutputParser()
text = "invalid json"
with pytest.raises(OutputParserError) as excinfo:
@@ -43,7 +43,7 @@ class TestRuleConfigGeneratorOutputParser:
assert "Parsing text" in str(excinfo.value)
assert "could not find json block in the output" in str(excinfo.value)
- def test_parse_missing_keys(self):
+ def test_parse_missing_keys(self) -> None:
parser = RuleConfigGeneratorOutputParser()
text = """
```json
@@ -57,7 +57,7 @@ class TestRuleConfigGeneratorOutputParser:
parser.parse(text)
assert "expected key `opening_statement` to be present" in str(excinfo.value)
- def test_parse_wrong_type_prompt(self):
+ def test_parse_wrong_type_prompt(self) -> None:
parser = RuleConfigGeneratorOutputParser()
text = """
```json
@@ -72,7 +72,7 @@ class TestRuleConfigGeneratorOutputParser:
parser.parse(text)
assert "Expected 'prompt' to be a string" in str(excinfo.value)
- def test_parse_wrong_type_variables(self):
+ def test_parse_wrong_type_variables(self) -> None:
parser = RuleConfigGeneratorOutputParser()
text = """
```json
@@ -87,7 +87,7 @@ class TestRuleConfigGeneratorOutputParser:
parser.parse(text)
assert "Expected 'variables' to be a list" in str(excinfo.value)
- def test_parse_wrong_type_opening_statement(self):
+ def test_parse_wrong_type_opening_statement(self) -> None:
parser = RuleConfigGeneratorOutputParser()
text = """
```json
diff --git a/api/tests/unit_tests/core/telemetry/test___init__.py b/api/tests/unit_tests/core/telemetry/test___init__.py
index 899d4a537dd..ac8a02ac65d 100644
--- a/api/tests/unit_tests/core/telemetry/test___init__.py
+++ b/api/tests/unit_tests/core/telemetry/test___init__.py
@@ -3,7 +3,8 @@
from __future__ import annotations
import queue
-from unittest.mock import MagicMock, patch
+from collections.abc import Callable, Iterator
+from unittest.mock import MagicMock, Mock, patch
import pytest
@@ -14,7 +15,7 @@ from core.telemetry.events import DraftNodeExecutionTraceEvent, TelemetryContext
@pytest.fixture
-def telemetry_test_setup():
+def telemetry_test_setup() -> Iterator[tuple[Callable[..., object], queue.Queue[TraceTask]]]:
trace_queue: queue.Queue[TraceTask] = queue.Queue()
with (
patch("core.ops.ops_trace_manager.OpsTraceManager.get_ops_trace_instance", return_value=None),
@@ -25,9 +26,14 @@ def telemetry_test_setup():
yield emit, trace_queue
+_TelemetrySetup = tuple[Callable[..., object], "queue.Queue[TraceTask]"]
+
+
class TestTelemetryEmit:
@patch("core.telemetry.gateway.is_enterprise_telemetry_enabled", return_value=True)
- def test_emit_enterprise_trace_creates_trace_task(self, mock_ee, telemetry_test_setup):
+ def test_emit_enterprise_trace_creates_trace_task(
+ self, mock_ee: Mock, telemetry_test_setup: _TelemetrySetup
+ ) -> None:
emit_fn, trace_queue = telemetry_test_setup
event = DraftNodeExecutionTraceEvent(
@@ -47,7 +53,7 @@ class TestTelemetryEmit:
assert called_task.user_id == "test-user"
assert called_task.trace_type == TraceTaskName.DRAFT_NODE_EXECUTION_TRACE
- def test_emit_enterprise_only_trace_dropped_when_ee_disabled(self, telemetry_test_setup):
+ def test_emit_enterprise_only_trace_dropped_when_ee_disabled(self, telemetry_test_setup: _TelemetrySetup) -> None:
emit_fn, trace_queue = telemetry_test_setup
event = DraftNodeExecutionTraceEvent(
@@ -64,7 +70,9 @@ class TestTelemetryEmit:
assert trace_queue.empty()
@patch("core.telemetry.gateway.is_enterprise_telemetry_enabled", return_value=True)
- def test_emit_passes_name_directly_to_trace_task(self, mock_ee, telemetry_test_setup):
+ def test_emit_passes_name_directly_to_trace_task(
+ self, mock_ee: Mock, telemetry_test_setup: _TelemetrySetup
+ ) -> None:
emit_fn, trace_queue = telemetry_test_setup
event = DraftNodeExecutionTraceEvent(
@@ -86,7 +94,7 @@ class TestTelemetryEmit:
assert isinstance(called_task.trace_type, TraceTaskName)
@patch("core.telemetry.gateway.is_enterprise_telemetry_enabled", return_value=True)
- def test_emit_with_provided_trace_manager(self, mock_ee, telemetry_test_setup):
+ def test_emit_with_provided_trace_manager(self, mock_ee: Mock, telemetry_test_setup: _TelemetrySetup) -> None:
emit_fn, trace_queue = telemetry_test_setup
mock_trace_manager = MagicMock()
diff --git a/api/tests/unit_tests/core/tools/__base/test_tool_provider.py b/api/tests/unit_tests/core/tools/__base/test_tool_provider.py
index 8fceb277412..457b3c5bf2b 100644
--- a/api/tests/unit_tests/core/tools/__base/test_tool_provider.py
+++ b/api/tests/unit_tests/core/tools/__base/test_tool_provider.py
@@ -4,6 +4,7 @@ from collections.abc import Generator
from typing import Any, override
import pytest
+from sqlalchemy.orm import Session
from core.entities.provider_entities import ProviderConfig, ProviderConfigType
from core.tools.__base.tool import Tool
@@ -29,12 +30,14 @@ class _DummyTool(Tool):
@override
def _invoke(
self,
+ session: Session,
user_id: str,
tool_parameters: dict[str, Any],
conversation_id: str | None = None,
app_id: str | None = None,
message_id: str | None = None,
) -> Generator[ToolInvokeMessage]:
+ del session
yield self.create_text_message("ok")
@@ -63,7 +66,7 @@ def _provider_identity() -> ToolProviderIdentity:
)
-def test_tool_provider_controller_get_credentials_schema_returns_deep_copy():
+def test_tool_provider_controller_get_credentials_schema_returns_deep_copy() -> None:
entity = ToolProviderEntity(
identity=_provider_identity(),
credentials_schema=[ProviderConfig(type=ProviderConfigType.TEXT_INPUT, name="api_key", required=False)],
@@ -76,14 +79,14 @@ def test_tool_provider_controller_get_credentials_schema_returns_deep_copy():
assert controller.entity.credentials_schema[0].name == "api_key"
-def test_tool_provider_controller_default_provider_type():
+def test_tool_provider_controller_default_provider_type() -> None:
entity = ToolProviderEntity(identity=_provider_identity(), credentials_schema=[])
controller = _DummyController(entity=entity)
assert controller.provider_type == ToolProviderType.BUILT_IN
-def test_validate_credentials_format_covers_required_default_and_type_rules():
+def test_validate_credentials_format_covers_required_default_and_type_rules() -> None:
select_options = [ProviderConfig.Option(value="opt-a", label=I18nObject(en_US="A"))]
entity = ToolProviderEntity(
identity=_provider_identity(),
diff --git a/api/tests/unit_tests/libs/test_pagination.py b/api/tests/unit_tests/libs/test_pagination.py
index af6286dcc05..0ca483952e6 100644
--- a/api/tests/unit_tests/libs/test_pagination.py
+++ b/api/tests/unit_tests/libs/test_pagination.py
@@ -6,15 +6,15 @@ from libs.pagination import PaginatedResult, clamp_pagination
class TestPaginatedResultPages:
- def test_pages_is_zero_for_empty_result(self):
+ def test_pages_is_zero_for_empty_result(self) -> None:
# Parity with Flask-SQLAlchemy's Pagination.pages, which PaginatedResult
# was introduced to replace as a drop-in (#38280): an empty result set
# has zero pages, not one.
- result = PaginatedResult(items=[], total=0, page=1, per_page=20)
+ result = PaginatedResult(items=list[object](), total=0, page=1, per_page=20)
assert result.pages == 0
- def test_has_next_is_false_for_empty_result(self):
- result = PaginatedResult(items=[], total=0, page=1, per_page=20)
+ def test_has_next_is_false_for_empty_result(self) -> None:
+ result = PaginatedResult(items=list[object](), total=0, page=1, per_page=20)
assert result.has_next is False
@pytest.mark.parametrize(
@@ -27,26 +27,26 @@ class TestPaginatedResultPages:
(41, 20, 3),
],
)
- def test_pages_for_non_empty_result(self, total, per_page, expected_pages):
+ def test_pages_for_non_empty_result(self, total: int, per_page: int, expected_pages: int) -> None:
result = PaginatedResult(items=[object()], total=total, page=1, per_page=per_page)
assert result.pages == expected_pages == math.ceil(total / per_page)
- def test_pages_is_zero_when_per_page_is_zero(self):
- result = PaginatedResult(items=[], total=0, page=1, per_page=0)
+ def test_pages_is_zero_when_per_page_is_zero(self) -> None:
+ result = PaginatedResult(items=list[object](), total=0, page=1, per_page=0)
assert result.pages == 0
class TestPaginatedResultHasNext:
- def test_has_next_true_when_more_pages_remain(self):
+ def test_has_next_true_when_more_pages_remain(self) -> None:
result = PaginatedResult(items=[object()], total=41, page=1, per_page=20)
assert result.has_next is True
- def test_has_next_false_on_last_page(self):
+ def test_has_next_false_on_last_page(self) -> None:
result = PaginatedResult(items=[object()], total=41, page=3, per_page=20)
assert result.has_next is False
-def test_paginated_result_is_iterable():
+def test_paginated_result_is_iterable() -> None:
items = [1, 2, 3]
result = PaginatedResult(items=items, total=3, page=1, per_page=20)
assert list(result) == items
@@ -61,27 +61,27 @@ class TestClampPagination:
"""
@pytest.mark.parametrize("per_page", [0, -1, -100])
- def test_per_page_below_one_is_floored(self, per_page):
+ def test_per_page_below_one_is_floored(self, per_page: int) -> None:
assert clamp_pagination(1, per_page) == (1, 1)
@pytest.mark.parametrize("page", [0, -1, -100])
- def test_page_below_one_is_floored(self, page):
+ def test_page_below_one_is_floored(self, page: int) -> None:
assert clamp_pagination(page, 20) == (1, 20)
- def test_max_per_page_caps_before_the_floor(self):
+ def test_max_per_page_caps_before_the_floor(self) -> None:
assert clamp_pagination(3, 500, 100) == (3, 100)
- def test_the_floor_wins_over_a_cap_below_one(self):
+ def test_the_floor_wins_over_a_cap_below_one(self) -> None:
"""Whatever the cap says, a page size of zero is the input that breaks the caller."""
assert clamp_pagination(1, 20, 0) == (1, 1)
- def test_no_cap_leaves_a_large_per_page_alone(self):
+ def test_no_cap_leaves_a_large_per_page_alone(self) -> None:
assert clamp_pagination(3, 500) == (3, 500)
- def test_valid_values_pass_through(self):
+ def test_valid_values_pass_through(self) -> None:
assert clamp_pagination(2, 20, 100) == (2, 20)
- def test_a_full_last_page_is_still_the_last_page(self):
+ def test_a_full_last_page_is_still_the_last_page(self) -> None:
"""The other guess this replaces: `len(items) == per_page`.
Forty rows at twenty per page means page two is exactly full and also last.
@@ -94,7 +94,7 @@ class TestClampPagination:
assert (page * size < 40) is result.has_next is False
@pytest.mark.parametrize("per_page", [0, -1])
- def test_clamped_values_agree_with_has_next(self, per_page):
+ def test_clamped_values_agree_with_has_next(self, per_page: int) -> None:
"""What the helper returns has to make the caller's arithmetic match the truth."""
total = 7
page, size = clamp_pagination(total, per_page, 100)
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 1c1fc0feecd..fa892553724 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -166,11 +166,9 @@ project-excludes = [
"core/app/apps/completion/test_app_generator.py",
"core/app/apps/completion/test_generate_response_converter.py",
"core/app/apps/pipeline/test_pipeline_config_manager.py",
- "core/app/apps/pipeline/test_generate_response_converter.py",
"core/app/apps/pipeline/test_pipeline_generator.py",
"core/app/apps/pipeline/test_pipeline_queue_manager.py",
"core/app/apps/pipeline/test_pipeline_runner.py",
- "core/app/apps/test_base_app_generate_response_converter.py",
"core/app/apps/test_base_app_generator.py",
"core/app/apps/test_base_app_queue_manager.py",
"core/app/apps/test_exc.py",
@@ -216,7 +214,6 @@ project-excludes = [
"core/external_data_tool/test_factory.py",
"core/helper/code_executor/test_code_executor.py",
"core/helper/test_ssrf_proxy.py",
- "core/llm_generator/output_parser/test_rule_config_generator.py",
"core/llm_generator/output_parser/test_structured_output.py",
"core/llm_generator/test_llm_generator.py",
"core/logging/test_filters.py",
@@ -283,7 +280,6 @@ project-excludes = [
"core/repositories/test_human_input_repository.py",
"core/repositories/test_sqlalchemy_workflow_execution_repository.py",
"core/repositories/test_sqlalchemy_workflow_node_execution_repository.py",
- "core/telemetry/test___init__.py",
"core/telemetry/test_gateway.py",
"../e2e_tests/contracts/core/test_file.py",
"core/test_model_manager.py",
@@ -303,7 +299,6 @@ project-excludes = [
"core/tools/test_tool_file_manager.py",
"core/tools/test_tool_label_manager.py",
"core/tools/test_tool_manager.py",
- "core/tools/__base/test_tool_provider.py",
"core/tools/utils/test_configuration.py",
"core/tools/utils/test_message_transformer.py",
"core/tools/utils/dataset_retriever/test_dataset_multi_retriever_tool.py",
@@ -406,7 +401,6 @@ project-excludes = [
"libs/test_helper.py",
"libs/test_login.py",
"libs/test_orjson.py",
- "libs/test_pagination.py",
"../e2e_tests/contracts/libs/test_pandas.py",
"libs/test_token.py",
"migrations/versions/test_2025_07_02_2332-1c9ba48be8e4_add_uuidv7_function_in_sql.py",
@@ -428,7 +422,6 @@ project-excludes = [
"services/data_migration/test_export_service.py",
"services/data_migration/test_import_service.py",
"services/data_migration/test_package_service.py",
- "services/data_migration/test_report_service.py",
"../helpers/unit/services/dataset_service_test_helpers.py",
"../helpers/unit/services/document_service_validation.py",
"services/enterprise/test_account_deletion_sync.py",
diff --git a/api/tests/unit_tests/services/data_migration/test_report_service.py b/api/tests/unit_tests/services/data_migration/test_report_service.py
index 6e85263f5c4..bdabd3c0f88 100644
--- a/api/tests/unit_tests/services/data_migration/test_report_service.py
+++ b/api/tests/unit_tests/services/data_migration/test_report_service.py
@@ -2,7 +2,7 @@ from services.data_migration.entities import ReportContext, ResourceIdMapping, R
from services.data_migration.report_service import MigrationReportService
-def test_report_summarizes_by_resource_type_and_status():
+def test_report_summarizes_by_resource_type_and_status() -> None:
lines = MigrationReportService().render(
[
ResourceReportItem(ResourceType.WORKFLOW, "app-1", "App", "exported"),
@@ -16,7 +16,7 @@ def test_report_summarizes_by_resource_type_and_status():
assert "dependency dependency-only: 1" in lines
-def test_report_includes_actionable_lines_for_skipped_and_unresolved_items():
+def test_report_includes_actionable_lines_for_skipped_and_unresolved_items() -> None:
lines = MigrationReportService().render(
[
ResourceReportItem(ResourceType.WORKFLOW, "app-1", "App", "skipped", "App already exists"),
@@ -31,7 +31,7 @@ def test_report_includes_actionable_lines_for_skipped_and_unresolved_items():
assert "dependency mcp-1: MCP provider not found" in lines
-def test_report_dependency_detail_uses_type_and_name_when_available():
+def test_report_dependency_detail_uses_type_and_name_when_available() -> None:
lines = MigrationReportService().render(
[
ResourceReportItem(
@@ -61,7 +61,7 @@ def test_report_dependency_detail_uses_type_and_name_when_available():
) in lines
-def test_report_includes_dependency_only_detail_lines():
+def test_report_includes_dependency_only_detail_lines() -> None:
lines = MigrationReportService().render(
[
ResourceReportItem(
@@ -78,7 +78,7 @@ def test_report_includes_dependency_only_detail_lines():
assert "dependency mcp-1: Configure manually in target tenant." in lines
-def test_report_includes_export_and_import_context():
+def test_report_includes_export_and_import_context() -> None:
lines = MigrationReportService().render(
[],
context=ReportContext(