2012-06-07 43 views
2

我想用AsyncHTTPTestCase来测试龙卷风。我想测试用@ tornado.web.authenticated注解标记的处理程序。由于这种处理需要身份验证,我们必须首先登录或以某种方式在思考我们正在验证我们的测试代码龙卷风测试@ tornado.web.authenticated

class HandlerToTest(BaseHandler): 
    @tornado.web.authenticated 
    def get(self): 
    self.render("hello.html", user=self.get_current_user()) 

根据this article我们可以捏造的cookie欺骗它。我有这个工作,但根据本达内尔龙卷风维护者这不建议。 Ben建议使用CookieLib模块,但需要我们没有的响应的'info'部分。

另一个blog post suggests mocking get_current_user()调用使用mox。但是我无法在博客中获得示例代码。

所以我的问题是: 测试标记为认证的处理程序的最佳方式是什么?有人可以指点我的示例应用程序吗?

回答

3

最终得到了Mocks的工作。不知道这是否是'最好的方式',但它可能对未来某个人有用。这段代码测试2个处理器和嘲笑get_current_user()呼叫通过@tornado.web.authenticated产生:

# 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() 
-2

在我而言只是工作:

BaseHandler.get_current_user = lambda x: {'username': 'user', 'email': '[email protected]'} 
+0

或者添加更多的细节来解释它如何解决这个问题。 –

+0

我的意思是BaseHandler方法get_current_user可以用AsyncHTTPTestCase之外的任何函数覆盖。在其他方面龙卷风认证装饰只是检查self.current_user的值 –