| 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", auto_error=False) |
| 10 |
|
| 11 |
|
| 12 |
class User(BaseModel): |
| 13 |
username: str |
| 14 |
|
| 15 |
|
| 16 |
def get_current_user(oauth_header: str | None = Security(api_key)): |
| 17 |
if oauth_header is None: |
| 18 |
return None |
| 19 |
user = User(username=oauth_header) |
| 20 |
return user |
| 21 |
|
| 22 |
|
| 23 |
@app.get("/users/me") |
| 24 |
def read_current_user(current_user: User = Depends(get_current_user)): |
| 25 |
if current_user is None: |
| 26 |
return {"msg": "Create an account first"} |
| 27 |
else: |
| 28 |
return current_user |
| 29 |
|
| 30 |
|
| 31 |
def test_security_api_key(): |
| 32 |
client = TestClient(app, cookies={"key": "secret"}) |
| 33 |
response = client.get("/users/me") |
| 34 |
assert response.status_code == 200, response.text |
| 35 |
assert response.json() == {"username": "secret"} |
| 36 |
|
| 37 |
|
| 38 |
def test_security_api_key_no_key(): |
| 39 |
client = TestClient(app) |
| 40 |
response = client.get("/users/me") |
| 41 |
assert response.status_code == 200, response.text |
| 42 |
assert response.json() == {"msg": "Create an account first"} |
| 43 |
|
| 44 |
|
| 45 |
def test_openapi_schema(): |
| 46 |
client = TestClient(app) |
| 47 |
response = client.get("/openapi.json") |
| 48 |
assert response.status_code == 200, response.text |
| 49 |
assert response.json() == snapshot( |
| 50 |
{ |
| 51 |
"openapi": "3.1.0", |
| 52 |
"info": {"title": "FastAPI", "version": "0.1.0"}, |
| 53 |
"paths": { |
| 54 |
"/users/me": { |
| 55 |
"get": { |
| 56 |
"responses": { |
| 57 |
"200": { |
| 58 |
"description": "Successful Response", |
| 59 |
"content": {"application/json": {"schema": {}}}, |
| 60 |
} |
| 61 |
}, |
| 62 |
"summary": "Read Current User", |
| 63 |
"operationId": "read_current_user_users_me_get", |
| 64 |
"security": [{"APIKeyCookie": []}], |
| 65 |
} |
| 66 |
} |
| 67 |
}, |
| 68 |
"components": { |
| 69 |
"securitySchemes": { |
| 70 |
"APIKeyCookie": {"type": "apiKey", "name": "key", "in": "cookie"} |
| 71 |
} |
| 72 |
}, |
| 73 |
} |
| 74 |
) |