如何使用通过安全cookie对用户进行身份验证的测试龙卷风服务器处理程序 [英] How to use a test tornado server handler that authenticates a user via a secure cookie

查看:64
本文介绍了如何使用通过安全cookie对用户进行身份验证的测试龙卷风服务器处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为通过安全cookie验证用户身份的龙卷风处理程序编写单元测试?这是我想通过的虚拟测试的代码(和sudo代码)。我正在使用Tornado 3.1。

How can I write a unit test for a tornado handler that authenticates a user via a secure cookie? Here is the code (and sudo code) for a dummy test that I'd like to make pass. I'm 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) )


推荐答案

使用模拟

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

这篇关于如何使用通过安全cookie对用户进行身份验证的测试龙卷风服务器处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆