Actually gen_test.py tests something slightly different : a handler
that asynchronously calls another handler on the same IOLoop.
Here is the relevant subset:
"""
class GenSequenceHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
self.io_loop = self.request.connection.stream.io_loop
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.write("1")
self.io_loop.add_callback((yield gen.Callback("k2")))
yield gen.Wait("k2")
self.write("2")
# reuse an old key
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.finish("3")
class GenTaskHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
io_loop = self.request.connection.stream.io_loop
client = AsyncHTTPClient(io_loop=io_loop)
response = yield gen.Task(client.fetch,
self.get_argument('url'))
response.rethrow()
self.finish(b("got response: ") + response.body)
class GenWebTest(AsyncHTTPTestCase, LogTrapTestCase):
def get_app(self):
return Application([
('/sequence', GenSequenceHandler),
('/task', GenTaskHandler),
])
def test_task_handler(self):
response = self.fetch('/task?url=%s' %
url_escape(self.get_url('/sequence')))
self.assertEqual(response.body, b("got response: 123"))
"""
My case is testing a handler that asynchronously calls a third-party
ws.
Trying to reduce even more the problem, here is an executable snippet
that fails:
"""
from tornado import ioloop , gen
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.web import asynchronous, RequestHandler, Application
from tornado.testing import AsyncHTTPTestCase
import sys
class MainHandler(RequestHandler):
url = u'
http://www.google.com'
@asynchronous
@gen.engine
def get(self):
http_client = AsyncHTTPClient()
request = HTTPRequest(self.url)
response = yield gen.Task(http_client.fetch, request)
response.rethrow()
self.write(repr(response))
self.finish()
application = Application([(r"/", MainHandler),], debug=True)
class Test(AsyncHTTPTestCase):
def get_app(self):
return application
def test_task_handler(self):
response = self.fetch('/')
print >>sys.stderr, response
if __name__ == "__main__":
application.listen(8888)
ioloop.IOLoop.instance().start()
"""
launch it with `python -m tornado.testing async` for unit-testing : it
fails
launch the server with `python async.py` and then `curl -gi 'http://
localhost:8888/'` : it succeeds...