Debian Codegraph @

tests/test_security_http_basic_optional.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(auto_error=False)
11
12
13 @app.get("/users/me")
14 def read_current_user(credentials: HTTPBasicCredentials | None = Security(security)):
15 if credentials is None:
16 return {"msg": "Create an account first"}
17 return {"username": credentials.username, "password": credentials.password}
18
19
20 client = TestClient(app)
21
22
23 def test_security_http_basic():
24 response = client.get("/users/me", auth=("john", "secret"))
25 assert response.status_code == 200, response.text
26 assert response.json() == {"username": "john", "password": "secret"}
27
28
29 def test_security_http_basic_no_credentials():
30 response = client.get("/users/me")
31 assert response.status_code == 200, response.text
32 assert response.json() == {"msg": "Create an account first"}
33
34
35 def test_security_http_basic_invalid_credentials():
36 response = client.get(
37 "/users/me", headers={"Authorization": "Basic notabase64token"}
38 )
39 assert response.status_code == 401, response.text
40 assert response.headers["WWW-Authenticate"] == "Basic"
41 assert response.json() == {"detail": "Not authenticated"}
42
43
44 def test_security_http_basic_non_basic_credentials():
45 payload = b64encode(b"johnsecret").decode("ascii")
46 auth_header = f"Basic {payload}"
47 response = client.get("/users/me", headers={"Authorization": auth_header})
48 assert response.status_code == 401, response.text
49 assert response.headers["WWW-Authenticate"] == "Basic"
50 assert response.json() == {"detail": "Not authenticated"}
51
52
53 def test_openapi_schema():
54 response = client.get("/openapi.json")
55 assert response.status_code == 200, response.text
56 assert response.json() == snapshot(
57 {
58 "openapi": "3.1.0",
59 "info": {"title": "FastAPI", "version": "0.1.0"},
60 "paths": {
61 "/users/me": {
62 "get": {
63 "responses": {
64 "200": {
65 "description": "Successful Response",
66 "content": {"application/json": {"schema": {}}},
67 }
68 },
69 "summary": "Read Current User",
70 "operationId": "read_current_user_users_me_get",
71 "security": [{"HTTPBasic": []}],
72 }
73 }
74 },
75 "components": {
76 "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}}
77 },
78 }
79 )