1
from typing import Optional
3
from fastapi import FastAPI, Security
4
from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest
5
from fastapi.testclient import TestClient
9
security = HTTPDigest(auto_error=False)
14
credentials: Optional[HTTPAuthorizationCredentials] = Security(security),
16
if credentials is None:
17
return {"msg": "Create an account first"}
18
return {"scheme": credentials.scheme, "credentials": credentials.credentials}
21
client = TestClient(app)
24
def test_security_http_digest():
25
response = client.get("/users/me", headers={"Authorization": "Digest foobar"})
26
assert response.status_code == 200, response.text
27
assert response.json() == {"scheme": "Digest", "credentials": "foobar"}
30
def test_security_http_digest_no_credentials():
31
response = client.get("/users/me")
32
assert response.status_code == 200, response.text
33
assert response.json() == {"msg": "Create an account first"}
36
def test_security_http_digest_incorrect_scheme_credentials():
37
response = client.get(
38
"/users/me", headers={"Authorization": "Other invalidauthorization"}
40
assert response.status_code == 403, response.text
41
assert response.json() == {"detail": "Invalid authentication credentials"}
44
def test_openapi_schema():
45
response = client.get("/openapi.json")
46
assert response.status_code == 200, response.text
47
assert response.json() == {
49
"info": {"title": "FastAPI", "version": "0.1.0"},
55
"description": "Successful Response",
56
"content": {"application/json": {"schema": {}}},
59
"summary": "Read Current User",
60
"operationId": "read_current_user_users_me_get",
61
"security": [{"HTTPDigest": []}],
66
"securitySchemes": {"HTTPDigest": {"type": "http", "scheme": "digest"}}