Coverage for tests / test_security_http_basic_realm.py: 100%
36 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
1from base64 import b64encode 1abcd
3from fastapi import FastAPI, Security 1abcd
4from fastapi.security import HTTPBasic, HTTPBasicCredentials 1abcd
5from fastapi.testclient import TestClient 1abcd
6from inline_snapshot import snapshot 1abcd
8app = FastAPI() 1abcd
10security = HTTPBasic(realm="simple") 1abcd
13@app.get("/users/me") 1abcd
14def read_current_user(credentials: HTTPBasicCredentials = Security(security)): 1abcd
15 return {"username": credentials.username, "password": credentials.password} 1hij
18client = TestClient(app) 1abcd
21def test_security_http_basic(): 1abcd
22 response = client.get("/users/me", auth=("john", "secret")) 1hij
23 assert response.status_code == 200, response.text 1hij
24 assert response.json() == {"username": "john", "password": "secret"} 1hij
27def test_security_http_basic_no_credentials(): 1abcd
28 response = client.get("/users/me") 1klm
29 assert response.json() == {"detail": "Not authenticated"} 1klm
30 assert response.status_code == 401, response.text 1klm
31 assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"' 1klm
34def test_security_http_basic_invalid_credentials(): 1abcd
35 response = client.get( 1nop
36 "/users/me", headers={"Authorization": "Basic notabase64token"}
37 )
38 assert response.status_code == 401, response.text 1nop
39 assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"' 1nop
40 assert response.json() == {"detail": "Not authenticated"} 1nop
43def test_security_http_basic_non_basic_credentials(): 1abcd
44 payload = b64encode(b"johnsecret").decode("ascii") 1efg
45 auth_header = f"Basic {payload}" 1efg
46 response = client.get("/users/me", headers={"Authorization": auth_header}) 1efg
47 assert response.status_code == 401, response.text 1efg
48 assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"' 1efg
49 assert response.json() == {"detail": "Not authenticated"} 1efg
52def test_openapi_schema(): 1abcd
53 response = client.get("/openapi.json") 1qrs
54 assert response.status_code == 200, response.text 1qrs
55 assert response.json() == snapshot( 1qrs
56 {
57 "openapi": "3.1.0",
58 "info": {"title": "FastAPI", "version": "0.1.0"},
59 "paths": {
60 "/users/me": {
61 "get": {
62 "responses": {
63 "200": {
64 "description": "Successful Response",
65 "content": {"application/json": {"schema": {}}},
66 }
67 },
68 "summary": "Read Current User",
69 "operationId": "read_current_user_users_me_get",
70 "security": [{"HTTPBasic": []}],
71 }
72 }
73 },
74 "components": {
75 "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}}
76 },
77 }
78 )