Unit test flask: send cookies after session change

I am writing some unit tests for my flash application, and I need to simulate a request from a registered user (I use the bulb entry).

I found out here that for this I need to change the session and add the user ID and the _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 multiple cookies along with the request. Sort of

 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 execute this request, the session "disappears" along with the variables that I set.

I think (and someone else in the IRC has the same idea) because my explicit cookie header definition overwrites the file containing the session cookie.

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

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

+6
source share
2 answers

The solution was much simpler than I thought.

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

 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') 
+11
source

Do it:

 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) 
0
source

Source: https://habr.com/ru/post/943888/


All Articles