Coverage for tests / test_top_level_security_scheme_in_openapi.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1# Test security scheme at the top level, including OpenAPI 

2# Ref: https://github.com/fastapi/fastapi/discussions/14263 

3# Ref: https://github.com/fastapi/fastapi/issues/14271 

4from fastapi import Depends, FastAPI 1abcd

5from fastapi.security import HTTPBearer 1abcd

6from fastapi.testclient import TestClient 1abcd

7from inline_snapshot import snapshot 1abcd

8 

9app = FastAPI() 1abcd

10 

11bearer_scheme = HTTPBearer() 1abcd

12 

13 

14@app.get("/", dependencies=[Depends(bearer_scheme)]) 1abcd

15async def get_root(): 1abcd

16 return {"message": "Hello, World!"} 1efg

17 

18 

19client = TestClient(app) 1abcd

20 

21 

22def test_get_root(): 1abcd

23 response = client.get("/", headers={"Authorization": "Bearer token"}) 1efg

24 assert response.status_code == 200, response.text 1efg

25 assert response.json() == {"message": "Hello, World!"} 1efg

26 

27 

28def test_get_root_no_token(): 1abcd

29 response = client.get("/") 1hij

30 assert response.status_code == 401, response.text 1hij

31 assert response.json() == {"detail": "Not authenticated"} 1hij

32 

33 

34def test_openapi_schema(): 1abcd

35 response = client.get("/openapi.json") 1klm

36 assert response.status_code == 200, response.text 1klm

37 assert response.json() == snapshot( 1klm

38 { 

39 "openapi": "3.1.0", 

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

41 "paths": { 

42 "/": { 

43 "get": { 

44 "summary": "Get Root", 

45 "operationId": "get_root__get", 

46 "responses": { 

47 "200": { 

48 "description": "Successful Response", 

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

50 } 

51 }, 

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

53 } 

54 } 

55 }, 

56 "components": { 

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

58 }, 

59 } 

60 )