Debian Codegraph @

tests/test_security_http_basic_realm_description.py

raw
1 from base64 import b64encode
2
3 from fastapi import FastAPI, Security
4 from fastapi.security import HTTPBasic, HTTPBasicCredentials
5 from fastapi.testclient import TestClient
6 from inline_snapshot import snapshot
7
8 app = FastAPI()
9
10 security = HTTPBasic(realm="simple", description="HTTPBasic scheme")
11
12
13 @app.get("/users/me")
14 def read_current_user(credentials: HTTPBasicCredentials = Security(security)):
15 return {"username": credentials.username, "password": credentials.password}
16
17
18 client = TestClient(app)
19
20
21 def test_security_http_basic():
22 response = client.get("/users/me", auth=("john", "secret"))
23 assert response.status_code == 200, response.text
24 assert response.json() == {"username": "john", "password": "secret"}
25
26
27 def test_security_http_basic_no_credentials():
28 response = client.get("/users/me")
29 assert response.json() == {"detail": "Not authenticated"}
30 assert response.status_code == 401, response.text
31 assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
32
33
34 def test_security_http_basic_invalid_credentials():
35 response = client.get(
36 "/users/me", headers={"Authorization": "Basic notabase64token"}
37 )
38 assert response.status_code == 401, response.text
39 assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
40 assert response.json() == {"detail": "Not authenticated"}
41
42
43 def test_security_http_basic_non_basic_credentials():
44 payload = b64encode(b"johnsecret").decode("ascii")
45 auth_header = f"Basic {payload}"
46 response = client.get("/users/me", headers={"Authorization": auth_header})
47 assert response.status_code == 401, response.text
48 assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
49 assert response.json() == {"detail": "Not authenticated"}
50
51
52 def test_openapi_schema():
53 response = client.get("/openapi.json")
54 assert response.status_code == 200, response.text
55 assert response.json() == snapshot(
56 {
57 "openapi": "3.1.0",
58 "info": {"title": "FastAPI", "version": "0.1.0"},
59 "paths": {
60 "/users/me": {
61 "get": {
62 "responses": {
63 "200": {
64 "description": "Successful Response",
65 "content": {"application/json": {"schema": {}}},
66 }
67 },
68 "summary": "Read Current User",
69 "operationId": "read_current_user_users_me_get",
70 "security": [{"HTTPBasic": []}],
71 }
72 }
73 },
74 "components": {
75 "securitySchemes": {
76 "HTTPBasic": {
77 "type": "http",
78 "scheme": "basic",
79 "description": "HTTPBasic scheme",
80 }
81 }
82 },
83 }
84 )