测试Tornado应用程序的4xx状态代码

时间:2014-09-29 11:16:02

标签: python unit-testing testing tornado

考虑以下Tornado(v 4.0.2)应用程序,它是官方hello world示例的一点点修改版本:

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代码很有用,所以我不想放弃它们。但是我是龙卷风的新手,我无法找到测试它们的方法。有没有?

1 个答案:

答案 0 :(得分:4)

试试这个:

    @gen_test
    def test_bad_request(self):
        request = HTTPRequest(url=self.get_url('/'))
        with self.assertRaises(tornado.httpclient.HTTPError) as context:
            yield self.http_client.fetch(request)

        self.assertEqual(context.exception.code, 400)

请参阅assertRaises的文档。