fastapi

Форк
0
/
test_starlette_exception.py 
202 строки · 7.4 Кб
1
from fastapi import FastAPI, HTTPException
2
from fastapi.testclient import TestClient
3
from starlette.exceptions import HTTPException as StarletteHTTPException
4

5
app = FastAPI()
6

7
items = {"foo": "The Foo Wrestlers"}
8

9

10
@app.get("/items/{item_id}")
11
async def read_item(item_id: str):
12
    if item_id not in items:
13
        raise HTTPException(
14
            status_code=404,
15
            detail="Item not found",
16
            headers={"X-Error": "Some custom header"},
17
        )
18
    return {"item": items[item_id]}
19

20

21
@app.get("/http-no-body-statuscode-exception")
22
async def no_body_status_code_exception():
23
    raise HTTPException(status_code=204)
24

25

26
@app.get("/http-no-body-statuscode-with-detail-exception")
27
async def no_body_status_code_with_detail_exception():
28
    raise HTTPException(status_code=204, detail="I should just disappear!")
29

30

31
@app.get("/starlette-items/{item_id}")
32
async def read_starlette_item(item_id: str):
33
    if item_id not in items:
34
        raise StarletteHTTPException(status_code=404, detail="Item not found")
35
    return {"item": items[item_id]}
36

37

38
client = TestClient(app)
39

40

41
def test_get_item():
42
    response = client.get("/items/foo")
43
    assert response.status_code == 200, response.text
44
    assert response.json() == {"item": "The Foo Wrestlers"}
45

46

47
def test_get_item_not_found():
48
    response = client.get("/items/bar")
49
    assert response.status_code == 404, response.text
50
    assert response.headers.get("x-error") == "Some custom header"
51
    assert response.json() == {"detail": "Item not found"}
52

53

54
def test_get_starlette_item():
55
    response = client.get("/starlette-items/foo")
56
    assert response.status_code == 200, response.text
57
    assert response.json() == {"item": "The Foo Wrestlers"}
58

59

60
def test_get_starlette_item_not_found():
61
    response = client.get("/starlette-items/bar")
62
    assert response.status_code == 404, response.text
63
    assert response.headers.get("x-error") is None
64
    assert response.json() == {"detail": "Item not found"}
65

66

67
def test_no_body_status_code_exception_handlers():
68
    response = client.get("/http-no-body-statuscode-exception")
69
    assert response.status_code == 204
70
    assert not response.content
71

72

73
def test_no_body_status_code_with_detail_exception_handlers():
74
    response = client.get("/http-no-body-statuscode-with-detail-exception")
75
    assert response.status_code == 204
76
    assert not response.content
77

78

79
def test_openapi_schema():
80
    response = client.get("/openapi.json")
81
    assert response.status_code == 200, response.text
82
    assert response.json() == {
83
        "openapi": "3.1.0",
84
        "info": {"title": "FastAPI", "version": "0.1.0"},
85
        "paths": {
86
            "/http-no-body-statuscode-exception": {
87
                "get": {
88
                    "operationId": "no_body_status_code_exception_http_no_body_statuscode_exception_get",
89
                    "responses": {
90
                        "200": {
91
                            "content": {"application/json": {"schema": {}}},
92
                            "description": "Successful Response",
93
                        }
94
                    },
95
                    "summary": "No Body Status Code Exception",
96
                }
97
            },
98
            "/http-no-body-statuscode-with-detail-exception": {
99
                "get": {
100
                    "operationId": "no_body_status_code_with_detail_exception_http_no_body_statuscode_with_detail_exception_get",
101
                    "responses": {
102
                        "200": {
103
                            "content": {"application/json": {"schema": {}}},
104
                            "description": "Successful Response",
105
                        }
106
                    },
107
                    "summary": "No Body Status Code With Detail Exception",
108
                }
109
            },
110
            "/items/{item_id}": {
111
                "get": {
112
                    "responses": {
113
                        "200": {
114
                            "description": "Successful Response",
115
                            "content": {"application/json": {"schema": {}}},
116
                        },
117
                        "422": {
118
                            "description": "Validation Error",
119
                            "content": {
120
                                "application/json": {
121
                                    "schema": {
122
                                        "$ref": "#/components/schemas/HTTPValidationError"
123
                                    }
124
                                }
125
                            },
126
                        },
127
                    },
128
                    "summary": "Read Item",
129
                    "operationId": "read_item_items__item_id__get",
130
                    "parameters": [
131
                        {
132
                            "required": True,
133
                            "schema": {"title": "Item Id", "type": "string"},
134
                            "name": "item_id",
135
                            "in": "path",
136
                        }
137
                    ],
138
                }
139
            },
140
            "/starlette-items/{item_id}": {
141
                "get": {
142
                    "responses": {
143
                        "200": {
144
                            "description": "Successful Response",
145
                            "content": {"application/json": {"schema": {}}},
146
                        },
147
                        "422": {
148
                            "description": "Validation Error",
149
                            "content": {
150
                                "application/json": {
151
                                    "schema": {
152
                                        "$ref": "#/components/schemas/HTTPValidationError"
153
                                    }
154
                                }
155
                            },
156
                        },
157
                    },
158
                    "summary": "Read Starlette Item",
159
                    "operationId": "read_starlette_item_starlette_items__item_id__get",
160
                    "parameters": [
161
                        {
162
                            "required": True,
163
                            "schema": {"title": "Item Id", "type": "string"},
164
                            "name": "item_id",
165
                            "in": "path",
166
                        }
167
                    ],
168
                }
169
            },
170
        },
171
        "components": {
172
            "schemas": {
173
                "ValidationError": {
174
                    "title": "ValidationError",
175
                    "required": ["loc", "msg", "type"],
176
                    "type": "object",
177
                    "properties": {
178
                        "loc": {
179
                            "title": "Location",
180
                            "type": "array",
181
                            "items": {
182
                                "anyOf": [{"type": "string"}, {"type": "integer"}]
183
                            },
184
                        },
185
                        "msg": {"title": "Message", "type": "string"},
186
                        "type": {"title": "Error Type", "type": "string"},
187
                    },
188
                },
189
                "HTTPValidationError": {
190
                    "title": "HTTPValidationError",
191
                    "type": "object",
192
                    "properties": {
193
                        "detail": {
194
                            "title": "Detail",
195
                            "type": "array",
196
                            "items": {"$ref": "#/components/schemas/ValidationError"},
197
                        }
198
                    },
199
                },
200
            }
201
        },
202
    }
203

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.