File: test_enum.py

package info (click to toggle)
django-ninja 1.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 11,280 kB
  • sloc: python: 16,041; javascript: 1,689; makefile: 40; sh: 25
file content (199 lines) | stat: -rw-r--r-- 5,210 bytes parent folder | download | duplicates (2)
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
from datetime import date
from enum import Enum
from typing import List, Optional

from pydantic import BaseModel

from ninja import NinjaAPI, Query
from ninja.testing import TestClient


class RoomEnum(str, Enum):
    double = "double"
    twin = "twin"
    single = "single"


class ExtraEnum(str, Enum):
    a = "a"
    b = "b"


class Booking(BaseModel):
    start: date
    end: date
    room: RoomEnum = RoomEnum.double


api = NinjaAPI()


@api.post("/book")
def create_booking(request, booking: Booking):
    return booking


@api.get("/search")
def booking_search(request, room: RoomEnum):
    return {"room": room}


@api.get("/optional")
def enum_optional(
    request, room: Optional[RoomEnum] = Query(None, description="description")
):
    return {"room": room}


@api.get("/optional2")
def enum_optional2(request, extra: Optional[ExtraEnum] = None):
    return {"extra": extra}


@api.get("/list")
def enum_list(request, rooms: List[RoomEnum] = Query(None, description="description")):
    return {"rooms": rooms}


class QueryOnlyEnum(str, Enum):
    one = "one"
    two = "two"


@api.get("/new-list")
def new_enum_list(
    request, q: List[QueryOnlyEnum] = Query(None, description="description")
):
    return {"q": q}


client = TestClient(api)


def test_enums():
    response = client.post(
        "/book", json={"start": "2020-01-01", "end": "2020-01-02", "room": "double"}
    )
    assert response.status_code == 200, response.content
    assert response.json() == {
        "start": "2020-01-01",
        "end": "2020-01-02",
        "room": "double",
    }

    response = client.post(
        "/book", json={"start": "2020-01-01", "end": "2020-01-02", "room": "triple"}
    )
    assert response.status_code == 422

    response = client.get("/search?room=twin")
    assert response.status_code == 200
    assert response.json() == {"room": "twin"}

    response = client.get("/search?room=other")
    assert response.status_code == 422

    response = client.get("/optional?room=twin")
    assert response.status_code == 200

    response = client.get("/optional")
    assert response.status_code == 200
    assert response.json() == {"room": None}

    response = client.get("/optional2?extra=a")
    assert response.status_code == 200
    assert response.json() == {"extra": "a"}

    response = client.get("/optional2")
    assert response.json() == {"extra": None}

    response = client.get("/list?rooms=twin&rooms=single")
    assert response.status_code == 200
    assert response.json() == {"rooms": ["twin", "single"]}

    response = client.get("/new-list?q=one&q=one")
    assert response.status_code == 200
    assert response.json() == {"q": ["one", "one"]}


def test_schema():
    schema = api.get_openapi_schema()

    booking_schema = schema["components"]["schemas"]["Booking"]
    room_prop = booking_schema["properties"]["room"]

    if "allOf" in room_prop:
        # pydantic 1.7+ change:
        assert room_prop["allOf"] == [{"$ref": "#/components/schemas/RoomEnum"}]
    else:
        assert room_prop == {"$ref": "#/components/schemas/RoomEnum"}

    assert schema["components"]["schemas"]["RoomEnum"] == {
        "enum": ["double", "twin", "single"],
        "title": "RoomEnum",
        "type": "string",
    }

    book_operation = schema["paths"]["/api/book"]["post"]
    assert book_operation["requestBody"]["content"]["application/json"]["schema"] == {
        "$ref": "#/components/schemas/Booking"
    }

    search_operation = schema["paths"]["/api/search"]["get"]
    room_param = search_operation["parameters"][0]
    assert room_param == {
        "in": "query",
        "name": "room",
        "required": True,
        "schema": {
            "title": "RoomEnum",
            "enum": ["double", "twin", "single"],
            "type": "string",
        },
    }

    optional_operation = schema["paths"]["/api/optional"]["get"]
    room_param = optional_operation["parameters"][0]
    assert room_param == {
        "in": "query",
        "name": "room",
        "schema": {
            "anyOf": [{"$ref": "#/components/schemas/RoomEnum"}, {"type": "null"}],
            "description": "description",
        },
        "required": False,
        "description": "description",
    }

    assert schema["paths"]["/api/new-list"]["get"]["parameters"][0] == {
        "description": "description",
        "in": "query",
        "name": "q",
        "required": False,
        "schema": {
            "description": "description",
            "title": "Q",
            "items": {
                "enum": ["one", "two"],
                "title": "QueryOnlyEnum",
                "type": "string",
            },
            "type": "array",
        },
    }


def test_optional_get_schema():
    "This tests that enum that is only used in GET operation puts a that enum into schema.components"
    schema = api.get_openapi_schema()

    op = schema["paths"]["/api/optional2"]["get"]
    print(op)
    assert op["parameters"][0]["schema"]["anyOf"] == [
        {"$ref": "#/components/schemas/ExtraEnum"},
        {"type": "null"},
    ]

    components = schema["components"]["schemas"]
    print(components)
    assert "ExtraEnum" in components