Debian Codegraph @

tests/test_security_oauth2_authorization_code_bearer.py

raw
1 from fastapi import FastAPI, Security
2 from fastapi.security import OAuth2AuthorizationCodeBearer
3 from fastapi.testclient import TestClient
4 from inline_snapshot import snapshot
5
6 app = FastAPI()
7
8 oauth2_scheme = OAuth2AuthorizationCodeBearer(
9 authorizationUrl="authorize", tokenUrl="token", auto_error=True
10 )
11
12
13 @app.get("/items/")
14 async def read_items(token: str | None = Security(oauth2_scheme)):
15 return {"token": token}
16
17
18 client = TestClient(app)
19
20
21 def test_no_token():
22 response = client.get("/items")
23 assert response.status_code == 401, response.text
24 assert response.json() == {"detail": "Not authenticated"}
25
26
27 def test_incorrect_token():
28 response = client.get("/items", headers={"Authorization": "Non-existent testtoken"})
29 assert response.status_code == 401, response.text
30 assert response.json() == {"detail": "Not authenticated"}
31
32
33 def test_token():
34 response = client.get("/items", headers={"Authorization": "Bearer testtoken"})
35 assert response.status_code == 200, response.text
36 assert response.json() == {"token": "testtoken"}
37
38
39 def test_token_with_whitespaces():
40 response = client.get("/items", headers={"Authorization": "Bearer testtoken "})
41 assert response.status_code == 200, response.text
42 assert response.json() == {"token": "testtoken"}
43
44
45 def test_openapi_schema():
46 response = client.get("/openapi.json")
47 assert response.status_code == 200, response.text
48 assert response.json() == snapshot(
49 {
50 "openapi": "3.1.0",
51 "info": {"title": "FastAPI", "version": "0.1.0"},
52 "paths": {
53 "/items/": {
54 "get": {
55 "responses": {
56 "200": {
57 "description": "Successful Response",
58 "content": {"application/json": {"schema": {}}},
59 }
60 },
61 "summary": "Read Items",
62 "operationId": "read_items_items__get",
63 "security": [{"OAuth2AuthorizationCodeBearer": []}],
64 }
65 }
66 },
67 "components": {
68 "securitySchemes": {
69 "OAuth2AuthorizationCodeBearer": {
70 "type": "oauth2",
71 "flows": {
72 "authorizationCode": {
73 "authorizationUrl": "authorize",
74 "tokenUrl": "token",
75 "scopes": {},
76 }
77 },
78 }
79 }
80 },
81 }
82 )