Debian Codegraph @

tests/test_tutorial/test_security/test_tutorial005.py

raw
1 import importlib
2 from functools import lru_cache
3 from types import ModuleType
4 from typing import Any, cast
5
6 import pytest
7 from fastapi.testclient import TestClient
8 from inline_snapshot import snapshot
9
10 from ...utils import needs_py310
11
12
13 @pytest.fixture(
14 name="mod",
15 params=[
16 pytest.param("tutorial005_py310", marks=needs_py310),
17 pytest.param("tutorial005_an_py310", marks=needs_py310),
18 ],
19 scope="module",
20 )
21 def get_mod(request: pytest.FixtureRequest):
22 mod = importlib.import_module(f"docs_src.security.{request.param}")
23
24 return mod
25
26
27 @pytest.fixture(scope="module", autouse=True)
28 def cache_verify_password(mod: ModuleType):
29 assert hasattr(mod, "verify_password"), (
30 f"Module {mod.__name__} does not have attribute 'verify_password'"
31 )
32
33 mod_any = cast(Any, mod)
34 original_func = mod_any.verify_password
35 cached_func = lru_cache()(original_func)
36
37 mod_any.verify_password = cached_func
38 yield
39 mod_any.verify_password = original_func
40
41
42 def get_access_token(
43 *, username="johndoe", password="secret", scope=None, client: TestClient
44 ):
45 data = {"username": username, "password": password}
46 if scope:
47 data["scope"] = scope
48 response = client.post("/token", data=data)
49 content = response.json()
50 access_token = content.get("access_token")
51 return access_token
52
53
54 def test_login(mod: ModuleType):
55 client = TestClient(mod.app)
56 response = client.post("/token", data={"username": "johndoe", "password": "secret"})
57 assert response.status_code == 200, response.text
58 content = response.json()
59 assert "access_token" in content
60 assert content["token_type"] == "bearer"
61
62
63 def test_login_incorrect_password(mod: ModuleType):
64 client = TestClient(mod.app)
65 response = client.post(
66 "/token", data={"username": "johndoe", "password": "incorrect"}
67 )
68 assert response.status_code == 400, response.text
69 assert response.json() == {"detail": "Incorrect username or password"}
70
71
72 def test_login_incorrect_username(mod: ModuleType):
73 client = TestClient(mod.app)
74 response = client.post("/token", data={"username": "foo", "password": "secret"})
75 assert response.status_code == 400, response.text
76 assert response.json() == {"detail": "Incorrect username or password"}
77
78
79 def test_no_token(mod: ModuleType):
80 client = TestClient(mod.app)
81 response = client.get("/users/me")
82 assert response.status_code == 401, response.text
83 assert response.json() == {"detail": "Not authenticated"}
84 assert response.headers["WWW-Authenticate"] == "Bearer"
85
86
87 def test_token(mod: ModuleType):
88 client = TestClient(mod.app)
89 access_token = get_access_token(scope="me", client=client)
90 response = client.get(
91 "/users/me", headers={"Authorization": f"Bearer {access_token}"}
92 )
93 assert response.status_code == 200, response.text
94 assert response.json() == {
95 "username": "johndoe",
96 "full_name": "John Doe",
97 "email": "[email protected]",
98 "disabled": False,
99 }
100
101
102 def test_incorrect_token(mod: ModuleType):
103 client = TestClient(mod.app)
104 response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"})
105 assert response.status_code == 401, response.text
106 assert response.json() == {"detail": "Could not validate credentials"}
107 assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
108
109
110 def test_incorrect_token_type(mod: ModuleType):
111 client = TestClient(mod.app)
112 response = client.get(
113 "/users/me", headers={"Authorization": "Notexistent testtoken"}
114 )
115 assert response.status_code == 401, response.text
116 assert response.json() == {"detail": "Not authenticated"}
117 assert response.headers["WWW-Authenticate"] == "Bearer"
118
119
120 def test_verify_password(mod: ModuleType):
121 assert mod.verify_password(
122 "secret", mod.fake_users_db["johndoe"]["hashed_password"]
123 )
124
125
126 def test_get_password_hash(mod: ModuleType):
127 assert mod.get_password_hash("secretalice")
128
129
130 def test_create_access_token(mod: ModuleType):
131 access_token = mod.create_access_token(data={"data": "foo"})
132 assert access_token
133
134
135 def test_token_no_sub(mod: ModuleType):
136 client = TestClient(mod.app)
137
138 response = client.get(
139 "/users/me",
140 headers={
141 "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE"
142 },
143 )
144 assert response.status_code == 401, response.text
145 assert response.json() == {"detail": "Could not validate credentials"}
146 assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
147
148
149 def test_token_no_username(mod: ModuleType):
150 client = TestClient(mod.app)
151
152 response = client.get(
153 "/users/me",
154 headers={
155 "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y"
156 },
157 )
158 assert response.status_code == 401, response.text
159 assert response.json() == {"detail": "Could not validate credentials"}
160 assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
161
162
163 def test_token_no_scope(mod: ModuleType):
164 client = TestClient(mod.app)
165
166 access_token = get_access_token(client=client)
167 response = client.get(
168 "/users/me", headers={"Authorization": f"Bearer {access_token}"}
169 )
170 assert response.status_code == 401, response.text
171 assert response.json() == {"detail": "Not enough permissions"}
172 assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
173
174
175 def test_token_nonexistent_user(mod: ModuleType):
176 client = TestClient(mod.app)
177
178 response = client.get(
179 "/users/me",
180 headers={
181 "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw"
182 },
183 )
184 assert response.status_code == 401, response.text
185 assert response.json() == {"detail": "Could not validate credentials"}
186 assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
187
188
189 def test_token_inactive_user(mod: ModuleType):
190 client = TestClient(mod.app)
191
192 access_token = get_access_token(
193 username="alice", password="secretalice", scope="me", client=client
194 )
195 response = client.get(
196 "/users/me", headers={"Authorization": f"Bearer {access_token}"}
197 )
198 assert response.status_code == 400, response.text
199 assert response.json() == {"detail": "Inactive user"}
200
201
202 def test_read_items(mod: ModuleType):
203 client = TestClient(mod.app)
204 access_token = get_access_token(scope="me items", client=client)
205 response = client.get(
206 "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"}
207 )
208 assert response.status_code == 200, response.text
209 assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}]
210
211
212 def test_read_system_status(mod: ModuleType):
213 client = TestClient(mod.app)
214 access_token = get_access_token(client=client)
215 response = client.get(
216 "/status/", headers={"Authorization": f"Bearer {access_token}"}
217 )
218 assert response.status_code == 200, response.text
219 assert response.json() == {"status": "ok"}
220
221
222 def test_read_system_status_no_token(mod: ModuleType):
223 client = TestClient(mod.app)
224 response = client.get("/status/")
225 assert response.status_code == 401, response.text
226 assert response.json() == {"detail": "Not authenticated"}
227 assert response.headers["WWW-Authenticate"] == "Bearer"
228
229
230 def test_openapi_schema(mod: ModuleType):
231 client = TestClient(mod.app)
232 response = client.get("/openapi.json")
233 assert response.status_code == 200, response.text
234 assert response.json() == snapshot(
235 {
236 "openapi": "3.1.0",
237 "info": {"title": "FastAPI", "version": "0.1.0"},
238 "paths": {
239 "/token": {
240 "post": {
241 "responses": {
242 "200": {
243 "description": "Successful Response",
244 "content": {
245 "application/json": {
246 "schema": {"$ref": "#/components/schemas/Token"}
247 }
248 },
249 },
250 "422": {
251 "description": "Validation Error",
252 "content": {
253 "application/json": {
254 "schema": {
255 "$ref": "#/components/schemas/HTTPValidationError"
256 }
257 }
258 },
259 },
260 },
261 "summary": "Login For Access Token",
262 "operationId": "login_for_access_token_token_post",
263 "requestBody": {
264 "content": {
265 "application/x-www-form-urlencoded": {
266 "schema": {
267 "$ref": "#/components/schemas/Body_login_for_access_token_token_post"
268 }
269 }
270 },
271 "required": True,
272 },
273 }
274 },
275 "/users/me/": {
276 "get": {
277 "responses": {
278 "200": {
279 "description": "Successful Response",
280 "content": {
281 "application/json": {
282 "schema": {"$ref": "#/components/schemas/User"}
283 }
284 },
285 }
286 },
287 "summary": "Read Users Me",
288 "operationId": "read_users_me_users_me__get",
289 "security": [{"OAuth2PasswordBearer": ["me"]}],
290 }
291 },
292 "/users/me/items/": {
293 "get": {
294 "responses": {
295 "200": {
296 "description": "Successful Response",
297 "content": {"application/json": {"schema": {}}},
298 }
299 },
300 "summary": "Read Own Items",
301 "operationId": "read_own_items_users_me_items__get",
302 "security": [{"OAuth2PasswordBearer": ["items", "me"]}],
303 }
304 },
305 "/status/": {
306 "get": {
307 "responses": {
308 "200": {
309 "description": "Successful Response",
310 "content": {"application/json": {"schema": {}}},
311 }
312 },
313 "summary": "Read System Status",
314 "operationId": "read_system_status_status__get",
315 "security": [{"OAuth2PasswordBearer": []}],
316 }
317 },
318 },
319 "components": {
320 "schemas": {
321 "User": {
322 "title": "User",
323 "required": ["username"],
324 "type": "object",
325 "properties": {
326 "username": {"title": "Username", "type": "string"},
327 "email": {
328 "title": "Email",
329 "anyOf": [{"type": "string"}, {"type": "null"}],
330 },
331 "full_name": {
332 "title": "Full Name",
333 "anyOf": [{"type": "string"}, {"type": "null"}],
334 },
335 "disabled": {
336 "title": "Disabled",
337 "anyOf": [{"type": "boolean"}, {"type": "null"}],
338 },
339 },
340 },
341 "Token": {
342 "title": "Token",
343 "required": ["access_token", "token_type"],
344 "type": "object",
345 "properties": {
346 "access_token": {"title": "Access Token", "type": "string"},
347 "token_type": {"title": "Token Type", "type": "string"},
348 },
349 },
350 "Body_login_for_access_token_token_post": {
351 "title": "Body_login_for_access_token_token_post",
352 "required": ["username", "password"],
353 "type": "object",
354 "properties": {
355 "grant_type": {
356 "title": "Grant Type",
357 "anyOf": [
358 {"pattern": "^password$", "type": "string"},
359 {"type": "null"},
360 ],
361 },
362 "username": {"title": "Username", "type": "string"},
363 "password": {
364 "title": "Password",
365 "type": "string",
366 "format": "password",
367 },
368 "scope": {
369 "title": "Scope",
370 "type": "string",
371 "default": "",
372 },
373 "client_id": {
374 "title": "Client Id",
375 "anyOf": [{"type": "string"}, {"type": "null"}],
376 },
377 "client_secret": {
378 "title": "Client Secret",
379 "anyOf": [{"type": "string"}, {"type": "null"}],
380 "format": "password",
381 },
382 },
383 },
384 "ValidationError": {
385 "title": "ValidationError",
386 "required": ["loc", "msg", "type"],
387 "type": "object",
388 "properties": {
389 "loc": {
390 "title": "Location",
391 "type": "array",
392 "items": {
393 "anyOf": [{"type": "string"}, {"type": "integer"}]
394 },
395 },
396 "msg": {"title": "Message", "type": "string"},
397 "type": {"title": "Error Type", "type": "string"},
398 "input": {"title": "Input"},
399 "ctx": {"title": "Context", "type": "object"},
400 },
401 },
402 "HTTPValidationError": {
403 "title": "HTTPValidationError",
404 "type": "object",
405 "properties": {
406 "detail": {
407 "title": "Detail",
408 "type": "array",
409 "items": {
410 "$ref": "#/components/schemas/ValidationError"
411 },
412 }
413 },
414 },
415 },
416 "securitySchemes": {
417 "OAuth2PasswordBearer": {
418 "type": "oauth2",
419 "flows": {
420 "password": {
421 "scopes": {
422 "me": "Read information about the current user.",
423 "items": "Read items.",
424 },
425 "tokenUrl": "token",
426 }
427 },
428 }
429 },
430 },
431 }
432 )