如何为通过安全Cookie验证用户身份的 Tornado 处理程序编写单元测试?这是我想通过的虚拟测试的代码(和sudo代码)。我正在使用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) )

最佳答案

使用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) )

关于python - 如何使用通过安全Cookie对用户进行身份验证的测试 Tornado 服务器处理程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18285947/

10-12 01:25
查看更多