fastapi

Форк
0
/
test_security_http_digest_optional.py 
68 строк · 2.2 Кб
1
from typing import Optional
2

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

7
app = FastAPI()
8

9
security = HTTPDigest(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_digest():
25
    response = client.get("/users/me", headers={"Authorization": "Digest foobar"})
26
    assert response.status_code == 200, response.text
27
    assert response.json() == {"scheme": "Digest", "credentials": "foobar"}
28

29

30
def test_security_http_digest_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_security_http_digest_incorrect_scheme_credentials():
37
    response = client.get(
38
        "/users/me", headers={"Authorization": "Other invalidauthorization"}
39
    )
40
    assert response.status_code == 403, response.text
41
    assert response.json() == {"detail": "Invalid authentication credentials"}
42

43

44
def test_openapi_schema():
45
    response = client.get("/openapi.json")
46
    assert response.status_code == 200, response.text
47
    assert response.json() == {
48
        "openapi": "3.1.0",
49
        "info": {"title": "FastAPI", "version": "0.1.0"},
50
        "paths": {
51
            "/users/me": {
52
                "get": {
53
                    "responses": {
54
                        "200": {
55
                            "description": "Successful Response",
56
                            "content": {"application/json": {"schema": {}}},
57
                        }
58
                    },
59
                    "summary": "Read Current User",
60
                    "operationId": "read_current_user_users_me_get",
61
                    "security": [{"HTTPDigest": []}],
62
                }
63
            }
64
        },
65
        "components": {
66
            "securitySchemes": {"HTTPDigest": {"type": "http", "scheme": "digest"}}
67
        },
68
    }
69

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

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

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

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