Debian Codegraph @

tests/test_security_oauth2_password_bearer_optional_description.py

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