Coverage for tests/test_tutorial/test_security/test_tutorial006_an.py: 100%
29 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1from base64 import b64encode 1abcde
3from fastapi.testclient import TestClient 1abcde
5from docs_src.security.tutorial006_an import app 1abcde
7client = TestClient(app) 1abcde
10def test_security_http_basic(): 1abcde
11 response = client.get("/users/me", auth=("john", "secret")) 1abcde
12 assert response.status_code == 200, response.text 1abcde
13 assert response.json() == {"username": "john", "password": "secret"} 1abcde
16def test_security_http_basic_no_credentials(): 1abcde
17 response = client.get("/users/me") 1abcde
18 assert response.json() == {"detail": "Not authenticated"} 1abcde
19 assert response.status_code == 401, response.text 1abcde
20 assert response.headers["WWW-Authenticate"] == "Basic" 1abcde
23def test_security_http_basic_invalid_credentials(): 1abcde
24 response = client.get( 1abcde
25 "/users/me", headers={"Authorization": "Basic notabase64token"}
26 )
27 assert response.status_code == 401, response.text 1abcde
28 assert response.headers["WWW-Authenticate"] == "Basic" 1abcde
29 assert response.json() == {"detail": "Invalid authentication credentials"} 1abcde
32def test_security_http_basic_non_basic_credentials(): 1abcde
33 payload = b64encode(b"johnsecret").decode("ascii") 1abcde
34 auth_header = f"Basic {payload}" 1abcde
35 response = client.get("/users/me", headers={"Authorization": auth_header}) 1abcde
36 assert response.status_code == 401, response.text 1abcde
37 assert response.headers["WWW-Authenticate"] == "Basic" 1abcde
38 assert response.json() == {"detail": "Invalid authentication credentials"} 1abcde
41def test_openapi_schema(): 1abcde
42 response = client.get("/openapi.json") 1abcde
43 assert response.status_code == 200, response.text 1abcde
44 assert response.json() == { 1abcde
45 "openapi": "3.1.0",
46 "info": {"title": "FastAPI", "version": "0.1.0"},
47 "paths": {
48 "/users/me": {
49 "get": {
50 "responses": {
51 "200": {
52 "description": "Successful Response",
53 "content": {"application/json": {"schema": {}}},
54 }
55 },
56 "summary": "Read Current User",
57 "operationId": "read_current_user_users_me_get",
58 "security": [{"HTTPBasic": []}],
59 }
60 }
61 },
62 "components": {
63 "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}}
64 },
65 }