Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask unit test: how to test request from logged in user

I'm writing some unit tests for my Flask web application and I'm trying to test the differences in the response between a request made by an anonymous user and a logged in user.

I'm using the Flask-Login extension to implement the user login/logout.

Obviously I'm able to perform an anonymous request, but how do I simulate a request from a logged in user?

I thought it was enough to send in the headers the session cookie, but it's not working.

headers = Headers({'Cookie':['WEBSITE_ID=%s; Domain=adsabs.harvard.edu; expires=Thu, 25-Apr-2213 16:53:22 GMT; Path=/' % cookie_value, 
                             'WEBSITE_ID=%s; Domain=.adsabs.harvard.edu; expires=Thu, 25-Apr-2213 16:53:22 GMT; Path=/' % cookie_value,
                             'session="A VERY LONG STRING"; Path=/; HttpOnly',
                 ]})
rv = app.test_client().get('/', headers=headers)

Where the session cookie value is a value I got from a real login in my browser.

What am I missing?

like image 860
Giovanni Di Milia Avatar asked Apr 26 '13 14:04

Giovanni Di Milia


1 Answers

Flask-Login looks for user_id in the session, you can set this in the tests using session_transaction:

with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['user_id'] = 'myuserid'
        sess['_fresh'] = True # https://flask-login.readthedocs.org/en/latest/#fresh-logins
    resp = c.get('/someurl')

Where myuserid is the id of your user object.

like image 89
DazWorrall Avatar answered Sep 19 '22 06:09

DazWorrall