Question

I'm writing some unit tests for my flask application and I need to simulate a request from a logged in user (I'm using flask login).

I learned here that to do this I need to modify the session and add the user id and a _fresh parameter:

with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['user_id'] = 'myuserid'
        sess['_fresh'] = True
    resp = c.get('/someurl')

My problem is that I need to send some other cookies together with the request. Something like

headers = Headers({'Cookie':'MYCOOKIE=cookie_value;'})
with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['user_id'] = 'myuserid'
        sess['_fresh'] = True
    resp = c.get('/someurl', headers=headers)

but when I perform this request the session "disappears" together with the variables I set.

I think (and someone else on IRC has the same idea) it's because my explicit definition of the cookie header overwrites the one containing the session cookie.

My question is: is there a way to set my cookie without removing the session one?

If not, is there a way to extract the session cookie after I modify the session so that I can add it manually to the list of cookies in the headers object?

Was it helpful?

Solution

the solution was much easier than I thought.

The test client object has a method set_cookie, so the code should simply be:

with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['user_id'] = 'myuserid'
        sess['_fresh'] = True
    c.set_cookie('localhost', 'MYCOOKIE', 'cookie_value')
    resp = c.get('/someurl')

OTHER TIPS

Do this:

with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['user_id'] = 'myuserid'
        sess['_fresh'] = True
    resp = make_response(redirect('/someurl'))
    resp.set_cookie('MYCOOKIE', cookie_value)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top