mirror of
https://github.com/langgenius/dify.git
synced 2026-11-29 16:18:01 +08:00
Use locking current reads for keyword state under MySQL repeatable read, preserve concurrent updates and caller ORM snapshots, and align migrated test fixtures with their current application and repository contracts.
162 lines
5.6 KiB
Python
162 lines
5.6 KiB
Python
from io import BytesIO
|
|
from types import SimpleNamespace
|
|
from unittest.mock import Mock
|
|
|
|
import pytest
|
|
from flask import Flask
|
|
from sqlalchemy.orm import Session
|
|
from werkzeug.exceptions import BadRequest
|
|
|
|
from controllers.common.errors import (
|
|
BlockedFileExtensionError,
|
|
FileTooLargeError,
|
|
UnsupportedFileTypeError,
|
|
)
|
|
from controllers.openapi._models import FileUploadPayload
|
|
from controllers.openapi._multipart import body_from_request
|
|
from controllers.openapi._upload import file_fields
|
|
from controllers.openapi.auth.context import Context
|
|
from controllers.openapi.files import AppFileUploadApi
|
|
from enums.creator import CreatorUserRole
|
|
from libs.exception import BaseHTTPException
|
|
from models import Account
|
|
from services.errors.file import BlockedFileExtensionError as ServiceBlockedFileExtensionError
|
|
from services.errors.file import FileTooLargeError as ServiceFileTooLargeError
|
|
from services.errors.file import UnsupportedFileTypeError as ServiceUnsupportedFileTypeError
|
|
from tests.helpers.unit.controllers.openapi.auth._world import account_subject, make_tenant
|
|
|
|
|
|
def _caller() -> Account:
|
|
caller = Account(name="Uploader", email="uploader@example.com")
|
|
caller.id = "account-1"
|
|
return caller
|
|
|
|
|
|
def _upload_result() -> SimpleNamespace:
|
|
return SimpleNamespace(
|
|
id="00000000-0000-0000-0000-000000000001",
|
|
name="note.txt",
|
|
size=5,
|
|
extension="txt",
|
|
mime_type="text/plain",
|
|
)
|
|
|
|
|
|
def _body() -> FileUploadPayload:
|
|
return FileUploadPayload.model_validate(body_from_request(file_fields=file_fields(FileUploadPayload)))
|
|
|
|
|
|
def _file_service(monkeypatch: pytest.MonkeyPatch) -> Mock:
|
|
from controllers.openapi import _files as module
|
|
|
|
service = Mock()
|
|
monkeypatch.setattr(module, "application_services", lambda: SimpleNamespace(files=service))
|
|
return service
|
|
|
|
|
|
def _context(caller: Account, session: Session) -> Context:
|
|
context = Context(account_subject(), session, {})
|
|
context._caller = caller
|
|
context._workspace = make_tenant(tenant_id="tenant-1")
|
|
return context
|
|
|
|
|
|
def test_upload_uses_injected_file_service(
|
|
app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
|
) -> None:
|
|
service = _file_service(monkeypatch)
|
|
service.upload_file.return_value = _upload_result()
|
|
caller = _caller()
|
|
|
|
with app.test_request_context(
|
|
"/openapi/v1/apps/app-1/files",
|
|
method="POST",
|
|
data={"file": (BytesIO(b"hello"), "note.txt", "text/plain")},
|
|
content_type="multipart/form-data",
|
|
):
|
|
api = AppFileUploadApi()
|
|
handler = vars(AppFileUploadApi.post)["__handler__"]
|
|
result = handler(api, _context(caller, sqlite_session), app_id="app-1", body=_body())
|
|
|
|
assert result.id == "00000000-0000-0000-0000-000000000001"
|
|
service.upload_file.assert_called_once()
|
|
kwargs = service.upload_file.call_args.kwargs
|
|
assert kwargs["filename"] == "note.txt"
|
|
assert kwargs["content"] == b"hello"
|
|
assert kwargs["mimetype"] == "text/plain"
|
|
assert kwargs["actor"].id == caller.id
|
|
assert kwargs["actor"].creator_role == CreatorUserRole.ACCOUNT
|
|
assert kwargs["tenant_id"] == "tenant-1"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("service_error", "controller_error", "status", "error_code", "message"),
|
|
[
|
|
(ServiceFileTooLargeError("too large"), FileTooLargeError, 413, "file_too_large", "too large"),
|
|
(
|
|
ServiceUnsupportedFileTypeError(),
|
|
UnsupportedFileTypeError,
|
|
415,
|
|
"unsupported_file_type",
|
|
"File type not allowed.",
|
|
),
|
|
(
|
|
ServiceBlockedFileExtensionError("blocked extension"),
|
|
BlockedFileExtensionError,
|
|
400,
|
|
"file_extension_blocked",
|
|
"blocked extension",
|
|
),
|
|
],
|
|
)
|
|
def test_upload_preserves_specific_file_errors(
|
|
app: Flask,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
sqlite_session: Session,
|
|
service_error: ValueError,
|
|
controller_error: type[BaseHTTPException],
|
|
status: int,
|
|
error_code: str,
|
|
message: str,
|
|
) -> None:
|
|
service = _file_service(monkeypatch)
|
|
service.upload_file.side_effect = service_error
|
|
|
|
with app.test_request_context(
|
|
"/openapi/v1/apps/app-1/files",
|
|
method="POST",
|
|
data={"file": (BytesIO(b"hello"), "note.txt", "text/plain")},
|
|
content_type="multipart/form-data",
|
|
):
|
|
api = AppFileUploadApi()
|
|
handler = vars(AppFileUploadApi.post)["__handler__"]
|
|
with pytest.raises(controller_error) as error_info:
|
|
handler(api, _context(_caller(), sqlite_session), app_id="app-1", body=_body())
|
|
|
|
assert error_info.value.code == status
|
|
assert error_info.value.error_code == error_code
|
|
assert error_info.value.data == {"code": error_code, "message": message, "status": status}
|
|
assert error_info.value.__cause__ is service_error
|
|
|
|
|
|
def test_upload_maps_other_value_errors_to_bad_request(
|
|
app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
|
) -> None:
|
|
service = _file_service(monkeypatch)
|
|
service_error = ValueError("Filename contains invalid characters")
|
|
service.upload_file.side_effect = service_error
|
|
|
|
with app.test_request_context(
|
|
"/openapi/v1/apps/app-1/files",
|
|
method="POST",
|
|
data={"file": (BytesIO(b"hello"), "../note.txt", "text/plain")},
|
|
content_type="multipart/form-data",
|
|
):
|
|
api = AppFileUploadApi()
|
|
handler = vars(AppFileUploadApi.post)["__handler__"]
|
|
with pytest.raises(BadRequest) as error_info:
|
|
handler(api, _context(_caller(), sqlite_session), app_id="app-1", body=_body())
|
|
|
|
assert error_info.value.description == str(service_error)
|
|
assert error_info.value.__cause__ is service_error
|