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