【问题标题】:Cookies not setting on starlette TestClient, with requests sent via Python RequestsCookie 未在 starlette TestClient 上设置,请求通过 Python 请求发送
【发布时间】:2020-06-18 21:58:31
【问题描述】:

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。有人有解决此问题的经验吗?

【问题讨论】:

    标签: python cookies python-requests fastapi starlette


    【解决方案1】:

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

    assert "Authorization" in response.headers['set-cookie']

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

    【讨论】:

      【解决方案2】:

      刚碰到这个问题,就我而言,确实是因为TestClient使用的cookie域。

      您可以将您的 cookie_domain 作为base_url 提供给您的TestClient

      client = TestClient(app, base_url="http://example.com") 
      

      set-cookie 应该可以工作,只要 base_url 与 cookie 域一致。

      编辑:确保您的 cookie 域是没有 http://https:// 前缀的 FQDN

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-26
        • 2019-11-06
        • 1970-01-01
        • 2012-10-11
        • 2020-08-19
        • 2021-05-29
        相关资源
        最近更新 更多