【问题标题】:How to test `@authenticated` handler using tornado.testing?如何使用 tornado.testing 测试`@authenticated` 处理程序?
【发布时间】:2016-08-03 13:01:55
【问题描述】:

我是使用脚本进行单元测试的新手。我尝试使用帖子数据中的参数验证登录,但我得到登录页面作为响应并且没有登录。由于@tornado.web.authenticated 我无法在没有登录的情况下访问其他功能并且它响应登录页面

import tornado
from tornado.testing import AsyncTestCase
from tornado.web import Application, RequestHandler
import app
import urllib

class MyTestCase(AsyncTestCase):
    @tornado.testing.gen_test
    def test_http_fetch_login(self):
        data = urllib.urlencode(dict(username='admin', password=''))
        client = AsyncHTTPClient(self.io_loop)
        response = yield client.fetch("http://localhost:8888/console/login/?", method="POST",body=data)
        # Test contents of response
        self.assertIn("Automaton web console", response.body)

    @tornado.testing.gen_test
    def test_http_fetch_config(self):
        client = AsyncHTTPClient(self.io_loop)
        response = yield client.fetch("http://localhost:8888/console/configuration/?")
        self.assertIn("server-version",response.body)

【问题讨论】:

    标签: python unit-testing web-applications tornado


    【解决方案1】:

    要测试使用 @authenticated 的代码(除非您正在测试重定向到登录页面本身),您需要传递一个 cookie(或您正在使用的任何形式的身份验证),该 cookie 将被您的 @987654322 接受@ 方法。具体细节取决于您进行身份验证的准确程度,但如果您使用 Tornado 的安全 cookie,您可能会使用 create_signed_value 函数对 cookie 进行编码。

    【讨论】:

      【解决方案2】:

      来自文档:

      如果您使用经过身份验证的装饰器装饰 post() 方法,并且用户未登录,则服务器将发送 403 响应。 @authenticated 装饰器只是 if not self.current_user: self.redirect() 的简写,可能不适用于非基于浏览器的登录方案。

      所以你可以使用mock 做这个答案中指出的:https://stackoverflow.com/a/18286742/1090700

      如果您有 secure_cookies=True 应用程序参数,则在 POST 调用中将引发另一个 403 状态。如果您想以非调试方式测试代码,您还可以使用模拟 POST 操作,同时保留 secure_cookies=True 应用程序参数,然后也模拟 check_xsrf_cookie Handler 方法,就像这样:

          # Some previous stuff...
          with mock.patch.object(YourSecuredHandler, 'get_secure_cookie') as mget:
              mget.return_value = 'user_email'
              response = self.fetch('/', method='GET')     
          with mock.patch.object(
                  YourSecuredHandler, 'check_xsrf_cookie') as mpost:
              mpost.return_value = None
              response = self.fetch(
                  url, method="POST", body=parse.urlencode(body1),
                  headers=headers)
              self.assertEqual(response.code, 201)
      

      【讨论】:

        猜你喜欢
        • 2012-03-09
        • 2017-03-28
        • 1970-01-01
        • 2019-08-25
        • 1970-01-01
        • 1970-01-01
        • 2017-03-30
        • 2022-08-18
        • 2016-09-23
        相关资源
        最近更新 更多