Coverage for tests/test_security_http_bearer_description.py: 100%

25 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-05 00:03 +0000

1from fastapi import FastAPI, Security 1abcdef

2from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer 1abcdef

3from fastapi.testclient import TestClient 1abcdef

4 

5app = FastAPI() 1abcdef

6 

7security = HTTPBearer(description="HTTP Bearer token scheme") 1abcdef

8 

9 

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

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

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

13 

14 

15client = TestClient(app) 1abcdef

16 

17 

18def test_security_http_bearer(): 1abcdef

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

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

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

22 

23 

24def test_security_http_bearer_no_credentials(): 1abcdef

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

26 assert response.status_code == 403, response.text 1mnopqr

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

28 

29 

30def test_security_http_bearer_incorrect_scheme_credentials(): 1abcdef

31 response = client.get("/users/me", headers={"Authorization": "Basic notreally"}) 1stuvwx

32 assert response.status_code == 403, response.text 1stuvwx

33 assert response.json() == {"detail": "Invalid authentication credentials"} 1stuvwx

34 

35 

36def test_openapi_schema(): 1abcdef

37 response = client.get("/openapi.json") 1yzABCD

38 assert response.status_code == 200, response.text 1yzABCD

39 assert response.json() == { 1yzABCD

40 "openapi": "3.1.0", 

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

42 "paths": { 

43 "/users/me": { 

44 "get": { 

45 "responses": { 

46 "200": { 

47 "description": "Successful Response", 

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

49 } 

50 }, 

51 "summary": "Read Current User", 

52 "operationId": "read_current_user_users_me_get", 

53 "security": [{"HTTPBearer": []}], 

54 } 

55 } 

56 }, 

57 "components": { 

58 "securitySchemes": { 

59 "HTTPBearer": { 

60 "type": "http", 

61 "scheme": "bearer", 

62 "description": "HTTP Bearer token scheme", 

63 } 

64 } 

65 }, 

66 }