Debian Codegraph @

tests/test_security_api_key_cookie_description.py

raw
1 from fastapi import Depends, FastAPI, Security
2 from fastapi.security import APIKeyCookie
3 from fastapi.testclient import TestClient
4 from inline_snapshot import snapshot
5 from pydantic import BaseModel
6
7 app = FastAPI()
8
9 api_key = APIKeyCookie(name="key", description="An API Cookie Key")
10
11
12 class User(BaseModel):
13 username: str
14
15
16 def get_current_user(oauth_header: str = Security(api_key)):
17 user = User(username=oauth_header)
18 return user
19
20
21 @app.get("/users/me")
22 def read_current_user(current_user: User = Depends(get_current_user)):
23 return current_user
24
25
26 def test_security_api_key():
27 client = TestClient(app, cookies={"key": "secret"})
28 response = client.get("/users/me")
29 assert response.status_code == 200, response.text
30 assert response.json() == {"username": "secret"}
31
32
33 def test_security_api_key_no_key():
34 client = TestClient(app)
35 response = client.get("/users/me")
36 assert response.status_code == 401, response.text
37 assert response.json() == {"detail": "Not authenticated"}
38 assert response.headers["WWW-Authenticate"] == "APIKey"
39
40
41 def test_openapi_schema():
42 client = TestClient(app)
43 response = client.get("/openapi.json")
44 assert response.status_code == 200, response.text
45 assert response.json() == snapshot(
46 {
47 "openapi": "3.1.0",
48 "info": {"title": "FastAPI", "version": "0.1.0"},
49 "paths": {
50 "/users/me": {
51 "get": {
52 "responses": {
53 "200": {
54 "description": "Successful Response",
55 "content": {"application/json": {"schema": {}}},
56 }
57 },
58 "summary": "Read Current User",
59 "operationId": "read_current_user_users_me_get",
60 "security": [{"APIKeyCookie": []}],
61 }
62 }
63 },
64 "components": {
65 "securitySchemes": {
66 "APIKeyCookie": {
67 "type": "apiKey",
68 "name": "key",
69 "in": "cookie",
70 "description": "An API Cookie Key",
71 }
72 }
73 },
74 }
75 )