Debian Codegraph @

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