Coverage for tests / test_security_http_bearer.py: 100%

28 statements  

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

1from fastapi import FastAPI, Security 1abcd

2from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer 1abcd

3from fastapi.testclient import TestClient 1abcd

4from inline_snapshot import snapshot 1abcd

5 

6app = FastAPI() 1abcd

7 

8security = HTTPBearer() 1abcd

9 

10 

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

12def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)): 1abcd

13 return {"scheme": credentials.scheme, "credentials": credentials.credentials} 1efg

14 

15 

16client = TestClient(app) 1abcd

17 

18 

19def test_security_http_bearer(): 1abcd

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

21 assert response.status_code == 200, response.text 1efg

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

23 

24 

25def test_security_http_bearer_no_credentials(): 1abcd

26 response = client.get("/users/me") 1hij

27 assert response.status_code == 401, response.text 1hij

28 assert response.json() == {"detail": "Not authenticated"} 1hij

29 assert response.headers["WWW-Authenticate"] == "Bearer" 1hij

30 

31 

32def test_security_http_bearer_incorrect_scheme_credentials(): 1abcd

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

34 assert response.status_code == 401, response.text 1klm

35 assert response.json() == {"detail": "Not authenticated"} 1klm

36 assert response.headers["WWW-Authenticate"] == "Bearer" 1klm

37 

38 

39def test_openapi_schema(): 1abcd

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

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

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

43 { 

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": [{"HTTPBearer": []}], 

58 } 

59 } 

60 }, 

61 "components": { 

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

63 }, 

64 } 

65 )