Debian Codegraph @

tests/test_tutorial/test_sql_databases/test_tutorial001.py

raw
1 import importlib
2 import warnings
3 from typing import Any, cast
4
5 import pytest
6 from dirty_equals import IsInt
7 from fastapi.testclient import TestClient
8 from inline_snapshot import snapshot
9 from sqlalchemy import StaticPool
10 from sqlmodel import SQLModel, create_engine
11 from sqlmodel.main import default_registry
12
13 from tests.utils import needs_py310
14
15
16 def clear_sqlmodel():
17 # Clear the tables in the metadata for the default base model
18 SQLModel.metadata.clear()
19 # Clear the Models associated with the registry, to avoid warnings
20 default_registry.dispose()
21
22
23 @pytest.fixture(
24 name="client",
25 params=[
26 pytest.param("tutorial001_py310", marks=needs_py310),
27 pytest.param("tutorial001_an_py310", marks=needs_py310),
28 ],
29 scope="module",
30 )
31 def get_client(request: pytest.FixtureRequest):
32 clear_sqlmodel()
33 # TODO: remove when updating SQL tutorial to use new lifespan API
34 with warnings.catch_warnings(record=True):
35 warnings.simplefilter("always")
36 mod = importlib.import_module(f"docs_src.sql_databases.{request.param}")
37 clear_sqlmodel()
38 importlib.reload(mod)
39 mod_any = cast(Any, mod)
40 mod_any.sqlite_url = "sqlite://"
41 mod_any.engine = create_engine(
42 mod_any.sqlite_url,
43 connect_args={"check_same_thread": False},
44 poolclass=StaticPool,
45 )
46
47 with TestClient(mod_any.app) as c:
48 yield c
49 # Clean up connection explicitly to avoid resource warning
50 mod_any.engine.dispose()
51
52
53 def test_crud_app(client: TestClient):
54 # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor
55 # this if using obj.model_validate becomes independent of Pydantic v2
56 with warnings.catch_warnings(record=True):
57 warnings.simplefilter("always")
58 # No heroes before creating
59 response = client.get("heroes/")
60 assert response.status_code == 200, response.text
61 assert response.json() == []
62
63 # Create a hero
64 response = client.post(
65 "/heroes/",
66 json={
67 "id": 999,
68 "name": "Dead Pond",
69 "age": 30,
70 "secret_name": "Dive Wilson",
71 },
72 )
73 assert response.status_code == 200, response.text
74 assert response.json() == snapshot(
75 {"age": 30, "secret_name": "Dive Wilson", "id": 999, "name": "Dead Pond"}
76 )
77
78 # Read a hero
79 hero_id = response.json()["id"]
80 response = client.get(f"/heroes/{hero_id}")
81 assert response.status_code == 200, response.text
82 assert response.json() == snapshot(
83 {"name": "Dead Pond", "age": 30, "id": 999, "secret_name": "Dive Wilson"}
84 )
85
86 # Read all heroes
87 # Create more heroes first
88 response = client.post(
89 "/heroes/",
90 json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"},
91 )
92 assert response.status_code == 200, response.text
93 response = client.post(
94 "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"}
95 )
96 assert response.status_code == 200, response.text
97
98 response = client.get("/heroes/")
99 assert response.status_code == 200, response.text
100 assert response.json() == snapshot(
101 [
102 {
103 "name": "Dead Pond",
104 "age": 30,
105 "id": IsInt(),
106 "secret_name": "Dive Wilson",
107 },
108 {
109 "name": "Spider-Boy",
110 "age": 18,
111 "id": IsInt(),
112 "secret_name": "Pedro Parqueador",
113 },
114 {
115 "name": "Rusty-Man",
116 "age": None,
117 "id": IsInt(),
118 "secret_name": "Tommy Sharp",
119 },
120 ]
121 )
122
123 response = client.get("/heroes/?offset=1&limit=1")
124 assert response.status_code == 200, response.text
125 assert response.json() == snapshot(
126 [
127 {
128 "name": "Spider-Boy",
129 "age": 18,
130 "id": IsInt(),
131 "secret_name": "Pedro Parqueador",
132 }
133 ]
134 )
135
136 # Delete a hero
137 response = client.delete(f"/heroes/{hero_id}")
138 assert response.status_code == 200, response.text
139 assert response.json() == snapshot({"ok": True})
140
141 response = client.get(f"/heroes/{hero_id}")
142 assert response.status_code == 404, response.text
143
144 response = client.delete(f"/heroes/{hero_id}")
145 assert response.status_code == 404, response.text
146 assert response.json() == snapshot({"detail": "Hero not found"})
147
148
149 def test_openapi_schema(client: TestClient):
150 response = client.get("/openapi.json")
151 assert response.status_code == 200, response.text
152 assert response.json() == snapshot(
153 {
154 "openapi": "3.1.0",
155 "info": {"title": "FastAPI", "version": "0.1.0"},
156 "paths": {
157 "/heroes/": {
158 "post": {
159 "summary": "Create Hero",
160 "operationId": "create_hero_heroes__post",
161 "requestBody": {
162 "required": True,
163 "content": {
164 "application/json": {
165 "schema": {"$ref": "#/components/schemas/Hero"}
166 }
167 },
168 },
169 "responses": {
170 "200": {
171 "description": "Successful Response",
172 "content": {
173 "application/json": {
174 "schema": {"$ref": "#/components/schemas/Hero"}
175 }
176 },
177 },
178 "422": {
179 "description": "Validation Error",
180 "content": {
181 "application/json": {
182 "schema": {
183 "$ref": "#/components/schemas/HTTPValidationError"
184 }
185 }
186 },
187 },
188 },
189 },
190 "get": {
191 "summary": "Read Heroes",
192 "operationId": "read_heroes_heroes__get",
193 "parameters": [
194 {
195 "name": "offset",
196 "in": "query",
197 "required": False,
198 "schema": {
199 "type": "integer",
200 "default": 0,
201 "title": "Offset",
202 },
203 },
204 {
205 "name": "limit",
206 "in": "query",
207 "required": False,
208 "schema": {
209 "type": "integer",
210 "maximum": 100,
211 "default": 100,
212 "title": "Limit",
213 },
214 },
215 ],
216 "responses": {
217 "200": {
218 "description": "Successful Response",
219 "content": {
220 "application/json": {
221 "schema": {
222 "type": "array",
223 "items": {
224 "$ref": "#/components/schemas/Hero"
225 },
226 "title": "Response Read Heroes Heroes Get",
227 }
228 }
229 },
230 },
231 "422": {
232 "description": "Validation Error",
233 "content": {
234 "application/json": {
235 "schema": {
236 "$ref": "#/components/schemas/HTTPValidationError"
237 }
238 }
239 },
240 },
241 },
242 },
243 },
244 "/heroes/{hero_id}": {
245 "get": {
246 "summary": "Read Hero",
247 "operationId": "read_hero_heroes__hero_id__get",
248 "parameters": [
249 {
250 "name": "hero_id",
251 "in": "path",
252 "required": True,
253 "schema": {"type": "integer", "title": "Hero Id"},
254 }
255 ],
256 "responses": {
257 "200": {
258 "description": "Successful Response",
259 "content": {
260 "application/json": {
261 "schema": {"$ref": "#/components/schemas/Hero"}
262 }
263 },
264 },
265 "422": {
266 "description": "Validation Error",
267 "content": {
268 "application/json": {
269 "schema": {
270 "$ref": "#/components/schemas/HTTPValidationError"
271 }
272 }
273 },
274 },
275 },
276 },
277 "delete": {
278 "summary": "Delete Hero",
279 "operationId": "delete_hero_heroes__hero_id__delete",
280 "parameters": [
281 {
282 "name": "hero_id",
283 "in": "path",
284 "required": True,
285 "schema": {"type": "integer", "title": "Hero Id"},
286 }
287 ],
288 "responses": {
289 "200": {
290 "description": "Successful Response",
291 "content": {"application/json": {"schema": {}}},
292 },
293 "422": {
294 "description": "Validation Error",
295 "content": {
296 "application/json": {
297 "schema": {
298 "$ref": "#/components/schemas/HTTPValidationError"
299 }
300 }
301 },
302 },
303 },
304 },
305 },
306 },
307 "components": {
308 "schemas": {
309 "HTTPValidationError": {
310 "properties": {
311 "detail": {
312 "items": {
313 "$ref": "#/components/schemas/ValidationError"
314 },
315 "type": "array",
316 "title": "Detail",
317 }
318 },
319 "type": "object",
320 "title": "HTTPValidationError",
321 },
322 "Hero": {
323 "properties": {
324 "id": {
325 "anyOf": [{"type": "integer"}, {"type": "null"}],
326 "title": "Id",
327 },
328 "name": {"type": "string", "title": "Name"},
329 "age": {
330 "anyOf": [{"type": "integer"}, {"type": "null"}],
331 "title": "Age",
332 },
333 "secret_name": {"type": "string", "title": "Secret Name"},
334 },
335 "type": "object",
336 "required": ["name", "secret_name"],
337 "title": "Hero",
338 },
339 "ValidationError": {
340 "properties": {
341 "ctx": {"title": "Context", "type": "object"},
342 "input": {"title": "Input"},
343 "loc": {
344 "items": {
345 "anyOf": [{"type": "string"}, {"type": "integer"}]
346 },
347 "type": "array",
348 "title": "Location",
349 },
350 "msg": {"type": "string", "title": "Message"},
351 "type": {"type": "string", "title": "Error Type"},
352 },
353 "type": "object",
354 "required": ["loc", "msg", "type"],
355 "title": "ValidationError",
356 },
357 }
358 },
359 }
360 )