Debian Codegraph @

tests/test_tutorial/test_security/test_tutorial004.py

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