Coverage for tests / test_security_http_base_optional.py: 100%

24 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.http import HTTPAuthorizationCredentials, HTTPBase 1abcd

3from fastapi.testclient import TestClient 1abcd

4from inline_snapshot import snapshot 1abcd

5 

6app = FastAPI() 1abcd

7 

8security = HTTPBase(scheme="Other", 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: 1efghijkl

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

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

18 

19 

20client = TestClient(app) 1abcd

21 

22 

23def test_security_http_base(): 1abcd

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

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

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

27 

28 

29def test_security_http_base_no_credentials(): 1abcd

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

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

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

33 

34 

35def test_openapi_schema(): 1abcd

36 response = client.get("/openapi.json") 1mnop

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

38 assert response.json() == snapshot( 1mnop

39 { 

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 } 

61 )