Coverage for tests/test_security_http_bearer_optional.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1from typing import Optional 1abcdefg

2 

3from fastapi import FastAPI, Security 1abcdefg

4from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer 1abcdefg

5from fastapi.testclient import TestClient 1abcdefg

6 

7app = FastAPI() 1abcdefg

8 

9security = HTTPBearer(auto_error=False) 1abcdefg

10 

11 

12@app.get("/users/me") 1abcdefg

13def read_current_user( 1abcdefg

14 credentials: Optional[HTTPAuthorizationCredentials] = Security(security), 

15): 

16 if credentials is None: 1hijklmnopqrstuvwxyzAB

17 return {"msg": "Create an account first"} 1ijlmoprsuvxyAB

18 return {"scheme": credentials.scheme, "credentials": credentials.credentials} 1hknqtwz

19 

20 

21client = TestClient(app) 1abcdefg

22 

23 

24def test_security_http_bearer(): 1abcdefg

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

26 assert response.status_code == 200, response.text 1hknqtwz

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

28 

29 

30def test_security_http_bearer_no_credentials(): 1abcdefg

31 response = client.get("/users/me") 1jmpsvyB

32 assert response.status_code == 200, response.text 1jmpsvyB

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

34 

35 

36def test_security_http_bearer_incorrect_scheme_credentials(): 1abcdefg

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

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

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

40 

41 

42def test_openapi_schema(): 1abcdefg

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

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

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

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 }