1 changed files with 17 additions and 13 deletions
@ -1,20 +1,24 @@ |
|||||
from fastapi import Depends, FastAPI |
from fastapi import Depends, FastAPI |
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials |
from fastapi.security import HTTPBasic, HTTPBasicCredentials |
||||
from starlette.testclient import TestClient |
from fastapi.testclient import TestClient |
||||
|
|
||||
|
|
||||
def test_http_basic_includes_realm_by_default(): |
|
||||
app = FastAPI() |
app = FastAPI() |
||||
security = HTTPBasic() # no realm provided |
security = HTTPBasic() |
||||
|
|
||||
@app.get("/protected") |
@app.get("/users/me") |
||||
def protected(credentials: HTTPBasicCredentials = Depends(security)): |
def read_current_user(credentials: HTTPBasicCredentials = Depends(security)): |
||||
return {"username": credentials.username} |
return {"username": credentials.username, "password": credentials.password} |
||||
|
|
||||
client = TestClient(app) |
client = TestClient(app) |
||||
resp = client.get("/protected") |
|
||||
|
|
||||
assert resp.status_code == 401 |
def test_security_http_basic_default_realm(): |
||||
www_auth = resp.headers.get("www-authenticate") |
# 401 branch: should include default realm |
||||
assert www_auth is not None |
response = client.get("/users/me") |
||||
assert www_auth.startswith('Basic realm="') |
assert response.status_code == 401, response.text |
||||
|
assert response.headers["WWW-Authenticate"] == 'Basic realm="FastAPI"' |
||||
|
assert response.json() == {"detail": "Not authenticated"} |
||||
|
|
||||
|
# 200 branch: execute the return line to satisfy 100% coverage |
||||
|
ok = client.get("/users/me", auth=("john", "secret")) |
||||
|
assert ok.status_code == 200, ok.text |
||||
|
assert ok.json() == {"username": "john", "password": "secret"} |
||||
|
|||||
Loading…
Reference in new issue