1
from typing import Optional
3
from fastapi import FastAPI, Security
4
from fastapi.security import OAuth2AuthorizationCodeBearer
5
from fastapi.testclient import TestClient
9
oauth2_scheme = OAuth2AuthorizationCodeBearer(
10
authorizationUrl="authorize", tokenUrl="token", auto_error=True
15
async def read_items(token: Optional[str] = Security(oauth2_scheme)):
16
return {"token": token}
19
client = TestClient(app)
23
response = client.get("/items")
24
assert response.status_code == 401, response.text
25
assert response.json() == {"detail": "Not authenticated"}
28
def test_incorrect_token():
29
response = client.get("/items", headers={"Authorization": "Non-existent testtoken"})
30
assert response.status_code == 401, response.text
31
assert response.json() == {"detail": "Not authenticated"}
35
response = client.get("/items", headers={"Authorization": "Bearer testtoken"})
36
assert response.status_code == 200, response.text
37
assert response.json() == {"token": "testtoken"}
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 Items",
56
"operationId": "read_items_items__get",
57
"security": [{"OAuth2AuthorizationCodeBearer": []}],
63
"OAuth2AuthorizationCodeBearer": {
66
"authorizationCode": {
67
"authorizationUrl": "authorize",