Coverage for tests/test_security_http_bearer.py: 100%
27 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
1from fastapi import FastAPI, Security 1abcdefg
2from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer 1abcdefg
3from fastapi.testclient import TestClient 1abcdefg
5app = FastAPI() 1abcdefg
7security = HTTPBearer() 1abcdefg
10@app.get("/users/me") 1abcdefg
11def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)): 1abcdefg
12 return {"scheme": credentials.scheme, "credentials": credentials.credentials} 1hijklmn
15client = TestClient(app) 1abcdefg
18def test_security_http_bearer(): 1abcdefg
19 response = client.get("/users/me", headers={"Authorization": "Bearer foobar"}) 1hijklmn
20 assert response.status_code == 200, response.text 1hijklmn
21 assert response.json() == {"scheme": "Bearer", "credentials": "foobar"} 1hijklmn
24def test_security_http_bearer_no_credentials(): 1abcdefg
25 response = client.get("/users/me") 1opqrstu
26 assert response.status_code == 401, response.text 1opqrstu
27 assert response.json() == {"detail": "Not authenticated"} 1opqrstu
28 assert response.headers["WWW-Authenticate"] == "Bearer" 1opqrstu
31def test_security_http_bearer_incorrect_scheme_credentials(): 1abcdefg
32 response = client.get("/users/me", headers={"Authorization": "Basic notreally"}) 1vwxyzAB
33 assert response.status_code == 401, response.text 1vwxyzAB
34 assert response.json() == {"detail": "Not authenticated"} 1vwxyzAB
35 assert response.headers["WWW-Authenticate"] == "Bearer" 1vwxyzAB
38def test_openapi_schema(): 1abcdefg
39 response = client.get("/openapi.json") 1CDEFGHI
40 assert response.status_code == 200, response.text 1CDEFGHI
41 assert response.json() == { 1CDEFGHI
42 "openapi": "3.1.0",
43 "info": {"title": "FastAPI", "version": "0.1.0"},
44 "paths": {
45 "/users/me": {
46 "get": {
47 "responses": {
48 "200": {
49 "description": "Successful Response",
50 "content": {"application/json": {"schema": {}}},
51 }
52 },
53 "summary": "Read Current User",
54 "operationId": "read_current_user_users_me_get",
55 "security": [{"HTTPBearer": []}],
56 }
57 }
58 },
59 "components": {
60 "securitySchemes": {"HTTPBearer": {"type": "http", "scheme": "bearer"}}
61 },
62 }