Coverage for tests/test_security_http_basic_optional.py: 100%
37 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 base64 import b64encode 1abcdefg
2from typing import Optional 1abcdefg
4from fastapi import FastAPI, Security 1abcdefg
5from fastapi.security import HTTPBasic, HTTPBasicCredentials 1abcdefg
6from fastapi.testclient import TestClient 1abcdefg
8app = FastAPI() 1abcdefg
10security = HTTPBasic(auto_error=False) 1abcdefg
13@app.get("/users/me") 1abcdefg
14def read_current_user(credentials: Optional[HTTPBasicCredentials] = Security(security)): 1abcdefg
15 if credentials is None: 1opqrstuvwxyzAB
16 return {"msg": "Create an account first"} 1prtvxzB
17 return {"username": credentials.username, "password": credentials.password} 1oqsuwyA
20client = TestClient(app) 1abcdefg
23def test_security_http_basic(): 1abcdefg
24 response = client.get("/users/me", auth=("john", "secret")) 1oqsuwyA
25 assert response.status_code == 200, response.text 1oqsuwyA
26 assert response.json() == {"username": "john", "password": "secret"} 1oqsuwyA
29def test_security_http_basic_no_credentials(): 1abcdefg
30 response = client.get("/users/me") 1prtvxzB
31 assert response.status_code == 200, response.text 1prtvxzB
32 assert response.json() == {"msg": "Create an account first"} 1prtvxzB
35def test_security_http_basic_invalid_credentials(): 1abcdefg
36 response = client.get( 1CDEFGHI
37 "/users/me", headers={"Authorization": "Basic notabase64token"}
38 )
39 assert response.status_code == 401, response.text 1CDEFGHI
40 assert response.headers["WWW-Authenticate"] == "Basic" 1CDEFGHI
41 assert response.json() == {"detail": "Not authenticated"} 1CDEFGHI
44def test_security_http_basic_non_basic_credentials(): 1abcdefg
45 payload = b64encode(b"johnsecret").decode("ascii") 1hijklmn
46 auth_header = f"Basic {payload}" 1hijklmn
47 response = client.get("/users/me", headers={"Authorization": auth_header}) 1hijklmn
48 assert response.status_code == 401, response.text 1hijklmn
49 assert response.headers["WWW-Authenticate"] == "Basic" 1hijklmn
50 assert response.json() == {"detail": "Not authenticated"} 1hijklmn
53def test_openapi_schema(): 1abcdefg
54 response = client.get("/openapi.json") 1JKLMNOP
55 assert response.status_code == 200, response.text 1JKLMNOP
56 assert response.json() == { 1JKLMNOP
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 }