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): annotate five controller test modules for strict pyrefly (#45458)

Felix Shibd1ed239e954
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_run.py b/api/tests/unit_tests/controllers/console/app/test_workflow_run.py
index d53bf8a1249..be36ad4622e 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow_run.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_run.py
@@ -152,8 +152,8 @@ class TestWorkflowPauseDetailsApiCases:
assert workflow_run_module.WorkflowPauseDetailsResponse.__name__ in workflow_run_module.console_ns.models
-def _serialize_200_response(handler, payload: Any) -> Any:
- response_doc = getattr(handler, "__apidoc__", {}).get("responses", {}).get("200")
+def _serialize_200_response(handler: Any, payload: Any) -> Any:
+ response_doc = handler.__apidoc__.get("responses", {}).get("200")
if response_doc is None:
return payload
@@ -193,7 +193,9 @@ def _workflow_run_api_mock_application_services(
)
-def _workflow_run_summary(session: Session, **overrides: object) -> WorkflowRun:
+def _workflow_run_summary(
+ session: Session, conversation_id: str | None = None, message_id: str | None = None
+) -> WorkflowRun:
created_at = datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)
workflow_run = WorkflowRun(
id="run-1",
@@ -217,9 +219,11 @@ def _workflow_run_summary(session: Session, **overrides: object) -> WorkflowRun:
exceptions_count=0,
)
workflow_run.created_at = created_at
- for name, value in overrides.items():
- setattr(workflow_run, name, value)
- workflow_run.retry_index = 0
+ if conversation_id is not None:
+ workflow_run.conversation_id = conversation_id # pyrefly: ignore[missing-attribute]
+ if message_id is not None:
+ workflow_run.message_id = message_id # pyrefly: ignore[missing-attribute]
+ workflow_run.retry_index = 0 # pyrefly: ignore[missing-attribute]
session.add(workflow_run)
session.commit()
return workflow_run
diff --git a/api/tests/unit_tests/controllers/console/datasets/test_data_source.py b/api/tests/unit_tests/controllers/console/datasets/test_data_source.py
index 77ec458bf22..9c550c4f842 100644
--- a/api/tests/unit_tests/controllers/console/datasets/test_data_source.py
+++ b/api/tests/unit_tests/controllers/console/datasets/test_data_source.py
@@ -705,7 +705,7 @@ class TestDataSourceCases:
"resource",
[data_source_controller.DataSourceNotionDatasetSyncApi, data_source_controller.DataSourceNotionDocumentSyncApi],
)
- def test_notion_sync_requires_dataset_edit_permission(resource):
+ def test_notion_sync_requires_dataset_edit_permission(resource: type) -> None:
[check] = rbac_checks(resource.get)
assert check.scene is RBACPermission.DATASET_EDIT
assert isinstance(check.locator, DatasetId)
diff --git a/api/tests/unit_tests/controllers/console/tag/test_tags.py b/api/tests/unit_tests/controllers/console/tag/test_tags.py
index 3efc2ff985f..8dd285e2e34 100644
--- a/api/tests/unit_tests/controllers/console/tag/test_tags.py
+++ b/api/tests/unit_tests/controllers/console/tag/test_tags.py
@@ -1,3 +1,5 @@
+from collections.abc import Iterator
+from inspect import unwrap
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -35,12 +37,6 @@ from tests.helpers.unit.config_override import config_overrides_context
from tests.helpers.unit.model_factories import make_account
-def unwrap(func):
- while hasattr(func, "__wrapped__"):
- func = func.__wrapped__
- return func
-
-
@pytest.fixture
def app() -> Flask:
app = Flask("test_tag")
@@ -63,7 +59,7 @@ def _account(role: TenantAccountRole) -> Account:
@pytest.fixture
-def tags_service() -> MagicMock:
+def tags_service() -> Iterator[MagicMock]:
tags = MagicMock()
with patch.object(module, "application_services", return_value=SimpleNamespace(tags=tags)):
yield tags
@@ -502,10 +498,12 @@ class TestTagResponseAndRoutes:
assert payload["binding_count"] == "1"
def test_binding_routes_keep_contract(self) -> None:
- assert TagBindingCollectionApi.post.__apidoc__["id"] == "create_tag_binding"
- assert TagBindingRemoveApi.post.__apidoc__["id"] == "remove_tag_bindings"
- assert TagBindingCollectionApi.post.__apidoc__.get("deprecated") is not True
- assert TagBindingRemoveApi.post.__apidoc__.get("deprecated") is not True
+ post_doc = TagBindingCollectionApi.post.__apidoc__ # pyrefly: ignore[missing-attribute]
+ remove_doc = TagBindingRemoveApi.post.__apidoc__ # pyrefly: ignore[missing-attribute]
+ assert post_doc["id"] == "create_tag_binding"
+ assert remove_doc["id"] == "remove_tag_bindings"
+ assert post_doc.get("deprecated") is not True
+ assert remove_doc.get("deprecated") is not True
route_map = {
resource.__name__: urls
diff --git a/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_config.py b/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_config.py
index 3a0d5b4e7c4..fcd9a32c222 100644
--- a/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_config.py
+++ b/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_config.py
@@ -2,8 +2,8 @@
from __future__ import annotations
-import inspect
from collections.abc import Callable
+from inspect import unwrap as _raw
from unittest.mock import patch
import pytest
@@ -25,10 +25,6 @@ MODULE = "controllers.inner_api.plugin.agent_config"
app = Flask(__name__)
-def _raw(method):
- return inspect.unwrap(method)
-
-
def test_manifest_happy_path_calls_service() -> None:
raw = _raw(AgentConfigManifestApi.get)
@@ -162,7 +158,7 @@ def test_skill_inspect_happy_path_returns_service_payload() -> None:
def test_push_happy_path_validates_body_and_preserves_execution_user() -> None:
raw = _raw(AgentConfigPushApi.post)
- payload = {
+ payload: dict[str, object] = {
"tenant_id": "tenant-1",
"user_id": "account-user-1",
"config_version_id": "cfg-1",
@@ -175,7 +171,7 @@ def test_push_happy_path_validates_body_and_preserves_execution_user() -> None:
with app.test_request_context("/", method="POST", json=payload):
with patch(f"{MODULE}.AgentConfigService") as service:
- service.return_value.push.return_value = {
+ push_result: dict[str, object] = {
"agent_id": "agent-1",
"config_version": {"id": "cfg-1", "kind": "build_draft", "writable": True},
"skills": {"items": []},
@@ -183,6 +179,7 @@ def test_push_happy_path_validates_body_and_preserves_execution_user() -> None:
"env_keys": ["KEY"],
"note": "hello",
}
+ service.return_value.push.return_value = push_result
body = raw(AgentConfigPushApi(), "agent-1")
assert body == {
@@ -329,6 +326,7 @@ def test_manifest_invalid_query_returns_400() -> None:
body, status = raw(AgentConfigManifestApi(), "agent-1")
assert status == 400
+ assert isinstance(body, dict)
assert body["code"] == "invalid_request"
@@ -345,6 +343,7 @@ def test_download_request_rejects_invalid_config_name() -> None:
body, status = raw(AgentConfigDownloadRequestApi(), "agent-1")
assert status == 400
+ assert isinstance(body, dict)
assert body["code"] == "invalid_request"
@@ -355,6 +354,7 @@ def test_push_invalid_body_returns_400() -> None:
body, status = raw(AgentConfigPushApi(), "agent-1")
assert status == 400
+ assert isinstance(body, dict)
assert body["code"] == "invalid_request"
@@ -376,7 +376,7 @@ def test_manifest_maps_service_errors() -> None:
def test_push_maps_service_errors() -> None:
raw = _raw(AgentConfigPushApi.post)
- payload = {
+ payload: dict[str, object] = {
"tenant_id": "tenant-1",
"user_id": "account-user-1",
"config_version_id": "cfg-1",
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_app.py b/api/tests/unit_tests/controllers/service_api/app/test_app.py
index 38d7eb7e678..cd049e87c45 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_app.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_app.py
@@ -12,7 +12,7 @@ from uuid import uuid4
import pytest
from flask import Flask
-from sqlalchemy.engine import Engine
+from sqlalchemy import delete
from sqlalchemy.orm import Session, scoped_session, sessionmaker
from werkzeug.exceptions import Forbidden, Unauthorized
@@ -23,7 +23,6 @@ from controllers.service_api.app.error import AgentNotPublishedError, AppUnavail
from controllers.service_api.app.site import AppSiteApi
from core.app.app_config.common.parameters_mapping import get_parameters_from_feature_dict
from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus
-from models.base import TypeBase
from models.model import App, AppMode
from services.app_definition_query_service import (
AppDefinitionNotPublishedError,
@@ -78,25 +77,17 @@ def flask_app() -> Flask:
@pytest.fixture
-def app_db(sqlite_engine: Engine, monkeypatch: pytest.MonkeyPatch) -> Iterator[AppDatabase]:
- """Create the minimal authentication schema and bind its database reference."""
-
- tables = [
- Tenant.__table__,
- Account.__table__,
- TenantAccountJoin.__table__,
- App.__table__,
- ]
- TypeBase.metadata.create_all(sqlite_engine, tables=tables)
- maker = sessionmaker(bind=sqlite_engine, expire_on_commit=False)
- registry = scoped_session(maker)
+def app_db(sqlite_session_factory: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch) -> Iterator[AppDatabase]:
+ """Bind the service-API database reference to the shared SQLite database."""
+
+ registry = scoped_session(sqlite_session_factory)
binding = _DatabaseBinding(session=registry)
monkeypatch.setattr("controllers.service_api.wraps.db", binding)
tenant_id = str(uuid4())
app_id = str(uuid4())
owner_id = str(uuid4())
- with maker.begin() as session:
+ with sqlite_session_factory.begin() as session:
tenant = Tenant(name="Visible tenant")
tenant.id = tenant_id
owner = Account(name="Test Author", email="[email protected]")
@@ -128,7 +119,7 @@ def app_db(sqlite_engine: Engine, monkeypatch: pytest.MonkeyPatch) -> Iterator[A
)
database = AppDatabase(
- session_maker=maker,
+ session_maker=sqlite_session_factory,
tenant_id=tenant_id,
app_id=app_id,
)
@@ -139,7 +130,7 @@ def app_db(sqlite_engine: Engine, monkeypatch: pytest.MonkeyPatch) -> Iterator[A
@pytest.fixture
-def authenticated_controller(app_db: AppDatabase, monkeypatch: pytest.MonkeyPatch) -> Iterator[AppDatabase]:
+def authenticated_controller(app_db: AppDatabase, monkeypatch: pytest.MonkeyPatch) -> AppDatabase:
"""Patch only token validation and Flask login signaling around real ORM auth."""
monkeypatch.setattr(
@@ -169,7 +160,7 @@ def test_get_parameters_queries_authenticated_app(
)
with flask_app.test_request_context("/parameters", headers={"Authorization": "Bearer token"}):
- response = AppParameterApi().get()
+ response = AppParameterApi().get(app_model=App())
app_definitions.get_public_parameters.assert_called_once_with(authenticated_controller.app_id)
assert response["opening_statement"] == "Hello"
@@ -199,14 +190,14 @@ def test_get_parameters_maps_query_errors(
with flask_app.test_request_context("/parameters", headers={"Authorization": "Bearer token"}):
with pytest.raises(http_error):
- AppParameterApi().get()
+ AppParameterApi().get(app_model=App())
def test_get_meta_queries_authenticated_app(
flask_app: Flask, authenticated_controller: AppDatabase, monkeypatch: pytest.MonkeyPatch
) -> None:
app_definitions = Mock()
- app_definitions.get_tool_icons.return_value = {}
+ app_definitions.get_tool_icons.return_value = dict[str, str]()
monkeypatch.setattr(
app_controller,
"application_services",
@@ -214,7 +205,7 @@ def test_get_meta_queries_authenticated_app(
)
with flask_app.test_request_context("/meta", headers={"Authorization": "Bearer token"}):
- response = AppMetaApi().get()
+ response = AppMetaApi().get(app_model=App())
app_definitions.get_tool_icons.assert_called_once_with(authenticated_controller.app_id)
assert response == {"tool_icons": {}}
@@ -234,7 +225,7 @@ def test_get_meta_maps_unavailable_definition_to_app_unavailable(
with flask_app.test_request_context("/meta", headers={"Authorization": "Bearer token"}):
with pytest.raises(AppUnavailableError) as raised:
- AppMetaApi().get()
+ AppMetaApi().get(app_model=App())
assert raised.value.data == {
"code": "app_unavailable",
@@ -263,7 +254,7 @@ def test_get_info_queries_authenticated_app(
)
with flask_app.test_request_context("/info", headers={"Authorization": "Bearer token"}):
- response = AppInfoApi().get()
+ response = AppInfoApi().get(app_model=App())
app_definitions.get_summary.assert_called_once_with(authenticated_controller.app_id)
assert response == {
@@ -290,7 +281,7 @@ def test_get_info_maps_unavailable_app(
with flask_app.test_request_context("/info", headers={"Authorization": "Bearer token"}):
with pytest.raises(AppUnavailableError):
- AppInfoApi().get()
+ AppInfoApi().get(app_model=App())
def test_get_site_configuration_queries_authenticated_app(
@@ -323,7 +314,7 @@ def test_get_site_configuration_queries_authenticated_app(
)
with flask_app.test_request_context("/site", headers={"Authorization": "Bearer token"}):
- response = AppSiteApi().get()
+ response = AppSiteApi().get(app_model=App())
app_definitions.get_site_configuration.assert_called_once_with(authenticated_controller.app_id)
assert response["title"] == "Test Site"
@@ -346,13 +337,14 @@ def test_get_site_configuration_maps_missing_site_to_forbidden(
with flask_app.test_request_context("/site", headers={"Authorization": "Bearer token"}):
with pytest.raises(Forbidden):
- AppSiteApi().get()
+ AppSiteApi().get(app_model=App())
@pytest.mark.parametrize("state", ["missing", "disabled", "archived", "ownerless"])
def test_authentication_rejects_empty_or_invisible_database_state(
flask_app: Flask,
authenticated_controller: AppDatabase,
+ sqlite_session: Session,
state: str,
) -> None:
expected_error: type[Exception] = Forbidden
@@ -363,10 +355,10 @@ def test_authentication_rejects_empty_or_invisible_database_state(
elif state == "archived":
authenticated_controller.update_tenant(status=TenantStatus.ARCHIVE)
else:
- with authenticated_controller.session_maker.begin() as session:
- session.execute(TenantAccountJoin.__table__.delete())
+ sqlite_session.execute(delete(TenantAccountJoin))
+ sqlite_session.commit()
expected_error = Unauthorized
with flask_app.test_request_context("/info", headers={"Authorization": "Bearer token"}):
with pytest.raises(expected_error):
- AppInfoApi().get()
+ AppInfoApi().get(app_model=App())
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 75a0b2b617f..635aa359f01 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -21,7 +21,6 @@ project-excludes = [
"controllers/console/app/test_model_config.py",
"controllers/console/app/test_workflow.py",
"controllers/console/app/test_workflow_node_output_inspector.py",
- "controllers/console/app/test_workflow_run.py",
"controllers/console/app/test_wraps.py",
"fields/test_workflow_draft_variable_fields.py",
"controllers/console/auth/test_activate.py",
@@ -30,7 +29,6 @@ project-excludes = [
"controllers/console/datasets/rag_pipeline/test_rag_pipeline.py",
"controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py",
"controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py",
- "controllers/console/datasets/test_data_source.py",
"controllers/console/datasets/test_datasets.py",
"controllers/console/datasets/test_datasets_document.py",
"controllers/console/datasets/test_external.py",
@@ -38,7 +36,6 @@ project-excludes = [
"controllers/console/datasets/test_hit_testing_base.py",
"controllers/console/datasets/test_metadata.py",
"controllers/console/snippets/test_snippet_workflow.py",
- "controllers/console/tag/test_tags.py",
"controllers/console/test_files.py",
"controllers/console/test_human_input_form.py",
"controllers/console/test_wraps.py",
@@ -49,7 +46,6 @@ project-excludes = [
"controllers/console/workspace/test_snippets.py",
"controllers/console/workspace/test_tool_providers.py",
"controllers/files/test_upload_file_delivery.py",
- "controllers/inner_api/plugin/test_agent_config.py",
"controllers/inner_api/plugin/test_plugin.py",
"controllers/inner_api/plugin/test_wraps.py",
"controllers/inner_api/knowledge/test_retrieval.py",
@@ -61,7 +57,6 @@ project-excludes = [
"controllers/openapi/test_human_input_form.py",
"controllers/openapi/test_workflow_events.py",
"controllers/openapi/test_workspaces.py",
- "controllers/service_api/app/test_app.py",
"controllers/service_api/app/test_audio.py",
"controllers/service_api/app/test_completion.py",
"controllers/service_api/app/test_file.py",