我正在尝试在编写Tornado应用程序时遵循TDD练习。我有一个get
方法的端点,它从几个API获取数据,过滤,组合并发送响应。对于这个get
处理程序,我创建了一个帮助程序,它负责异步数据提取。我想为它编写测试。
Helper看起来像这样:
class DummyHelper(object):
@gen.coroutine
def fetch(self, url):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(url)
raise gen.Return(response.body)
测试是:
from tornado.testing import AsyncHTTPTestCase
from tornado.web import HTTPError
import app
from lib.handlers.dummy import DummyHelper
from tornado.testing import gen_test
class TestDummyHandler(AsyncHTTPTestCase):
def get_app(self):
return app.get_app()
@gen_test
def test_200_fetch(self):
helper = DummyHelper()
response = yield helper.fetch("http://google.com/")
self.assertEqual(response.code, 200)
@gen_test
def test_404_fetch(self):
helper = DummyHelper()
with self.assertRaises(HTTPError):
yield helper.fetch("http://google.com/test")
test_200_fetch
的一切正常。但它不适用于test_404_fetch
。如何使它工作?我应该写这些测试吗?
答案 0 :(得分:1)
该测试针对不同的例外。有两个HTTPError
RequestHandler
中使用的from tornado.web import HTTPError
- 将变成HTTP错误响应的异常,from tornado.httpclient import HTTPError
由AsyncHTTPClient
在http错误上提出
您需要使用httpclient中的那个。
<强>提示强>
RequestHandler
进行测试,则可以使用AsyncTestCase
,但不需要get_app
示例强>
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
class DummyHelper(object):
@gen.coroutine
def fetch(self, url):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(url)
raise gen.Return(response)
import unittest
from tornado.testing import AsyncTestCase
from tornado.httpclient import HTTPError
from tornado.testing import gen_test
class TestDummyHandler(AsyncTestCase):
@gen_test
def test_200_fetch(self):
helper = DummyHelper()
response = yield helper.fetch("http://google.com/")
self.assertEqual(response.code, 200)
@gen_test
def test_404_fetch(self):
helper = DummyHelper()
with self.assertRaises(HTTPError):
yield helper.fetch("http://google.com/test")
if __name__ == '__main__':
unittest.main()