Debian Codegraph @

tests/test_security_http_digest_optional.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(auto_error=False)
9
10
11 @app.get("/users/me")
12 def read_current_user(
13 credentials: HTTPAuthorizationCredentials | None = Security(security),
14 ):
15 if credentials is None:
16 return {"msg": "Create an account first"}
17 return {"scheme": credentials.scheme, "credentials": credentials.credentials}
18
19
20 client = TestClient(app)
21
22
23 def test_security_http_digest():
24 response = client.get("/users/me", headers={"Authorization": "Digest foobar"})
25 assert response.status_code == 200, response.text
26 assert response.json() == {"scheme": "Digest", "credentials": "foobar"}
27
28
29 def test_security_http_digest_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_digest_incorrect_scheme_credentials():
36 response = client.get(
37 "/users/me", headers={"Authorization": "Other invalidauthorization"}
38 )
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 "/users/me": {
52 "get": {
53 "responses": {
54 "200": {
55 "description": "Successful Response",
56 "content": {"application/json": {"schema": {}}},
57 }
58 },
59 "summary": "Read Current User",
60 "operationId": "read_current_user_users_me_get",
61 "security": [{"HTTPDigest": []}],
62 }
63 }
64 },
65 "components": {
66 "securitySchemes": {"HTTPDigest": {"type": "http", "scheme": "digest"}}
67 },
68 }
69 )