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

starlette TestClient上未设置Cookie,请求通过Python请求发送,python,cookies,python-requests,fastapi,starlette,Python,Cookies,Python Requests,Fastapi,Starlette,FastAPI上的登录/注销功能在浏览器中工作,但我正在尝试为其编写单元测试。当我的应用程序设置cookie时,我可以看到响应确实发送了cookie。当我通过Python请求收到cookie时,cookie已从响应中剥离,因此登录不起作用 @pytest.fixture(scope='module') def test_client(): app = create_app(testing=True) client = TestClient(app) client.base

FastAPI上的登录/注销功能在浏览器中工作,但我正在尝试为其编写单元测试。当我的应用程序设置cookie时,我可以看到响应确实发送了cookie。当我通过Python请求收到cookie时,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=/'})

(Pdb) response.headers
{'content-length': '24956', 'content-type': 'text/html; charset=utf-8'}

(Pdb) response.cookies
<RequestsCookieJar[]>
(Pdb) response.cookies.get_dict()
{}

收到响应后,在测试客户端的断点B()处,response.headers和response.cookies是这样的:

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=/'})

(Pdb) response.headers
{'content-length': '24956', 'content-type': 'text/html; charset=utf-8'}

(Pdb) response.cookies
<RequestsCookieJar[]>
(Pdb) response.cookies.get_dict()
{}

(Pdb)response.headers
{'content-length':'24956','content-type':'text/html;charset=utf-8'}
(Pdb)response.cookies
(Pdb)response.cookies.get_dict()
{}

我强烈怀疑这是因为域名问题-但我如何纠正这一点?在我的TestClient()中,我设置了
client.base\u url='1!'https://localhost“
,并在我的端点中创建我设置的cookie
域=https://localhost
。有人有过解决这个问题的经验吗?

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

在响应中断言“授权”。标题['set-cookie']

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