Debian Codegraph @

tests/test_security_http_bearer.py

raw
1 from fastapi import FastAPI, Security
2 from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
3 from fastapi.testclient import TestClient
4 from inline_snapshot import snapshot
5
6 app = FastAPI()
7
8 security = HTTPBearer()
9
10
11 @app.get("/users/me")
12 def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
13 return {"scheme": credentials.scheme, "credentials": credentials.credentials}
14
15
16 client = TestClient(app)
17
18
19 def test_security_http_bearer():
20 response = client.get("/users/me", headers={"Authorization": "Bearer foobar"})
21 assert response.status_code == 200, response.text
22 assert response.json() == {"scheme": "Bearer", "credentials": "foobar"}
23
24
25 def test_security_http_bearer_no_credentials():
26 response = client.get("/users/me")
27 assert response.status_code == 401, response.text
28 assert response.json() == {"detail": "Not authenticated"}
29 assert response.headers["WWW-Authenticate"] == "Bearer"
30
31
32 def test_security_http_bearer_incorrect_scheme_credentials():
33 response = client.get("/users/me", headers={"Authorization": "Basic notreally"})
34 assert response.status_code == 401, response.text
35 assert response.json() == {"detail": "Not authenticated"}
36 assert response.headers["WWW-Authenticate"] == "Bearer"
37
38
39 def test_openapi_schema():
40 response = client.get("/openapi.json")
41 assert response.status_code == 200, response.text
42 assert response.json() == snapshot(
43 {
44 "openapi": "3.1.0",
45 "info": {"title": "FastAPI", "version": "0.1.0"},
46 "paths": {
47 "/users/me": {
48 "get": {
49 "responses": {
50 "200": {
51 "description": "Successful Response",
52 "content": {"application/json": {"schema": {}}},
53 }
54 },
55 "summary": "Read Current User",
56 "operationId": "read_current_user_users_me_get",
57 "security": [{"HTTPBearer": []}],
58 }
59 }
60 },
61 "components": {
62 "securitySchemes": {"HTTPBearer": {"type": "http", "scheme": "bearer"}}
63 },
64 }
65 )