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