File: test_request.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 (631 lines) | stat: -rw-r--r-- 23,330 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
"""A large part of the tests in this file were adapted from:

https://github.com/encode/starlette/blob/master/tests/test_requests.py. And are meant to ensure our compatibility with
their API.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Callable, Dict, Generator
from unittest.mock import patch

import pytest

from litestar import MediaType, Request, get, post
from litestar.connection.base import AuthT, StateT, UserT, empty_send
from litestar.datastructures import Address, Cookie, State
from litestar.exceptions import (
    InternalServerException,
    LitestarException,
    LitestarWarning,
    SerializationException,
)
from litestar.middleware import MiddlewareProtocol
from litestar.response.base import ASGIResponse
from litestar.serialization import encode_json, encode_msgpack
from litestar.static_files.config import StaticFilesConfig
from litestar.status_codes import HTTP_400_BAD_REQUEST, HTTP_413_REQUEST_ENTITY_TOO_LARGE
from litestar.testing import TestClient, create_test_client

if TYPE_CHECKING:
    from pathlib import Path

    from litestar.types import ASGIApp, Receive, Scope, Send


@get("/", sync_to_thread=False, request_max_body_size=None)
def _route_handler() -> None:
    pass


@pytest.fixture(name="scope")
def scope_fixture(create_scope: Callable[..., Scope]) -> Scope:
    return create_scope(type="http", route_handler=_route_handler)


async def test_request_empty_body_to_json(anyio_backend: str, scope: Scope) -> None:
    with patch.object(Request, "body", return_value=b""):
        request_empty_payload: Request[Any, Any, State] = Request(scope=scope)
        request_json = await request_empty_payload.json()
        assert request_json is None


async def test_request_invalid_body_to_json(anyio_backend: str, scope: Scope) -> None:
    with patch.object(Request, "body", return_value=b"invalid"), pytest.raises(SerializationException):
        request_empty_payload: Request[Any, Any, State] = Request(scope=scope)
        await request_empty_payload.json()


async def test_request_valid_body_to_json(anyio_backend: str, scope: Scope) -> None:
    with patch.object(Request, "body", return_value=b'{"test": "valid"}'):
        request_empty_payload: Request[Any, Any, State] = Request(scope=scope)
        request_json = await request_empty_payload.json()
        assert request_json == {"test": "valid"}


async def test_request_empty_body_to_msgpack(anyio_backend: str, scope: Scope) -> None:
    with patch.object(Request, "body", return_value=b""):
        request_empty_payload: Request[Any, Any, State] = Request(scope=scope)
        request_msgpack = await request_empty_payload.msgpack()
        assert request_msgpack is None


async def test_request_invalid_body_to_msgpack(anyio_backend: str, scope: Scope) -> None:
    with patch.object(Request, "body", return_value=b"invalid"), pytest.raises(SerializationException):
        request_empty_payload: Request[Any, Any, State] = Request(scope=scope)
        await request_empty_payload.msgpack()


async def test_request_valid_body_to_msgpack(anyio_backend: str, scope: Scope) -> None:
    with patch.object(Request, "body", return_value=encode_msgpack({"test": "valid"})):
        request_empty_payload: Request[Any, Any, State] = Request(scope=scope)
        request_msgpack = await request_empty_payload.msgpack()
        assert request_msgpack == {"test": "valid"}


def test_request_url_for() -> None:
    @get(path="/proxy", name="proxy")
    def proxy() -> None:
        pass

    @get(path="/test", signature_namespace={"dict": Dict})
    def root(request: Request[Any, Any, State]) -> dict[str, str]:
        return {"url": request.url_for("proxy")}

    @get(path="/test-none", signature_namespace={"dict": Dict})
    def test_none(request: Request[Any, Any, State]) -> dict[str, str]:
        return {"url": request.url_for("none")}

    with create_test_client(route_handlers=[proxy, root, test_none]) as client:
        response = client.get("/test")
        assert response.json() == {"url": "http://testserver.local/proxy"}

        response = client.get("/test-none")
        assert response.status_code == 500


def test_request_asset_url(tmp_path: Path) -> None:
    @get(path="/resolver", signature_namespace={"dict": Dict})
    def resolver(request: Request[Any, Any, State]) -> dict[str, str]:
        return {"url": request.url_for_static_asset("js", "main.js")}

    @get(path="/resolver-none", signature_namespace={"dict": Dict})
    def resolver_none(request: Request[Any, Any, State]) -> dict[str, str]:
        return {"url": request.url_for_static_asset("none", "main.js")}

    with create_test_client(
        route_handlers=[resolver, resolver_none],
        static_files_config=[StaticFilesConfig(path="/static/js", directories=[tmp_path], name="js")],
    ) as client:
        response = client.get("/resolver")
        assert response.json() == {"url": "http://testserver.local/static/js/main.js"}

        response = client.get("/resolver-none")
        assert response.status_code == 500


def test_request_url_for_by_name() -> None:
    @get(path="/proxy")
    def proxy() -> None:
        pass

    @get(path="/test")
    def root(request: Request[Any, Any, State]) -> Dict[str, str]:  # noqa: UP006
        return {"url": request.url_for(proxy)}

    with create_test_client(route_handlers=[proxy, root]) as client:
        response = client.get("/test")
        assert response.json() == {"url": "http://testserver.local/proxy"}


def test_route_handler_property() -> None:
    value: Any = {}

    @get("/")
    def handler(request: Request[Any, Any, State]) -> None:
        value["handler"] = request.route_handler

    with create_test_client(route_handlers=[handler]) as client:
        client.get("/")
        assert str(value["handler"]) == str(handler)


def test_custom_request_class() -> None:
    value: Any = {}

    class MyRequest(Request[UserT, AuthT, StateT]):
        def __init__(self, *args: Any, **kwargs: Any) -> None:
            super().__init__(*args, **kwargs)
            self.scope["called"] = True  # type: ignore[typeddict-unknown-key]

    @get("/", signature_types=[MyRequest])
    def handler(request: MyRequest[Any, Any, State]) -> None:
        value["called"] = request.scope.get("called")

    with create_test_client(route_handlers=[handler], request_class=MyRequest) as client:
        client.get("/")
        assert value["called"]


def test_request_url() -> None:
    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope, receive)
        data = {"method": request.method, "url": str(request.url)}
        response = ASGIResponse(body=encode_json(data))
        await response(scope, receive, send)

    client = TestClient(app)
    response = client.get("/123?a=abc")
    assert response.json() == {"method": "GET", "url": "http://testserver.local/123?a=abc"}

    response = client.get("https://example.org:123/")
    assert response.json() == {"method": "GET", "url": "https://example.org:123/"}


def test_request_query_params() -> None:
    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope, receive)
        params = dict(request.query_params)
        response = ASGIResponse(body=encode_json({"params": params}))
        await response(scope, receive, send)

    client = TestClient(app)
    response = client.get("/?a=123&b=456")
    assert response.json() == {"params": {"a": "123", "b": "456"}}


def test_request_headers() -> None:
    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope, receive)
        headers = dict(request.headers)
        response = ASGIResponse(body=encode_json({"headers": headers}))
        await response(scope, receive, send)

    client = TestClient(app)
    response = client.get("/", headers={"host": "example.org"})
    assert response.json() == {
        "headers": {
            "host": "example.org",
            "user-agent": "testclient",
            "accept-encoding": "gzip, deflate, br",
            "accept": "*/*",
            "connection": "keep-alive",
        }
    }


def test_request_accept_header() -> None:
    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope, receive)
        response = ASGIResponse(body=encode_json({"accepted_types": list(request.accept)}))
        await response(scope, receive, send)

    client = TestClient(app)
    response = client.get("/", headers={"Accept": "text/plain, application/xml;q=0.7, text/html;p=test"})
    assert response.json() == {"accepted_types": ["text/html;p=test", "text/plain", "application/xml;q=0.7"]}


@pytest.mark.parametrize(
    "scope_values,expected_client",
    (
        ({"type": "http", "route_handler": _route_handler, "client": ["client", 42]}, Address("client", 42)),
        ({"type": "http", "route_handler": _route_handler, "client": None}, None),
        ({"type": "http", "route_handler": _route_handler}, None),
    ),
)
def test_request_client(
    scope_values: dict[str, Any], expected_client: Address | None, create_scope: Callable[..., Scope]
) -> None:
    scope = create_scope()
    scope.update(scope_values)  # type: ignore[typeddict-item]
    if "client" not in scope_values:
        del scope["client"]  # type: ignore[misc]
    client = Request[Any, Any, State](scope).client
    assert client == expected_client


def test_request_body() -> None:
    @post("/")
    async def handler(request: Request) -> bytes:
        body = await request.body()
        return encode_json({"body": body.decode()})

    with create_test_client([handler]) as client:
        response = client.post("/")
        assert response.json() == {"body": ""}

        response = client.post("/", content="foo")
        assert response.json() == {"body": "foo"}


def test_request_stream() -> None:
    @post("/")
    async def handler(request: Request) -> bytes:
        body = b""
        async for chunk in request.stream():
            body += chunk
        return encode_json({"body": body.decode()})

    with create_test_client([handler]) as client:
        response = client.post("/")
        assert response.json() == {"body": ""}

        response = client.post("/", content="abc")
        assert response.json() == {"body": "abc"}


def test_request_form_urlencoded() -> None:
    @post("/")
    async def handler(request: Request) -> bytes:
        form = await request.form()

        return encode_json({"form": dict(form)})

    with create_test_client([handler]) as client:
        response = client.post("/", data={"abc": "123 @"})
        assert response.json() == {"form": {"abc": "123 @"}}


def test_request_form_urlencoded_multi_keys() -> None:
    @post("/")
    async def handler(request: Request) -> Any:
        return (await request.form()).getall("foo")

    with create_test_client(handler) as client:
        assert client.post("/", data={"foo": ["1", "2"]}).json() == ["1", "2"]


def test_request_form_multipart_multi_keys() -> None:
    @post("/")
    async def handler(request: Request) -> int:
        return len((await request.form()).getall("foo"))

    with create_test_client(handler) as client:
        assert client.post("/", data={"foo": "1"}, files={"foo": b"a"}).json() == 2


def test_request_body_then_stream() -> None:
    @post("/")
    async def handler(request: Request) -> bytes:
        body = await request.body()
        chunks = b""
        async for chunk in request.stream():
            chunks += chunk
        return encode_json({"body": body.decode(), "stream": chunks.decode()})

    with create_test_client([handler]) as client:
        response = client.post("/", content="abc")
        assert response.json() == {"body": "abc", "stream": "abc"}


def test_request_stream_then_body() -> None:
    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope, receive)
        chunks = b""
        async for chunk in request.stream():
            chunks += chunk
        try:
            body = await request.body()
        except InternalServerException:
            body = b"<stream consumed>"
        response = ASGIResponse(body=encode_json({"body": body.decode(), "stream": chunks.decode()}))
        await response(scope, receive, send)

    @post("/")
    async def handler(request: Request) -> bytes:
        chunks = b""
        async for chunk in request.stream():
            chunks += chunk
        try:
            body = await request.body()
        except InternalServerException:
            body = b"<stream consumed>"
        return encode_json({"body": body.decode(), "stream": chunks.decode()})

    with create_test_client([handler]) as client:
        response = client.post("/", content="abc")
        assert response.json() == {"body": "<stream consumed>", "stream": "abc"}


def test_request_json() -> None:
    @post("/")
    async def handler(request: Request) -> bytes:
        data = await request.json()
        return encode_json({"json": data})

    with create_test_client(handler) as client:
        response = client.post("/", json={"a": "123"})
        assert response.json() == {"json": {"a": "123"}}


def test_request_raw_path() -> None:
    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope, receive)
        path = str(request.scope["path"])
        raw_path = str(request.scope["raw_path"])
        response = ASGIResponse(body=f"{path}, {raw_path}".encode(), media_type=MediaType.TEXT)
        await response(scope, receive, send)

    client = TestClient(app)
    response = client.get("/he%2Fllo")
    assert response.text == "/he/llo, b'/he%2Fllo'"


def test_request_without_setting_receive(create_scope: Callable[..., Scope]) -> None:
    """If Request is instantiated without the 'receive' channel, then .body() is not available."""

    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        scope.update(create_scope(route_handler=_route_handler))  # type: ignore[typeddict-item]
        request = Request[Any, Any, State](scope)
        try:
            data = await request.json()
        except RuntimeError:
            data = "Receive channel not available"
        response = ASGIResponse(body=encode_json({"json": data}))
        await response(scope, receive, send)

    client = TestClient(app)
    response = client.post("/", json={"a": "123"})
    assert response.json() == {"json": "Receive channel not available"}


async def test_request_disconnect(create_scope: Callable[..., Scope]) -> None:
    """If a client disconnect occurs while reading request body then InternalServerException should be raised."""

    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope, receive)
        await request.body()

    async def receiver() -> dict[str, str]:
        return {"type": "http.disconnect"}

    with pytest.raises(InternalServerException):
        await app(
            create_scope(type="http", route_handler=_route_handler, method="POST", path="/"),
            receiver,  # type: ignore[arg-type]
            empty_send,
        )


def test_request_state() -> None:
    @get("/", signature_namespace={"dict": Dict})
    def handler(request: Request[Any, Any, State]) -> dict[Any, Any]:
        request.state.test = 1
        assert request.state.test == 1
        return request.state.dict()

    with create_test_client(handler) as client:
        response = client.get("/")
        assert response.json()["test"] == 1


def test_request_cookies() -> None:
    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope, receive)
        mycookie = request.cookies.get("mycookie")
        if mycookie:
            asgi_response = ASGIResponse(body=mycookie.encode("utf-8"), media_type="text/plain")
        else:
            asgi_response = ASGIResponse(
                body=b"Hello, world!",
                media_type="text/plain",
                cookies=[Cookie(key="mycookie", value="Hello, cookies!")],
            )

        await asgi_response(scope, receive, send)

    client = TestClient(app)
    response = client.get("/")
    assert response.text == "Hello, world!"
    response = client.get("/")
    assert response.text == "Hello, cookies!"


def test_chunked_encoding() -> None:
    @post("/")
    async def handler(request: Request) -> bytes:
        body = await request.body()
        return encode_json({"body": body.decode()})

    with create_test_client([handler]) as client:

        def post_body() -> Generator[bytes, None, None]:
            yield b"foo"
            yield b"bar"

        response = client.post("/", content=post_body())
        assert response.json() == {"body": "foobar"}


def test_request_send_push_promise() -> None:
    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        # the server is push-enabled
        scope["extensions"]["http.response.push"] = {}  # type: ignore[index]

        request = Request[Any, Any, State](scope, receive, send)
        await request.send_push_promise("/style.css")

        response = ASGIResponse(body=encode_json({"json": "OK"}))
        await response(scope, receive, send)

    client = TestClient(app)
    response = client.get("/")
    assert response.json() == {"json": "OK"}


def test_request_send_push_promise_without_push_extension() -> None:
    """If server does not support the `http.response.push` extension,

    .send_push_promise() does nothing.
    """

    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope)

        with pytest.warns(LitestarWarning, match="Attempted to send a push promise"):
            await request.send_push_promise("/style.css")

        response = ASGIResponse(body=encode_json({"json": "OK"}))
        await response(scope, receive, send)

    client = TestClient(app)
    response = client.get("/")
    assert response.json() == {"json": "OK"}


def test_request_send_push_promise_without_push_extension_raises() -> None:
    """If server does not support the `http.response.push` extension,

    .send_push_promise() does nothing.
    """

    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        request = Request[Any, Any, State](scope)

        with pytest.raises(LitestarException, match="Attempted to send a push promise"):
            await request.send_push_promise("/style.css", raise_if_unavailable=True)

        response = ASGIResponse(body=encode_json({"json": "OK"}))
        await response(scope, receive, send)

    TestClient(app).get("/")


def test_request_send_push_promise_without_setting_send() -> None:
    """If Request is instantiated without the send channel, then.

    .send_push_promise() is not available.
    """

    async def app(scope: Scope, receive: Receive, send: Send) -> None:
        # the server is push-enabled
        scope["extensions"]["http.response.push"] = {}  # type: ignore[index]

        data = "OK"
        request = Request[Any, Any, State](scope)
        try:
            await request.send_push_promise("/style.css")
        except RuntimeError:
            data = "Send channel not available"
        response = ASGIResponse(body=encode_json({"json": data}))
        await response(scope, receive, send)

    client = TestClient(app)
    response = client.get("/")
    assert response.json() == {"json": "Send channel not available"}


class BeforeRequestMiddleWare(MiddlewareProtocol):
    def __init__(self, app: ASGIApp) -> None:
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        scope["state"]["main"] = 1
        await self.app(scope, receive, send)


def test_state() -> None:
    def before_request(request: Request[Any, Any, State]) -> None:
        assert request.state.main == 1
        request.state.main = 2

    @get(path="/", signature_namespace={"dict": Dict})
    async def get_state(request: Request[Any, Any, State]) -> dict[str, str]:
        return {"state": request.state.main}

    with create_test_client(
        route_handlers=[get_state], middleware=[BeforeRequestMiddleWare], before_request=before_request
    ) as client:
        response = client.get("/")
        assert response.json() == {"state": 2}


def test_request_body_exceeds_content_length() -> None:
    @post("/")
    def handler(body: bytes) -> None:
        pass

    with create_test_client([handler]) as client:
        response = client.post("/", headers={"content-length": "1"}, content=b"ab")
        assert response.status_code == HTTP_400_BAD_REQUEST
        assert response.json() == {"status_code": 400, "detail": "Malformed request"}


def test_request_body_exceeds_max_request_body_size() -> None:
    @post("/one", request_max_body_size=1)
    async def handler_one(request: Request) -> None:
        await request.body()

    @post("/two", request_max_body_size=1)
    async def handler_two(body: bytes) -> None:
        pass

    with create_test_client([handler_one, handler_two]) as client:
        response = client.post("/one", headers={"content-length": "2"}, content=b"ab")
        assert response.status_code == HTTP_413_REQUEST_ENTITY_TOO_LARGE

        response = client.post("/two", headers={"content-length": "2"}, content=b"ab")
        assert response.status_code == HTTP_413_REQUEST_ENTITY_TOO_LARGE


def test_request_body_exceeds_max_request_body_size_chunked() -> None:
    @post("/one", request_max_body_size=1)
    async def handler_one(request: Request) -> None:
        assert request.headers["transfer-encoding"] == "chunked"
        await request.body()

    @post("/two", request_max_body_size=1)
    async def handler_two(body: bytes, request: Request) -> None:
        assert request.headers["transfer-encoding"] == "chunked"
        await request.body()

    def generator() -> Generator[bytes, None, None]:
        yield b"1"
        yield b"2"

    with create_test_client([handler_one, handler_two]) as client:
        response = client.post("/one", content=generator())
        assert response.status_code == HTTP_413_REQUEST_ENTITY_TOO_LARGE

        response = client.post("/two", content=generator())
        assert response.status_code == HTTP_413_REQUEST_ENTITY_TOO_LARGE


def test_request_content_length() -> None:
    @post("/")
    def handler(request: Request) -> dict:
        return {"content-length": request.content_length}

    with create_test_client([handler]) as client:
        assert client.post("/", content=b"1").json() == {"content-length": 1}


def test_request_invalid_content_length() -> None:
    @post("/")
    def handler(request: Request) -> dict:
        return {"content-length": request.content_length}

    with create_test_client([handler]) as client:
        response = client.post("/", content=b"1", headers={"content-length": "a"})
        assert response.status_code == HTTP_400_BAD_REQUEST
        assert response.json() == {"detail": "Invalid content-length: 'a'", "status_code": 400}