mirror of https://github.com/tiangolo/fastapi.git
HTTP Basic and Bearer auto error detail tests
This commit is contained in:
parent
d2cb0f73df
commit
f347a3583b
|
|
@ -0,0 +1,30 @@
|
|||
from typing import Optional
|
||||
|
||||
from fastapi import FastAPI, Security
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
error_message = "not a 20 minute adventure"
|
||||
security = HTTPBasic(auto_error=True, auto_error_detail=error_message)
|
||||
|
||||
|
||||
@app.get("/users/me")
|
||||
def read_current_user(credentials: Optional[HTTPBasicCredentials] = Security(security)):
|
||||
return {"username": credentials.username, "password": credentials.password}
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_security_http_basic():
|
||||
response = client.get("/users/me", auth=("john", "secret"))
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {"username": "john", "password": "secret"}
|
||||
|
||||
|
||||
def test_security_http_basic_no_credentials():
|
||||
response = client.get("/users/me")
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": error_message}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
from fastapi import FastAPI, Security
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
error_message = "not a 20 minute adventure"
|
||||
security = HTTPBearer(auto_error=True, auto_error_detail=error_message)
|
||||
|
||||
|
||||
@app.get("/users/me")
|
||||
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
|
||||
return {"scheme": credentials.scheme, "credentials": credentials.credentials}
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_security_http_bearer():
|
||||
response = client.get("/users/me", headers={"Authorization": "Bearer foobar"})
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {"scheme": "Bearer", "credentials": "foobar"}
|
||||
|
||||
|
||||
def test_security_http_bearer_no_credentials():
|
||||
response = client.get("/users/me")
|
||||
assert response.status_code == 403, response.text
|
||||
assert response.json() == {"detail": error_message}
|
||||
Loading…
Reference in New Issue