fastapi

Форк
0
/
test_security_oauth2_authorization_code_bearer.py 
75 строк · 2.3 Кб
1
from typing import Optional
2

3
from fastapi import FastAPI, Security
4
from fastapi.security import OAuth2AuthorizationCodeBearer
5
from fastapi.testclient import TestClient
6

7
app = FastAPI()
8

9
oauth2_scheme = OAuth2AuthorizationCodeBearer(
10
    authorizationUrl="authorize", tokenUrl="token", auto_error=True
11
)
12

13

14
@app.get("/items/")
15
async def read_items(token: Optional[str] = Security(oauth2_scheme)):
16
    return {"token": token}
17

18

19
client = TestClient(app)
20

21

22
def test_no_token():
23
    response = client.get("/items")
24
    assert response.status_code == 401, response.text
25
    assert response.json() == {"detail": "Not authenticated"}
26

27

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"}
32

33

34
def test_token():
35
    response = client.get("/items", headers={"Authorization": "Bearer testtoken"})
36
    assert response.status_code == 200, response.text
37
    assert response.json() == {"token": "testtoken"}
38

39

40
def test_openapi_schema():
41
    response = client.get("/openapi.json")
42
    assert response.status_code == 200, response.text
43
    assert response.json() == {
44
        "openapi": "3.1.0",
45
        "info": {"title": "FastAPI", "version": "0.1.0"},
46
        "paths": {
47
            "/items/": {
48
                "get": {
49
                    "responses": {
50
                        "200": {
51
                            "description": "Successful Response",
52
                            "content": {"application/json": {"schema": {}}},
53
                        }
54
                    },
55
                    "summary": "Read Items",
56
                    "operationId": "read_items_items__get",
57
                    "security": [{"OAuth2AuthorizationCodeBearer": []}],
58
                }
59
            }
60
        },
61
        "components": {
62
            "securitySchemes": {
63
                "OAuth2AuthorizationCodeBearer": {
64
                    "type": "oauth2",
65
                    "flows": {
66
                        "authorizationCode": {
67
                            "authorizationUrl": "authorize",
68
                            "tokenUrl": "token",
69
                            "scopes": {},
70
                        }
71
                    },
72
                }
73
            }
74
        },
75
    }
76

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.