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 console controller tests (#43932)

Eddy ZHANG7b69dea2c802
diff --git a/api/tests/unit_tests/controllers/console/test_extension.py b/api/tests/unit_tests/controllers/console/test_extension.py
index 4497c505874..93cb11d5cd2 100644
--- a/api/tests/unit_tests/controllers/console/test_extension.py
+++ b/api/tests/unit_tests/controllers/console/test_extension.py
@@ -176,7 +176,7 @@ class TestAPIBasedExtensionAPI:
)
with app.test_request_context("/console/api/api-based-extension", method="POST"):
- response, status = unwrap(APIBasedExtensionAPI().post)(APIBasedExtensionAPI(), payload, request_context)
+ result = unwrap(APIBasedExtensionAPI().post)(APIBasedExtensionAPI(), payload, request_context)
extensions_service.create_extension.assert_called_once_with(
request_context,
@@ -184,7 +184,10 @@ class TestAPIBasedExtensionAPI:
name="Docs API", api_endpoint="https://docs.example.com/hook", api_key="plain-secret"
),
)
+ assert isinstance(result, tuple)
+ response, status = result
assert status == 201
+ assert isinstance(response, dict)
assert response["id"] == created.id
assert response["name"] == "Docs API"
assert response["api_key"] == _masked_api_key("plain-secret")
@@ -214,6 +217,7 @@ class TestAPIBasedExtensionDetailAPI:
)
extensions_service.get_extension.assert_called_once_with(request_context, str(extension_id))
+ assert isinstance(response, dict)
assert response["id"] == extension.id
assert response["name"] == "Docs API"
assert response["api_key"] == _masked_api_key("abcdefg12345")
@@ -248,6 +252,7 @@ class TestAPIBasedExtensionDetailAPI:
str(extension_id),
APIBasedExtensionUpdate(name="Docs API Updated", api_endpoint="https://docs.example.com/v2", api_key=None),
)
+ assert isinstance(response, dict)
assert response["name"] == "Docs API Updated"
assert response["api_key"] == _masked_api_key("keep-me")
@@ -268,6 +273,7 @@ class TestAPIBasedExtensionDetailAPI:
update = extensions_service.update_extension.call_args.args[2]
assert update.api_key == "new-secret"
+ assert isinstance(response, dict)
assert response["api_key"] == _masked_api_key("new-secret")
def test_delete_removes_extension(
@@ -276,11 +282,13 @@ class TestAPIBasedExtensionDetailAPI:
extension_id = uuid.uuid4()
with app.test_request_context(f"/console/api/api-based-extension/{extension_id}", method="DELETE"):
- response, status = unwrap(APIBasedExtensionDetailAPI().delete)(
+ result = unwrap(APIBasedExtensionDetailAPI().delete)(
APIBasedExtensionDetailAPI(), request_context, extension_id
)
extensions_service.delete_extension.assert_called_once_with(request_context, str(extension_id))
+ assert isinstance(result, tuple)
+ response, status = result
assert status == 204
assert response == ""
diff --git a/api/tests/unit_tests/controllers/console/test_files_security.py b/api/tests/unit_tests/controllers/console/test_files_security.py
index 7bab15a5a95..3f120feb4ae 100644
--- a/api/tests/unit_tests/controllers/console/test_files_security.py
+++ b/api/tests/unit_tests/controllers/console/test_files_security.py
@@ -21,7 +21,7 @@ class TestFileUploadSecurity:
"""Test file upload security logic without complex framework setup"""
# Test 1: Basic file validation
- def test_should_validate_file_presence(self):
+ def test_should_validate_file_presence(self) -> None:
"""Test that missing file is detected"""
from flask import Flask, request
@@ -33,7 +33,7 @@ class TestFileUploadSecurity:
with pytest.raises(NoFileUploadedError):
raise NoFileUploadedError()
- def test_should_validate_multiple_files(self):
+ def test_should_validate_multiple_files(self) -> None:
"""Test that multiple files are rejected"""
from flask import Flask, request
@@ -50,7 +50,7 @@ class TestFileUploadSecurity:
with pytest.raises(TooManyFilesError):
raise TooManyFilesError()
- def test_should_validate_empty_filename(self):
+ def test_should_validate_empty_filename(self) -> None:
"""Test that empty filename is rejected"""
from flask import Flask, request
@@ -65,7 +65,7 @@ class TestFileUploadSecurity:
raise FilenameNotExistsError
# Test 2: Security - Filename sanitization
- def test_should_detect_path_traversal_in_filename(self):
+ def test_should_detect_path_traversal_in_filename(self) -> None:
"""Test protection against directory traversal attacks"""
dangerous_filenames = [
"../../../etc/passwd",
@@ -78,7 +78,7 @@ class TestFileUploadSecurity:
# Any filename containing .. should be considered dangerous
assert ".." in filename, f"Filename {filename} should be detected as path traversal"
- def test_should_detect_null_byte_injection(self):
+ def test_should_detect_null_byte_injection(self) -> None:
"""Test protection against null byte injection"""
dangerous_filenames = [
"file.jpg\x00.php",
@@ -90,7 +90,7 @@ class TestFileUploadSecurity:
# Null bytes should be detected
assert "\x00" in filename, f"Filename {filename} should be detected as null byte injection"
- def test_should_sanitize_special_characters(self):
+ def test_should_sanitize_special_characters(self) -> None:
"""Test that special characters in filenames are handled safely"""
# Characters that could be problematic in various contexts
dangerous_chars = ["/", "\\", ":", "*", "?", '"', "<", ">", "|", "\x00"]
@@ -101,7 +101,7 @@ class TestFileUploadSecurity:
assert any(c in filename for c in dangerous_chars)
# Test 3: Permission validation
- def test_should_validate_dataset_permissions(self):
+ def test_should_validate_dataset_permissions(self) -> None:
"""Test dataset upload permission logic"""
user = Account(name="Viewer", email="[email protected]", status=AccountStatus.ACTIVE)
user.role = TenantAccountRole.NORMAL
@@ -112,7 +112,7 @@ class TestFileUploadSecurity:
with pytest.raises(Forbidden):
raise Forbidden()
- def test_should_allow_general_upload_without_permission(self):
+ def test_should_allow_general_upload_without_permission(self) -> None:
"""Test general upload doesn't require dataset permission"""
user = Account(name="Viewer", email="[email protected]", status=AccountStatus.ACTIVE)
user.role = TenantAccountRole.NORMAL
@@ -124,7 +124,7 @@ class TestFileUploadSecurity:
# Test passes if no exception is raised
# Test 4: File type security
- def test_should_identify_dangerous_file_extensions(self):
+ def test_should_identify_dangerous_file_extensions(self) -> None:
"""Test detection of potentially dangerous file extensions"""
dangerous_extensions = [
".php",
@@ -155,7 +155,7 @@ class TestFileUploadSecurity:
for ext in safe_extensions:
assert ext.lower() not in [".php", ".exe", ".sh", ".bat", ".cmd", ".ps1", ".jar", ".vbs"]
- def test_should_detect_double_extensions(self):
+ def test_should_detect_double_extensions(self) -> None:
"""Test detection of double extension attacks"""
suspicious_filenames = [
"image.jpg.php",
@@ -170,7 +170,7 @@ class TestFileUploadSecurity:
assert len(parts) > 2, f"Filename {filename} should have multiple extensions"
# Test 5: Configuration validation
- def test_upload_configuration_structure(self):
+ def test_upload_configuration_structure(self) -> None:
"""Test that upload configuration has correct structure"""
# Simulate the configuration returned by FileApi.get()
config = {
@@ -198,7 +198,7 @@ class TestFileUploadSecurity:
assert config[field] > 0, f"Field {field} should be positive"
# Test 7: Source parameter handling
- def test_source_parameter_normalization(self):
+ def test_source_parameter_normalization(self) -> None:
"""Test that source parameter is properly normalized"""
test_cases = [
("datasets", "datasets"),
@@ -215,7 +215,7 @@ class TestFileUploadSecurity:
assert source == expected
# Test 8: Boundary conditions
- def test_should_handle_edge_case_file_sizes(self):
+ def test_should_handle_edge_case_file_sizes(self) -> None:
"""Test handling of boundary file sizes"""
test_cases = [
(0, "Empty file"), # 0 bytes
@@ -230,7 +230,7 @@ class TestFileUploadSecurity:
assert isinstance(size, int), f"{description}: Size should be integer"
assert size >= 0, f"{description}: Size should be non-negative"
- def test_should_handle_special_mime_types(self):
+ def test_should_handle_special_mime_types(self) -> None:
"""Test handling of various MIME types"""
mime_type_tests = [
("application/octet-stream", "Generic binary"),
diff --git a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py
index a67c64f850f..852c2ca9e6c 100644
--- a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py
+++ b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py
@@ -9,6 +9,7 @@ from unittest.mock import MagicMock
import pytest
from flask import Flask
from werkzeug.exceptions import Conflict, Forbidden, NotFound
+from werkzeug.wrappers import Response
from controllers.console import flask_admission, workflow_run_archive
from controllers.console.workflow_run_archive import (
@@ -53,7 +54,7 @@ def _account(role: TenantAccountRole) -> Account:
return make_account(name="Test User", email="[email protected]", role=role)
-def _original(method):
+def _original(method: Callable[..., object]) -> Callable[..., object]:
while hasattr(method, "__wrapped__"):
method = method.__wrapped__
return method
@@ -134,7 +135,7 @@ def test_workflow_run_archive_endpoint_allows_admitted_role_when_rbac_is_enabled
monkeypatch.setattr(flask_admission, "current_account_with_tenant", lambda: account_with_tenant)
monkeypatch.setattr("controllers.console.wraps.current_account_with_tenant", lambda: account_with_tenant)
- def get_billing_info(tenant_id: str, *, exclude_vector_space: bool):
+ def get_billing_info(tenant_id: str, *, exclude_vector_space: bool) -> dict[str, object]:
assert tenant_id == "tenant-1"
assert exclude_vector_space
return {
@@ -228,7 +229,7 @@ def test_workflow_run_archive_endpoints_delegate_to_application_service(
)
def test_workflow_run_archive_endpoints_translate_service_errors(
monkeypatch: pytest.MonkeyPatch,
- method,
+ method: Callable[..., object],
service_method: str,
service_error: Exception,
http_error: type[Exception],
@@ -259,5 +260,6 @@ def test_workflow_run_archive_file_redirects_to_signed_url(monkeypatch: pytest.M
with app.test_request_context():
response = _original(WorkflowRunArchiveDownloadFileApi.get)(None, _CONTEXT, "download-1")
+ assert isinstance(response, Response)
assert response.status_code == 302
assert response.location == "https://storage.example.com/archive.zip"
diff --git a/api/tests/unit_tests/controllers/console/test_workspace_account.py b/api/tests/unit_tests/controllers/console/test_workspace_account.py
index bd4e0b18f30..60e0bb821a3 100644
--- a/api/tests/unit_tests/controllers/console/test_workspace_account.py
+++ b/api/tests/unit_tests/controllers/console/test_workspace_account.py
@@ -6,6 +6,7 @@ from uuid import NAMESPACE_URL, uuid5
import pytest
from flask import Flask, request
from sqlalchemy.orm import Session
+from typing_extensions import TypedDict
from controllers.console.auth.error import InvalidTokenError
from controllers.console.error import EducationActivateLimitError, EducationVerifyLimitError, EmailDomainSuspendedError
@@ -36,11 +37,12 @@ from services.entities.auth_entities import (
ChangeEmailOldEmailToken,
ChangeEmailOldEmailVerifiedToken,
ChangeEmailPhase,
+ ChangeEmailTokenBase,
)
@pytest.fixture
-def app():
+def app() -> Flask:
app = Flask(__name__)
app.config["TESTING"] = True
app.config["RESTX_MASK_HEADER"] = "X-Fields"
@@ -86,6 +88,13 @@ def _persist_account_with_tenant(session: Session, email: str, account_name: str
return account, tenant
+class _ChangeEmailTokenKwargs(TypedDict, closed=True):
+ account_id: str
+ email: str
+ old_email: str
+ code: str
+
+
def _build_change_email_token(
phase: str,
*,
@@ -93,8 +102,8 @@ def _build_change_email_token(
email: str,
old_email: str,
code: str = "1234",
-):
- token_kwargs = {
+) -> ChangeEmailTokenBase:
+ token_kwargs: _ChangeEmailTokenKwargs = {
"account_id": account_id,
"email": email,
"old_email": old_email,
@@ -112,7 +121,7 @@ def _build_change_email_token(
class TestEducationApi:
- def test_post_activates_education_discount(self, app: Flask):
+ def test_post_activates_education_discount(self, app: Flask) -> None:
education = MagicMock()
education.activate.return_value = AccountEducationActivation(message="success")
request_context = RequestContext(
@@ -145,7 +154,7 @@ class TestEducationApi:
role="Student",
)
- def test_verify_maps_rate_limit_error(self, app: Flask):
+ def test_verify_maps_rate_limit_error(self, app: Flask) -> None:
education = MagicMock()
education.verify.side_effect = account_errors.EducationRateLimitExceededError
request_context = RequestContext(
@@ -166,7 +175,7 @@ class TestEducationApi:
with pytest.raises(EducationVerifyLimitError):
inspect.unwrap(api.get)(api, request_context)
- def test_post_maps_rate_limit_error(self, app: Flask):
+ def test_post_maps_rate_limit_error(self, app: Flask) -> None:
education = MagicMock()
education.activate.side_effect = account_errors.EducationRateLimitExceededError
request_context = RequestContext(
@@ -204,7 +213,7 @@ def _change_email_context(account_id: str = "acc") -> RequestContext:
class TestChangeEmailControllers:
- def test_send_delegates_parsed_request_to_application_service(self, app: Flask):
+ def test_send_delegates_parsed_request_to_application_service(self, app: Flask) -> None:
change_email = MagicMock()
change_email.send_code.return_value = "change-token"
context = _change_email_context()
@@ -242,7 +251,7 @@ class TestChangeEmailControllers:
ip_address="127.0.0.1",
)
- def test_send_maps_invalid_state_to_http_error(self, app: Flask):
+ def test_send_maps_invalid_state_to_http_error(self, app: Flask) -> None:
change_email = MagicMock()
change_email.send_code.side_effect = account_errors.InvalidChangeEmailTokenError
@@ -262,7 +271,7 @@ class TestChangeEmailControllers:
with pytest.raises(InvalidTokenError):
method(api, ChangeEmailSendPayload.model_validate(request.get_json() or {}), _change_email_context())
- def test_validity_serializes_promoted_token(self, app: Flask):
+ def test_validity_serializes_promoted_token(self, app: Flask) -> None:
change_email = MagicMock()
change_email.verify_code.return_value = ChangeEmailVerification(
@@ -294,7 +303,7 @@ class TestChangeEmailControllers:
token="pending-token",
)
- def test_reset_returns_updated_account(self, app: Flask):
+ def test_reset_returns_updated_account(self, app: Flask) -> None:
change_email = MagicMock()
updated_account = _build_account("[email protected]", "acc")
change_email.reset.return_value = updated_account
@@ -323,7 +332,7 @@ class TestChangeEmailControllers:
token="verified-token",
)
- def test_reset_maps_suspended_email_domain(self, app: Flask):
+ def test_reset_maps_suspended_email_domain(self, app: Flask) -> None:
change_email = MagicMock()
change_email.reset.side_effect = account_errors.AccountEmailDomainSuspendedError
@@ -346,7 +355,7 @@ class TestChangeEmailControllers:
class TestAccountDeletionFeedback:
- def test_delegates_feedback_to_application_service(self, app: Flask):
+ def test_delegates_feedback_to_application_service(self, app: Flask) -> None:
deletion_feedback = MagicMock()
with (
app.test_request_context(
@@ -370,7 +379,7 @@ class TestAccountDeletionFeedback:
class TestCheckEmailUnique:
- def test_delegates_to_email_availability_policy(self, app: Flask):
+ def test_delegates_to_email_availability_policy(self, app: Flask) -> None:
change_email = MagicMock()
with (
@@ -390,7 +399,7 @@ class TestCheckEmailUnique:
assert response == {"result": "success"}
change_email.ensure_available.assert_called_once_with("[email protected]")
- def test_maps_suspended_email_domain(self, app: Flask):
+ def test_maps_suspended_email_domain(self, app: Flask) -> None:
change_email = MagicMock()
change_email.ensure_available.side_effect = account_errors.AccountEmailDomainSuspendedError
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_load_balancing_config.py b/api/tests/unit_tests/controllers/console/workspace/test_load_balancing_config.py
index 986a4f35c52..7c476f35d6c 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_load_balancing_config.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_load_balancing_config.py
@@ -5,6 +5,8 @@ from __future__ import annotations
import builtins
import importlib
import sys
+from collections.abc import Callable
+from types import ModuleType
from unittest.mock import ANY, MagicMock
import pytest
@@ -30,13 +32,13 @@ def app() -> Flask:
@pytest.fixture
-def load_balancing_module(monkeypatch: pytest.MonkeyPatch):
+def load_balancing_module(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
"""Reload controller module with lightweight decorators for testing."""
from controllers.console import console_ns, wraps
from libs import login
- def _noop(func):
+ def _noop(func: Callable[..., object]) -> Callable[..., object]:
return func
monkeypatch.setattr(login, "login_required", _noop)
@@ -44,7 +46,7 @@ def load_balancing_module(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(wraps, "account_initialization_required", _noop)
def _noop_route[**P](*args: P.args, **kwargs: P.kwargs): # type: ignore[override]
- def _decorator(cls):
+ def _decorator(cls: type) -> type:
return cls
return _decorator
@@ -61,7 +63,9 @@ def _account(role: TenantAccountRole) -> Account:
return make_account(name="Owner", email="[email protected]", role=role)
-def _prepare_context(module, monkeypatch: pytest.MonkeyPatch, role=TenantAccountRole.OWNER):
+def _prepare_context(
+ module: ModuleType, monkeypatch: pytest.MonkeyPatch, role: TenantAccountRole = TenantAccountRole.OWNER
+) -> MagicMock:
user = _account(role)
from controllers.console import wraps
@@ -71,11 +75,13 @@ def _prepare_context(module, monkeypatch: pytest.MonkeyPatch, role=TenantAccount
return mock_service
-def _request_payload():
+def _request_payload() -> dict[str, object]:
return {"model": "gpt-4o", "model_type": ModelType.LLM, "credentials": {"api_key": "sk-***"}}
-def test_validate_credentials_success(app: Flask, load_balancing_module, monkeypatch: pytest.MonkeyPatch):
+def test_validate_credentials_success(
+ app: Flask, load_balancing_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
service = _prepare_context(load_balancing_module, monkeypatch)
with app.test_request_context(
@@ -96,7 +102,9 @@ def test_validate_credentials_success(app: Flask, load_balancing_module, monkeyp
)
-def test_validate_credentials_returns_error_message(app: Flask, load_balancing_module, monkeypatch: pytest.MonkeyPatch):
+def test_validate_credentials_returns_error_message(
+ app: Flask, load_balancing_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
service = _prepare_context(load_balancing_module, monkeypatch)
service.validate_load_balancing_credentials.side_effect = CredentialsValidateFailedError("invalid credentials")
@@ -111,8 +119,8 @@ def test_validate_credentials_returns_error_message(app: Flask, load_balancing_m
def test_validate_credentials_requires_privileged_role(
- app: Flask, load_balancing_module, monkeypatch: pytest.MonkeyPatch
-):
+ app: Flask, load_balancing_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
_prepare_context(load_balancing_module, monkeypatch, role=TenantAccountRole.NORMAL)
with app.test_request_context(
@@ -125,7 +133,9 @@ def test_validate_credentials_requires_privileged_role(
api.post(provider="openai")
-def test_validate_credentials_with_config_id(app: Flask, load_balancing_module, monkeypatch: pytest.MonkeyPatch):
+def test_validate_credentials_with_config_id(
+ app: Flask, load_balancing_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
service = _prepare_context(load_balancing_module, monkeypatch)
with app.test_request_context(
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 6c81589dbae..65f91eaf15a 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -92,25 +92,20 @@ project-excludes = [
"controllers/console/snippets/test_snippet_workflow_draft_variable.py",
"controllers/console/tag/test_tags.py",
"controllers/console/test_document_detail_api_data_source_info.py",
- "controllers/console/test_extension.py",
"controllers/console/test_fastopenapi_ping.py",
"controllers/console/test_fastopenapi_setup.py",
"controllers/console/test_fastopenapi_version.py",
"controllers/console/test_feature.py",
"controllers/console/test_files.py",
- "controllers/console/test_files_security.py",
"controllers/console/test_human_input_form.py",
"controllers/console/test_knowledge_fs_proxy.py",
"controllers/console/test_remote_files.py",
"controllers/console/test_spec.py",
"controllers/console/test_version.py",
- "controllers/console/test_workflow_run_archive.py",
- "controllers/console/test_workspace_account.py",
"controllers/console/test_wraps.py",
"controllers/console/workspace/test_accounts.py",
"controllers/console/workspace/test_agent_providers.py",
"controllers/console/workspace/test_endpoint.py",
- "controllers/console/workspace/test_load_balancing_config.py",
"controllers/console/workspace/test_members.py",
"controllers/console/workspace/test_model_providers.py",
"controllers/console/workspace/test_plugin.py",