Coverage for tests/test_top_level_security_scheme_in_openapi.py: 100%
22 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +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 1abcdefg
5from fastapi.security import HTTPBearer 1abcdefg
6from fastapi.testclient import TestClient 1abcdefg
7from inline_snapshot import snapshot 1abcdefg
9app = FastAPI() 1abcdefg
11bearer_scheme = HTTPBearer() 1abcdefg
14@app.get("/", dependencies=[Depends(bearer_scheme)]) 1abcdefg
15async def get_root(): 1abcdefg
16 return {"message": "Hello, World!"} 1hijklmn
19client = TestClient(app) 1abcdefg
22def test_get_root(): 1abcdefg
23 response = client.get("/", headers={"Authorization": "Bearer token"}) 1hijklmn
24 assert response.status_code == 200, response.text 1hijklmn
25 assert response.json() == {"message": "Hello, World!"} 1hijklmn
28def test_get_root_no_token(): 1abcdefg
29 response = client.get("/") 1opqrstu
30 assert response.status_code == 401, response.text 1opqrstu
31 assert response.json() == {"detail": "Not authenticated"} 1opqrstu
34def test_openapi_schema(): 1abcdefg
35 response = client.get("/openapi.json") 1vwxyzAB
36 assert response.status_code == 200, response.text 1vwxyzAB
37 assert response.json() == snapshot( 1vwxyzAB
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 )