1
考虑以下龙卷风(V 4.0.2)的应用程序,这是官方hello world例如一点点修改的版本:测试龙卷风应用为4xx状态代码
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.set_status(400)
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
正如你所看到的,这里唯一的区别set_status
致电MainHandler
。现在,我将这段代码保存为app.py
,然后我打开tests.py
,我把有这种简单的单元测试:
import tornado.ioloop
from tornado.httpclient import HTTPRequest
from tornado.testing import AsyncHTTPTestCase, gen_test
from app import application
class SimpleTest(AsyncHTTPTestCase):
def get_app(self):
return application
def get_new_ioloop(self):
return tornado.ioloop.IOLoop.instance()
@gen_test
def test_bad_request(self):
request = HTTPRequest(url=self.get_url('/'))
response = yield self.http_client.fetch(request)
self.assertEqual(response.code, 400)
当我运行这个测试与python -m tornado.test.runtests tests
我得到以下结果:
E
======================================================================
ERROR: test_bad_request (tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/testing.py", line 118, in __call__
result = self.orig_method(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tornado/testing.py", line 494, in post_coroutine
timeout=timeout)
File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 418, in run_sync
return future_cell[0].result()
File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 109, in result
raise_exc_info(self._exc_info)
File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 631, in run
yielded = self.gen.throw(*sys.exc_info())
File "tests.py", line 18, in test_bad_request
response = yield self.http_client.fetch(request)
File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 628, in run
value = future.result()
File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 111, in result
raise self._exception
HTTPError: HTTP 400: Bad Request
----------------------------------------------------------------------
Ran 1 test in 0.022s
FAILED (errors=1)
[E 140929 12:55:59 testing:687] FAIL
显然这是正确的,因为处理程序设置了400个状态码。 但是,如何测试我的应用程序的这种情况?我认为4xx代码很有用,所以我不想放弃它们。不过,我对Tornado并不陌生,因此我无法找到测试它们的方法。有没有?
确实有效。但是,应该有''context.exception.code''而不是''context.error.code''。还值得一提的是应该抓住''tornado.httpclient.HTTPError'',而不是''tornado.web.HTTPError''。尽管解决方案对我来说不太合适(为什么4xx响应是个例外?),答案是令人满意的。谢谢! – piotrekw 2014-09-29 13:59:56
感谢您的更正,我已经更新了我的答案。我认为Tornado的HTTP客户端如果因任何原因(包括服务器错误)无法下载URL,就会引发异常。无论如何,这是它提供的API。 =) – 2014-09-29 15:47:07