Browse Source

Cover success path in default realm test

pull/14647/head
westinjiang 6 months ago
parent
commit
397bd62483
  1. 30
      tests/test_security_http_basic_default_realm.py

30
tests/test_security_http_basic_default_realm.py

@ -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
app = FastAPI()
security = HTTPBasic()
def test_http_basic_includes_realm_by_default(): @app.get("/users/me")
app = FastAPI() def read_current_user(credentials: HTTPBasicCredentials = Depends(security)):
security = HTTPBasic() # no realm provided return {"username": credentials.username, "password": credentials.password}
@app.get("/protected") client = TestClient(app)
def protected(credentials: HTTPBasicCredentials = Depends(security)):
return {"username": credentials.username}
client = TestClient(app) def test_security_http_basic_default_realm():
resp = client.get("/protected") # 401 branch: should include default realm
response = client.get("/users/me")
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == 'Basic realm="FastAPI"'
assert response.json() == {"detail": "Not authenticated"}
assert resp.status_code == 401 # 200 branch: execute the return line to satisfy 100% coverage
www_auth = resp.headers.get("www-authenticate") ok = client.get("/users/me", auth=("john", "secret"))
assert www_auth is not None assert ok.status_code == 200, ok.text
assert www_auth.startswith('Basic realm="') assert ok.json() == {"username": "john", "password": "secret"}

Loading…
Cancel
Save