FastAPI 上的登录/注销功能在浏览器中工作,但我正在尝试为它编写单元测试。当我的应用设置 cookie 时,我可以看到响应确实发送了 cookie。当我通过 Python 请求收到它时,cookie 已从响应中删除,因此登录不起作用。
@pytest.fixture(scope='module')
def test_client():
app = create_app(testing=True)
client = TestClient(app)
client.base_url = 'https://localhost'
from app.models import Base, User
Base.metadata.create_all(bind=engine)
yield client
db.flush()
Base.metadata.drop_all(bind=engine)
# Simple login functions.
def test_login(test_client):
response = test_client.post(url='/login', data=dict(
username=username,
password=password
), allow_redirects=True, proxies=proxies)
breakpointB()
assert response.headers
然后在浏览器中工作的服务器端:
@core.post("/login", response_model=schemas.Token)
async def login_for_access_token(*, request: Request, form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_db)):
token = jsonable_encoder(access_token)
response = RedirectResponse(url=request.url_for('index'), status_code=303)
response.set_cookie(
"Authorization",
value=f"Bearer {token}",
domain=os.environ.get('DOMAIN'),
httponly=False,
max_age=1800,
expires=1800,
)
breakpointA()
return response
所以在 BreakpointA() 处,就在发送响应之前,response.headers
如下所示:
MutableHeaders({'location': 'https://localhost/', 'set-cookie': 'Authorization="Bearer e
yJ0eXAiO5JKV1iLCJ4bGciOiJ2UzI1NiJ9.eyJzdWIiOi2b2Vqb2UiL253JleH1iOjE1DM0ODEzNTR7.zwbT9yV
OnV2V14Yrtuc1PP8wv82alz2354sgm0Rc7PgZIvc"; Domain=https://localhost; expires=Fri, 06 Mar 202
0 07:55:54 GMT; Max-Age=1800; Path=/'})
在 BreakpointB(),在我的测试客户端收到响应后,response.headers 和 response.cookies 如下所示:
(Pdb) response.headers
{'content-length': '24956', 'content-type': 'text/html; charset=utf-8'}
(Pdb) response.cookies
<RequestsCookieJar[]>
(Pdb) response.cookies.get_dict()
{}
我强烈怀疑这是因为域问题 - 但我该如何纠正呢?在我的 TestClient ( Starlette TestClient ) 中,我已经设置client.base_url = 'https://localhost'
了 ,并且在我的端点中制作了我设置的 cookie DOMAIN=https://localhost
。有人有解决这个问题的经验吗?