| 1 |
from fastapi import Depends, FastAPI, Security |
| 2 |
from fastapi.security import APIKeyQuery |
| 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 = APIKeyQuery(name="key", description="API Key Query") |
| 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 |
client = TestClient(app) |
| 27 |
|
| 28 |
|
| 29 |
def test_security_api_key(): |
| 30 |
response = client.get("/users/me?key=secret") |
| 31 |
assert response.status_code == 200, response.text |
| 32 |
assert response.json() == {"username": "secret"} |
| 33 |
|
| 34 |
|
| 35 |
def test_security_api_key_no_key(): |
| 36 |
response = client.get("/users/me") |
| 37 |
assert response.status_code == 401, response.text |
| 38 |
assert response.json() == {"detail": "Not authenticated"} |
| 39 |
assert response.headers["WWW-Authenticate"] == "APIKey" |
| 40 |
|
| 41 |
|
| 42 |
def test_openapi_schema(): |
| 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": [{"APIKeyQuery": []}], |
| 61 |
} |
| 62 |
} |
| 63 |
}, |
| 64 |
"components": { |
| 65 |
"securitySchemes": { |
| 66 |
"APIKeyQuery": { |
| 67 |
"type": "apiKey", |
| 68 |
"name": "key", |
| 69 |
"in": "query", |
| 70 |
"description": "API Key Query", |
| 71 |
} |
| 72 |
} |
| 73 |
}, |
| 74 |
} |
| 75 |
) |