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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With