How to use a test tornado server handler that authenticates a user through a secure cookie

How can I write unit test for a tornado handler that authenticates a user through a secure cookie? Here is the code (and sudo code) for the dummy test I would like to do. I am using Tornado 3.1.

from tornado.web import Application, RequestHandler from tornado.escape import to_unicode, json_decode, json_encode from tornado.testing import AsyncHTTPTestCase class MainHandler(RequestHandler): """ Base handler to authenticate user via a secure cookie. This is used for an API. """ def get(self): user = self.get_secure_cookie('user') if user == 'user_email': self.write('sucess') else: self.write('fail') class UserAPITest(AsyncHTTPTestCase): def get_app(self): self.app = Application([('/', MainHandler)], cookie_secret='asdfasdf') return self.app def test_user_profile_annoymous(self): #SUDO CODE (what should go here?) #cookie = make_secure_cookie('user', 'user_email', cookie_secret) #headers = {'Cookie':cookie} response = self.fetch('/', method='GET', headers=headers) self.assertEqual('sucess', to_unicode(response.body) ) 
+8
python tornado unit-testing cookies
source share
2 answers

Using mock :

 import mock ... class UserAPITest(AsyncHTTPTestCase): def get_app(self): self.app = Application([('/', MainHandler)], cookie_secret='asdfasdf') return self.app def test_user_profile_annoymous(self): with mock.patch.object(MainHandler, 'get_secure_cookie') as m: m.return_value = 'user_email' response = self.fetch('/', method='GET') self.assertEqual('sucess', to_unicode(response.body) ) 
+9
source share

It seems you can try using the create_signed_value from the tornado.web module:

 from tornado.web import create_signed_value class UserAPITest(AsyncHTTPTestCase): def get_app(self): self.app = Application([('/', MainHandler)], cookie_secret='asdfasdf') return self.app def test_user_profile_annoymous(self): cookie_name, cookie_value = 'Cookie', 'value' secure_cookie = create_signed_value( self.app.settings["cookie_secret"], cookie_name, cookie_value) headers = {'Cookie': '='.join((cookie_name, secure_cookie))} response = self.fetch('/', method='GET', headers=headers) self.assertEqual('success', response.body) 
+6
source share

All Articles