我想试着按照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编写测试,还是有人在应用程序内部调用处理程序?要遵循什么模式?如果有人能分享相关的代码那就太好了。
使用
AsyncHTTPTestCase
模式的主要原因是,它为您生成了所有的请求内容。当然,也可以使用AsyncTestCase
并手动处理它。AsyncTestCase示例。因为它将测试协同程序的} 使其更简单一些。^{} 需要
get
方法,所以我们将使用^{Application
和HTTPRequest
对象。因为我们没有转发应用程序的设置、ui_方法等,Application
是一个简单的模拟。我看你该用哪种模式。我为http动词方法(get、post等)选择
AsyncHTTPTestCase
,因为:当然,处理程序的其他方法都是用
AsyncTestCase
测试的。AsyncHTTPTestCase
是为与第一个示例类似的测试而设计的,使用self.fetch
而不是直接实例化处理程序。RequestHandler
不是设计为在不使用Application
的情况下手动实例化的,因此如果您有希望在没有完整HTTP堆栈的情况下测试的功能,则此代码通常应位于静态函数或非RequestHandler
类中。相关问题 更多 >
编程相关推荐