1
from fastapi import Depends, FastAPI, Security
2
from fastapi.security import APIKeyQuery
3
from fastapi.testclient import TestClient
4
from pydantic import BaseModel
8
api_key = APIKeyQuery(name="key", description="API Key Query")
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
client = TestClient(app)
28
def test_security_api_key():
29
response = client.get("/users/me?key=secret")
30
assert response.status_code == 200, response.text
31
assert response.json() == {"username": "secret"}
34
def test_security_api_key_no_key():
35
response = client.get("/users/me")
36
assert response.status_code == 403, response.text
37
assert response.json() == {"detail": "Not authenticated"}
40
def test_openapi_schema():
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": [{"APIKeyQuery": []}],
67
"description": "API Key Query",