gpt4 book ai didi

python - 如何使用通过安全 cookie 对用户进行身份验证的测试 Tornado 服务器处理程序

转载 作者:太空狗 更新时间:2023-10-29 20:43:56 28 4
gpt4 key购买 nike

如何为通过安全 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com