Coverage for tests/test_tutorial/test_security/test_tutorial006_an.py: 100%
29 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-13 13:38 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-13 13:38 +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")) 1uvwxy
12 assert response.status_code == 200, response.text 1uvwxy
13 assert response.json() == {"username": "john", "password": "secret"} 1uvwxy
16def test_security_http_basic_no_credentials(): 1abcde
17 response = client.get("/users/me") 1klmno
18 assert response.json() == {"detail": "Not authenticated"} 1klmno
19 assert response.status_code == 401, response.text 1klmno
20 assert response.headers["WWW-Authenticate"] == "Basic" 1klmno
23def test_security_http_basic_invalid_credentials(): 1abcde
24 response = client.get( 1pqrst
25 "/users/me", headers={"Authorization": "Basic notabase64token"}
26 )
27 assert response.status_code == 401, response.text 1pqrst
28 assert response.headers["WWW-Authenticate"] == "Basic" 1pqrst
29 assert response.json() == {"detail": "Invalid authentication credentials"} 1pqrst
32def test_security_http_basic_non_basic_credentials(): 1abcde
33 payload = b64encode(b"johnsecret").decode("ascii") 1fghij
34 auth_header = f"Basic {payload}" 1fghij
35 response = client.get("/users/me", headers={"Authorization": auth_header}) 1fghij
36 assert response.status_code == 401, response.text 1fghij
37 assert response.headers["WWW-Authenticate"] == "Basic" 1fghij
38 assert response.json() == {"detail": "Invalid authentication credentials"} 1fghij
41def test_openapi_schema(): 1abcde
42 response = client.get("/openapi.json") 1zABCD
43 assert response.status_code == 200, response.text 1zABCD
44 assert response.json() == { 1zABCD
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 }