未在starlette TestClient上设置Cookie,并且通过Python请求发送了请求

时间:2020-03-06 07:31:29

标签: python cookies python-requests fastapi starlette

FastAPI的登录/注销功能可在浏览器中使用,但我试图为此编写单元测试。当我的应用设置cookie时,我可以看到响应确实发送了cookie。当我通过Python Request收到它时,该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.header和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。任何人都有解决此问题的经验吗?

1 个答案:

答案 0 :(得分:0)

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

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

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