1
from fastapi import Depends, FastAPI, Security
2
from fastapi.security import APIKeyCookie
3
from fastapi.testclient import TestClient
4
from pydantic import BaseModel
8
api_key = APIKeyCookie(name="key", description="An API Cookie Key")
15
def get_current_user(oauth_header: str = Security(api_key)):
16
user = User(username=oauth_header)
21
def read_current_user(current_user: User = Depends(get_current_user)):
25
def test_security_api_key():
26
client = TestClient(app, cookies={"key": "secret"})
27
response = client.get("/users/me")
28
assert response.status_code == 200, response.text
29
assert response.json() == {"username": "secret"}
32
def test_security_api_key_no_key():
33
client = TestClient(app)
34
response = client.get("/users/me")
35
assert response.status_code == 403, response.text
36
assert response.json() == {"detail": "Not authenticated"}
39
def test_openapi_schema():
40
client = TestClient(app)
41
response = client.get("/openapi.json")
42
assert response.status_code == 200, response.text
43
assert response.json() == {
45
"info": {"title": "FastAPI", "version": "0.1.0"},
51
"description": "Successful Response",
52
"content": {"application/json": {"schema": {}}},
55
"summary": "Read Current User",
56
"operationId": "read_current_user_users_me_get",
57
"security": [{"APIKeyCookie": []}],
67
"description": "An API Cookie Key",