我正在尝试使用AsyncHTTPTestCase测试tornado。我想测试标记有@tornado.web.authenticated注释的处理程序。因为这个处理程序需要身份验证,所以我们必须首先登录,否则就会以某种方式欺骗它,以为我们在测试代码中通过了身份验证
class HandlerToTest(BaseHandler):
@tornado.web.authenticated
def get(self):
self.render("hello.html", user=self.get_current_user() )根据this article的说法,我们可以在饼干上做些手脚。我已经让它工作了,但根据Ben Darnell tornado maintainer的说法,不推荐这样做。本建议使用CookieLib模块,但这需要响应中的“info”部分,而我们没有。
另一个使用mox的blog post suggests mocking get_current_user()调用。然而,我不能让博客中的示例代码正常工作。
所以我的问题是:测试标记为已验证的处理程序的最佳方法是什么?有人能给我介绍一个样例应用程序吗?
发布于 2012-06-08 02:14:56
最终让Mocks工作了。我不知道这是不是“最好的方法”,但它可能会在未来对某些人有用。此代码测试2个处理程序并模拟@tornado.web.authenticated生成的get_current_user()调用
# encoding: utf-8
import os, os.path, sys
import tornado.web
import tornado.testing
import mox
class BaseHandler(tornado.web.RequestHandler):
def get_login_url(self):
return u"/login"
def get_current_user(self):
user_json = self.get_secure_cookie("user")
if user_json:
return tornado.escape.json_decode(user_json)
else:
return None
class HelloHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
self.render("protected.html")
class Protected(tornado.web.RequestHandler):
def get_current_user(self):
# get an user from somewhere
return "andy"
@tornado.web.authenticated
def get(self):
self.render("protected.html")
class TestAuthenticatedHandlers(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
self.mox = mox.Mox()
app = tornado.web.Application([
(r'/protected', Protected),
(r'/hello', HelloHandler)
])
return app
def tearDown(self):
self.mox.UnsetStubs()
self.mox.ResetAll()
def test_new_admin(self):
self.mox.StubOutWithMock(Protected, 'get_current_user', use_mock_anything=True)
Protected.get_current_user().AndReturn("test_user")
self.mox.ReplayAll()
resp = self.fetch('/protected')
self.assertEqual(resp.code, 200)
self.mox.VerifyAll()
def test_hello_page(self):
self.mox.StubOutWithMock(HelloHandler, 'get_current_user', use_mock_anything=True)
HelloHandler.get_current_user().AndReturn("test_user")
self.mox.ReplayAll()
resp = self.fetch('/hello')
self.assertEqual(resp.code, 200)
self.assertIn( "Hello", resp.body )
self.mox.VerifyAll()发布于 2012-11-22 22:57:58
此Torando utils库还允许您测试经过身份验证的处理程序:tornado_utils/http_test_client.py
发布于 2014-03-28 14:40:21
在我的例子中,工作很简单:
BaseHandler.get_current_user = lambda x: {'username': 'user', 'email': 'user@ex.com'}https://stackoverflow.com/questions/10936978
复制相似问题