python - Cookie 未在 starlette TestClient 上设置,请求通过 Python 请求发送

标签 python cookies python-requests fastapi starlette

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://本地主机。有人有解决这个问题的经验吗?

最佳答案

我遇到了同样的问题。虽然不是一个完美的解决方案,但我最终在测试中这样做了:

在 response.headers['set-cookie'] 中断言“授权”

...您可以根据需要检查字符串中的更多内容。

关于python - Cookie 未在 starlette TestClient 上设置,请求通过 Python 请求发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60559432/

相关文章:

java - 我该怎么办 session URL 很长,我无法附加 JSESSIONID=389729387392。解决方案是什么?

java - 更新 cookie 的 maxage 以使其在 Struts 2 中过期

python - 无法使用 requests.post 登录网站 - 指定 URL

Python请求模块url编码

python - Azure 网站 Kudu REST API - Python 中的身份验证

python - 如何在 Python 中调试卡住的 asyncio 协程?

python - 如何将 python-trio 与谷歌 Protocol Buffer 一起使用?

python - 如何在 Anaconda 中安装 binstar 包?

Python 3.x C API : Do I have to free the memory after extracting a string from a PyObject?

php - 删除 cookie 时出现问题,不会取消设置