fastapi

Форк
0
/
test_security_http_base_optional.py 
60 строк · 1.9 Кб
1
from typing import Optional
2

3
from fastapi import FastAPI, Security
4
from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase
5
from fastapi.testclient import TestClient
6

7
app = FastAPI()
8

9
security = HTTPBase(scheme="Other", auto_error=False)
10

11

12
@app.get("/users/me")
13
def read_current_user(
14
    credentials: Optional[HTTPAuthorizationCredentials] = Security(security),
15
):
16
    if credentials is None:
17
        return {"msg": "Create an account first"}
18
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}
19

20

21
client = TestClient(app)
22

23

24
def test_security_http_base():
25
    response = client.get("/users/me", headers={"Authorization": "Other foobar"})
26
    assert response.status_code == 200, response.text
27
    assert response.json() == {"scheme": "Other", "credentials": "foobar"}
28

29

30
def test_security_http_base_no_credentials():
31
    response = client.get("/users/me")
32
    assert response.status_code == 200, response.text
33
    assert response.json() == {"msg": "Create an account first"}
34

35

36
def test_openapi_schema():
37
    response = client.get("/openapi.json")
38
    assert response.status_code == 200, response.text
39
    assert response.json() == {
40
        "openapi": "3.1.0",
41
        "info": {"title": "FastAPI", "version": "0.1.0"},
42
        "paths": {
43
            "/users/me": {
44
                "get": {
45
                    "responses": {
46
                        "200": {
47
                            "description": "Successful Response",
48
                            "content": {"application/json": {"schema": {}}},
49
                        }
50
                    },
51
                    "summary": "Read Current User",
52
                    "operationId": "read_current_user_users_me_get",
53
                    "security": [{"HTTPBase": []}],
54
                }
55
            }
56
        },
57
        "components": {
58
            "securitySchemes": {"HTTPBase": {"type": "http", "scheme": "Other"}}
59
        },
60
    }
61

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

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

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

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