flask test_client request with cookies in pytest

Viewed 11

I use flask to build APIs and some APIs require authentication. User will be authenticated via set-cookies when login.

# server side response
@app.route('/api/login', methods=['POST'])
def login():
    ...
    response = jsonify({"message":"success"})
    response.set_cookie("cookie-name", session_cookie,
                                expires=expires, httponly=True, secure=False)
    return response

In Postman, I can run all APIs successfully.

In pytest, I add cookies to the request header manually. But it is not working.

@pytest.fixture
def got_cookie(test_client):
    ...
    res = test_client.post("/api/login", headers=Headers)
    cookie = res.headers["Set-Cookie"]
    return cookie

def test_do_with_login_required(test_client, got_cookie):
    ...
    headers = {"Cookie": got_cookie}
    res = test_client.post("/api/do_something", data=data, headers=headers)
    assert res.status_code == 200

I have multiple APIs that require login authentication. What is the right way to request with cookies in pytest?

If possible please give me a simple example

0 Answers
Related