Coverage for tests/test_security_http_digest.py: 100%

27 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1from fastapi import FastAPI, Security 1abcdefg

2from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest 1abcdefg

3from fastapi.testclient import TestClient 1abcdefg

4 

5app = FastAPI() 1abcdefg

6 

7security = HTTPDigest() 1abcdefg

8 

9 

10@app.get("/users/me") 1abcdefg

11def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)): 1abcdefg

12 return {"scheme": credentials.scheme, "credentials": credentials.credentials} 1hijklmn

13 

14 

15client = TestClient(app) 1abcdefg

16 

17 

18def test_security_http_digest(): 1abcdefg

19 response = client.get("/users/me", headers={"Authorization": "Digest foobar"}) 1hijklmn

20 assert response.status_code == 200, response.text 1hijklmn

21 assert response.json() == {"scheme": "Digest", "credentials": "foobar"} 1hijklmn

22 

23 

24def test_security_http_digest_no_credentials(): 1abcdefg

25 response = client.get("/users/me") 1opqrstu

26 assert response.status_code == 401, response.text 1opqrstu

27 assert response.json() == {"detail": "Not authenticated"} 1opqrstu

28 assert response.headers["WWW-Authenticate"] == "Digest" 1opqrstu

29 

30 

31def test_security_http_digest_incorrect_scheme_credentials(): 1abcdefg

32 response = client.get( 1vwxyzAB

33 "/users/me", headers={"Authorization": "Other invalidauthorization"} 

34 ) 

35 assert response.status_code == 401, response.text 1vwxyzAB

36 assert response.json() == {"detail": "Not authenticated"} 1vwxyzAB

37 assert response.headers["WWW-Authenticate"] == "Digest" 1vwxyzAB

38 

39 

40def test_openapi_schema(): 1abcdefg

41 response = client.get("/openapi.json") 1CDEFGHI

42 assert response.status_code == 200, response.text 1CDEFGHI

43 assert response.json() == { 1CDEFGHI

44 "openapi": "3.1.0", 

45 "info": {"title": "FastAPI", "version": "0.1.0"}, 

46 "paths": { 

47 "/users/me": { 

48 "get": { 

49 "responses": { 

50 "200": { 

51 "description": "Successful Response", 

52 "content": {"application/json": {"schema": {}}}, 

53 } 

54 }, 

55 "summary": "Read Current User", 

56 "operationId": "read_current_user_users_me_get", 

57 "security": [{"HTTPDigest": []}], 

58 } 

59 } 

60 }, 

61 "components": { 

62 "securitySchemes": {"HTTPDigest": {"type": "http", "scheme": "digest"}} 

63 }, 

64 }