如何为python tornado应用程序编写单元测试?

2024-09-28 17:30:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想试着按照TDD实践写一些代码。我想创建一个基于python龙卷风框架的简单应用程序。我在网上搜索人们是如何为龙卷风编写测试的,发现了这样的东西:

class TestSomeHandler(AsyncHTTPTestCase):
    def test_success(self):
        response = self.fetch('/something')
        self.assertEqual(response.code, 200)

如果我错了,请纠正我,但它看起来更像集成测试。我试图为一些虚拟处理程序编写简单的单元测试。例如:

class SomeHandler(BaseHandler):
    @gen.coroutine
    def get(self):
        try:
            from_date = self.get_query_argument("from", default=None)
            datetime.datetime.strptime(from_date, '%Y-%m-%d')
        except ValueError:
            raise ValueError("Incorrect argument value for from_date = %s, should be YYYY-MM-DD" % from_date)

测试结果如下:

class TestSomeHandler(AsyncHTTPTestCase):

    def test_no_from_date_param(self):
        handler = SomeHandler()
        with self.assertRaises(ValueError):
            handler.get()

我知道我错过了get()应用程序和请求。尚未处理如何创建它们。

但我的问题是,人们是像第一个例子那样为tornado编写测试,还是有人在应用程序内部调用处理程序?要遵循什么模式?如果有人能分享相关的代码那就太好了。


Tags: 代码fromtestself应用程序处理程序getdate
2条回答

使用AsyncHTTPTestCase模式的主要原因是,它为您生成了所有的请求内容。当然,也可以使用AsyncTestCase并手动处理它。

AsyncTestCase示例。因为它将测试协同程序的get方法,所以我们将使用^{}使其更简单一些。^{}需要ApplicationHTTPRequest对象。因为我们没有转发应用程序的设置、ui_方法等,Application是一个简单的模拟。

from tornado.testing import AsyncTestCase, gen_test
from tornado.web import Application
from tornado.httpserver import HTTPRequest
from unittest.mock import Mock

class TestSomeHandler(AsyncTestCase):

    @gen_test
    def test_no_from_date_param(self):
        mock_application = Mock(spec=Application)
        payload_request = HTTPRequest(
            method='GET', uri='/test', headers=None, body=None
        )
        handler = SomeHandler(mock_applciation, payload_request)
        with self.assertRaises(ValueError):
            yield handler.get()

我看你该用哪种模式。我为http动词方法(get、post等)选择AsyncHTTPTestCase,因为:

  • 这样比较容易
  • 此方法的使用者是HTTP客户端,因此断言响应代码body非常有意义
  • 它防止了过于复杂的方法

当然,处理程序的其他方法都是用AsyncTestCase测试的。

AsyncHTTPTestCase是为与第一个示例类似的测试而设计的,使用self.fetch而不是直接实例化处理程序。

RequestHandler不是设计为在不使用Application的情况下手动实例化的,因此如果您有希望在没有完整HTTP堆栈的情况下测试的功能,则此代码通常应位于静态函数或非RequestHandler类中。

相关问题 更多 >