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.

test(api): strictly type service API message and workflow tests (#45334)

Felix Shi33aacca661fc
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_message.py b/api/tests/unit_tests/controllers/service_api/app/test_message.py
index 1ff146a0009..5a004a0cd58 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_message.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_message.py
@@ -21,33 +21,33 @@ from services.errors.message import (
class TestMessageListQuery:
"""Test suite for MessageListQuery Pydantic model."""
- def test_query_requires_conversation_id(self):
+ def test_query_requires_conversation_id(self) -> None:
"""Test conversation_id is required."""
conversation_id = str(uuid.uuid4())
query = MessageListQuery(conversation_id=conversation_id)
assert query.conversation_id == conversation_id
- def test_query_with_defaults(self):
+ def test_query_with_defaults(self) -> None:
"""Test query with default values."""
conversation_id = str(uuid.uuid4())
query = MessageListQuery(conversation_id=conversation_id)
assert query.first_id is None
assert query.limit == 20
- def test_query_with_first_id(self):
+ def test_query_with_first_id(self) -> None:
"""Test query with first_id for pagination."""
conversation_id = str(uuid.uuid4())
first_id = str(uuid.uuid4())
query = MessageListQuery(conversation_id=conversation_id, first_id=first_id)
assert str(query.first_id) == first_id
- def test_query_with_custom_limit(self):
+ def test_query_with_custom_limit(self) -> None:
"""Test query with custom limit."""
conversation_id = str(uuid.uuid4())
query = MessageListQuery(conversation_id=conversation_id, limit=50)
assert query.limit == 50
- def test_query_limit_boundaries(self):
+ def test_query_limit_boundaries(self) -> None:
"""Test query respects limit boundaries."""
conversation_id = str(uuid.uuid4())
@@ -57,13 +57,13 @@ class TestMessageListQuery:
query_max = MessageListQuery(conversation_id=conversation_id, limit=100)
assert query_max.limit == 100
- def test_query_rejects_limit_below_minimum(self):
+ def test_query_rejects_limit_below_minimum(self) -> None:
"""Test query rejects limit < 1."""
conversation_id = str(uuid.uuid4())
with pytest.raises(ValueError, match="1 validation error for MessageListQuery\\\nlimit"):
MessageListQuery(conversation_id=conversation_id, limit=0) # pyrefly: ignore[bad-argument-type]
- def test_query_rejects_limit_above_maximum(self):
+ def test_query_rejects_limit_above_maximum(self) -> None:
"""Test query rejects limit > 100."""
conversation_id = str(uuid.uuid4())
with pytest.raises(ValueError, match="1 validation error for MessageListQuery\\\nlimit"):
@@ -73,42 +73,42 @@ class TestMessageListQuery:
class TestMessageFeedbackPayload:
"""Test suite for MessageFeedbackPayload Pydantic model."""
- def test_payload_with_defaults(self):
+ def test_payload_with_defaults(self) -> None:
"""Test payload with default values."""
payload = MessageFeedbackPayload()
assert payload.rating is None
assert payload.content is None
- def test_payload_with_like_rating(self):
+ def test_payload_with_like_rating(self) -> None:
"""Test payload with like rating."""
payload = MessageFeedbackPayload(rating="like")
assert payload.rating == "like"
- def test_payload_with_dislike_rating(self):
+ def test_payload_with_dislike_rating(self) -> None:
"""Test payload with dislike rating."""
payload = MessageFeedbackPayload(rating="dislike")
assert payload.rating == "dislike"
- def test_payload_with_content_only(self):
+ def test_payload_with_content_only(self) -> None:
"""Test payload with content but no rating."""
payload = MessageFeedbackPayload(content="This response was helpful")
assert payload.content == "This response was helpful"
assert payload.rating is None
- def test_payload_with_rating_and_content(self):
+ def test_payload_with_rating_and_content(self) -> None:
"""Test payload with both rating and content."""
payload = MessageFeedbackPayload(rating="like", content="Great answer, very detailed!")
assert payload.rating == "like"
assert payload.content == "Great answer, very detailed!"
- def test_payload_with_long_content(self):
+ def test_payload_with_long_content(self) -> None:
"""Test payload with long feedback content."""
long_content = "A" * 1000
payload = MessageFeedbackPayload(content=long_content)
assert payload.content is not None
assert len(payload.content) == 1000
- def test_payload_with_unicode_content(self):
+ def test_payload_with_unicode_content(self) -> None:
"""Test payload with unicode characters."""
unicode_content = "很好的回答 👍 Отличный ответ"
payload = MessageFeedbackPayload(content=unicode_content)
@@ -118,29 +118,29 @@ class TestMessageFeedbackPayload:
class TestFeedbackListQuery:
"""Test suite for FeedbackListQuery Pydantic model."""
- def test_query_with_defaults(self):
+ def test_query_with_defaults(self) -> None:
"""Test query with default values."""
query = FeedbackListQuery()
assert query.page == 1
assert query.limit == 20
- def test_query_with_custom_pagination(self):
+ def test_query_with_custom_pagination(self) -> None:
"""Test query with custom page and limit."""
query = FeedbackListQuery(page=3, limit=50)
assert query.page == 3
assert query.limit == 50
- def test_query_page_minimum(self):
+ def test_query_page_minimum(self) -> None:
"""Test query page minimum validation."""
query = FeedbackListQuery(page=1)
assert query.page == 1
- def test_query_rejects_page_below_minimum(self):
+ def test_query_rejects_page_below_minimum(self) -> None:
"""Test query rejects page < 1."""
with pytest.raises(ValueError, match="1 validation error for FeedbackListQuery\\\npage"):
FeedbackListQuery(page=0) # pyrefly: ignore[bad-argument-type]
- def test_query_limit_boundaries(self):
+ def test_query_limit_boundaries(self) -> None:
"""Test query limit boundaries."""
query_min = FeedbackListQuery(limit=1)
assert query_min.limit == 1
@@ -148,12 +148,12 @@ class TestFeedbackListQuery:
query_max = FeedbackListQuery(limit=101)
assert query_max.limit == 101 # Max is 101
- def test_query_rejects_limit_below_minimum(self):
+ def test_query_rejects_limit_below_minimum(self) -> None:
"""Test query rejects limit < 1."""
with pytest.raises(ValueError, match="1 validation error for FeedbackListQuery\\\nlimit"):
FeedbackListQuery(limit=0) # pyrefly: ignore[bad-argument-type]
- def test_query_rejects_limit_above_maximum(self):
+ def test_query_rejects_limit_above_maximum(self) -> None:
"""Test query rejects limit > 101."""
with pytest.raises(ValueError, match="1 validation error for FeedbackListQuery\\\nlimit"):
FeedbackListQuery(limit=102) # pyrefly: ignore[bad-argument-type]
@@ -162,23 +162,23 @@ class TestFeedbackListQuery:
class TestMessageAppModeValidation:
"""Test app mode validation for message endpoints."""
- def test_chat_modes_are_valid_for_message_endpoints(self):
+ def test_chat_modes_are_valid_for_message_endpoints(self) -> None:
"""Test that all chat modes are valid."""
valid_modes = {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}
for mode in valid_modes:
assert mode in valid_modes
- def test_completion_mode_is_invalid_for_message_endpoints(self):
+ def test_completion_mode_is_invalid_for_message_endpoints(self) -> None:
"""Test that COMPLETION mode is invalid."""
chat_modes = {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}
assert AppMode.COMPLETION not in chat_modes
- def test_workflow_mode_is_invalid_for_message_endpoints(self):
+ def test_workflow_mode_is_invalid_for_message_endpoints(self) -> None:
"""Test that WORKFLOW mode is invalid."""
chat_modes = {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}
assert AppMode.WORKFLOW not in chat_modes
- def test_not_chat_app_error_can_be_raised(self):
+ def test_not_chat_app_error_can_be_raised(self) -> None:
"""Test NotChatAppError can be raised."""
error = NotChatAppError()
assert error is not None
@@ -187,17 +187,17 @@ class TestMessageAppModeValidation:
class TestMessageErrorTypes:
"""Test message-related error types."""
- def test_message_not_exists_error_can_be_raised(self):
+ def test_message_not_exists_error_can_be_raised(self) -> None:
"""Test MessageNotExistsError can be raised."""
error = MessageNotExistsError()
assert isinstance(error, MessageNotExistsError)
- def test_first_message_not_exists_error_can_be_raised(self):
+ def test_first_message_not_exists_error_can_be_raised(self) -> None:
"""Test FirstMessageNotExistsError can be raised."""
error = FirstMessageNotExistsError()
assert isinstance(error, FirstMessageNotExistsError)
- def test_suggested_questions_after_answer_disabled_error_can_be_raised(self):
+ def test_suggested_questions_after_answer_disabled_error_can_be_raised(self) -> None:
"""Test SuggestedQuestionsAfterAnswerDisabledError can be raised."""
error = SuggestedQuestionsAfterAnswerDisabledError()
assert isinstance(error, SuggestedQuestionsAfterAnswerDisabledError)
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py b/api/tests/unit_tests/controllers/service_api/app/test_workflow.py
index f27ab593aa6..fcdc5807b7a 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_workflow.py
@@ -5,6 +5,7 @@ from collections.abc import Callable
from datetime import UTC, datetime
from inspect import unwrap
from types import SimpleNamespace
+from typing import Literal
from unittest.mock import MagicMock, Mock
import httpx
@@ -244,14 +245,14 @@ class TestWorkflowCases:
class TestWorkflowRunPayload:
"""Test suite for WorkflowRunPayload Pydantic model."""
- def test_payload_with_required_inputs(self):
+ def test_payload_with_required_inputs(self) -> None:
"""Test payload with required inputs field."""
payload = WorkflowRunPayload(inputs={"key": "value"})
assert payload.inputs == {"key": "value"}
assert payload.files is None
assert payload.response_mode is None
- def test_payload_with_all_fields(self):
+ def test_payload_with_all_fields(self) -> None:
"""Test payload with all fields populated."""
files = [{"type": "image", "url": "http://example.com/img.png"}]
payload = WorkflowRunPayload(
@@ -261,12 +262,12 @@ class TestWorkflowCases:
assert payload.files == files
assert payload.response_mode == "streaming"
- def test_payload_response_mode_blocking(self):
+ def test_payload_response_mode_blocking(self) -> None:
"""Test payload with blocking response mode."""
payload = WorkflowRunPayload(inputs={}, response_mode="blocking")
assert payload.response_mode == "blocking"
- def test_payload_with_complex_inputs(self):
+ def test_payload_with_complex_inputs(self) -> None:
"""Test payload with nested complex inputs."""
complex_inputs = {
"config": {"nested": {"value": 123}},
@@ -276,12 +277,12 @@ class TestWorkflowCases:
payload = WorkflowRunPayload(inputs=complex_inputs)
assert payload.inputs == complex_inputs
- def test_payload_with_empty_inputs(self):
+ def test_payload_with_empty_inputs(self) -> None:
"""Test payload with empty inputs dict."""
payload = WorkflowRunPayload(inputs={})
assert payload.inputs == {}
- def test_payload_with_multiple_files(self):
+ def test_payload_with_multiple_files(self) -> None:
"""Test payload with multiple file attachments."""
files = [
{"type": "image", "url": "http://example.com/img1.png"},
@@ -295,7 +296,7 @@ class TestWorkflowCases:
class TestWorkflowLogQuery:
"""Test suite for WorkflowLogQuery Pydantic model."""
- def test_query_with_defaults(self):
+ def test_query_with_defaults(self) -> None:
"""Test query with default values."""
query = WorkflowLogQuery()
assert query.keyword is None
@@ -307,7 +308,7 @@ class TestWorkflowCases:
assert query.page == 1
assert query.limit == 20
- def test_query_with_all_filters(self):
+ def test_query_with_all_filters(self) -> None:
"""Test query with all filter fields populated."""
query = WorkflowLogQuery(
keyword="search term",
@@ -329,12 +330,12 @@ class TestWorkflowCases:
assert query.limit == 50
@pytest.mark.parametrize("status", ["succeeded", "failed", "stopped"])
- def test_query_valid_status_values(self, status):
+ def test_query_valid_status_values(self, status: Literal["succeeded", "failed", "stopped"]) -> None:
"""Test all valid status values."""
query = WorkflowLogQuery(status=status)
assert query.status == status
- def test_query_pagination_limits(self):
+ def test_query_pagination_limits(self) -> None:
"""Test query pagination boundaries."""
query_min_page = WorkflowLogQuery(page=1)
assert query_min_page.page == 1
@@ -348,12 +349,12 @@ class TestWorkflowCases:
query_max_limit = WorkflowLogQuery(limit=100)
assert query_max_limit.limit == 100
- def test_query_with_keyword_search(self):
+ def test_query_with_keyword_search(self) -> None:
"""Test query with keyword filter."""
query = WorkflowLogQuery(keyword="workflow execution")
assert query.keyword == "workflow execution"
- def test_query_with_date_filters(self):
+ def test_query_with_date_filters(self) -> None:
"""Test query with before/after date filters."""
query = WorkflowLogQuery(
created_at__before="2024-12-31T23:59:59Z", created_at__after="2024-01-01T00:00:00Z"
@@ -362,7 +363,7 @@ class TestWorkflowCases:
assert query.created_at__after == "2024-01-01T00:00:00Z"
class TestWorkflowRunResponse:
- def test_validates_workflow_run_object_shape_and_clears_paused_outputs(self):
+ def test_validates_workflow_run_object_shape_and_clears_paused_outputs(self) -> None:
run = _make_workflow_run(run_id="run-paused")
run.status = WorkflowExecutionStatus.PAUSED
run.outputs = json.dumps({"should": "not leak"})
@@ -387,7 +388,7 @@ class TestWorkflowCases:
"""Test workflow run repository interface."""
@pytest.mark.parametrize("sqlite_session", [(WorkflowRun,)], indirect=True)
- def test_workflow_run_repository_get_by_id(self, sqlite_engine: Engine, sqlite_session: Session):
+ def test_workflow_run_repository_get_by_id(self, sqlite_engine: Engine, sqlite_session: Session) -> None:
"""Test repository lookup against committed tenant-scoped state."""
run = _make_workflow_run(run_id=str(uuid.uuid4()))
sqlite_session.add(run)
@@ -839,7 +840,7 @@ class TestWorkflowCases:
monkeypatch: pytest.MonkeyPatch,
sqlite_engine: Engine,
sqlite_session: Session,
- ):
+ ) -> None:
"""Test successful workflow run detail retrieval."""
run = _make_workflow_run(
run_id="run-1",
@@ -873,7 +874,7 @@ class TestWorkflowCases:
"elapsed_time": 0.1,
}
- def test_get_workflow_run_wrong_app_mode(self, app: Flask):
+ def test_get_workflow_run_wrong_app_mode(self, app: Flask) -> None:
"""Test NotWorkflowAppError when app mode is not workflow or advanced_chat."""
from controllers.service_api.app.workflow import WorkflowRunDetailApi
@@ -895,7 +896,7 @@ class TestWorkflowCases:
app: Flask,
workflow_app: App,
monkeypatch: pytest.MonkeyPatch,
- ):
+ ) -> None:
"""Test successful workflow log retrieval."""
_stub_workflow_app_logs(monkeypatch)
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 558657c644c..adf9c351a8a 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -74,8 +74,6 @@ project-excludes = [
"controllers/service_api/app/test_completion.py",
"controllers/service_api/app/test_file.py",
"controllers/service_api/app/test_workflow_events.py",
- "controllers/service_api/app/test_message.py",
- "controllers/service_api/app/test_workflow.py",
"controllers/service_api/dataset/rag_pipeline/test_rag_pipeline_workflow.py",
"controllers/service_api/dataset/test_segment.py",
"controllers/service_api/dataset/test_document.py",