File: test_json_data.py

package info (click to toggle)
litestar 2.21.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,568 kB
  • sloc: python: 70,588; makefile: 254; javascript: 104; sh: 60
file content (46 lines) | stat: -rw-r--r-- 1,378 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
from dataclasses import asdict

from msgspec import Struct

from litestar import post
from litestar.params import Body
from litestar.status_codes import HTTP_201_CREATED
from litestar.testing import create_test_client

from . import Form


def test_request_body_json() -> None:
    @post(path="/test")
    def test_method(data: Form = Body()) -> None:
        assert isinstance(data, Form)

    with create_test_client(test_method) as client:
        response = client.post("/test", json=asdict(Form(name="Moishe Zuchmir", age=30, programmer=True, value="100")))
        assert response.status_code == HTTP_201_CREATED


def test_empty_dict_allowed() -> None:
    @post(path="/test")
    def test_method(data: dict) -> None:
        assert isinstance(data, dict)

    with create_test_client(test_method) as client:
        response = client.post("/test", json={})
        assert response.status_code == HTTP_201_CREATED


def test_no_body_with_default() -> None:
    class Test(Struct, frozen=True):
        name: str

    default = Test(name="default")

    @post(path="/test", signature_types=[Test])
    def test_method(data: Test = default) -> Test:
        return data

    with create_test_client(test_method) as client:
        response = client.post("/test")
        assert response.status_code == HTTP_201_CREATED
        assert response.json() == {"name": "default"}