3

我是 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

我编写以下代码作为示例。将其作为单元测试(鼻子)运行,出现上述错误。在将其作为独立应用程序运行并通过浏览器访问 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()
4

2 回答 2

13

发生的事情是您的 RequestHandler 中的 AsyncHTTPClient 正在另一个 IOLoop 上运行,该 IOLoop 永远不会启动。

您可以通过get_new_ioloop在测试用例中覆盖来解决此问题:

def get_new_ioloop(self):
    return tornado.ioloop.IOLoop.instance()

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

于 2013-02-08T18:49:22.617 回答
3

就我而言,默认超时是不够的,因为我正在对远程服务进行集成测试。

我在我的设置方法中覆盖了默认超时。

def setUp(self):
    super(AsyncHTTPTestCase, self).setUp()
    ## allow more time before timeout since we are doing remote access..
    os.environ["ASYNC_TEST_TIMEOUT"] = str(60)
于 2016-02-29T03:21:12.663 回答