Coverage for tests / test_security_http_bearer_optional.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +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(auto_error=False) 1abcd

9 

10 

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

12def read_current_user( 1abcd

13 credentials: HTTPAuthorizationCredentials | None = Security(security), 

14): 

15 if credentials is None: 1efghijklmno

16 return {"msg": "Create an account first"} 1efhpjkmn

17 return {"scheme": credentials.scheme, "credentials": credentials.credentials} 1gilo

18 

19 

20client = TestClient(app) 1abcd

21 

22 

23def test_security_http_bearer(): 1abcd

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

25 assert response.status_code == 200, response.text 1gilo

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

27 

28 

29def test_security_http_bearer_no_credentials(): 1abcd

30 response = client.get("/users/me") 1fpkn

31 assert response.status_code == 200, response.text 1fpkn

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

33 

34 

35def test_security_http_bearer_incorrect_scheme_credentials(): 1abcd

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

37 assert response.status_code == 200, response.text 1ehjm

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

39 

40 

41def test_openapi_schema(): 1abcd

42 response = client.get("/openapi.json") 1qrst

43 assert response.status_code == 200, response.text 1qrst

44 assert response.json() == snapshot( 1qrst

45 { 

46 "openapi": "3.1.0", 

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

48 "paths": { 

49 "/users/me": { 

50 "get": { 

51 "responses": { 

52 "200": { 

53 "description": "Successful Response", 

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

55 } 

56 }, 

57 "summary": "Read Current User", 

58 "operationId": "read_current_user_users_me_get", 

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

60 } 

61 } 

62 }, 

63 "components": { 

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

65 }, 

66 } 

67 )