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 file fetcher, common controller and app factory tests (#44379)

Eddy ZHANGa491dabb32d6
diff --git a/api/tests/unit_tests/.ruff.toml b/api/tests/unit_tests/.ruff.toml
index 36cb20d72e3..bc2dc76e53b 100644
--- a/api/tests/unit_tests/.ruff.toml
+++ b/api/tests/unit_tests/.ruff.toml
@@ -10,7 +10,6 @@ extend-select = ["ANN401", "ARG"]
"commands/test_archive_workflow_runs.py" = ["ARG005"]
"commands/test_legacy_model_type_migration.py" = ["ARG001", "ARG002", "ARG005"]
"repositories/test_app_definition_query_repository_agent.py" = ["ARG005", "TID251"]
-"controllers/common/test_app_access.py" = ["ARG005"]
"controllers/console/agent/test_agent_controllers.py" = ["ARG001", "ARG002", "ARG003", "ARG005", "TID251"]
"controllers/console/app/test_agent_config_inspector.py" = ["ARG005"]
"controllers/console/app/test_agent_manage_guard.py" = ["ARG001"]
@@ -323,7 +322,6 @@ extend-select = ["ANN401", "ARG"]
"tasks/test_process_tenant_plugin_autoupgrade_check_task.py" = ["ARG001"]
"tasks/test_remove_app_and_related_data_task.py" = ["ARG002"]
"tasks/test_workflow_execute_task.py" = ["ARG005"]
-"test_app_factory.py" = ["ARG001"]
"test_pytest_dify.py" = ["ARG001"]
"tools/test_mcp_tool.py" = ["TID251"]
diff --git a/api/tests/unit_tests/controllers/common/test_app_access.py b/api/tests/unit_tests/controllers/common/test_app_access.py
index 2caae866da5..5893c1f1865 100644
--- a/api/tests/unit_tests/controllers/common/test_app_access.py
+++ b/api/tests/unit_tests/controllers/common/test_app_access.py
@@ -39,26 +39,26 @@ def _permissions(
class TestHasAppListPermission:
- def test_matches_known_preview_keys(self):
+ def test_matches_known_preview_keys(self) -> None:
for key in APP_LIST_PERMISSION_KEYS:
assert has_app_list_permission([key])
- def test_rejects_unknown_keys(self):
+ def test_rejects_unknown_keys(self) -> None:
assert not has_app_list_permission(["app.export", "app.delete"])
assert not has_app_list_permission([])
class TestAppAccessFilterIsAppAccessible:
- def test_unrestricted_sees_everything(self):
+ def test_unrestricted_sees_everything(self) -> None:
flt = AppAccessFilter.unrestricted()
assert flt.is_app_accessible("app-1", maintainer="someone", account_id="acc-1")
- def test_whitelisted_app_is_visible(self):
+ def test_whitelisted_app_is_visible(self) -> None:
flt = AppAccessFilter(accessible_app_ids={"app-1"}, can_manage_own_apps=False)
assert flt.is_app_accessible("app-1", maintainer=None, account_id="acc-1")
assert not flt.is_app_accessible("app-2", maintainer=None, account_id="acc-1")
- def test_own_app_visible_only_with_manage_permission(self):
+ def test_own_app_visible_only_with_manage_permission(self) -> None:
own = AppAccessFilter(accessible_app_ids=set(), can_manage_own_apps=True)
assert own.is_app_accessible("app-1", maintainer="acc-1", account_id="acc-1")
assert not own.is_app_accessible("app-1", maintainer="acc-2", account_id="acc-1")
@@ -68,20 +68,20 @@ class TestAppAccessFilterIsAppAccessible:
class TestAppAccessFilterApplyToParams:
- def test_unrestricted_leaves_params_untouched(self):
+ def test_unrestricted_leaves_params_untouched(self) -> None:
params = AppListParams()
AppAccessFilter.unrestricted().apply_to_params(params)
assert params.accessible_app_ids is None
assert params.include_own_apps is False
assert params.is_created_by_me is None
- def test_whitelisted_ids_are_sorted_with_own_apps_flag(self):
+ def test_whitelisted_ids_are_sorted_with_own_apps_flag(self) -> None:
params = AppListParams()
AppAccessFilter(accessible_app_ids={"b", "a"}, can_manage_own_apps=True).apply_to_params(params)
assert params.accessible_app_ids == ["a", "b"]
assert params.include_own_apps is True
- def test_empty_set_with_manage_falls_back_to_maintained_apps(self):
+ def test_empty_set_with_manage_falls_back_to_maintained_apps(self) -> None:
# Own-app fallback must use maintainer (include_own_apps), consistent
# with is_app_accessible — not created_by (is_created_by_me).
params = AppListParams()
@@ -90,7 +90,7 @@ class TestAppAccessFilterApplyToParams:
assert params.include_own_apps is True
assert params.is_created_by_me is None
- def test_empty_set_without_manage_sees_nothing(self):
+ def test_empty_set_without_manage_sees_nothing(self) -> None:
params = AppListParams()
AppAccessFilter(accessible_app_ids=set(), can_manage_own_apps=False).apply_to_params(params)
assert params.accessible_app_ids == []
@@ -102,10 +102,10 @@ class TestResolveAppAccessFilter:
def _patch_whitelist(self, monkeypatch: pytest.MonkeyPatch, whitelist: ResourceWhitelistResources) -> None:
monkeypatch.setattr(
f"{_RBAC_MODULE}.RBACService.AppAccess.whitelist_resources",
- lambda tenant_id, account_id: whitelist,
+ lambda *_args, **_kwargs: whitelist,
)
- def test_default_preview_is_unrestricted(self):
+ def test_default_preview_is_unrestricted(self) -> None:
permissions = _permissions(app_default_keys=["app.preview"])
flt = app_access_filter_from_permissions(permissions, ResourceWhitelistResources(unrestricted=True))
@@ -113,7 +113,7 @@ class TestResolveAppAccessFilter:
assert flt.accessible_app_ids is None
assert flt.can_manage_own_apps is False
- def test_restricted_whitelist_overrides_default_preview(self):
+ def test_restricted_whitelist_overrides_default_preview(self) -> None:
permissions = _permissions(
workspace_keys=["app.full_access", "app.create_and_management"],
)
@@ -125,7 +125,7 @@ class TestResolveAppAccessFilter:
assert flt.accessible_app_ids == {"app-9"}
assert flt.can_manage_own_apps is False
- def test_override_apps_collected_without_default_preview(self):
+ def test_override_apps_collected_without_default_preview(self) -> None:
permissions = _permissions(
app_overrides=[
ResourcePermissionKeys(resource_id="app-1", permission_keys=["app.preview"]),
@@ -137,7 +137,7 @@ class TestResolveAppAccessFilter:
assert flt.accessible_app_ids == {"app-1"}
- def test_restricted_whitelist_ignores_override_apps(self):
+ def test_restricted_whitelist_ignores_override_apps(self) -> None:
permissions = _permissions(
app_overrides=[ResourcePermissionKeys(resource_id="app-1", permission_keys=["app.acl.preview"])],
)
@@ -148,11 +148,11 @@ class TestResolveAppAccessFilter:
assert flt.accessible_app_ids == {"app-5"}
- def test_fetches_permissions_when_not_supplied(self, monkeypatch: pytest.MonkeyPatch):
+ def test_fetches_permissions_when_not_supplied(self, monkeypatch: pytest.MonkeyPatch) -> None:
self._patch_whitelist(monkeypatch, ResourceWhitelistResources(unrestricted=False, resource_ids=[]))
captured: dict[str, object] = {}
- def get_permissions(tenant_id: str, account_id: str):
+ def get_permissions(tenant_id: str, account_id: str) -> MyPermissionsResponse:
captured.update(tenant_id=tenant_id, account_id=account_id)
return _permissions(workspace_keys=["app.create_and_management"])
diff --git a/api/tests/unit_tests/controllers/common/test_fields.py b/api/tests/unit_tests/controllers/common/test_fields.py
index 830c587f1f5..1d0dd8a9462 100644
--- a/api/tests/unit_tests/controllers/common/test_fields.py
+++ b/api/tests/unit_tests/controllers/common/test_fields.py
@@ -1,19 +1,11 @@
-import builtins
from unittest.mock import patch
-from flask.views import MethodView as FlaskMethodView
-
from controllers.common.fields import Parameters, Site
from core.app.app_config.common.parameters_mapping import get_parameters_from_feature_dict
from models.model import IconType
-_NEEDS_METHOD_VIEW_CLEANUP = False
-if not hasattr(builtins, "MethodView"):
- builtins.MethodView = FlaskMethodView
- _NEEDS_METHOD_VIEW_CLEANUP = True
-
-def test_parameters_model_round_trip():
+def test_parameters_model_round_trip() -> None:
parameters = get_parameters_from_feature_dict(features_dict={}, user_input_form=[])
model = Parameters.model_validate(parameters)
@@ -21,7 +13,7 @@ def test_parameters_model_round_trip():
assert model.model_dump(mode="json") == parameters
-def test_site_icon_url_uses_signed_url_for_image_icon():
+def test_site_icon_url_uses_signed_url_for_image_icon() -> None:
site = Site(
title="Example",
chat_color_theme=None,
@@ -45,7 +37,7 @@ def test_site_icon_url_uses_signed_url_for_image_icon():
mock_helper.assert_called_once_with("file-id")
-def test_site_icon_url_is_none_for_non_image_icon():
+def test_site_icon_url_is_none_for_non_image_icon() -> None:
site = Site(
title="Example",
chat_color_theme=None,
diff --git a/api/tests/unit_tests/controllers/common/test_session.py b/api/tests/unit_tests/controllers/common/test_session.py
index 888738bdfd6..c8f2f3d49eb 100644
--- a/api/tests/unit_tests/controllers/common/test_session.py
+++ b/api/tests/unit_tests/controllers/common/test_session.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+from collections.abc import Generator
from contextlib import contextmanager
+from typing import NoReturn
from unittest.mock import patch
import pytest
@@ -13,7 +15,7 @@ from models import Tenant
@contextmanager
-def _bind_session_factory(session: Session):
+def _bind_session_factory(session: Session) -> Generator[None]:
database_session_factory = sessionmaker(
bind=session.get_bind(),
expire_on_commit=False,
@@ -34,7 +36,7 @@ def test_with_session_write_commits_on_success(sqlite_session: Session) -> None:
class Handler:
@session_module.with_session(write=True)
- def post(self, session: Session):
+ def post(self, session: Session) -> str:
nonlocal commit_observed, injected_session
injected_session = session
@@ -59,7 +61,7 @@ def test_with_session_write_commits_on_success(sqlite_session: Session) -> None:
def test_with_session_default_write_commits_on_success(sqlite_session: Session) -> None:
class Handler:
@session_module.with_session
- def post(self, session: Session):
+ def post(self, session: Session) -> str:
session.add(Tenant(name="default write tenant"))
return "ok"
@@ -76,7 +78,7 @@ def test_with_session_write_rolls_back_on_error(sqlite_session: Session) -> None
class Handler:
@session_module.with_session(write=True)
- def get(self, session: Session):
+ def get(self, session: Session) -> NoReturn:
nonlocal rollback_observed, injected_session
injected_session = session
@@ -103,7 +105,7 @@ def test_with_session_write_allows_commit_then_more_database_work(sqlite_engine:
class Handler:
@session_module.with_session
- def post(self, session: Session):
+ def post(self, session: Session) -> int | None:
session.commit()
return session.scalar(select(literal(1)))
@@ -116,7 +118,7 @@ def test_with_session_read_mode_does_not_commit(sqlite_session: Session) -> None
class Handler:
@session_module.with_session(write=False)
- def get(self, session: Session):
+ def get(self, session: Session) -> str:
nonlocal injected_session
injected_session = session
session.add(Tenant(name="uncommitted read tenant"))
@@ -134,7 +136,7 @@ def test_with_session_read_mode_does_not_commit(sqlite_session: Session) -> None
def test_with_session_preserves_wrapped_metadata() -> None:
class Handler:
@session_module.with_session
- def get(self, _session: Session):
+ def get(self, _session: Session) -> str:
"""handler docs"""
return "ok"
diff --git a/api/tests/unit_tests/core/file/test_models.py b/api/tests/unit_tests/core/file/test_models.py
index 8cb09385755..446a8c2f56d 100644
--- a/api/tests/unit_tests/core/file/test_models.py
+++ b/api/tests/unit_tests/core/file/test_models.py
@@ -1,7 +1,7 @@
from graphon.file import File, FileTransferMethod, FileType
-def test_file():
+def test_file() -> None:
file = File(
file_id="test-file",
tenant_id="test-tenant-id",
@@ -25,7 +25,7 @@ def test_file():
assert file.size == 67
-def test_file_constructor_accepts_legacy_tenant_id():
+def test_file_constructor_accepts_legacy_tenant_id() -> None:
file = File(
file_id="test-file",
tenant_id="test-tenant-id",
diff --git a/api/tests/unit_tests/core/file/test_remote_fetcher.py b/api/tests/unit_tests/core/file/test_remote_fetcher.py
index 5351efb8ab7..cdaf98bbd5c 100644
--- a/api/tests/unit_tests/core/file/test_remote_fetcher.py
+++ b/api/tests/unit_tests/core/file/test_remote_fetcher.py
@@ -38,7 +38,9 @@ class FileDatabase:
@pytest.fixture(autouse=True)
def file_database(monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine) -> Iterator[FileDatabase]:
"""Persist file records and bind remote-fetcher sessions to SQLite."""
- UploadFile.metadata.create_all(sqlite_engine, tables=[UploadFile.__table__, ToolFile.__table__])
+ UploadFile.metadata.create_all(
+ sqlite_engine, tables=[model.metadata.tables[model.__tablename__] for model in (UploadFile, ToolFile)]
+ )
sqlite_session_maker = sessionmaker(bind=sqlite_engine, expire_on_commit=False)
monkeypatch.setattr("core.db.session_factory._session_maker", sqlite_session_maker)
@@ -83,7 +85,7 @@ def file_database(monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine) -> Ite
statements: list[str] = []
- def record_statement(_connection, _cursor, statement, _parameters, _context, _executemany) -> None:
+ def record_statement(_connection, _cursor, statement: str, _parameters, _context, _executemany) -> None:
statements.append(statement)
with sqlite_session_maker() as session:
@@ -131,19 +133,19 @@ def _file_fetcher_config(monkeypatch: pytest.MonkeyPatch, config_overrides: Call
monkeypatch.setattr(remote_fetcher.time, "time", lambda: 1700000100)
-def _patch_ssrf_make_request(monkeypatch: pytest.MonkeyPatch, response=None):
+def _patch_ssrf_make_request(monkeypatch: pytest.MonkeyPatch, response: httpx.Response | None = None) -> MagicMock:
make_request = MagicMock(return_value=response) if response is not None else MagicMock()
monkeypatch.setattr(remote_fetcher.ssrf_proxy, "make_request", make_request)
return make_request
-def _patch_signer_times(monkeypatch: pytest.MonkeyPatch):
+def _patch_signer_times(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("core.datasource.datasource_file_manager.time.time", lambda: 1700000000)
monkeypatch.setattr("core.tools.signature.time.time", lambda: 1700000000)
monkeypatch.setattr("core.tools.tool_file_manager.time.time", lambda: 1700000000)
-def test_get_signed_upload_file_url_reads_storage_without_ssrf(monkeypatch: pytest.MonkeyPatch):
+def test_get_signed_upload_file_url_reads_storage_without_ssrf(monkeypatch: pytest.MonkeyPatch) -> None:
load_once = MagicMock(return_value=b"hello")
monkeypatch.setattr(remote_fetcher.storage, "load_once", load_once)
ssrf_make_request = _patch_ssrf_make_request(monkeypatch)
@@ -166,7 +168,7 @@ def test_get_signed_upload_file_url_reads_storage_without_ssrf(monkeypatch: pyte
def test_make_request_resolves_upload_preview_url_generated_by_signer(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
_patch_signer_times(monkeypatch)
file_database.upload_file.key = "upload_files/tenant/image.png"
file_database.upload_file.name = "image.png"
@@ -191,7 +193,7 @@ def test_make_request_resolves_upload_preview_url_generated_by_signer(
def test_make_request_resolves_sign_tool_file_url_with_empty_extension(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
_patch_signer_times(monkeypatch)
file_database.tool_file.file_key = "tools/tenant/no-extension"
file_database.tool_file.name = "no-extension"
@@ -215,7 +217,7 @@ def test_make_request_resolves_sign_tool_file_url_with_empty_extension(
def test_make_request_resolves_tool_manager_url_with_empty_extension(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
_patch_signer_times(monkeypatch)
file_database.tool_file.file_key = "tools/tenant/manager-file"
file_database.tool_file.name = "manager-file"
@@ -238,7 +240,7 @@ def test_make_request_resolves_tool_manager_url_with_empty_extension(
def test_make_request_resolves_datasource_manager_url_with_empty_extension(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
_patch_signer_times(monkeypatch)
file_database.datasource_upload_file.key = "datasources/tenant/no-extension"
file_database.datasource_upload_file.name = "no-extension"
@@ -261,7 +263,7 @@ def test_make_request_resolves_datasource_manager_url_with_empty_extension(
ssrf_make_request.assert_not_called()
-def test_head_signed_upload_file_url_returns_metadata_without_storage_content(monkeypatch: pytest.MonkeyPatch):
+def test_head_signed_upload_file_url_returns_metadata_without_storage_content(monkeypatch: pytest.MonkeyPatch) -> None:
load_once = MagicMock(return_value=b"hello")
monkeypatch.setattr(remote_fetcher.storage, "load_once", load_once)
ssrf_make_request = _patch_ssrf_make_request(monkeypatch)
@@ -282,7 +284,7 @@ def test_head_signed_upload_file_url_returns_metadata_without_storage_content(mo
ssrf_make_request.assert_not_called()
-def test_make_request_get_signed_upload_file_url_reads_storage_without_ssrf(monkeypatch: pytest.MonkeyPatch):
+def test_make_request_get_signed_upload_file_url_reads_storage_without_ssrf(monkeypatch: pytest.MonkeyPatch) -> None:
load_once = MagicMock(return_value=b"hello")
monkeypatch.setattr(remote_fetcher.storage, "load_once", load_once)
ssrf_make_request = _patch_ssrf_make_request(monkeypatch)
@@ -301,7 +303,9 @@ def test_make_request_get_signed_upload_file_url_reads_storage_without_ssrf(monk
ssrf_make_request.assert_not_called()
-def test_make_request_head_signed_upload_file_url_returns_metadata_without_ssrf(monkeypatch: pytest.MonkeyPatch):
+def test_make_request_head_signed_upload_file_url_returns_metadata_without_ssrf(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
load_once = MagicMock(return_value=b"hello")
monkeypatch.setattr(remote_fetcher.storage, "load_once", load_once)
ssrf_make_request = _patch_ssrf_make_request(monkeypatch)
@@ -324,7 +328,7 @@ def test_make_request_head_signed_upload_file_url_returns_metadata_without_ssrf(
def test_make_request_get_unsigned_dify_url_delegates_to_ssrf_proxy(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
url = f"http://localhost:5001/files/{UPLOAD_FILE_ID}/file-preview?timestamp=1700000000&nonce=nonce"
proxy_response = httpx.Response(403, request=httpx.Request("GET", url))
ssrf_make_request = _patch_ssrf_make_request(monkeypatch, proxy_response)
@@ -343,7 +347,7 @@ def test_make_request_get_unsigned_dify_url_delegates_to_ssrf_proxy(
def test_make_request_post_signed_upload_file_url_delegates_to_ssrf_proxy(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
proxy_response = httpx.Response(201, request=httpx.Request("POST", f"http://localhost:5001/files/{UPLOAD_FILE_ID}"))
ssrf_make_request = _patch_ssrf_make_request(monkeypatch, proxy_response)
url = _signed_url(
@@ -366,7 +370,7 @@ def test_make_request_post_signed_upload_file_url_delegates_to_ssrf_proxy(
def test_get_signed_image_preview_url_uses_image_preview_signature(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
file_database.upload_file.key = "upload_files/tenant/image.png"
file_database.upload_file.name = "image.png"
file_database.upload_file.mime_type = "image/png"
@@ -391,7 +395,7 @@ def test_get_signed_image_preview_url_uses_image_preview_signature(
ssrf_make_request.assert_not_called()
-def test_image_preview_url_with_file_preview_signature_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
+def test_image_preview_url_with_file_preview_signature_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
proxy_response = httpx.Response(403, request=httpx.Request("GET", "http://localhost:5001/bad"))
ssrf_make_request = _patch_ssrf_make_request(monkeypatch, proxy_response)
url = _signed_url(
@@ -410,7 +414,7 @@ def test_image_preview_url_with_file_preview_signature_delegates_to_ssrf_proxy(m
)
-def test_duplicate_signature_query_value_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
+def test_duplicate_signature_query_value_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
url = (
_signed_url(
base_url="http://localhost:5001",
@@ -432,7 +436,7 @@ def test_duplicate_signature_query_value_delegates_to_ssrf_proxy(monkeypatch: py
)
-def test_malformed_timestamp_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
+def test_malformed_timestamp_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
url = _signed_url(
base_url="http://localhost:5001",
path=f"/files/{UPLOAD_FILE_ID}/file-preview",
@@ -451,7 +455,7 @@ def test_malformed_timestamp_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyP
)
-def test_expired_signature_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
+def test_expired_signature_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(remote_fetcher.time, "time", lambda: 1700004001)
url = _signed_url(
base_url="http://localhost:5001",
@@ -471,7 +475,7 @@ def test_expired_signature_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPat
)
-def test_invalid_signature_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
+def test_invalid_signature_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
proxy_response = httpx.Response(403, request=httpx.Request("GET", "http://localhost:5001/bad"))
ssrf_make_request = _patch_ssrf_make_request(monkeypatch, proxy_response)
url = f"http://localhost:5001/files/{UPLOAD_FILE_ID}/file-preview?timestamp=1700000000&nonce=nonce&sign=bad"
@@ -487,7 +491,7 @@ def test_invalid_signature_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPat
)
-def test_host_mismatch_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
+def test_host_mismatch_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
url = _signed_url(
base_url="http://example.com",
path=f"/files/{UPLOAD_FILE_ID}/file-preview",
@@ -506,7 +510,7 @@ def test_host_mismatch_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
)
-def test_unsupported_dify_path_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
+def test_unsupported_dify_path_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
url = _signed_url(
base_url="http://localhost:5001",
path=f"/files/{UPLOAD_FILE_ID}/not-preview",
@@ -526,7 +530,7 @@ def test_unsupported_dify_path_delegates_to_ssrf_proxy(monkeypatch: pytest.Monke
)
-def test_invalid_url_scheme_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
+def test_invalid_url_scheme_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
url = f"file:///tmp/files/{UPLOAD_FILE_ID}/file-preview?timestamp=1700000000&nonce=nonce&sign=ignored"
proxy_response = httpx.Response(403, request=httpx.Request("GET", url))
ssrf_make_request = _patch_ssrf_make_request(monkeypatch, proxy_response)
@@ -541,7 +545,7 @@ def test_invalid_url_scheme_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPa
)
-def test_invalid_url_port_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch):
+def test_invalid_url_port_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
url = f"http://localhost:invalid/files/{UPLOAD_FILE_ID}/file-preview?timestamp=1700000000&nonce=nonce&sign=ignored"
proxy_response = httpx.Response(403, request=httpx.Request("GET", "http://proxy.example/fallback"))
ssrf_make_request = _patch_ssrf_make_request(monkeypatch, proxy_response)
@@ -558,7 +562,7 @@ def test_invalid_url_port_delegates_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatc
def test_invalid_configured_file_origin_delegates_to_ssrf_proxy(
monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
-):
+) -> None:
config_overrides(FILES_URL="", INTERNAL_FILES_URL="file:///tmp/files")
url = _signed_url(
base_url="http://localhost:5001",
@@ -580,7 +584,7 @@ def test_invalid_configured_file_origin_delegates_to_ssrf_proxy(
def test_signed_upload_file_url_returns_404_when_record_missing(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
file_database.session.delete(file_database.upload_file)
file_database.session.commit()
ssrf_make_request = _patch_ssrf_make_request(monkeypatch)
@@ -597,7 +601,7 @@ def test_signed_upload_file_url_returns_404_when_record_missing(
ssrf_make_request.assert_not_called()
-def test_get_signed_tool_file_url_reads_storage_without_ssrf(monkeypatch: pytest.MonkeyPatch):
+def test_get_signed_tool_file_url_reads_storage_without_ssrf(monkeypatch: pytest.MonkeyPatch) -> None:
load_once = MagicMock(return_value=b"result")
monkeypatch.setattr(remote_fetcher.storage, "load_once", load_once)
ssrf_make_request = _patch_ssrf_make_request(monkeypatch)
@@ -618,7 +622,7 @@ def test_get_signed_tool_file_url_reads_storage_without_ssrf(monkeypatch: pytest
def test_signed_tool_file_url_returns_404_when_record_missing(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
file_database.session.delete(file_database.tool_file)
file_database.session.commit()
ssrf_make_request = _patch_ssrf_make_request(monkeypatch)
@@ -635,7 +639,7 @@ def test_signed_tool_file_url_returns_404_when_record_missing(
ssrf_make_request.assert_not_called()
-def test_get_signed_datasource_file_url_reads_upload_storage_without_ssrf(monkeypatch: pytest.MonkeyPatch):
+def test_get_signed_datasource_file_url_reads_upload_storage_without_ssrf(monkeypatch: pytest.MonkeyPatch) -> None:
load_once = MagicMock(return_value=b"data")
monkeypatch.setattr(remote_fetcher.storage, "load_once", load_once)
ssrf_make_request = _patch_ssrf_make_request(monkeypatch)
@@ -655,7 +659,7 @@ def test_get_signed_datasource_file_url_reads_upload_storage_without_ssrf(monkey
def test_get_signed_datasource_file_url_reads_tool_storage_when_upload_missing(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
file_database.session.delete(file_database.datasource_upload_file)
datasource_tool_file = ToolFile(
user_id=USER_ID,
@@ -690,7 +694,7 @@ def test_get_signed_datasource_file_url_reads_tool_storage_when_upload_missing(
def test_signed_datasource_file_url_returns_404_when_records_missing(
monkeypatch: pytest.MonkeyPatch, file_database: FileDatabase
-):
+) -> None:
file_database.session.delete(file_database.datasource_upload_file)
file_database.session.commit()
ssrf_make_request = _patch_ssrf_make_request(monkeypatch)
@@ -708,7 +712,7 @@ def test_signed_datasource_file_url_returns_404_when_records_missing(
@pytest.mark.parametrize("method_name", ["POST", "PUT", "DELETE", "PATCH"])
-def test_non_get_make_request_methods_delegate_to_ssrf_proxy(monkeypatch, method_name):
+def test_non_get_make_request_methods_delegate_to_ssrf_proxy(monkeypatch: pytest.MonkeyPatch, method_name: str) -> None:
url = "https://example.com/file.txt"
proxy_response = httpx.Response(200, request=httpx.Request(method_name, url))
ssrf_make_request = _patch_ssrf_make_request(monkeypatch, proxy_response)
@@ -719,7 +723,7 @@ def test_non_get_make_request_methods_delegate_to_ssrf_proxy(monkeypatch, method
ssrf_make_request.assert_called_once_with(method=method_name, url=url, max_retries=2, timeout=3)
-def test_graphon_remote_file_fetcher_exposes_ssrf_error_types():
+def test_graphon_remote_file_fetcher_exposes_ssrf_error_types() -> None:
fetcher = remote_fetcher.GraphonRemoteFileFetcher()
assert fetcher.max_retries_exceeded_error is remote_fetcher.max_retries_exceeded_error
@@ -727,7 +731,9 @@ def test_graphon_remote_file_fetcher_exposes_ssrf_error_types():
@pytest.mark.parametrize("method_name", ["get", "head", "post", "put", "delete", "patch"])
-def test_graphon_remote_file_fetcher_adapts_fetcher_responses(monkeypatch, method_name):
+def test_graphon_remote_file_fetcher_adapts_fetcher_responses(
+ monkeypatch: pytest.MonkeyPatch, method_name: str
+) -> None:
url = "https://example.com/file.txt"
response = httpx.Response(200, request=httpx.Request(method_name.upper(), url), content=b"ok")
make_request = MagicMock(return_value=response)
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 761a3889586..c0f3b40c38c 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -15,12 +15,9 @@ project-excludes = [
"commands/test_lint_response_contracts.py",
"commands/test_upgrade_db.py",
"repositories/test_app_definition_query_repository_agent.py",
- "controllers/common/test_app_access.py",
"controllers/common/test_errors.py",
- "controllers/common/test_fields.py",
"controllers/common/test_file_response.py",
"controllers/common/test_schema.py",
- "controllers/common/test_session.py",
"controllers/console/app/test_agent_config_inspector.py",
"controllers/console/app/test_agent_manage_guard.py",
"controllers/console/app/test_annotation_api.py",
@@ -253,8 +250,6 @@ project-excludes = [
"core/extension/test_api_based_extension_requestor.py",
"core/external_data_tool/test_external_data_fetch.py",
"core/external_data_tool/test_factory.py",
- "core/file/test_models.py",
- "core/file/test_remote_fetcher.py",
"core/helper/code_executor/javascript/test_javascript_transformer.py",
"core/helper/code_executor/jinja2/test_jinja2_sandbox.py",
"core/helper/code_executor/python3/test_python3_transformer.py",
@@ -625,7 +620,6 @@ project-excludes = [
"tasks/test_resume_agent_app_task.py",
"tasks/test_summary_queue_isolation.py",
"tasks/test_workflow_execute_task.py",
- "test_app_factory.py",
"test_makefile_backend_tests.py",
"test_pytest_dify.py",
"tools/test_api_tool.py",
diff --git a/api/tests/unit_tests/test_app_factory.py b/api/tests/unit_tests/test_app_factory.py
index fc946e1ec04..816f49dd045 100644
--- a/api/tests/unit_tests/test_app_factory.py
+++ b/api/tests/unit_tests/test_app_factory.py
@@ -4,6 +4,8 @@ Enterprise license gating through the global ``before_request`` hook, and the
flask-restx defaults every API surface inherits from the app config.
"""
+from contextlib import AbstractContextManager
+from typing import NoReturn
from unittest.mock import patch
import pytest
@@ -20,15 +22,15 @@ INVALID_STATUSES = [LicenseStatus.INACTIVE, LicenseStatus.EXPIRED, LicenseStatus
VALID_STATUSES = [LicenseStatus.ACTIVE, LicenseStatus.EXPIRING]
-def _license(status: LicenseStatus | None):
+def _license(status: LicenseStatus | None) -> AbstractContextManager[object]:
return patch("app_factory.EnterpriseService.get_cached_license_status", return_value=status)
-def _enterprise():
+def _enterprise() -> AbstractContextManager[None]:
return config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
-def _community():
+def _community() -> AbstractContextManager[None]:
return config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
@@ -37,47 +39,47 @@ def gated_app() -> Flask:
app = create_flask_app_with_configs()
@app.route("/v1/chat-messages", methods=["POST"])
- def service_api_route():
+ def service_api_route() -> dict[str, str]:
return {"surface": "service_api"}
@app.route("/v1/")
- def service_api_index_route():
+ def service_api_index_route() -> dict[str, str]:
return {"surface": "service_api_index"}
@app.route("/mcp/server/<server_code>/mcp", methods=["POST"])
- def mcp_route(server_code: str):
+ def mcp_route(**_kwargs: str) -> dict[str, str]:
return {"surface": "mcp"}
@app.route("/triggers/webhook/<webhook_id>", methods=["POST"])
- def trigger_route(webhook_id: str):
+ def trigger_route(**_kwargs: str) -> dict[str, str]:
return {"surface": "triggers"}
@app.route("/console/api/apps")
- def console_route():
+ def console_route() -> dict[str, str]:
return {"surface": "console"}
@app.route("/console/api/login", methods=["POST"])
- def console_bootstrap_route():
+ def console_bootstrap_route() -> dict[str, str]:
return {"surface": "console_bootstrap"}
@app.route("/api/messages")
- def webapp_route():
+ def webapp_route() -> dict[str, str]:
return {"surface": "webapp"}
@app.route("/api/system-features")
- def webapp_bootstrap_route():
+ def webapp_bootstrap_route() -> dict[str, str]:
return {"surface": "webapp_bootstrap"}
@app.route("/health")
- def health_route():
+ def health_route() -> dict[str, str]:
return {"surface": "health"}
@app.route("/inner/api/rbac/check-access", methods=["POST"])
- def inner_api_route():
+ def inner_api_route() -> dict[str, str]:
return {"surface": "inner_api"}
@app.route("/files/upload/for-plugin", methods=["POST"])
- def files_route():
+ def files_route() -> dict[str, str]:
return {"surface": "files"}
return app
@@ -87,31 +89,31 @@ class TestServiceApiLicenseGate:
"""/v1 is a bearer-token surface, so it is gated with an opaque 403."""
@pytest.mark.parametrize("status", INVALID_STATUSES)
- def test_blocks_when_license_invalid(self, gated_app: Flask, status: LicenseStatus):
+ def test_blocks_when_license_invalid(self, gated_app: Flask, status: LicenseStatus) -> None:
with _enterprise(), _license(status):
response = gated_app.test_client().post("/v1/chat-messages")
assert response.status_code == 403
- def test_block_response_carries_machine_readable_marker(self, gated_app: Flask):
+ def test_block_response_carries_machine_readable_marker(self, gated_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().post("/v1/chat-messages")
assert b"license_required" in response.data
- def test_block_response_does_not_leak_license_status(self, gated_app: Flask):
+ def test_block_response_does_not_leak_license_status(self, gated_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().post("/v1/chat-messages")
assert b"expired" not in response.data.lower()
- def test_blocks_when_license_status_unavailable(self, gated_app: Flask):
+ def test_blocks_when_license_status_unavailable(self, gated_app: Flask) -> None:
with _enterprise(), _license(None):
response = gated_app.test_client().post("/v1/chat-messages")
assert response.status_code == 403
- def test_blocks_when_license_lookup_raises(self, gated_app: Flask):
+ def test_blocks_when_license_lookup_raises(self, gated_app: Flask) -> None:
lookup_failed = patch(
"app_factory.EnterpriseService.get_cached_license_status",
side_effect=RuntimeError("enterprise api unreachable"),
@@ -121,7 +123,7 @@ class TestServiceApiLicenseGate:
assert response.status_code == 403
- def test_blocks_index_route(self, gated_app: Flask):
+ def test_blocks_index_route(self, gated_app: Flask) -> None:
"""/v1 has no sign-in page to bootstrap, so nothing on it is exempt."""
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().get("/v1/")
@@ -129,13 +131,13 @@ class TestServiceApiLicenseGate:
assert response.status_code == 403
@pytest.mark.parametrize("status", VALID_STATUSES)
- def test_allows_when_license_valid(self, gated_app: Flask, status: LicenseStatus):
+ def test_allows_when_license_valid(self, gated_app: Flask, status: LicenseStatus) -> None:
with _enterprise(), _license(status):
response = gated_app.test_client().post("/v1/chat-messages")
assert response.status_code == 200
- def test_allows_unclassified_status(self, gated_app: Flask):
+ def test_allows_unclassified_status(self, gated_app: Flask) -> None:
"""LicenseStatus.NONE is not in the blocked set — parity with console/webapp."""
with _enterprise(), _license(LicenseStatus.NONE):
response = gated_app.test_client().post("/v1/chat-messages")
@@ -143,7 +145,7 @@ class TestServiceApiLicenseGate:
assert response.status_code == 200
@pytest.mark.parametrize("status", INVALID_STATUSES)
- def test_does_not_gate_community_edition(self, gated_app: Flask, status: LicenseStatus):
+ def test_does_not_gate_community_edition(self, gated_app: Flask, status: LicenseStatus) -> None:
with _community(), _license(status):
response = gated_app.test_client().post("/v1/chat-messages")
@@ -154,27 +156,27 @@ class TestMcpLicenseGate:
"""/mcp invokes apps for external MCP clients, so it is gated like the Service API."""
@pytest.mark.parametrize("status", INVALID_STATUSES)
- def test_blocks_when_license_invalid(self, gated_app: Flask, status: LicenseStatus):
+ def test_blocks_when_license_invalid(self, gated_app: Flask, status: LicenseStatus) -> None:
with _enterprise(), _license(status):
response = gated_app.test_client().post("/mcp/server/srv-code/mcp")
assert response.status_code == 403
- def test_block_response_carries_machine_readable_marker(self, gated_app: Flask):
+ def test_block_response_carries_machine_readable_marker(self, gated_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().post("/mcp/server/srv-code/mcp")
assert b"license_required" in response.data
@pytest.mark.parametrize("status", VALID_STATUSES)
- def test_allows_when_license_valid(self, gated_app: Flask, status: LicenseStatus):
+ def test_allows_when_license_valid(self, gated_app: Flask, status: LicenseStatus) -> None:
with _enterprise(), _license(status):
response = gated_app.test_client().post("/mcp/server/srv-code/mcp")
assert response.status_code == 200
@pytest.mark.parametrize("status", INVALID_STATUSES)
- def test_does_not_gate_community_edition(self, gated_app: Flask, status: LicenseStatus):
+ def test_does_not_gate_community_edition(self, gated_app: Flask, status: LicenseStatus) -> None:
with _community(), _license(status):
response = gated_app.test_client().post("/mcp/server/srv-code/mcp")
@@ -185,27 +187,27 @@ class TestTriggerLicenseGate:
"""Inbound webhooks are refused so senders retry, rather than dropping events."""
@pytest.mark.parametrize("status", INVALID_STATUSES)
- def test_blocks_when_license_invalid(self, gated_app: Flask, status: LicenseStatus):
+ def test_blocks_when_license_invalid(self, gated_app: Flask, status: LicenseStatus) -> None:
with _enterprise(), _license(status):
response = gated_app.test_client().post("/triggers/webhook/hook-id")
assert response.status_code == 503
- def test_block_response_carries_machine_readable_marker(self, gated_app: Flask):
+ def test_block_response_carries_machine_readable_marker(self, gated_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().post("/triggers/webhook/hook-id")
assert b"license_required" in response.data
@pytest.mark.parametrize("status", VALID_STATUSES)
- def test_allows_when_license_valid(self, gated_app: Flask, status: LicenseStatus):
+ def test_allows_when_license_valid(self, gated_app: Flask, status: LicenseStatus) -> None:
with _enterprise(), _license(status):
response = gated_app.test_client().post("/triggers/webhook/hook-id")
assert response.status_code == 200
@pytest.mark.parametrize("status", INVALID_STATUSES)
- def test_does_not_gate_community_edition(self, gated_app: Flask, status: LicenseStatus):
+ def test_does_not_gate_community_edition(self, gated_app: Flask, status: LicenseStatus) -> None:
with _community(), _license(status):
response = gated_app.test_client().post("/triggers/webhook/hook-id")
@@ -224,7 +226,7 @@ class TestGateThroughRealErrorHandlers:
@api.route("/chat-messages")
class ChatMessages(Resource):
- def post(self):
+ def post(self) -> dict[str, str]:
return {"surface": "service_api"}
app.register_blueprint(service_api_bp)
@@ -232,13 +234,13 @@ class TestGateThroughRealErrorHandlers:
trigger_bp = Blueprint("trigger_test", __name__, url_prefix="/triggers")
@trigger_bp.route("/webhook/<webhook_id>", methods=["POST"])
- def webhook_route(webhook_id: str):
+ def webhook_route(**_kwargs: str) -> dict[str, str]:
return {"surface": "triggers"}
app.register_blueprint(trigger_bp)
return app
- def test_service_api_block_is_json_with_license_marker(self, wired_app: Flask):
+ def test_service_api_block_is_json_with_license_marker(self, wired_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = wired_app.test_client().post("/v1/chat-messages")
@@ -247,21 +249,21 @@ class TestGateThroughRealErrorHandlers:
assert body["message"] == "license_required"
assert body["status"] == 403
- def test_service_api_block_does_not_clear_cookies(self, wired_app: Flask):
+ def test_service_api_block_does_not_clear_cookies(self, wired_app: Flask) -> None:
"""Force-logout cookie clearing belongs to the cookie-authed surfaces only."""
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = wired_app.test_client().post("/v1/chat-messages")
assert response.headers.getlist("Set-Cookie") == []
- def test_trigger_block_survives_plain_blueprint_handling(self, wired_app: Flask):
+ def test_trigger_block_survives_plain_blueprint_handling(self, wired_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = wired_app.test_client().post("/triggers/webhook/hook-id")
assert response.status_code == 503
assert b"license_required" in response.data
- def test_surfaces_are_reachable_when_license_valid(self, wired_app: Flask):
+ def test_surfaces_are_reachable_when_license_valid(self, wired_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.ACTIVE):
service_api = wired_app.test_client().post("/v1/chat-messages")
triggers = wired_app.test_client().post("/triggers/webhook/hook-id")
@@ -273,14 +275,14 @@ class TestGateThroughRealErrorHandlers:
class TestUngatedSurfaces:
"""Surfaces that must stay reachable while the license is invalid."""
- def test_inner_api_is_not_gated(self, gated_app: Flask):
+ def test_inner_api_is_not_gated(self, gated_app: Flask) -> None:
"""dify-enterprise control plane — gating it could block license recovery itself."""
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().post("/inner/api/rbac/check-access")
assert response.status_code == 200
- def test_files_data_plane_is_not_gated(self, gated_app: Flask):
+ def test_files_data_plane_is_not_gated(self, gated_app: Flask) -> None:
"""Signed file URLs are fetched by the plugin daemon and by LLM vendors."""
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().post("/files/upload/for-plugin")
@@ -292,32 +294,32 @@ class TestSessionSurfaceLicenseGate:
"""Console and webapp are cookie-authed, so they keep force-logout 401 semantics."""
@pytest.mark.parametrize("status", INVALID_STATUSES)
- def test_blocks_console_with_force_logout(self, gated_app: Flask, status: LicenseStatus):
+ def test_blocks_console_with_force_logout(self, gated_app: Flask, status: LicenseStatus) -> None:
with _enterprise(), _license(status):
response = gated_app.test_client().get("/console/api/apps")
assert response.status_code == 401
@pytest.mark.parametrize("status", INVALID_STATUSES)
- def test_blocks_webapp_with_force_logout(self, gated_app: Flask, status: LicenseStatus):
+ def test_blocks_webapp_with_force_logout(self, gated_app: Flask, status: LicenseStatus) -> None:
with _enterprise(), _license(status):
response = gated_app.test_client().get("/api/messages")
assert response.status_code == 401
- def test_console_bootstrap_route_stays_reachable(self, gated_app: Flask):
+ def test_console_bootstrap_route_stays_reachable(self, gated_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().post("/console/api/login")
assert response.status_code == 200
- def test_webapp_bootstrap_route_stays_reachable(self, gated_app: Flask):
+ def test_webapp_bootstrap_route_stays_reachable(self, gated_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().get("/api/system-features")
assert response.status_code == 200
- def test_health_route_is_never_gated(self, gated_app: Flask):
+ def test_health_route_is_never_gated(self, gated_app: Flask) -> None:
with _enterprise(), _license(LicenseStatus.EXPIRED):
response = gated_app.test_client().get("/health")
@@ -336,13 +338,13 @@ class TestRestxRoute404Help:
# An admission gate (edition, license) answers 404 on a route that exists.
@api.route("/account/education")
class EducationGated(Resource):
- def get(self):
+ def get(self) -> NoReturn:
abort(404)
app.register_blueprint(bp)
return app
- def test_404_body_carries_no_route_suggestions(self, gated_route_app: Flask):
+ def test_404_body_carries_no_route_suggestions(self, gated_route_app: Flask) -> None:
response = gated_route_app.test_client().get("/console/api/account/education")
assert response.status_code == 404