Coverage for tests / test_security_http_digest_optional.py: 100%

29 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1from typing import Optional 1abcd

2 

3from fastapi import FastAPI, Security 1abcd

4from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest 1abcd

5from fastapi.testclient import TestClient 1abcd

6from inline_snapshot import snapshot 1abcd

7 

8app = FastAPI() 1abcd

9 

10security = HTTPDigest(auto_error=False) 1abcd

11 

12 

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

14def read_current_user( 1abcd

15 credentials: Optional[HTTPAuthorizationCredentials] = Security(security), 

16): 

17 if credentials is None: 1efghijklm

18 return {"msg": "Create an account first"} 1fgijlm

19 return {"scheme": credentials.scheme, "credentials": credentials.credentials} 1ehk

20 

21 

22client = TestClient(app) 1abcd

23 

24 

25def test_security_http_digest(): 1abcd

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

27 assert response.status_code == 200, response.text 1ehk

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

29 

30 

31def test_security_http_digest_no_credentials(): 1abcd

32 response = client.get("/users/me") 1gjm

33 assert response.status_code == 200, response.text 1gjm

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

35 

36 

37def test_security_http_digest_incorrect_scheme_credentials(): 1abcd

38 response = client.get( 1fil

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

40 ) 

41 assert response.status_code == 200, response.text 1fil

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

43 

44 

45def test_openapi_schema(): 1abcd

46 response = client.get("/openapi.json") 1nop

47 assert response.status_code == 200, response.text 1nop

48 assert response.json() == snapshot( 1nop

49 { 

50 "openapi": "3.1.0", 

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

52 "paths": { 

53 "/users/me": { 

54 "get": { 

55 "responses": { 

56 "200": { 

57 "description": "Successful Response", 

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

59 } 

60 }, 

61 "summary": "Read Current User", 

62 "operationId": "read_current_user_users_me_get", 

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

64 } 

65 } 

66 }, 

67 "components": { 

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

69 }, 

70 } 

71 )