fastapi

Форк
0
/
test_security_api_key_cookie_optional.py 
73 строки · 2.1 Кб
1
from typing import Optional
2

3
from fastapi import Depends, FastAPI, Security
4
from fastapi.security import APIKeyCookie
5
from fastapi.testclient import TestClient
6
from pydantic import BaseModel
7

8
app = FastAPI()
9

10
api_key = APIKeyCookie(name="key", auto_error=False)
11

12

13
class User(BaseModel):
14
    username: str
15

16

17
def get_current_user(oauth_header: Optional[str] = Security(api_key)):
18
    if oauth_header is None:
19
        return None
20
    user = User(username=oauth_header)
21
    return user
22

23

24
@app.get("/users/me")
25
def read_current_user(current_user: User = Depends(get_current_user)):
26
    if current_user is None:
27
        return {"msg": "Create an account first"}
28
    else:
29
        return current_user
30

31

32
def test_security_api_key():
33
    client = TestClient(app, cookies={"key": "secret"})
34
    response = client.get("/users/me")
35
    assert response.status_code == 200, response.text
36
    assert response.json() == {"username": "secret"}
37

38

39
def test_security_api_key_no_key():
40
    client = TestClient(app)
41
    response = client.get("/users/me")
42
    assert response.status_code == 200, response.text
43
    assert response.json() == {"msg": "Create an account first"}
44

45

46
def test_openapi_schema():
47
    client = TestClient(app)
48
    response = client.get("/openapi.json")
49
    assert response.status_code == 200, response.text
50
    assert response.json() == {
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

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

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

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

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