Debian Codegraph @

tests/test_security_http_digest.py

raw
1 from fastapi import FastAPI, Security
2 from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest
3 from fastapi.testclient import TestClient
4 from inline_snapshot import snapshot
5
6 app = FastAPI()
7
8 security = HTTPDigest()
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_digest():
20 response = client.get("/users/me", headers={"Authorization": "Digest foobar"})
21 assert response.status_code == 200, response.text
22 assert response.json() == {"scheme": "Digest", "credentials": "foobar"}
23
24
25 def test_security_http_digest_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"] == "Digest"
30
31
32 def test_security_http_digest_incorrect_scheme_credentials():
33 response = client.get(
34 "/users/me", headers={"Authorization": "Other invalidauthorization"}
35 )
36 assert response.status_code == 401, response.text
37 assert response.json() == {"detail": "Not authenticated"}
38 assert response.headers["WWW-Authenticate"] == "Digest"
39
40
41 def test_openapi_schema():
42 response = client.get("/openapi.json")
43 assert response.status_code == 200, response.text
44 assert response.json() == snapshot(
45 {
46 "openapi": "3.1.0",
47 "info": {"title": "FastAPI", "version": "0.1.0"},
48 "paths": {
49 "/users/me": {
50 "get": {
51 "responses": {
52 "200": {
53 "description": "Successful Response",
54 "content": {"application/json": {"schema": {}}},
55 }
56 },
57 "summary": "Read Current User",
58 "operationId": "read_current_user_users_me_get",
59 "security": [{"HTTPDigest": []}],
60 }
61 }
62 },
63 "components": {
64 "securitySchemes": {"HTTPDigest": {"type": "http", "scheme": "digest"}}
65 },
66 }
67 )