fastapi

Форк
0
/
test_security_http_basic_realm_description.py 
81 строка · 2.8 Кб
1
from base64 import b64encode
2

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

7
app = FastAPI()
8

9
security = HTTPBasic(realm="simple", description="HTTPBasic scheme")
10

11

12
@app.get("/users/me")
13
def read_current_user(credentials: HTTPBasicCredentials = Security(security)):
14
    return {"username": credentials.username, "password": credentials.password}
15

16

17
client = TestClient(app)
18

19

20
def test_security_http_basic():
21
    response = client.get("/users/me", auth=("john", "secret"))
22
    assert response.status_code == 200, response.text
23
    assert response.json() == {"username": "john", "password": "secret"}
24

25

26
def test_security_http_basic_no_credentials():
27
    response = client.get("/users/me")
28
    assert response.json() == {"detail": "Not authenticated"}
29
    assert response.status_code == 401, response.text
30
    assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
31

32

33
def test_security_http_basic_invalid_credentials():
34
    response = client.get(
35
        "/users/me", headers={"Authorization": "Basic notabase64token"}
36
    )
37
    assert response.status_code == 401, response.text
38
    assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
39
    assert response.json() == {"detail": "Invalid authentication credentials"}
40

41

42
def test_security_http_basic_non_basic_credentials():
43
    payload = b64encode(b"johnsecret").decode("ascii")
44
    auth_header = f"Basic {payload}"
45
    response = client.get("/users/me", headers={"Authorization": auth_header})
46
    assert response.status_code == 401, response.text
47
    assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
48
    assert response.json() == {"detail": "Invalid authentication credentials"}
49

50

51
def test_openapi_schema():
52
    response = client.get("/openapi.json")
53
    assert response.status_code == 200, response.text
54
    assert response.json() == {
55
        "openapi": "3.1.0",
56
        "info": {"title": "FastAPI", "version": "0.1.0"},
57
        "paths": {
58
            "/users/me": {
59
                "get": {
60
                    "responses": {
61
                        "200": {
62
                            "description": "Successful Response",
63
                            "content": {"application/json": {"schema": {}}},
64
                        }
65
                    },
66
                    "summary": "Read Current User",
67
                    "operationId": "read_current_user_users_me_get",
68
                    "security": [{"HTTPBasic": []}],
69
                }
70
            }
71
        },
72
        "components": {
73
            "securitySchemes": {
74
                "HTTPBasic": {
75
                    "type": "http",
76
                    "scheme": "basic",
77
                    "description": "HTTPBasic scheme",
78
                }
79
            }
80
        },
81
    }
82

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

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

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

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