File: test_request_body.py

package info (click to toggle)
litestar 2.19.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,500 kB
  • sloc: python: 70,169; makefile: 254; javascript: 105; sh: 60
file content (218 lines) | stat: -rw-r--r-- 7,384 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Type, TypedDict
from unittest.mock import ANY, MagicMock

import pytest
from typing_extensions import Annotated, ReadOnly

from litestar import Controller, Litestar, get, post
from litestar._openapi.datastructures import OpenAPIContext
from litestar._openapi.request_body import create_request_body
from litestar.datastructures.upload_file import UploadFile
from litestar.dto import AbstractDTO
from litestar.enums import RequestEncodingType
from litestar.handlers import BaseRouteHandler
from litestar.openapi.config import OpenAPIConfig
from litestar.openapi.spec import RequestBody
from litestar.params import Body
from litestar.typing import FieldDefinition


@dataclass
class FormData:
    cv: UploadFile
    image: UploadFile


RequestBodyFactory = Callable[[BaseRouteHandler, FieldDefinition], RequestBody]


@pytest.fixture()
def openapi_context() -> OpenAPIContext:
    return OpenAPIContext(
        openapi_config=OpenAPIConfig(title="test", version="1.0.0", create_examples=True),
        plugins=[],
    )


@pytest.fixture()
def create_request(openapi_context: OpenAPIContext) -> RequestBodyFactory:
    def _factory(route_handler: BaseRouteHandler, data_field: FieldDefinition) -> RequestBody:
        return create_request_body(
            context=openapi_context,
            handler_id=route_handler.handler_id,
            resolved_data_dto=route_handler.resolve_data_dto(),
            data_field=data_field,
        )

    return _factory


def test_create_request_body(person_controller: Type[Controller], create_request: RequestBodyFactory) -> None:
    for route in Litestar(route_handlers=[person_controller]).routes:
        for route_handler, _ in route.route_handler_map.values():  # type: ignore[union-attr]
            handler_fields = route_handler.parsed_fn_signature.parameters
            if "data" in handler_fields:
                request_body = create_request(route_handler, handler_fields["data"])
                assert request_body


def test_request_body_schema_extra() -> None:
    @dataclass
    class RequestBody:
        foo: str

    @get()
    async def handler(
        body1: Annotated[
            RequestBody,
            Body(
                title="Default title",
                schema_extra={
                    "title": "Overridden title",
                },
            ),
        ],
    ) -> Any:
        return body1

    app = Litestar([handler])
    schema = app.openapi_schema.to_schema()
    resp = next(iter(schema["components"]["schemas"].values()))
    assert resp["title"] == "Overridden title"


def test_upload_single_file_schema_generation() -> None:
    @post(path="/file-upload")
    async def handle_file_upload(
        data: UploadFile = Body(media_type=RequestEncodingType.MULTI_PART),
    ) -> None:
        return None

    app = Litestar([handle_file_upload])
    schema = app.openapi_schema.to_schema()

    assert schema["paths"]["/file-upload"]["post"]["requestBody"]["content"]["multipart/form-data"]["schema"] == {
        "properties": {"file": {"type": "string", "format": "binary", "contentMediaType": "application/octet-stream"}},
        "type": "object",
    }


def test_upload_list_of_files_schema_generation() -> None:
    @post(path="/file-list-upload")
    async def handle_file_list_upload(
        data: List[UploadFile] = Body(media_type=RequestEncodingType.MULTI_PART),
    ) -> None:
        return None

    app = Litestar([handle_file_list_upload])
    schema = app.openapi_schema.to_schema()

    assert schema["paths"]["/file-list-upload"]["post"]["requestBody"]["content"]["multipart/form-data"]["schema"] == {
        "type": "object",
        "properties": {
            "files": {
                "items": {"type": "string", "contentMediaType": "application/octet-stream", "format": "binary"},
                "type": "array",
            }
        },
    }


def test_upload_file_dict_schema_generation() -> None:
    @post(path="/file-dict-upload")
    async def handle_file_list_upload(
        data: Dict[str, UploadFile] = Body(media_type=RequestEncodingType.MULTI_PART),
    ) -> None:
        return None

    app = Litestar([handle_file_list_upload])
    schema = app.openapi_schema.to_schema()

    assert schema["paths"]["/file-dict-upload"]["post"]["requestBody"]["content"]["multipart/form-data"]["schema"] == {
        "type": "object",
        "properties": {
            "files": {
                "items": {"type": "string", "contentMediaType": "application/octet-stream", "format": "binary"},
                "type": "array",
            }
        },
    }


def test_upload_file_model_schema_generation() -> None:
    @post(path="/form-upload")
    async def handle_form_upload(
        data: FormData = Body(media_type=RequestEncodingType.MULTI_PART),
    ) -> None:
        return None

    app = Litestar([handle_form_upload])
    schema = app.openapi_schema.to_schema()

    assert schema["paths"]["/form-upload"]["post"]["requestBody"]["content"]["multipart/form-data"] == {
        "schema": {"$ref": "#/components/schemas/FormData"}
    }
    assert schema["components"] == {
        "schemas": {
            "FormData": {
                "properties": {
                    "cv": {"type": "string", "contentMediaType": "application/octet-stream", "format": "binary"},
                    "image": {"type": "string", "contentMediaType": "application/octet-stream", "format": "binary"},
                },
                "type": "object",
                "required": ["cv", "image"],
                "title": "FormData",
            }
        }
    }


def test_request_body_generation_with_dto(create_request: RequestBodyFactory) -> None:
    mock_dto = MagicMock(spec=AbstractDTO)

    @post(path="/form-upload", dto=mock_dto)  # pyright: ignore
    async def handler(data: Dict[str, Any]) -> None:
        return None

    Litestar(route_handlers=[handler])
    field_definition = FieldDefinition.from_annotation(Dict[str, Any])
    create_request(handler, field_definition)
    mock_dto.create_openapi_schema.assert_called_once_with(
        field_definition=field_definition, handler_id=handler.handler_id, schema_creator=ANY
    )


def test_unwrap_read_only() -> None:
    class SchemaDict(TypedDict):
        id: ReadOnly[int]  # pyright: ignore
        email: str

    @post("/")
    async def handler(
        data: SchemaDict,
    ) -> SchemaDict:
        return {"id": data["id"], "email": "new@example.com"}

    app = Litestar([handler])
    schema = app.openapi_schema.to_schema()

    assert schema["paths"]["/"]["post"]["requestBody"]["content"]["application/json"] == {
        "schema": {"$ref": "#/components/schemas/test_unwrap_read_only.SchemaDict"}
    }
    assert schema["paths"]["/"]["post"]["responses"]["201"]["content"]["application/json"] == {
        "schema": {"$ref": "#/components/schemas/test_unwrap_read_only.SchemaDict"}
    }
    assert schema["components"] == {
        "schemas": {
            "test_unwrap_read_only.SchemaDict": {
                "properties": {
                    "id": {"type": "integer"},
                    "email": {"type": "string"},
                },
                "type": "object",
                "required": ["email", "id"],
                "title": "SchemaDict",
            }
        }
    }