Coverage for tests / test_security_http_digest_optional.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +0000

1from fastapi import FastAPI, Security 1abcd

2from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest 1abcd

3from fastapi.testclient import TestClient 1abcd

4from inline_snapshot import snapshot 1abcd

5 

6app = FastAPI() 1abcd

7 

8security = HTTPDigest(auto_error=False) 1abcd

9 

10 

11@app.get("/users/me") 1abcd

12def read_current_user( 1abcd

13 credentials: HTTPAuthorizationCredentials | None = Security(security), 

14): 

15 if credentials is None: 1efghijklmno

16 return {"msg": "Create an account first"} 1efphjkmn

17 return {"scheme": credentials.scheme, "credentials": credentials.credentials} 1gilo

18 

19 

20client = TestClient(app) 1abcd

21 

22 

23def test_security_http_digest(): 1abcd

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

25 assert response.status_code == 200, response.text 1gilo

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

27 

28 

29def test_security_http_digest_no_credentials(): 1abcd

30 response = client.get("/users/me") 1fhkn

31 assert response.status_code == 200, response.text 1fhkn

32 assert response.json() == {"msg": "Create an account first"} 1fhkn

33 

34 

35def test_security_http_digest_incorrect_scheme_credentials(): 1abcd

36 response = client.get( 1epjm

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

38 ) 

39 assert response.status_code == 200, response.text 1epjm

40 assert response.json() == {"msg": "Create an account first"} 1epjm

41 

42 

43def test_openapi_schema(): 1abcd

44 response = client.get("/openapi.json") 1qrst

45 assert response.status_code == 200, response.text 1qrst

46 assert response.json() == snapshot( 1qrst

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 )