Coverage for tests / test_security_http_bearer_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, HTTPBearer 1abcd

5from fastapi.testclient import TestClient 1abcd

6from inline_snapshot import snapshot 1abcd

7 

8app = FastAPI() 1abcd

9 

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

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

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

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

29 

30 

31def test_security_http_bearer_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_bearer_incorrect_scheme_credentials(): 1abcd

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

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

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

41 

42 

43def test_openapi_schema(): 1abcd

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

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

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

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

62 } 

63 } 

64 }, 

65 "components": { 

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

67 }, 

68 } 

69 )