Coverage for tests/test_security_http_base_optional.py: 100%

24 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-05 00:03 +0000

1from typing import Optional 1abcdef

2 

3from fastapi import FastAPI, Security 1abcdef

4from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase 1abcdef

5from fastapi.testclient import TestClient 1abcdef

6 

7app = FastAPI() 1abcdef

8 

9security = HTTPBase(scheme="Other", auto_error=False) 1abcdef

10 

11 

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

13def read_current_user( 1abcdef

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

15): 

16 if credentials is None: 1ghijklmnopqr

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

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

19 

20 

21client = TestClient(app) 1abcdef

22 

23 

24def test_security_http_base(): 1abcdef

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

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

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

28 

29 

30def test_security_http_base_no_credentials(): 1abcdef

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

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

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

34 

35 

36def test_openapi_schema(): 1abcdef

37 response = client.get("/openapi.json") 1stuvwx

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

39 assert response.json() == { 1stuvwx

40 "openapi": "3.1.0", 

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

42 "paths": { 

43 "/users/me": { 

44 "get": { 

45 "responses": { 

46 "200": { 

47 "description": "Successful Response", 

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

49 } 

50 }, 

51 "summary": "Read Current User", 

52 "operationId": "read_current_user_users_me_get", 

53 "security": [{"HTTPBase": []}], 

54 } 

55 } 

56 }, 

57 "components": { 

58 "securitySchemes": {"HTTPBase": {"type": "http", "scheme": "Other"}} 

59 }, 

60 }