使用AsyncHttpTastCase测试异步方法时,龙卷风被阻止

cla*_*ark 3 unit-testing asynchronous tornado

我是python和tornado的新手,并尝试使用@ tornado.web.asynchronous为GET方法编写单元测试.但它始终阻止并输出以下错误消息:

Failure
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 327, in run
    testMethod()
File "/Developer/PycharmProjects/CanMusic/tornadotestcase.py", line 19, in test_gen
    response = self.fetch(r'/gen')
File "/Developer/python/canmusic_env/lib/python2.7/site-packages/tornado/testing.py", line 265, in fetch
    return self.wait()
File "/Developer/python/canmusic_env/lib/python2.7/site-packages/tornado/testing.py", line 205, in wait
    self.__rethrow()
File "/Developer/python/canmusic_env/lib/python2.7/site-packages/tornado/testing.py", line 149, in __rethrow
    raise_exc_info(failure)
File "/Developer/python/canmusic_env/lib/python2.7/site-packages/tornado/testing.py", line 186, in timeout_func
    timeout)
AssertionError: Async operation timed out after 5 seconds
Run Code Online (Sandbox Code Playgroud)

我编写以下代码作为示例.将其作为单元测试(鼻子)运行,得到上面的错误.当它作为独立的应用程序运行并通过浏览器访问URL时,它工作正常.我也尝试异步的回调版本(没有@ tornado.gen.engine和yield),结果相同.

为什么?我错过了什么?

import tornado.web, tornado.gen, tornado.httpclient, tornado.testing

class GenHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        http = tornado.httpclient.AsyncHTTPClient()
        response = yield tornado.gen.Task(http.fetch, 'http://www.google.com')
        self.finish()

# code for run nose test
class GenTestCase(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        return tornado.web.Application([(r'/gen', GenHandler)])
    def test_gen(self):
        response = self.fetch(r'/gen')
        assert response.code == 200

# code for run standalone
application = tornado.web.Application([(r'/gen', GenHandler),])
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Run Code Online (Sandbox Code Playgroud)

Col*_*ean 13

发生的事情是RequestHandler中的AsyncHTTPClient正在另一个永不启动的IOLoop上运行.

您可以通过覆盖get_new_ioloop测试用例来解决这个问题:

def get_new_ioloop(self):
    return tornado.ioloop.IOLoop.instance()
Run Code Online (Sandbox Code Playgroud)

这有点奇怪,但它发生的原因是每个AsyncTestCase/AsyncHTTPTestCase方法都会生成它自己的IOLoop,以实现更好的隔离.