Debian Codegraph @

tests/test_top_level_security_scheme_in_openapi.py

raw
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
4 from fastapi import Depends, FastAPI
5 from fastapi.security import HTTPBearer
6 from fastapi.testclient import TestClient
7 from inline_snapshot import snapshot
8
9 app = FastAPI()
10
11 bearer_scheme = HTTPBearer()
12
13
14 @app.get("/", dependencies=[Depends(bearer_scheme)])
15 async def get_root():
16 return {"message": "Hello, World!"}
17
18
19 client = TestClient(app)
20
21
22 def test_get_root():
23 response = client.get("/", headers={"Authorization": "Bearer token"})
24 assert response.status_code == 200, response.text
25 assert response.json() == {"message": "Hello, World!"}
26
27
28 def test_get_root_no_token():
29 response = client.get("/")
30 assert response.status_code == 401, response.text
31 assert response.json() == {"detail": "Not authenticated"}
32
33
34 def test_openapi_schema():
35 response = client.get("/openapi.json")
36 assert response.status_code == 200, response.text
37 assert response.json() == snapshot(
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 )