Skip to main content
 首页 » 编程设计

python之Tornado 测试@tornado.web.authenticated

2025年05月04日33落叶无声

我正在尝试使用 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我们可以捏造 cookies 。我有这个工作,但根据 Ben Darnell tornado 维护者的说法,不推荐这样做。 Ben 建议使用 CookieLib模块,但这需要我们没有的响应的“信息”部分。

另一个blog post suggests mocking使用 mox 的 get_current_user() 调用.但是我无法使博客中的示例代码正常工作。

所以我的问题是: 测试标记为已验证的处理程序的最佳方法是什么?谁能给我指出一个示例应用程序?

请您参考如下方法:

最终让模拟工作。不知道这是否是“最佳方式”,但将来可能对某人有用。此代码测试 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()