fastapi

Форк
0
/
test_security_api_key_cookie_description.py 
71 строка · 2.1 Кб
1
from fastapi import Depends, FastAPI, Security
2
from fastapi.security import APIKeyCookie
3
from fastapi.testclient import TestClient
4
from pydantic import BaseModel
5

6
app = FastAPI()
7

8
api_key = APIKeyCookie(name="key", description="An API Cookie Key")
9

10

11
class User(BaseModel):
12
    username: str
13

14

15
def get_current_user(oauth_header: str = Security(api_key)):
16
    user = User(username=oauth_header)
17
    return user
18

19

20
@app.get("/users/me")
21
def read_current_user(current_user: User = Depends(get_current_user)):
22
    return current_user
23

24

25
def test_security_api_key():
26
    client = TestClient(app, cookies={"key": "secret"})
27
    response = client.get("/users/me")
28
    assert response.status_code == 200, response.text
29
    assert response.json() == {"username": "secret"}
30

31

32
def test_security_api_key_no_key():
33
    client = TestClient(app)
34
    response = client.get("/users/me")
35
    assert response.status_code == 403, response.text
36
    assert response.json() == {"detail": "Not authenticated"}
37

38

39
def test_openapi_schema():
40
    client = TestClient(app)
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
            "/users/me": {
48
                "get": {
49
                    "responses": {
50
                        "200": {
51
                            "description": "Successful Response",
52
                            "content": {"application/json": {"schema": {}}},
53
                        }
54
                    },
55
                    "summary": "Read Current User",
56
                    "operationId": "read_current_user_users_me_get",
57
                    "security": [{"APIKeyCookie": []}],
58
                }
59
            }
60
        },
61
        "components": {
62
            "securitySchemes": {
63
                "APIKeyCookie": {
64
                    "type": "apiKey",
65
                    "name": "key",
66
                    "in": "cookie",
67
                    "description": "An API Cookie Key",
68
                }
69
            }
70
        },
71
    }
72

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

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

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

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