Coverage for tests/test_security_http_base.py: 100%

22 statements  

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

1from fastapi import FastAPI, Security 1abcdefg

2from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase 1abcdefg

3from fastapi.testclient import TestClient 1abcdefg

4 

5app = FastAPI() 1abcdefg

6 

7security = HTTPBase(scheme="Other") 1abcdefg

8 

9 

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

11def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)): 1abcdefg

12 return {"scheme": credentials.scheme, "credentials": credentials.credentials} 1hijklmn

13 

14 

15client = TestClient(app) 1abcdefg

16 

17 

18def test_security_http_base(): 1abcdefg

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

20 assert response.status_code == 200, response.text 1hijklmn

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

22 

23 

24def test_security_http_base_no_credentials(): 1abcdefg

25 response = client.get("/users/me") 1opqrstu

26 assert response.status_code == 401, response.text 1opqrstu

27 assert response.json() == {"detail": "Not authenticated"} 1opqrstu

28 assert response.headers["WWW-Authenticate"] == "Other" 1opqrstu

29 

30 

31def test_openapi_schema(): 1abcdefg

32 response = client.get("/openapi.json") 1vwxyzAB

33 assert response.status_code == 200, response.text 1vwxyzAB

34 assert response.json() == { 1vwxyzAB

35 "openapi": "3.1.0", 

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

37 "paths": { 

38 "/users/me": { 

39 "get": { 

40 "responses": { 

41 "200": { 

42 "description": "Successful Response", 

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

44 } 

45 }, 

46 "summary": "Read Current User", 

47 "operationId": "read_current_user_users_me_get", 

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

49 } 

50 } 

51 }, 

52 "components": { 

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

54 }, 

55 }