Coverage for tests/test_security_http_bearer.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, HTTPBearer 1abcdefg

3from fastapi.testclient import TestClient 1abcdefg

4 

5app = FastAPI() 1abcdefg

6 

7security = HTTPBearer() 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_bearer(): 1abcdefg

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

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

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

22 

23 

24def test_security_http_bearer_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"] == "Bearer" 1opqrstu

29 

30 

31def test_security_http_bearer_incorrect_scheme_credentials(): 1abcdefg

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

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

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

35 assert response.headers["WWW-Authenticate"] == "Bearer" 1vwxyzAB

36 

37 

38def test_openapi_schema(): 1abcdefg

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

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

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

42 "openapi": "3.1.0", 

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

44 "paths": { 

45 "/users/me": { 

46 "get": { 

47 "responses": { 

48 "200": { 

49 "description": "Successful Response", 

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

51 } 

52 }, 

53 "summary": "Read Current User", 

54 "operationId": "read_current_user_users_me_get", 

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

56 } 

57 } 

58 }, 

59 "components": { 

60 "securitySchemes": {"HTTPBearer": {"type": "http", "scheme": "bearer"}} 

61 }, 

62 }