{
    "file_diffs": [
        {
            "old_file_content": "\"\"\"``tornado.gen`` is a generator-based interface to make it easier to\nwork in an asynchronous environment.  Code using the ``gen`` module\nis technically asynchronous, but it is written as a single generator\ninstead of a collection of separate functions.\n\nFor example, the following asynchronous handler:\n\n.. testcode::\n\n    class AsyncHandler(RequestHandler):\n        @asynchronous\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=self.on_fetch)\n\n        def on_fetch(self, response):\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n.. testoutput::\n   :hide:\n\ncould be written with ``gen`` as:\n\n.. testcode::\n\n    class GenAsyncHandler(RequestHandler):\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield http_client.fetch(\"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n.. testoutput::\n   :hide:\n\nMost asynchronous functions in Tornado return a `.Future`;\nyielding this object returns its `~.Future.result`.\n\nYou can also yield a list or dict of ``Futures``, which will be\nstarted at the same time and run in parallel; a list or dict of results will\nbe returned when they are all finished:\n\n.. testcode::\n\n    @gen.coroutine\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [http_client.fetch(url1),\n                                      http_client.fetch(url2)]\n        response_dict = yield dict(response3=http_client.fetch(url3),\n                                   response4=http_client.fetch(url4))\n        response3 = response_dict['response3']\n        response4 = response_dict['response4']\n\n.. testoutput::\n   :hide:\n\nIf the `~functools.singledispatch` library is available (standard in\nPython 3.4, available via the `singledispatch\n<https://pypi.python.org/pypi/singledispatch>`_ package on older\nversions), additional types of objects may be yielded. Tornado includes\nsupport for ``asyncio.Future`` and Twisted's ``Deferred`` class when\n``tornado.platform.asyncio`` and ``tornado.platform.twisted`` are imported.\nSee the `convert_yielded` function to extend this mechanism.\n\n.. versionchanged:: 3.2\n   Dict support added.\n\n.. versionchanged:: 4.1\n   Support added for yielding ``asyncio`` Futures and Twisted Deferreds\n   via ``singledispatch``.\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport functools\nimport itertools\nimport sys\nimport types\nimport weakref\n\nfrom tornado.concurrent import Future, TracebackFuture, is_future, chain_future\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import app_log\nfrom tornado import stack_context\n\ntry:\n    from functools import singledispatch  # py34+\nexcept ImportError as e:\n    try:\n        from singledispatch import singledispatch  # backport\n    except ImportError:\n        singledispatch = None\n\n\nclass KeyReuseError(Exception):\n    pass\n\n\nclass UnknownKeyError(Exception):\n    pass\n\n\nclass LeakedCallbackError(Exception):\n    pass\n\n\nclass BadYieldError(Exception):\n    pass\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n\nclass TimeoutError(Exception):\n    \"\"\"Exception raised by ``with_timeout``.\"\"\"\n\n\ndef engine(func):\n    \"\"\"Callback-oriented decorator for asynchronous generators.\n\n    This is an older interface; for new code that does not need to be\n    compatible with versions of Tornado older than 3.0 the\n    `coroutine` decorator is recommended instead.\n\n    This decorator is similar to `coroutine`, except it does not\n    return a `.Future` and the ``callback`` argument is not treated\n    specially.\n\n    In most cases, functions decorated with `engine` should take\n    a ``callback`` argument and invoke it with their result when\n    they are finished.  One notable exception is the\n    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,\n    which use ``self.finish()`` in place of a callback argument.\n    \"\"\"\n    func = _make_coroutine_wrapper(func, replace_callback=False)\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        future = func(*args, **kwargs)\n\n        def final_callback(future):\n            if future.result() is not None:\n                raise ReturnValueIgnoredError(\n                    \"@gen.engine functions cannot return values: %r\" %\n                    (future.result(),))\n        # The engine interface doesn't give us any way to return\n        # errors but to raise them into the stack context.\n        # Save the stack context here to use when the Future has resolved.\n        future.add_done_callback(stack_context.wrap(final_callback))\n    return wrapper\n\n\ndef coroutine(func, replace_callback=True):\n    \"\"\"Decorator for asynchronous generators.\n\n    Any generator that yields objects from this module must be wrapped\n    in either this decorator or `engine`.\n\n    Coroutines may \"return\" by raising the special exception\n    `Return(value) <Return>`.  In Python 3.3+, it is also possible for\n    the function to simply use the ``return value`` statement (prior to\n    Python 3.3 generators were not allowed to also return values).\n    In all versions of Python a coroutine that simply wishes to exit\n    early may use the ``return`` statement without a value.\n\n    Functions with this decorator return a `.Future`.  Additionally,\n    they may be called with a ``callback`` keyword argument, which\n    will be invoked with the future's result when it resolves.  If the\n    coroutine fails, the callback will not be run and an exception\n    will be raised into the surrounding `.StackContext`.  The\n    ``callback`` argument is not visible inside the decorated\n    function; it is handled by the decorator itself.\n\n    From the caller's perspective, ``@gen.coroutine`` is similar to\n    the combination of ``@return_future`` and ``@gen.engine``.\n\n    .. warning::\n\n       When exceptions occur inside a coroutine, the exception\n       information will be stored in the `.Future` object. You must\n       examine the result of the `.Future` object, or the exception\n       may go unnoticed by your code. This means yielding the function\n       if called from another coroutine, using something like\n       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`\n       to `.IOLoop.add_future`.\n\n    \"\"\"\n    return _make_coroutine_wrapper(func, replace_callback=True)\n\n\ndef _make_coroutine_wrapper(func, replace_callback):\n    \"\"\"The inner workings of ``@gen.coroutine`` and ``@gen.engine``.\n\n    The two decorators differ in their treatment of the ``callback``\n    argument, so we cannot simply implement ``@engine`` in terms of\n    ``@coroutine``.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        future = TracebackFuture()\n\n        if replace_callback and 'callback' in kwargs:\n            callback = kwargs.pop('callback')\n            IOLoop.current().add_future(\n                future, lambda future: callback(future.result()))\n\n        try:\n            result = func(*args, **kwargs)\n        except (Return, StopIteration) as e:\n            result = getattr(e, 'value', None)\n        except Exception:\n            future.set_exc_info(sys.exc_info())\n            return future\n        else:\n            if isinstance(result, types.GeneratorType):\n                # Inline the first iteration of Runner.run.  This lets us\n                # avoid the cost of creating a Runner when the coroutine\n                # never actually yields, which in turn allows us to\n                # use \"optional\" coroutines in critical path code without\n                # performance penalty for the synchronous case.\n                try:\n                    orig_stack_contexts = stack_context._state.contexts\n                    yielded = next(result)\n                    if stack_context._state.contexts is not orig_stack_contexts:\n                        yielded = TracebackFuture()\n                        yielded.set_exception(\n                            stack_context.StackContextInconsistentError(\n                                'stack_context inconsistency (probably caused '\n                                'by yield within a \"with StackContext\" block)'))\n                except (StopIteration, Return) as e:\n                    future.set_result(getattr(e, 'value', None))\n                except Exception:\n                    future.set_exc_info(sys.exc_info())\n                else:\n                    Runner(result, future, yielded)\n                try:\n                    return future\n                finally:\n                    # Subtle memory optimization: if next() raised an exception,\n                    # the future's exc_info contains a traceback which\n                    # includes this stack frame.  This creates a cycle,\n                    # which will be collected at the next full GC but has\n                    # been shown to greatly increase memory usage of\n                    # benchmarks (relative to the refcount-based scheme\n                    # used in the absence of cycles).  We can avoid the\n                    # cycle by clearing the local variable after we return it.\n                    future = None\n        future.set_result(result)\n        return future\n    return wrapper\n\n\nclass Return(Exception):\n    \"\"\"Special exception to return a value from a `coroutine`.\n\n    If this exception is raised, its value argument is used as the\n    result of the coroutine::\n\n        @gen.coroutine\n        def fetch_json(url):\n            response = yield AsyncHTTPClient().fetch(url)\n            raise gen.Return(json_decode(response.body))\n\n    In Python 3.3, this exception is no longer necessary: the ``return``\n    statement can be used directly to return a value (previously\n    ``yield`` and ``return`` with a value could not be combined in the\n    same function).\n\n    By analogy with the return statement, the value argument is optional,\n    but it is never necessary to ``raise gen.Return()``.  The ``return``\n    statement can be used with no arguments instead.\n    \"\"\"\n    def __init__(self, value=None):\n        super(Return, self).__init__()\n        self.value = value\n\n\nclass WaitIterator(object):\n    \"\"\"Provides an iterator to yield the results of futures as they finish.\n\n    Yielding a set of futures like this:\n\n    ``results = yield [future1, future2]``\n\n    pauses the coroutine until both ``future1`` and ``future2``\n    return, and then restarts the coroutine with the results of both\n    futures. If either future is an exception, the expression will\n    raise that exception and all the results will be lost.\n\n    If you need to get the result of each future as soon as possible,\n    or if you need the result of some futures even if others produce\n    errors, you can use ``WaitIterator``::\n\n      wait_iterator = gen.WaitIterator(future1, future2)\n      while not wait_iterator.done():\n          try:\n              result = yield wait_iterator.next()\n          except Exception as e:\n              print(\"Error {} from {}\".format(e, wait_iterator.current_future))\n          else:\n              print(\"Result {} recieved from {} at {}\".format(\n                  result, wait_iterator.current_future,\n                  wait_iterator.current_index))\n\n    Because results are returned as soon as they are available the\n    output from the iterator *will not be in the same order as the\n    input arguments*. If you need to know which future produced the\n    current result, you can use the attributes\n    ``WaitIterator.current_future``, or ``WaitIterator.current_index``\n    to get the index of the future from the input list. (if keyword\n    arguments were used in the construction of the `WaitIterator`,\n    ``current_index`` will use the corresponding keyword).\n\n    .. versionadded:: 4.1\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        if args and kwargs:\n            raise ValueError(\n                \"You must provide args or kwargs, not both\")\n\n        if kwargs:\n            self._unfinished = dict((f, k) for (k, f) in kwargs.items())\n            futures = list(kwargs.values())\n        else:\n            self._unfinished = dict((f, i) for (i, f) in enumerate(args))\n            futures = args\n\n        self._finished = collections.deque()\n        self.current_index = self.current_future = None\n        self._running_future = None\n\n        self_ref = weakref.ref(self)\n        for future in futures:\n            future.add_done_callback(functools.partial(\n                self._done_callback, self_ref))\n\n    def done(self):\n        \"\"\"Returns True if this iterator has no more results.\"\"\"\n        if self._finished or self._unfinished:\n            return False\n        # Clear the 'current' values when iteration is done.\n        self.current_index = self.current_future = None\n        return True\n\n    def next(self):\n        \"\"\"Returns a `.Future` that will yield the next available result.\n\n        Note that this `.Future` will not be the same object as any of\n        the inputs.\n        \"\"\"\n        self._running_future = TracebackFuture()\n\n        if self._finished:\n            self._return_result(self._finished.popleft())\n\n        return self._running_future\n\n    @staticmethod\n    def _done_callback(self_ref, done):\n        self = self_ref()\n        if self is not None:\n            if self._running_future and not self._running_future.done():\n                self._return_result(done)\n            else:\n                self._finished.append(done)\n\n    def _return_result(self, done):\n        \"\"\"Called set the returned future's state that of the future\n        we yielded, and set the current future for the iterator.\n        \"\"\"\n        chain_future(done, self._running_future)\n\n        self.current_future = done\n        self.current_index = self._unfinished.pop(done)\n\n\nclass YieldPoint(object):\n    \"\"\"Base class for objects that may be yielded from the generator.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def start(self, runner):\n        \"\"\"Called by the runner after the generator has yielded.\n\n        No other methods will be called on this object before ``start``.\n        \"\"\"\n        raise NotImplementedError()\n\n    def is_ready(self):\n        \"\"\"Called by the runner to determine whether to resume the generator.\n\n        Returns a boolean; may be called more than once.\n        \"\"\"\n        raise NotImplementedError()\n\n    def get_result(self):\n        \"\"\"Returns the value to use as the result of the yield expression.\n\n        This method will only be called once, and only after `is_ready`\n        has returned true.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass Callback(YieldPoint):\n    \"\"\"Returns a callable object that will allow a matching `Wait` to proceed.\n\n    The key may be any value suitable for use as a dictionary key, and is\n    used to match ``Callbacks`` to their corresponding ``Waits``.  The key\n    must be unique among outstanding callbacks within a single run of the\n    generator function, but may be reused across different runs of the same\n    function (so constants generally work fine).\n\n    The callback may be called with zero or one arguments; if an argument\n    is given it will be returned by `Wait`.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n        runner.register_callback(self.key)\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return self.runner.result_callback(self.key)\n\n\nclass Wait(YieldPoint):\n    \"\"\"Returns the argument passed to the result of a previous `Callback`.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key)\n\n\nclass WaitAll(YieldPoint):\n    \"\"\"Returns the results of multiple previous `Callbacks <Callback>`.\n\n    The argument is a sequence of `Callback` keys, and the result is\n    a list of results in the same order.\n\n    `WaitAll` is equivalent to yielding a list of `Wait` objects.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def __init__(self, keys):\n        self.keys = keys\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return all(self.runner.is_ready(key) for key in self.keys)\n\n    def get_result(self):\n        return [self.runner.pop_result(key) for key in self.keys]\n\n\ndef Task(func, *args, **kwargs):\n    \"\"\"Adapts a callback-based asynchronous function for use in coroutines.\n\n    Takes a function (and optional additional arguments) and runs it with\n    those arguments plus a ``callback`` keyword argument.  The argument passed\n    to the callback is returned as the result of the yield expression.\n\n    .. versionchanged:: 4.0\n       ``gen.Task`` is now a function that returns a `.Future`, instead of\n       a subclass of `YieldPoint`.  It still behaves the same way when\n       yielded.\n    \"\"\"\n    future = Future()\n\n    def handle_exception(typ, value, tb):\n        if future.done():\n            return False\n        future.set_exc_info((typ, value, tb))\n        return True\n\n    def set_result(result):\n        if future.done():\n            return\n        future.set_result(result)\n    with stack_context.ExceptionStackContext(handle_exception):\n        func(*args, callback=_argument_adapter(set_result), **kwargs)\n    return future\n\n\nclass YieldFuture(YieldPoint):\n    def __init__(self, future, io_loop=None):\n        \"\"\"Adapts a `.Future` to the `YieldPoint` interface.\n\n        .. versionchanged:: 4.1\n           The ``io_loop`` argument is deprecated.\n        \"\"\"\n        self.future = future\n        self.io_loop = io_loop or IOLoop.current()\n\n    def start(self, runner):\n        if not self.future.done():\n            self.runner = runner\n            self.key = object()\n            runner.register_callback(self.key)\n            self.io_loop.add_future(self.future, runner.result_callback(self.key))\n        else:\n            self.runner = None\n            self.result = self.future.result()\n\n    def is_ready(self):\n        if self.runner is not None:\n            return self.runner.is_ready(self.key)\n        else:\n            return True\n\n    def get_result(self):\n        if self.runner is not None:\n            return self.runner.pop_result(self.key).result()\n        else:\n            return self.result\n\n\nclass Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``YieldPoints`` or ``Futures`` and returns a list of\n    their responses.  It is not necessary to call `Multi` explicitly,\n    since the engine will do so automatically when the generator yields\n    a list of ``YieldPoints`` or a mixture of ``YieldPoints`` and ``Futures``.\n\n    Instead of a list, the argument may also be a dictionary whose values are\n    Futures, in which case a parallel dictionary is returned mapping the same\n    keys to their results.\n    \"\"\"\n    def __init__(self, children):\n        self.keys = None\n        if isinstance(children, dict):\n            self.keys = list(children.keys())\n            children = children.values()\n        self.children = []\n        for i in children:\n            if is_future(i):\n                i = YieldFuture(i)\n            self.children.append(i)\n        assert all(isinstance(i, YieldPoint) for i in self.children)\n        self.unfinished_children = set(self.children)\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        finished = list(itertools.takewhile(\n            lambda i: i.is_ready(), self.unfinished_children))\n        self.unfinished_children.difference_update(finished)\n        return not self.unfinished_children\n\n    def get_result(self):\n        result = (i.get_result() for i in self.children)\n        if self.keys is not None:\n            return dict(zip(self.keys, result))\n        else:\n            return list(result)\n\n\ndef multi_future(children):\n    \"\"\"Wait for multiple asynchronous futures in parallel.\n\n    Takes a list of ``Futures`` (but *not* other ``YieldPoints``) and returns\n    a new Future that resolves when all the other Futures are done.\n    If all the ``Futures`` succeeded, the returned Future's result is a list\n    of their results.  If any failed, the returned Future raises the exception\n    of the first one to fail.\n\n    Instead of a list, the argument may also be a dictionary whose values are\n    Futures, in which case a parallel dictionary is returned mapping the same\n    keys to their results.\n\n    It is not necessary to call `multi_future` explcitly, since the engine will\n    do so automatically when the generator yields a list of `Futures`.\n    This function is faster than the `Multi` `YieldPoint` because it does not\n    require the creation of a stack context.\n\n    .. versionadded:: 4.0\n    \"\"\"\n    if isinstance(children, dict):\n        keys = list(children.keys())\n        children = children.values()\n    else:\n        keys = None\n    assert all(is_future(i) for i in children)\n    unfinished_children = set(children)\n\n    future = Future()\n    if not children:\n        future.set_result({} if keys is not None else [])\n\n    def callback(f):\n        unfinished_children.remove(f)\n        if not unfinished_children:\n            try:\n                result_list = [i.result() for i in children]\n            except Exception:\n                future.set_exc_info(sys.exc_info())\n            else:\n                if keys is not None:\n                    future.set_result(dict(zip(keys, result_list)))\n                else:\n                    future.set_result(result_list)\n    for f in children:\n        f.add_done_callback(callback)\n    return future\n\n\ndef maybe_future(x):\n    \"\"\"Converts ``x`` into a `.Future`.\n\n    If ``x`` is already a `.Future`, it is simply returned; otherwise\n    it is wrapped in a new `.Future`.  This is suitable for use as\n    ``result = yield gen.maybe_future(f())`` when you don't know whether\n    ``f()`` returns a `.Future` or not.\n    \"\"\"\n    if is_future(x):\n        return x\n    else:\n        fut = Future()\n        fut.set_result(x)\n        return fut\n\n\ndef with_timeout(timeout, future, io_loop=None, quiet_exceptions=()):\n    \"\"\"Wraps a `.Future` in a timeout.\n\n    Raises `TimeoutError` if the input future does not complete before\n    ``timeout``, which may be specified in any form allowed by\n    `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time\n    relative to `.IOLoop.time`)\n\n    If the wrapped `.Future` fails after it has timed out, the exception\n    will be logged unless it is of a type contained in ``quiet_exceptions``\n    (which may be an exception type or a sequence of types).\n\n    Currently only supports Futures, not other `YieldPoint` classes.\n\n    .. versionadded:: 4.0\n\n    .. versionchanged:: 4.1\n       Added the ``quiet_exceptions`` argument and the logging of unhandled\n       exceptions.\n    \"\"\"\n    # TODO: allow yield points in addition to futures?\n    # Tricky to do with stack_context semantics.\n    #\n    # It's tempting to optimize this by cancelling the input future on timeout\n    # instead of creating a new one, but A) we can't know if we are the only\n    # one waiting on the input future, so cancelling it might disrupt other\n    # callers and B) concurrent futures can only be cancelled while they are\n    # in the queue, so cancellation cannot reliably bound our waiting time.\n    result = Future()\n    chain_future(future, result)\n    if io_loop is None:\n        io_loop = IOLoop.current()\n\n    def error_callback(future):\n        try:\n            future.result()\n        except Exception as e:\n            if not isinstance(e, quiet_exceptions):\n                app_log.error(\"Exception in Future %r after timeout\",\n                              future, exc_info=True)\n\n    def timeout_callback():\n        result.set_exception(TimeoutError(\"Timeout\"))\n        # In case the wrapped future goes on to fail, log it.\n        future.add_done_callback(error_callback)\n    timeout_handle = io_loop.add_timeout(\n        timeout, timeout_callback)\n    if isinstance(future, Future):\n        # We know this future will resolve on the IOLoop, so we don't\n        # need the extra thread-safety of IOLoop.add_future (and we also\n        # don't care about StackContext here.\n        future.add_done_callback(\n            lambda future: io_loop.remove_timeout(timeout_handle))\n    else:\n        # concurrent.futures.Futures may resolve on any thread, so we\n        # need to route them back to the IOLoop.\n        io_loop.add_future(\n            future, lambda future: io_loop.remove_timeout(timeout_handle))\n    return result\n\n\ndef sleep(duration):\n    \"\"\"Return a `.Future` that resolves after the given number of seconds.\n\n    When used with ``yield`` in a coroutine, this is a non-blocking\n    analogue to `time.sleep` (which should not be used in coroutines\n    because it is blocking)::\n\n        yield gen.sleep(0.5)\n\n    Note that calling this function on its own does nothing; you must\n    wait on the `.Future` it returns (usually by yielding it).\n\n    .. versionadded:: 4.1\n    \"\"\"\n    f = Future()\n    IOLoop.current().call_later(duration, lambda: f.set_result(None))\n    return f\n\n\n_null_future = Future()\n_null_future.set_result(None)\n\nmoment = Future()\nmoment.__doc__ = \\\n    \"\"\"A special object which may be yielded to allow the IOLoop to run for\none iteration.\n\nThis is not needed in normal use but it can be helpful in long-running\ncoroutines that are likely to yield Futures that are ready instantly.\n\nUsage: ``yield gen.moment``\n\n.. versionadded:: 4.0\n\"\"\"\nmoment.set_result(None)\n\n\nclass Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.TracebackFuture`)\n    \"\"\"\n    def __init__(self, gen, result_future, first_yielded):\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future\n        self.yield_point = None\n        self.pending_callbacks = None\n        self.results = None\n        self.running = False\n        self.finished = False\n        self.had_exception = False\n        self.io_loop = IOLoop.current()\n        # For efficiency, we do not create a stack context until we\n        # reach a YieldPoint (stack contexts are required for the historical\n        # semantics of YieldPoints, but not for Futures).  When we have\n        # done so, this field will be set and must be called at the end\n        # of the coroutine.\n        self.stack_context_deactivate = None\n        if self.handle_yield(first_yielded):\n            self.run()\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if self.pending_callbacks is None:\n            # Lazily initialize the old-style YieldPoint data structures.\n            self.pending_callbacks = set()\n            self.results = {}\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if self.pending_callbacks is None or key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        if self.yield_point is not None and self.yield_point.is_ready():\n            try:\n                self.future.set_result(self.yield_point.get_result())\n            except:\n                self.future.set_exc_info(sys.exc_info())\n            self.yield_point = None\n            self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    orig_stack_contexts = stack_context._state.contexts\n                    try:\n                        value = future.result()\n                    except Exception:\n                        self.had_exception = True\n                        yielded = self.gen.throw(*sys.exc_info())\n                    else:\n                        yielded = self.gen.send(value)\n                    if stack_context._state.contexts is not orig_stack_contexts:\n                        self.gen.throw(\n                            stack_context.StackContextInconsistentError(\n                                'stack_context inconsistency (probably caused '\n                                'by yield within a \"with StackContext\" block)'))\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.result_future.set_result(getattr(e, 'value', None))\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    self.result_future.set_exc_info(sys.exc_info())\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                if not self.handle_yield(yielded):\n                    return\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded):\n        # Lists containing YieldPoints require stack contexts;\n        # other lists are handled via multi_future in convert_yielded.\n        if (isinstance(yielded, list) and\n                any(isinstance(f, YieldPoint) for f in yielded)):\n            yielded = Multi(yielded)\n        elif (isinstance(yielded, dict) and\n              any(isinstance(f, YieldPoint) for f in yielded.values())):\n            yielded = Multi(yielded)\n\n        if isinstance(yielded, YieldPoint):\n            # YieldPoints are too closely coupled to the Runner to go\n            # through the generic convert_yielded mechanism.\n            self.future = TracebackFuture()\n\n            def start_yield_point():\n                try:\n                    yielded.start(self)\n                    if yielded.is_ready():\n                        self.future.set_result(\n                            yielded.get_result())\n                    else:\n                        self.yield_point = yielded\n                except Exception:\n                    self.future = TracebackFuture()\n                    self.future.set_exc_info(sys.exc_info())\n\n            if self.stack_context_deactivate is None:\n                # Start a stack context if this is the first\n                # YieldPoint we've seen.\n                with stack_context.ExceptionStackContext(\n                        self.handle_exception) as deactivate:\n                    self.stack_context_deactivate = deactivate\n\n                    def cb():\n                        start_yield_point()\n                        self.run()\n                    self.io_loop.add_callback(cb)\n                    return False\n            else:\n                start_yield_point()\n        else:\n            try:\n                self.future = convert_yielded(yielded)\n            except BadYieldError:\n                self.future = TracebackFuture()\n                self.future.set_exc_info(sys.exc_info())\n\n        if not self.future.done() or self.future is moment:\n            self.io_loop.add_future(\n                self.future, lambda f: self.run())\n            return False\n        return True\n\n    def result_callback(self, key):\n        return stack_context.wrap(_argument_adapter(\n            functools.partial(self.set_result, key)))\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.future = TracebackFuture()\n            self.future.set_exc_info((typ, value, tb))\n            self.run()\n            return True\n        else:\n            return False\n\n    def _deactivate_stack_context(self):\n        if self.stack_context_deactivate is not None:\n            self.stack_context_deactivate()\n            self.stack_context_deactivate = None\n\nArguments = collections.namedtuple('Arguments', ['args', 'kwargs'])\n\n\ndef _argument_adapter(callback):\n    \"\"\"Returns a function that when invoked runs ``callback`` with one arg.\n\n    If the function returned by this function is called with exactly\n    one argument, that argument is passed to ``callback``.  Otherwise\n    the args tuple and kwargs dict are wrapped in an `Arguments` object.\n    \"\"\"\n    def wrapper(*args, **kwargs):\n        if kwargs or len(args) > 1:\n            callback(Arguments(args, kwargs))\n        elif args:\n            callback(args[0])\n        else:\n            callback(None)\n    return wrapper\n\n\ndef convert_yielded(yielded):\n    \"\"\"Convert a yielded object into a `.Future`.\n\n    The default implementation accepts lists, dictionaries, and Futures.\n\n    If the `~functools.singledispatch` library is available, this function\n    may be extended to support additional types. For example::\n\n        @convert_yielded.register(asyncio.Future)\n        def _(asyncio_future):\n            return tornado.platform.asyncio.to_tornado_future(asyncio_future)\n\n    .. versionadded:: 4.1\n    \"\"\"\n    # Lists and dicts containing YieldPoints were handled separately\n    # via Multi().\n    if isinstance(yielded, (list, dict)):\n        return multi_future(yielded)\n    elif is_future(yielded):\n        return yielded\n    else:\n        raise BadYieldError(\"yielded unknown object %r\" % (yielded,))\n\nif singledispatch is not None:\n    convert_yielded = singledispatch(convert_yielded)\n",
            "new_file_content": "\"\"\"``tornado.gen`` is a generator-based interface to make it easier to\nwork in an asynchronous environment.  Code using the ``gen`` module\nis technically asynchronous, but it is written as a single generator\ninstead of a collection of separate functions.\n\nFor example, the following asynchronous handler:\n\n.. testcode::\n\n    class AsyncHandler(RequestHandler):\n        @asynchronous\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=self.on_fetch)\n\n        def on_fetch(self, response):\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n.. testoutput::\n   :hide:\n\ncould be written with ``gen`` as:\n\n.. testcode::\n\n    class GenAsyncHandler(RequestHandler):\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield http_client.fetch(\"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n.. testoutput::\n   :hide:\n\nMost asynchronous functions in Tornado return a `.Future`;\nyielding this object returns its `~.Future.result`.\n\nYou can also yield a list or dict of ``Futures``, which will be\nstarted at the same time and run in parallel; a list or dict of results will\nbe returned when they are all finished:\n\n.. testcode::\n\n    @gen.coroutine\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [http_client.fetch(url1),\n                                      http_client.fetch(url2)]\n        response_dict = yield dict(response3=http_client.fetch(url3),\n                                   response4=http_client.fetch(url4))\n        response3 = response_dict['response3']\n        response4 = response_dict['response4']\n\n.. testoutput::\n   :hide:\n\nIf the `~functools.singledispatch` library is available (standard in\nPython 3.4, available via the `singledispatch\n<https://pypi.python.org/pypi/singledispatch>`_ package on older\nversions), additional types of objects may be yielded. Tornado includes\nsupport for ``asyncio.Future`` and Twisted's ``Deferred`` class when\n``tornado.platform.asyncio`` and ``tornado.platform.twisted`` are imported.\nSee the `convert_yielded` function to extend this mechanism.\n\n.. versionchanged:: 3.2\n   Dict support added.\n\n.. versionchanged:: 4.1\n   Support added for yielding ``asyncio`` Futures and Twisted Deferreds\n   via ``singledispatch``.\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport functools\nimport itertools\nimport sys\nimport types\nimport weakref\n\nfrom tornado.concurrent import Future, TracebackFuture, is_future, chain_future\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import app_log\nfrom tornado import stack_context\n\ntry:\n    from functools import singledispatch  # py34+\nexcept ImportError as e:\n    try:\n        from singledispatch import singledispatch  # backport\n    except ImportError:\n        singledispatch = None\n\n\nclass KeyReuseError(Exception):\n    pass\n\n\nclass UnknownKeyError(Exception):\n    pass\n\n\nclass LeakedCallbackError(Exception):\n    pass\n\n\nclass BadYieldError(Exception):\n    pass\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n\nclass TimeoutError(Exception):\n    \"\"\"Exception raised by ``with_timeout``.\"\"\"\n\n\ndef engine(func):\n    \"\"\"Callback-oriented decorator for asynchronous generators.\n\n    This is an older interface; for new code that does not need to be\n    compatible with versions of Tornado older than 3.0 the\n    `coroutine` decorator is recommended instead.\n\n    This decorator is similar to `coroutine`, except it does not\n    return a `.Future` and the ``callback`` argument is not treated\n    specially.\n\n    In most cases, functions decorated with `engine` should take\n    a ``callback`` argument and invoke it with their result when\n    they are finished.  One notable exception is the\n    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,\n    which use ``self.finish()`` in place of a callback argument.\n    \"\"\"\n    func = _make_coroutine_wrapper(func, replace_callback=False)\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        future = func(*args, **kwargs)\n\n        def final_callback(future):\n            if future.result() is not None:\n                raise ReturnValueIgnoredError(\n                    \"@gen.engine functions cannot return values: %r\" %\n                    (future.result(),))\n        # The engine interface doesn't give us any way to return\n        # errors but to raise them into the stack context.\n        # Save the stack context here to use when the Future has resolved.\n        future.add_done_callback(stack_context.wrap(final_callback))\n    return wrapper\n\n\ndef coroutine(func, replace_callback=True):\n    \"\"\"Decorator for asynchronous generators.\n\n    Any generator that yields objects from this module must be wrapped\n    in either this decorator or `engine`.\n\n    Coroutines may \"return\" by raising the special exception\n    `Return(value) <Return>`.  In Python 3.3+, it is also possible for\n    the function to simply use the ``return value`` statement (prior to\n    Python 3.3 generators were not allowed to also return values).\n    In all versions of Python a coroutine that simply wishes to exit\n    early may use the ``return`` statement without a value.\n\n    Functions with this decorator return a `.Future`.  Additionally,\n    they may be called with a ``callback`` keyword argument, which\n    will be invoked with the future's result when it resolves.  If the\n    coroutine fails, the callback will not be run and an exception\n    will be raised into the surrounding `.StackContext`.  The\n    ``callback`` argument is not visible inside the decorated\n    function; it is handled by the decorator itself.\n\n    From the caller's perspective, ``@gen.coroutine`` is similar to\n    the combination of ``@return_future`` and ``@gen.engine``.\n\n    .. warning::\n\n       When exceptions occur inside a coroutine, the exception\n       information will be stored in the `.Future` object. You must\n       examine the result of the `.Future` object, or the exception\n       may go unnoticed by your code. This means yielding the function\n       if called from another coroutine, using something like\n       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`\n       to `.IOLoop.add_future`.\n\n    \"\"\"\n    return _make_coroutine_wrapper(func, replace_callback=True)\n\n\ndef _make_coroutine_wrapper(func, replace_callback):\n    \"\"\"The inner workings of ``@gen.coroutine`` and ``@gen.engine``.\n\n    The two decorators differ in their treatment of the ``callback``\n    argument, so we cannot simply implement ``@engine`` in terms of\n    ``@coroutine``.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        future = TracebackFuture()\n\n        if replace_callback and 'callback' in kwargs:\n            callback = kwargs.pop('callback')\n            IOLoop.current().add_future(\n                future, lambda future: callback(future.result()))\n\n        try:\n            result = func(*args, **kwargs)\n        except (Return, StopIteration) as e:\n            result = getattr(e, 'value', None)\n        except Exception:\n            future.set_exc_info(sys.exc_info())\n            return future\n        else:\n            if isinstance(result, types.GeneratorType):\n                # Inline the first iteration of Runner.run.  This lets us\n                # avoid the cost of creating a Runner when the coroutine\n                # never actually yields, which in turn allows us to\n                # use \"optional\" coroutines in critical path code without\n                # performance penalty for the synchronous case.\n                try:\n                    orig_stack_contexts = stack_context._state.contexts\n                    yielded = next(result)\n                    if stack_context._state.contexts is not orig_stack_contexts:\n                        yielded = TracebackFuture()\n                        yielded.set_exception(\n                            stack_context.StackContextInconsistentError(\n                                'stack_context inconsistency (probably caused '\n                                'by yield within a \"with StackContext\" block)'))\n                except (StopIteration, Return) as e:\n                    future.set_result(getattr(e, 'value', None))\n                except Exception:\n                    future.set_exc_info(sys.exc_info())\n                else:\n                    Runner(result, future, yielded)\n                try:\n                    return future\n                finally:\n                    # Subtle memory optimization: if next() raised an exception,\n                    # the future's exc_info contains a traceback which\n                    # includes this stack frame.  This creates a cycle,\n                    # which will be collected at the next full GC but has\n                    # been shown to greatly increase memory usage of\n                    # benchmarks (relative to the refcount-based scheme\n                    # used in the absence of cycles).  We can avoid the\n                    # cycle by clearing the local variable after we return it.\n                    future = None\n        future.set_result(result)\n        return future\n    return wrapper\n\n\nclass Return(Exception):\n    \"\"\"Special exception to return a value from a `coroutine`.\n\n    If this exception is raised, its value argument is used as the\n    result of the coroutine::\n\n        @gen.coroutine\n        def fetch_json(url):\n            response = yield AsyncHTTPClient().fetch(url)\n            raise gen.Return(json_decode(response.body))\n\n    In Python 3.3, this exception is no longer necessary: the ``return``\n    statement can be used directly to return a value (previously\n    ``yield`` and ``return`` with a value could not be combined in the\n    same function).\n\n    By analogy with the return statement, the value argument is optional,\n    but it is never necessary to ``raise gen.Return()``.  The ``return``\n    statement can be used with no arguments instead.\n    \"\"\"\n    def __init__(self, value=None):\n        super(Return, self).__init__()\n        self.value = value\n\n\nclass WaitIterator(object):\n    \"\"\"Provides an iterator to yield the results of futures as they finish.\n\n    Yielding a set of futures like this:\n\n    ``results = yield [future1, future2]``\n\n    pauses the coroutine until both ``future1`` and ``future2``\n    return, and then restarts the coroutine with the results of both\n    futures. If either future is an exception, the expression will\n    raise that exception and all the results will be lost.\n\n    If you need to get the result of each future as soon as possible,\n    or if you need the result of some futures even if others produce\n    errors, you can use ``WaitIterator``::\n\n      wait_iterator = gen.WaitIterator(future1, future2)\n      while not wait_iterator.done():\n          try:\n              result = yield wait_iterator.next()\n          except Exception as e:\n              print(\"Error {} from {}\".format(e, wait_iterator.current_future))\n          else:\n              print(\"Result {} recieved from {} at {}\".format(\n                  result, wait_iterator.current_future,\n                  wait_iterator.current_index))\n\n    Because results are returned as soon as they are available the\n    output from the iterator *will not be in the same order as the\n    input arguments*. If you need to know which future produced the\n    current result, you can use the attributes\n    ``WaitIterator.current_future``, or ``WaitIterator.current_index``\n    to get the index of the future from the input list. (if keyword\n    arguments were used in the construction of the `WaitIterator`,\n    ``current_index`` will use the corresponding keyword).\n\n    .. versionadded:: 4.1\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        if args and kwargs:\n            raise ValueError(\n                \"You must provide args or kwargs, not both\")\n\n        if kwargs:\n            self._unfinished = dict((f, k) for (k, f) in kwargs.items())\n            futures = list(kwargs.values())\n        else:\n            self._unfinished = dict((f, i) for (i, f) in enumerate(args))\n            futures = args\n\n        self._finished = collections.deque()\n        self.current_index = self.current_future = None\n        self._running_future = None\n\n        self_ref = weakref.ref(self)\n        for future in futures:\n            future.add_done_callback(functools.partial(\n                self._done_callback, self_ref))\n\n    def done(self):\n        \"\"\"Returns True if this iterator has no more results.\"\"\"\n        if self._finished or self._unfinished:\n            return False\n        # Clear the 'current' values when iteration is done.\n        self.current_index = self.current_future = None\n        return True\n\n    def next(self):\n        \"\"\"Returns a `.Future` that will yield the next available result.\n\n        Note that this `.Future` will not be the same object as any of\n        the inputs.\n        \"\"\"\n        self._running_future = TracebackFuture()\n\n        if self._finished:\n            self._return_result(self._finished.popleft())\n\n        return self._running_future\n\n    @staticmethod\n    def _done_callback(self_ref, done):\n        self = self_ref()\n        if self is not None:\n            if self._running_future and not self._running_future.done():\n                self._return_result(done)\n            else:\n                self._finished.append(done)\n\n    def _return_result(self, done):\n        \"\"\"Called set the returned future's state that of the future\n        we yielded, and set the current future for the iterator.\n        \"\"\"\n        chain_future(done, self._running_future)\n\n        self.current_future = done\n        self.current_index = self._unfinished.pop(done)\n\n\nclass YieldPoint(object):\n    \"\"\"Base class for objects that may be yielded from the generator.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def start(self, runner):\n        \"\"\"Called by the runner after the generator has yielded.\n\n        No other methods will be called on this object before ``start``.\n        \"\"\"\n        raise NotImplementedError()\n\n    def is_ready(self):\n        \"\"\"Called by the runner to determine whether to resume the generator.\n\n        Returns a boolean; may be called more than once.\n        \"\"\"\n        raise NotImplementedError()\n\n    def get_result(self):\n        \"\"\"Returns the value to use as the result of the yield expression.\n\n        This method will only be called once, and only after `is_ready`\n        has returned true.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass Callback(YieldPoint):\n    \"\"\"Returns a callable object that will allow a matching `Wait` to proceed.\n\n    The key may be any value suitable for use as a dictionary key, and is\n    used to match ``Callbacks`` to their corresponding ``Waits``.  The key\n    must be unique among outstanding callbacks within a single run of the\n    generator function, but may be reused across different runs of the same\n    function (so constants generally work fine).\n\n    The callback may be called with zero or one arguments; if an argument\n    is given it will be returned by `Wait`.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n        runner.register_callback(self.key)\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return self.runner.result_callback(self.key)\n\n\nclass Wait(YieldPoint):\n    \"\"\"Returns the argument passed to the result of a previous `Callback`.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key)\n\n\nclass WaitAll(YieldPoint):\n    \"\"\"Returns the results of multiple previous `Callbacks <Callback>`.\n\n    The argument is a sequence of `Callback` keys, and the result is\n    a list of results in the same order.\n\n    `WaitAll` is equivalent to yielding a list of `Wait` objects.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def __init__(self, keys):\n        self.keys = keys\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return all(self.runner.is_ready(key) for key in self.keys)\n\n    def get_result(self):\n        return [self.runner.pop_result(key) for key in self.keys]\n\n\ndef Task(func, *args, **kwargs):\n    \"\"\"Adapts a callback-based asynchronous function for use in coroutines.\n\n    Takes a function (and optional additional arguments) and runs it with\n    those arguments plus a ``callback`` keyword argument.  The argument passed\n    to the callback is returned as the result of the yield expression.\n\n    .. versionchanged:: 4.0\n       ``gen.Task`` is now a function that returns a `.Future`, instead of\n       a subclass of `YieldPoint`.  It still behaves the same way when\n       yielded.\n    \"\"\"\n    future = Future()\n\n    def handle_exception(typ, value, tb):\n        if future.done():\n            return False\n        future.set_exc_info((typ, value, tb))\n        return True\n\n    def set_result(result):\n        if future.done():\n            return\n        future.set_result(result)\n    with stack_context.ExceptionStackContext(handle_exception):\n        func(*args, callback=_argument_adapter(set_result), **kwargs)\n    return future\n\n\nclass YieldFuture(YieldPoint):\n    def __init__(self, future, io_loop=None):\n        \"\"\"Adapts a `.Future` to the `YieldPoint` interface.\n\n        .. versionchanged:: 4.1\n           The ``io_loop`` argument is deprecated.\n        \"\"\"\n        self.future = future\n        self.io_loop = io_loop or IOLoop.current()\n\n    def start(self, runner):\n        if not self.future.done():\n            self.runner = runner\n            self.key = object()\n            runner.register_callback(self.key)\n            self.io_loop.add_future(self.future, runner.result_callback(self.key))\n        else:\n            self.runner = None\n            self.result = self.future.result()\n\n    def is_ready(self):\n        if self.runner is not None:\n            return self.runner.is_ready(self.key)\n        else:\n            return True\n\n    def get_result(self):\n        if self.runner is not None:\n            return self.runner.pop_result(self.key).result()\n        else:\n            return self.result\n\n\nclass Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``YieldPoints`` or ``Futures`` and returns a list of\n    their responses.  It is not necessary to call `Multi` explicitly,\n    since the engine will do so automatically when the generator yields\n    a list of ``YieldPoints`` or a mixture of ``YieldPoints`` and ``Futures``.\n\n    Instead of a list, the argument may also be a dictionary whose values are\n    Futures, in which case a parallel dictionary is returned mapping the same\n    keys to their results.\n    \"\"\"\n    def __init__(self, children):\n        self.keys = None\n        if isinstance(children, dict):\n            self.keys = list(children.keys())\n            children = children.values()\n        self.children = []\n        for i in children:\n            if is_future(i):\n                i = YieldFuture(i)\n            self.children.append(i)\n        assert all(isinstance(i, YieldPoint) for i in self.children)\n        self.unfinished_children = set(self.children)\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        finished = list(itertools.takewhile(\n            lambda i: i.is_ready(), self.unfinished_children))\n        self.unfinished_children.difference_update(finished)\n        return not self.unfinished_children\n\n    def get_result(self):\n        result = (i.get_result() for i in self.children)\n        if self.keys is not None:\n            return dict(zip(self.keys, result))\n        else:\n            return list(result)\n\n\ndef multi_future(children):\n    \"\"\"Wait for multiple asynchronous futures in parallel.\n\n    Takes a list of ``Futures`` (but *not* other ``YieldPoints``) and returns\n    a new Future that resolves when all the other Futures are done.\n    If all the ``Futures`` succeeded, the returned Future's result is a list\n    of their results.  If any failed, the returned Future raises the exception\n    of the first one to fail.\n\n    Instead of a list, the argument may also be a dictionary whose values are\n    Futures, in which case a parallel dictionary is returned mapping the same\n    keys to their results.\n\n    It is not necessary to call `multi_future` explcitly, since the engine will\n    do so automatically when the generator yields a list of `Futures`.\n    This function is faster than the `Multi` `YieldPoint` because it does not\n    require the creation of a stack context.\n\n    .. versionadded:: 4.0\n    \"\"\"\n    if isinstance(children, dict):\n        keys = list(children.keys())\n        children = children.values()\n    else:\n        keys = None\n    assert all(is_future(i) for i in children)\n    unfinished_children = set(children)\n\n    future = Future()\n    if not children:\n        future.set_result({} if keys is not None else [])\n\n    def callback(f):\n        unfinished_children.remove(f)\n        if not unfinished_children:\n            try:\n                result_list = [i.result() for i in children]\n            except Exception:\n                future.set_exc_info(sys.exc_info())\n            else:\n                if keys is not None:\n                    future.set_result(dict(zip(keys, result_list)))\n                else:\n                    future.set_result(result_list)\n    for f in children:\n        f.add_done_callback(callback)\n    return future\n\n\ndef maybe_future(x):\n    \"\"\"Converts ``x`` into a `.Future`.\n\n    If ``x`` is already a `.Future`, it is simply returned; otherwise\n    it is wrapped in a new `.Future`.  This is suitable for use as\n    ``result = yield gen.maybe_future(f())`` when you don't know whether\n    ``f()`` returns a `.Future` or not.\n    \"\"\"\n    if is_future(x):\n        return x\n    else:\n        fut = Future()\n        fut.set_result(x)\n        return fut\n\n\ndef with_timeout(timeout, future, io_loop=None, quiet_exceptions=()):\n    \"\"\"Wraps a `.Future` in a timeout.\n\n    Raises `TimeoutError` if the input future does not complete before\n    ``timeout``, which may be specified in any form allowed by\n    `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time\n    relative to `.IOLoop.time`)\n\n    If the wrapped `.Future` fails after it has timed out, the exception\n    will be logged unless it is of a type contained in ``quiet_exceptions``\n    (which may be an exception type or a sequence of types).\n\n    Currently only supports Futures, not other `YieldPoint` classes.\n\n    .. versionadded:: 4.0\n\n    .. versionchanged:: 4.1\n       Added the ``quiet_exceptions`` argument and the logging of unhandled\n       exceptions.\n    \"\"\"\n    # TODO: allow yield points in addition to futures?\n    # Tricky to do with stack_context semantics.\n    #\n    # It's tempting to optimize this by cancelling the input future on timeout\n    # instead of creating a new one, but A) we can't know if we are the only\n    # one waiting on the input future, so cancelling it might disrupt other\n    # callers and B) concurrent futures can only be cancelled while they are\n    # in the queue, so cancellation cannot reliably bound our waiting time.\n    result = Future()\n    chain_future(future, result)\n    if io_loop is None:\n        io_loop = IOLoop.current()\n\n    def error_callback(future):\n        try:\n            future.result()\n        except Exception as e:\n            if not isinstance(e, quiet_exceptions):\n                app_log.error(\"Exception in Future %r after timeout\",\n                              future, exc_info=True)\n\n    def timeout_callback():\n        result.set_exception(TimeoutError(\"Timeout\"))\n        # In case the wrapped future goes on to fail, log it.\n        future.add_done_callback(error_callback)\n    timeout_handle = io_loop.add_timeout(\n        timeout, timeout_callback)\n    if isinstance(future, Future):\n        # We know this future will resolve on the IOLoop, so we don't\n        # need the extra thread-safety of IOLoop.add_future (and we also\n        # don't care about StackContext here.\n        future.add_done_callback(\n            lambda future: io_loop.remove_timeout(timeout_handle))\n    else:\n        # concurrent.futures.Futures may resolve on any thread, so we\n        # need to route them back to the IOLoop.\n        io_loop.add_future(\n            future, lambda future: io_loop.remove_timeout(timeout_handle))\n    return result\n\n\ndef sleep(duration):\n    \"\"\"Return a `.Future` that resolves after the given number of seconds.\n\n    When used with ``yield`` in a coroutine, this is a non-blocking\n    analogue to `time.sleep` (which should not be used in coroutines\n    because it is blocking)::\n\n        yield gen.sleep(0.5)\n\n    Note that calling this function on its own does nothing; you must\n    wait on the `.Future` it returns (usually by yielding it).\n\n    .. versionadded:: 4.1\n    \"\"\"\n    f = Future()\n    IOLoop.current().call_later(duration, lambda: f.set_result(None))\n    return f\n\n\n_null_future = Future()\n_null_future.set_result(None)\n\nmoment = Future()\nmoment.__doc__ = \\\n    \"\"\"A special object which may be yielded to allow the IOLoop to run for\none iteration.\n\nThis is not needed in normal use but it can be helpful in long-running\ncoroutines that are likely to yield Futures that are ready instantly.\n\nUsage: ``yield gen.moment``\n\n.. versionadded:: 4.0\n\"\"\"\nmoment.set_result(None)\n\n\nclass Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.TracebackFuture`)\n    \"\"\"\n    def __init__(self, gen, result_future, first_yielded):\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future\n        self.yield_point = None\n        self.pending_callbacks = None\n        self.results = None\n        self.running = False\n        self.finished = False\n        self.had_exception = False\n        self.io_loop = IOLoop.current()\n        # For efficiency, we do not create a stack context until we\n        # reach a YieldPoint (stack contexts are required for the historical\n        # semantics of YieldPoints, but not for Futures).  When we have\n        # done so, this field will be set and must be called at the end\n        # of the coroutine.\n        self.stack_context_deactivate = None\n        if self.handle_yield(first_yielded):\n            self.run()\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if self.pending_callbacks is None:\n            # Lazily initialize the old-style YieldPoint data structures.\n            self.pending_callbacks = set()\n            self.results = {}\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if self.pending_callbacks is None or key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        if self.yield_point is not None and self.yield_point.is_ready():\n            try:\n                self.future.set_result(self.yield_point.get_result())\n            except:\n                self.future.set_exc_info(sys.exc_info())\n            self.yield_point = None\n            self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    orig_stack_contexts = stack_context._state.contexts\n                    exc_info = None\n\n                    try:\n                        value = future.result()\n                    except Exception:\n                        self.had_exception = True\n                        exc_info = sys.exc_info()\n\n                    if exc_info is not None:\n                        yielded = self.gen.throw(*exc_info)\n                        exc_info = None\n                    else:\n                        yielded = self.gen.send(value)\n\n                    if stack_context._state.contexts is not orig_stack_contexts:\n                        self.gen.throw(\n                            stack_context.StackContextInconsistentError(\n                                'stack_context inconsistency (probably caused '\n                                'by yield within a \"with StackContext\" block)'))\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.result_future.set_result(getattr(e, 'value', None))\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    self.result_future.set_exc_info(sys.exc_info())\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                if not self.handle_yield(yielded):\n                    return\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded):\n        # Lists containing YieldPoints require stack contexts;\n        # other lists are handled via multi_future in convert_yielded.\n        if (isinstance(yielded, list) and\n                any(isinstance(f, YieldPoint) for f in yielded)):\n            yielded = Multi(yielded)\n        elif (isinstance(yielded, dict) and\n              any(isinstance(f, YieldPoint) for f in yielded.values())):\n            yielded = Multi(yielded)\n\n        if isinstance(yielded, YieldPoint):\n            # YieldPoints are too closely coupled to the Runner to go\n            # through the generic convert_yielded mechanism.\n            self.future = TracebackFuture()\n\n            def start_yield_point():\n                try:\n                    yielded.start(self)\n                    if yielded.is_ready():\n                        self.future.set_result(\n                            yielded.get_result())\n                    else:\n                        self.yield_point = yielded\n                except Exception:\n                    self.future = TracebackFuture()\n                    self.future.set_exc_info(sys.exc_info())\n\n            if self.stack_context_deactivate is None:\n                # Start a stack context if this is the first\n                # YieldPoint we've seen.\n                with stack_context.ExceptionStackContext(\n                        self.handle_exception) as deactivate:\n                    self.stack_context_deactivate = deactivate\n\n                    def cb():\n                        start_yield_point()\n                        self.run()\n                    self.io_loop.add_callback(cb)\n                    return False\n            else:\n                start_yield_point()\n        else:\n            try:\n                self.future = convert_yielded(yielded)\n            except BadYieldError:\n                self.future = TracebackFuture()\n                self.future.set_exc_info(sys.exc_info())\n\n        if not self.future.done() or self.future is moment:\n            self.io_loop.add_future(\n                self.future, lambda f: self.run())\n            return False\n        return True\n\n    def result_callback(self, key):\n        return stack_context.wrap(_argument_adapter(\n            functools.partial(self.set_result, key)))\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.future = TracebackFuture()\n            self.future.set_exc_info((typ, value, tb))\n            self.run()\n            return True\n        else:\n            return False\n\n    def _deactivate_stack_context(self):\n        if self.stack_context_deactivate is not None:\n            self.stack_context_deactivate()\n            self.stack_context_deactivate = None\n\nArguments = collections.namedtuple('Arguments', ['args', 'kwargs'])\n\n\ndef _argument_adapter(callback):\n    \"\"\"Returns a function that when invoked runs ``callback`` with one arg.\n\n    If the function returned by this function is called with exactly\n    one argument, that argument is passed to ``callback``.  Otherwise\n    the args tuple and kwargs dict are wrapped in an `Arguments` object.\n    \"\"\"\n    def wrapper(*args, **kwargs):\n        if kwargs or len(args) > 1:\n            callback(Arguments(args, kwargs))\n        elif args:\n            callback(args[0])\n        else:\n            callback(None)\n    return wrapper\n\n\ndef convert_yielded(yielded):\n    \"\"\"Convert a yielded object into a `.Future`.\n\n    The default implementation accepts lists, dictionaries, and Futures.\n\n    If the `~functools.singledispatch` library is available, this function\n    may be extended to support additional types. For example::\n\n        @convert_yielded.register(asyncio.Future)\n        def _(asyncio_future):\n            return tornado.platform.asyncio.to_tornado_future(asyncio_future)\n\n    .. versionadded:: 4.1\n    \"\"\"\n    # Lists and dicts containing YieldPoints were handled separately\n    # via Multi().\n    if isinstance(yielded, (list, dict)):\n        return multi_future(yielded)\n    elif is_future(yielded):\n        return yielded\n    else:\n        raise BadYieldError(\"yielded unknown object %r\" % (yielded,))\n\nif singledispatch is not None:\n    convert_yielded = singledispatch(convert_yielded)\n",
            "header": {
                "file": {
                    "path": "tornado/gen.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "3d87d717",
                "new_commit_hash": "b405b2f7",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/gen.py"
            },
            "plus_file": {
                "path": "b/tornado/gen.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 824,
                            "length": 13
                        },
                        "new_range": {
                            "start": 824,
                            "length": 20
                        },
                        "section": "class Runner(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                self.future = None",
                                "type": "context"
                            },
                            {
                                "content": "                try:",
                                "type": "context"
                            },
                            {
                                "content": "                    orig_stack_contexts = stack_context._state.contexts",
                                "type": "context"
                            },
                            {
                                "content": "                    exc_info = None",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "                    try:",
                                "type": "context"
                            },
                            {
                                "content": "                        value = future.result()",
                                "type": "context"
                            },
                            {
                                "content": "                    except Exception:",
                                "type": "context"
                            },
                            {
                                "content": "                        self.had_exception = True",
                                "type": "context"
                            },
                            {
                                "content": "                        yielded = self.gen.throw(*sys.exc_info())",
                                "type": "deleted"
                            },
                            {
                                "content": "                        exc_info = sys.exc_info()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "                    if exc_info is not None:",
                                "type": "added"
                            },
                            {
                                "content": "                        yielded = self.gen.throw(*exc_info)",
                                "type": "added"
                            },
                            {
                                "content": "                        exc_info = None",
                                "type": "added"
                            },
                            {
                                "content": "                    else:",
                                "type": "context"
                            },
                            {
                                "content": "                        yielded = self.gen.send(value)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "                    if stack_context._state.contexts is not orig_stack_contexts:",
                                "type": "context"
                            },
                            {
                                "content": "                        self.gen.throw(",
                                "type": "context"
                            },
                            {
                                "content": "                            stack_context.StackContextInconsistentError(",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/gen.py",
                            "type": "method",
                            "name": "Runner.run",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.TracebackFuture`)\n    \"\"\"\n    def __init__(self, gen, result_future, first_yielded):\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future\n        self.yield_point = None\n        self.pending_callbacks = None\n        self.results = None\n        self.running = False\n        self.finished = False\n        self.had_exception = False\n        self.io_loop = IOLoop.current()\n        # For efficiency, we do not create a stack context until we\n        # reach a YieldPoint (stack contexts are required for the historical\n        # semantics of YieldPoints, but not for Futures).  When we have\n        # done so, this field will be set and must be called at the end\n        # of the coroutine.\n        self.stack_context_deactivate = None\n        if self.handle_yield(first_yielded):\n            self.run()\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if self.pending_callbacks is None:\n            # Lazily initialize the old-style YieldPoint data structures.\n            self.pending_callbacks = set()\n            self.results = {}\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if self.pending_callbacks is None or key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        if self.yield_point is not None and self.yield_point.is_ready():\n            try:\n                self.future.set_result(self.yield_point.get_result())\n            except:\n                self.future.set_exc_info(sys.exc_info())\n            self.yield_point = None\n            self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    orig_stack_contexts = stack_context._state.contexts\n                    try:\n                        value = future.result()\n                    except Exception:\n                        self.had_exception = True\n                        yielded = self.gen.throw(*sys.exc_info())\n                    else:\n                        yielded = self.gen.send(value)\n                    if stack_context._state.contexts is not orig_stack_contexts:\n                        self.gen.throw(\n                            stack_context.StackContextInconsistentError(\n                                'stack_context inconsistency (probably caused '\n                                'by yield within a \"with StackContext\" block)'))\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.result_future.set_result(getattr(e, 'value', None))\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    self.result_future.set_exc_info(sys.exc_info())\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                if not self.handle_yield(yielded):\n                    return\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded):\n        # Lists containing YieldPoints require stack contexts;\n        # other lists are handled via multi_future in convert_yielded.\n        if (isinstance(yielded, list) and\n                any(isinstance(f, YieldPoint) for f in yielded)):\n            yielded = Multi(yielded)\n        elif (isinstance(yielded, dict) and\n              any(isinstance(f, YieldPoint) for f in yielded.values())):\n            yielded = Multi(yielded)\n\n        if isinstance(yielded, YieldPoint):\n            # YieldPoints are too closely coupled to the Runner to go\n            # through the generic convert_yielded mechanism.\n            self.future = TracebackFuture()\n\n            def start_yield_point():\n                try:\n                    yielded.start(self)\n                    if yielded.is_ready():\n                        self.future.set_result(\n                            yielded.get_result())\n                    else:\n                        self.yield_point = yielded\n                except Exception:\n                    self.future = TracebackFuture()\n                    self.future.set_exc_info(sys.exc_info())\n\n            if self.stack_context_deactivate is None:\n                # Start a stack context if this is the first\n                # YieldPoint we've seen.\n                with stack_context.ExceptionStackContext(\n                        self.handle_exception) as deactivate:\n                    self.stack_context_deactivate = deactivate\n\n                    def cb():\n                        start_yield_point()\n                        self.run()\n                    self.io_loop.add_callback(cb)\n                    return False\n            else:\n                start_yield_point()\n        else:\n            try:\n                self.future = convert_yielded(yielded)\n            except BadYieldError:\n                self.future = TracebackFuture()\n                self.future.set_exc_info(sys.exc_info())\n\n        if not self.future.done() or self.future is moment:\n            self.io_loop.add_future(\n                self.future, lambda f: self.run())\n            return False\n        return True\n\n    def result_callback(self, key):\n        return stack_context.wrap(_argument_adapter(\n            functools.partial(self.set_result, key)))\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.future = TracebackFuture()\n            self.future.set_exc_info((typ, value, tb))\n            self.run()\n            return True\n        else:\n            return False\n\n    def _deactivate_stack_context(self):\n        if self.stack_context_deactivate is not None:\n            self.stack_context_deactivate()\n            self.stack_context_deactivate = None",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 812,
                            "end_lineno": 864,
                            "parent": {
                                "file_name": "tornado/gen.py",
                                "type": "class",
                                "name": "Runner",
                                "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.TracebackFuture`)\n    \"\"\"\n    def __init__(self, gen, result_future, first_yielded):\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future\n        self.yield_point = None\n        self.pending_callbacks = None\n        self.results = None\n        self.running = False\n        self.finished = False\n        self.had_exception = False\n        self.io_loop = IOLoop.current()\n        # For efficiency, we do not create a stack context until we\n        # reach a YieldPoint (stack contexts are required for the historical\n        # semantics of YieldPoints, but not for Futures).  When we have\n        # done so, this field will be set and must be called at the end\n        # of the coroutine.\n        self.stack_context_deactivate = None\n        if self.handle_yield(first_yielded):\n            self.run()\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if self.pending_callbacks is None:\n            # Lazily initialize the old-style YieldPoint data structures.\n            self.pending_callbacks = set()\n            self.results = {}\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if self.pending_callbacks is None or key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        if self.yield_point is not None and self.yield_point.is_ready():\n            try:\n                self.future.set_result(self.yield_point.get_result())\n            except:\n                self.future.set_exc_info(sys.exc_info())\n            self.yield_point = None\n            self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    orig_stack_contexts = stack_context._state.contexts\n                    try:\n                        value = future.result()\n                    except Exception:\n                        self.had_exception = True\n                        yielded = self.gen.throw(*sys.exc_info())\n                    else:\n                        yielded = self.gen.send(value)\n                    if stack_context._state.contexts is not orig_stack_contexts:\n                        self.gen.throw(\n                            stack_context.StackContextInconsistentError(\n                                'stack_context inconsistency (probably caused '\n                                'by yield within a \"with StackContext\" block)'))\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.result_future.set_result(getattr(e, 'value', None))\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    self.result_future.set_exc_info(sys.exc_info())\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                if not self.handle_yield(yielded):\n                    return\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded):\n        # Lists containing YieldPoints require stack contexts;\n        # other lists are handled via multi_future in convert_yielded.\n        if (isinstance(yielded, list) and\n                any(isinstance(f, YieldPoint) for f in yielded)):\n            yielded = Multi(yielded)\n        elif (isinstance(yielded, dict) and\n              any(isinstance(f, YieldPoint) for f in yielded.values())):\n            yielded = Multi(yielded)\n\n        if isinstance(yielded, YieldPoint):\n            # YieldPoints are too closely coupled to the Runner to go\n            # through the generic convert_yielded mechanism.\n            self.future = TracebackFuture()\n\n            def start_yield_point():\n                try:\n                    yielded.start(self)\n                    if yielded.is_ready():\n                        self.future.set_result(\n                            yielded.get_result())\n                    else:\n                        self.yield_point = yielded\n                except Exception:\n                    self.future = TracebackFuture()\n                    self.future.set_exc_info(sys.exc_info())\n\n            if self.stack_context_deactivate is None:\n                # Start a stack context if this is the first\n                # YieldPoint we've seen.\n                with stack_context.ExceptionStackContext(\n                        self.handle_exception) as deactivate:\n                    self.stack_context_deactivate = deactivate\n\n                    def cb():\n                        start_yield_point()\n                        self.run()\n                    self.io_loop.add_callback(cb)\n                    return False\n            else:\n                start_yield_point()\n        else:\n            try:\n                self.future = convert_yielded(yielded)\n            except BadYieldError:\n                self.future = TracebackFuture()\n                self.future.set_exc_info(sys.exc_info())\n\n        if not self.future.done() or self.future is moment:\n            self.io_loop.add_future(\n                self.future, lambda f: self.run())\n            return False\n        return True\n\n    def result_callback(self, key):\n        return stack_context.wrap(_argument_adapter(\n            functools.partial(self.set_result, key)))\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.future = TracebackFuture()\n            self.future.set_exc_info((typ, value, tb))\n            self.run()\n            return True\n        else:\n            return False\n\n    def _deactivate_stack_context(self):\n        if self.stack_context_deactivate is not None:\n            self.stack_context_deactivate()\n            self.stack_context_deactivate = None",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 752,
                                "end_lineno": 936,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/gen.py",
                            "type": "class",
                            "name": "Runner",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.TracebackFuture`)\n    \"\"\"\n    def __init__(self, gen, result_future, first_yielded):\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future\n        self.yield_point = None\n        self.pending_callbacks = None\n        self.results = None\n        self.running = False\n        self.finished = False\n        self.had_exception = False\n        self.io_loop = IOLoop.current()\n        # For efficiency, we do not create a stack context until we\n        # reach a YieldPoint (stack contexts are required for the historical\n        # semantics of YieldPoints, but not for Futures).  When we have\n        # done so, this field will be set and must be called at the end\n        # of the coroutine.\n        self.stack_context_deactivate = None\n        if self.handle_yield(first_yielded):\n            self.run()\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if self.pending_callbacks is None:\n            # Lazily initialize the old-style YieldPoint data structures.\n            self.pending_callbacks = set()\n            self.results = {}\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if self.pending_callbacks is None or key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        if self.yield_point is not None and self.yield_point.is_ready():\n            try:\n                self.future.set_result(self.yield_point.get_result())\n            except:\n                self.future.set_exc_info(sys.exc_info())\n            self.yield_point = None\n            self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    orig_stack_contexts = stack_context._state.contexts\n                    try:\n                        value = future.result()\n                    except Exception:\n                        self.had_exception = True\n                        yielded = self.gen.throw(*sys.exc_info())\n                    else:\n                        yielded = self.gen.send(value)\n                    if stack_context._state.contexts is not orig_stack_contexts:\n                        self.gen.throw(\n                            stack_context.StackContextInconsistentError(\n                                'stack_context inconsistency (probably caused '\n                                'by yield within a \"with StackContext\" block)'))\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.result_future.set_result(getattr(e, 'value', None))\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    self.result_future.set_exc_info(sys.exc_info())\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                if not self.handle_yield(yielded):\n                    return\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded):\n        # Lists containing YieldPoints require stack contexts;\n        # other lists are handled via multi_future in convert_yielded.\n        if (isinstance(yielded, list) and\n                any(isinstance(f, YieldPoint) for f in yielded)):\n            yielded = Multi(yielded)\n        elif (isinstance(yielded, dict) and\n              any(isinstance(f, YieldPoint) for f in yielded.values())):\n            yielded = Multi(yielded)\n\n        if isinstance(yielded, YieldPoint):\n            # YieldPoints are too closely coupled to the Runner to go\n            # through the generic convert_yielded mechanism.\n            self.future = TracebackFuture()\n\n            def start_yield_point():\n                try:\n                    yielded.start(self)\n                    if yielded.is_ready():\n                        self.future.set_result(\n                            yielded.get_result())\n                    else:\n                        self.yield_point = yielded\n                except Exception:\n                    self.future = TracebackFuture()\n                    self.future.set_exc_info(sys.exc_info())\n\n            if self.stack_context_deactivate is None:\n                # Start a stack context if this is the first\n                # YieldPoint we've seen.\n                with stack_context.ExceptionStackContext(\n                        self.handle_exception) as deactivate:\n                    self.stack_context_deactivate = deactivate\n\n                    def cb():\n                        start_yield_point()\n                        self.run()\n                    self.io_loop.add_callback(cb)\n                    return False\n            else:\n                start_yield_point()\n        else:\n            try:\n                self.future = convert_yielded(yielded)\n            except BadYieldError:\n                self.future = TracebackFuture()\n                self.future.set_exc_info(sys.exc_info())\n\n        if not self.future.done() or self.future is moment:\n            self.io_loop.add_future(\n                self.future, lambda f: self.run())\n            return False\n        return True\n\n    def result_callback(self, key):\n        return stack_context.wrap(_argument_adapter(\n            functools.partial(self.set_result, key)))\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.future = TracebackFuture()\n            self.future.set_exc_info((typ, value, tb))\n            self.run()\n            return True\n        else:\n            return False\n\n    def _deactivate_stack_context(self):\n        if self.stack_context_deactivate is not None:\n            self.stack_context_deactivate()\n            self.stack_context_deactivate = None",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 752,
                            "end_lineno": 936,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport datetime\nimport functools\nimport sys\nimport textwrap\nimport time\nimport platform\nimport weakref\n\nfrom tornado.concurrent import return_future, Future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler, asynchronous, HTTPError\n\nfrom tornado import gen\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\nskipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')\nskipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython',\n                                 'Not CPython implementation')\n\n\nclass GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_with_arg_tuple(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback((1, 2)))((3, 4))\n            res = yield gen.Wait((1, 2))\n            self.assertEqual((3, 4), res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_reuse_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_key_mismatch_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Wait((2, 3))\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_leaked_callback_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.engine\n        def f():\n            yield (1, 2)\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_dict(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield dict(foo=gen.Wait(\"k1\"), bar=gen.Wait(\"k2\"))\n            self.assertEqual(results, dict(foo=\"v1\", bar=\"v2\"))\n            self.stop()\n        self.run_gen(f)\n\n    # The following tests explicitly run with both gen.Multi\n    # and gen.multi_future (Task returns a Future, so it can be used\n    # with either).\n    def test_multi_yieldpoint_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.Multi([\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ])\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_yieldpoint_dict_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.Multi(dict(\n                foo=gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                bar=gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ))\n            self.assertEqual(responses, dict(foo=\"v1\", bar=\"v2\"))\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_future_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future([\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ])\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_future_dict_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future(dict(\n                foo=gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                bar=gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ))\n            self.assertEqual(responses, dict(foo=\"v1\", bar=\"v2\"))\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_multi_empty(self):\n        # Empty lists or dicts should return the same type.\n        x = yield []\n        self.assertTrue(isinstance(x, list))\n        y = yield {}\n        self.assertTrue(isinstance(y, dict))\n\n    @gen_test\n    def test_multi_mixed_types(self):\n        # A YieldPoint (Wait) and Future (Task) can be combined\n        # (and use the YieldPoint codepath)\n        (yield gen.Callback(\"k1\"))(\"v1\")\n        responses = yield [gen.Wait(\"k1\"),\n                           gen.Task(self.delay_callback, 3, arg=\"v2\")]\n        self.assertEqual(responses, [\"v1\", \"v2\"])\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    @gen_test\n    def test_multi_dict_future(self):\n        results = yield dict(foo=self.async_future(1), bar=self.async_future(2))\n        self.assertEqual(results, dict(foo=1, bar=2))\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        def _stack_depth():\n            head = stack_context._state.contexts[1]\n            length = 0\n\n            while head is not None:\n                length += 1\n                head = head.old_contexts[1]\n\n            return length\n\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n\n            stack_increase = _stack_depth() - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = _stack_depth()\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value_tuple(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return (1, 2)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    @skipNotCPython\n    def test_task_refcounting(self):\n        # On CPython, tasks and their arguments should be released immediately\n        # without waiting for garbage collection.\n        @gen.engine\n        def f():\n            class Foo(object):\n                pass\n            arg = Foo()\n            self.arg_ref = weakref.ref(arg)\n            task = gen.Task(self.io_loop.add_callback, arg=arg)\n            self.task_ref = weakref.ref(task)\n            yield task\n            self.stop()\n\n        self.run_gen(f)\n        self.assertIs(self.arg_ref(), None)\n        self.assertIs(self.task_ref(), None)\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        # Note that this test and the following are for behavior that is\n        # not really supported any more:  coroutines no longer create a\n        # stack context automatically; but one is created after the first\n        # YieldPoint (i.e. not a Future).\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_moment(self):\n        calls = []\n\n        @gen.coroutine\n        def f(name, yieldable):\n            for i in range(5):\n                calls.append(name)\n                yield yieldable\n        # First, confirm the behavior without moment: each coroutine\n        # monopolizes the event loop until it finishes.\n        immediate = Future()\n        immediate.set_result(None)\n        yield [f('a', immediate), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'aaaaabbbbb')\n\n        # With moment, they take turns.\n        calls = []\n        yield [f('a', gen.moment), f('b', gen.moment)]\n        self.assertEqual(''.join(calls), 'ababababab')\n        self.finished = True\n\n        calls = []\n        yield [f('a', gen.moment), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'abbbbbaaaa')\n\n    @gen_test\n    def test_sleep(self):\n        yield gen.sleep(0.01)\n        self.finished = True\n\n\nclass GenSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")\n\n\nclass GenTaskHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        client = AsyncHTTPClient(io_loop=io_loop)\n        response = yield gen.Task(client.fetch, self.get_argument('url'))\n        response.rethrow()\n        self.finish(b\"got response: \" + response.body)\n\n\nclass GenExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenCoroutineExceptionHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenYieldExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        # Test the interaction of the two stack_contexts.\n\n        def fail_task(callback):\n            io_loop.add_callback(lambda: 1 / 0)\n        try:\n            yield gen.Task(fail_task)\n            raise Exception(\"did not get expected exception\")\n        except ZeroDivisionError:\n            self.finish('ok')\n\n\nclass UndecoratedCoroutinesHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        self.chunks = []\n        yield gen.Task(IOLoop.current().add_callback)\n        self.chunks.append('1')\n\n    @gen.coroutine\n    def get(self):\n        self.chunks.append('2')\n        yield gen.Task(IOLoop.current().add_callback)\n        self.chunks.append('3')\n        yield gen.Task(IOLoop.current().add_callback)\n        self.write(''.join(self.chunks))\n\n\nclass AsyncPrepareErrorHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        yield gen.Task(IOLoop.current().add_callback)\n        raise HTTPError(403)\n\n    def get(self):\n        self.finish('ok')\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n            ('/undecorated_coroutine', UndecoratedCoroutinesHandler),\n            ('/async_prepare_error', AsyncPrepareErrorHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\n\n    def test_undecorated_coroutines(self):\n        response = self.fetch('/undecorated_coroutine')\n        self.assertEqual(response.body, b'123')\n\n    def test_async_prepare_error_handler(self):\n        response = self.fetch('/async_prepare_error')\n        self.assertEqual(response.code, 403)\n\n\nclass WithTimeoutTest(AsyncTestCase):\n    @gen_test\n    def test_timeout(self):\n        with self.assertRaises(gen.TimeoutError):\n            yield gen.with_timeout(datetime.timedelta(seconds=0.1),\n                                   Future())\n\n    @gen_test\n    def test_completes_before_timeout(self):\n        future = Future()\n        self.io_loop.add_timeout(datetime.timedelta(seconds=0.1),\n                                 lambda: future.set_result('asdf'))\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                        future, io_loop=self.io_loop)\n        self.assertEqual(result, 'asdf')\n\n    @gen_test\n    def test_fails_before_timeout(self):\n        future = Future()\n        self.io_loop.add_timeout(\n            datetime.timedelta(seconds=0.1),\n            lambda: future.set_exception(ZeroDivisionError()))\n        with self.assertRaises(ZeroDivisionError):\n            yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                   future, io_loop=self.io_loop)\n\n    @gen_test\n    def test_already_resolved(self):\n        future = Future()\n        future.set_result('asdf')\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                        future, io_loop=self.io_loop)\n        self.assertEqual(result, 'asdf')\n\n    @unittest.skipIf(futures is None, 'futures module not present')\n    @gen_test\n    def test_timeout_concurrent_future(self):\n        with futures.ThreadPoolExecutor(1) as executor:\n            with self.assertRaises(gen.TimeoutError):\n                yield gen.with_timeout(self.io_loop.time(),\n                                       executor.submit(time.sleep, 0.1))\n\n    @unittest.skipIf(futures is None, 'futures module not present')\n    @gen_test\n    def test_completed_concurrent_future(self):\n        with futures.ThreadPoolExecutor(1) as executor:\n            yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                   executor.submit(lambda: None))\n\n\nclass WaitIteratorTest(AsyncTestCase):\n    @gen_test\n    def test_empty_iterator(self):\n        g = gen.WaitIterator()\n        self.assertTrue(g.done(), 'empty generator iterated')\n\n        with self.assertRaises(ValueError):\n            g = gen.WaitIterator(False, bar=False)\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n    @gen_test\n    def test_already_done(self):\n        f1 = Future()\n        f2 = Future()\n        f3 = Future()\n        f1.set_result(24)\n        f2.set_result(42)\n        f3.set_result(84)\n\n        g = gen.WaitIterator(f1, f2, f3)\n        i = 0\n        while not g.done():\n            r = yield g.next()\n            # Order is not guaranteed, but the current implementation\n            # preserves ordering of already-done Futures.\n            if i == 0:\n                self.assertEqual(g.current_index, 0)\n                self.assertIs(g.current_future, f1)\n                self.assertEqual(r, 24)\n            elif i == 1:\n                self.assertEqual(g.current_index, 1)\n                self.assertIs(g.current_future, f2)\n                self.assertEqual(r, 42)\n            elif i == 2:\n                self.assertEqual(g.current_index, 2)\n                self.assertIs(g.current_future, f3)\n                self.assertEqual(r, 84)\n            i += 1\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n        dg = gen.WaitIterator(f1=f1, f2=f2)\n\n        while not dg.done():\n            dr = yield dg.next()\n            if dg.current_index == \"f1\":\n                self.assertTrue(dg.current_future == f1 and dr == 24,\n                                \"WaitIterator dict status incorrect\")\n            elif dg.current_index == \"f2\":\n                self.assertTrue(dg.current_future == f2 and dr == 42,\n                                \"WaitIterator dict status incorrect\")\n            else:\n                self.fail(\"got bad WaitIterator index {}\".format(\n                    dg.current_index))\n\n            i += 1\n\n        self.assertEqual(dg.current_index, None, \"bad nil current index\")\n        self.assertEqual(dg.current_future, None, \"bad nil current future\")\n\n    def finish_coroutines(self, iteration, futures):\n        if iteration == 3:\n            futures[2].set_result(24)\n        elif iteration == 5:\n            futures[0].set_exception(ZeroDivisionError())\n        elif iteration == 8:\n            futures[1].set_result(42)\n            futures[3].set_result(84)\n\n        if iteration < 8:\n            self.io_loop.add_callback(self.finish_coroutines, iteration + 1, futures)\n\n    @gen_test\n    def test_iterator(self):\n        futures = [Future(), Future(), Future(), Future()]\n\n        self.finish_coroutines(0, futures)\n\n        g = gen.WaitIterator(*futures)\n\n        i = 0\n        while not g.done():\n            try:\n                r = yield g.next()\n            except ZeroDivisionError:\n                self.assertIs(g.current_future, futures[0],\n                              'exception future invalid')\n            else:\n                if i == 0:\n                    self.assertEqual(r, 24, 'iterator value incorrect')\n                    self.assertEqual(g.current_index, 2, 'wrong index')\n                elif i == 2:\n                    self.assertEqual(r, 42, 'iterator value incorrect')\n                    self.assertEqual(g.current_index, 1, 'wrong index')\n                elif i == 3:\n                    self.assertEqual(r, 84, 'iterator value incorrect')\n                    self.assertEqual(g.current_index, 3, 'wrong index')\n            i += 1\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport datetime\nimport functools\nimport sys\nimport textwrap\nimport time\nimport platform\nimport weakref\n\nfrom tornado.concurrent import return_future, Future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler, asynchronous, HTTPError\n\nfrom tornado import gen\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\nskipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')\nskipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython',\n                                 'Not CPython implementation')\n\n\nclass GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_with_arg_tuple(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback((1, 2)))((3, 4))\n            res = yield gen.Wait((1, 2))\n            self.assertEqual((3, 4), res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_reuse_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_key_mismatch_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Wait((2, 3))\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_leaked_callback_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.engine\n        def f():\n            yield (1, 2)\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_dict(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield dict(foo=gen.Wait(\"k1\"), bar=gen.Wait(\"k2\"))\n            self.assertEqual(results, dict(foo=\"v1\", bar=\"v2\"))\n            self.stop()\n        self.run_gen(f)\n\n    # The following tests explicitly run with both gen.Multi\n    # and gen.multi_future (Task returns a Future, so it can be used\n    # with either).\n    def test_multi_yieldpoint_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.Multi([\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ])\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_yieldpoint_dict_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.Multi(dict(\n                foo=gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                bar=gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ))\n            self.assertEqual(responses, dict(foo=\"v1\", bar=\"v2\"))\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_future_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future([\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ])\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_future_dict_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future(dict(\n                foo=gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                bar=gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ))\n            self.assertEqual(responses, dict(foo=\"v1\", bar=\"v2\"))\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_multi_empty(self):\n        # Empty lists or dicts should return the same type.\n        x = yield []\n        self.assertTrue(isinstance(x, list))\n        y = yield {}\n        self.assertTrue(isinstance(y, dict))\n\n    @gen_test\n    def test_multi_mixed_types(self):\n        # A YieldPoint (Wait) and Future (Task) can be combined\n        # (and use the YieldPoint codepath)\n        (yield gen.Callback(\"k1\"))(\"v1\")\n        responses = yield [gen.Wait(\"k1\"),\n                           gen.Task(self.delay_callback, 3, arg=\"v2\")]\n        self.assertEqual(responses, [\"v1\", \"v2\"])\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    @gen_test\n    def test_multi_dict_future(self):\n        results = yield dict(foo=self.async_future(1), bar=self.async_future(2))\n        self.assertEqual(results, dict(foo=1, bar=2))\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        def _stack_depth():\n            head = stack_context._state.contexts[1]\n            length = 0\n\n            while head is not None:\n                length += 1\n                head = head.old_contexts[1]\n\n            return length\n\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n\n            stack_increase = _stack_depth() - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = _stack_depth()\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value_tuple(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return (1, 2)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    @skipNotCPython\n    def test_task_refcounting(self):\n        # On CPython, tasks and their arguments should be released immediately\n        # without waiting for garbage collection.\n        @gen.engine\n        def f():\n            class Foo(object):\n                pass\n            arg = Foo()\n            self.arg_ref = weakref.ref(arg)\n            task = gen.Task(self.io_loop.add_callback, arg=arg)\n            self.task_ref = weakref.ref(task)\n            yield task\n            self.stop()\n\n        self.run_gen(f)\n        self.assertIs(self.arg_ref(), None)\n        self.assertIs(self.task_ref(), None)\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        # Note that this test and the following are for behavior that is\n        # not really supported any more:  coroutines no longer create a\n        # stack context automatically; but one is created after the first\n        # YieldPoint (i.e. not a Future).\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_moment(self):\n        calls = []\n\n        @gen.coroutine\n        def f(name, yieldable):\n            for i in range(5):\n                calls.append(name)\n                yield yieldable\n        # First, confirm the behavior without moment: each coroutine\n        # monopolizes the event loop until it finishes.\n        immediate = Future()\n        immediate.set_result(None)\n        yield [f('a', immediate), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'aaaaabbbbb')\n\n        # With moment, they take turns.\n        calls = []\n        yield [f('a', gen.moment), f('b', gen.moment)]\n        self.assertEqual(''.join(calls), 'ababababab')\n        self.finished = True\n\n        calls = []\n        yield [f('a', gen.moment), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'abbbbbaaaa')\n\n    @gen_test\n    def test_sleep(self):\n        yield gen.sleep(0.01)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_py3_leak_exception_context(self):\n        class LeakedException(Exception):\n            pass\n\n        @gen.coroutine\n        def inner(iteration):\n            raise LeakedException(iteration)\n\n        try:\n            yield inner(1)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"1\")\n            self.assertIsNone(e.__context__)\n\n        try:\n            yield inner(2)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"2\")\n            self.assertIsNone(e.__context__)\n\n        self.finished = True\n\nclass GenSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")\n\n\nclass GenTaskHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        client = AsyncHTTPClient(io_loop=io_loop)\n        response = yield gen.Task(client.fetch, self.get_argument('url'))\n        response.rethrow()\n        self.finish(b\"got response: \" + response.body)\n\n\nclass GenExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenCoroutineExceptionHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenYieldExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        # Test the interaction of the two stack_contexts.\n\n        def fail_task(callback):\n            io_loop.add_callback(lambda: 1 / 0)\n        try:\n            yield gen.Task(fail_task)\n            raise Exception(\"did not get expected exception\")\n        except ZeroDivisionError:\n            self.finish('ok')\n\n\nclass UndecoratedCoroutinesHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        self.chunks = []\n        yield gen.Task(IOLoop.current().add_callback)\n        self.chunks.append('1')\n\n    @gen.coroutine\n    def get(self):\n        self.chunks.append('2')\n        yield gen.Task(IOLoop.current().add_callback)\n        self.chunks.append('3')\n        yield gen.Task(IOLoop.current().add_callback)\n        self.write(''.join(self.chunks))\n\n\nclass AsyncPrepareErrorHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        yield gen.Task(IOLoop.current().add_callback)\n        raise HTTPError(403)\n\n    def get(self):\n        self.finish('ok')\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n            ('/undecorated_coroutine', UndecoratedCoroutinesHandler),\n            ('/async_prepare_error', AsyncPrepareErrorHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\n\n    def test_undecorated_coroutines(self):\n        response = self.fetch('/undecorated_coroutine')\n        self.assertEqual(response.body, b'123')\n\n    def test_async_prepare_error_handler(self):\n        response = self.fetch('/async_prepare_error')\n        self.assertEqual(response.code, 403)\n\n\nclass WithTimeoutTest(AsyncTestCase):\n    @gen_test\n    def test_timeout(self):\n        with self.assertRaises(gen.TimeoutError):\n            yield gen.with_timeout(datetime.timedelta(seconds=0.1),\n                                   Future())\n\n    @gen_test\n    def test_completes_before_timeout(self):\n        future = Future()\n        self.io_loop.add_timeout(datetime.timedelta(seconds=0.1),\n                                 lambda: future.set_result('asdf'))\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                        future, io_loop=self.io_loop)\n        self.assertEqual(result, 'asdf')\n\n    @gen_test\n    def test_fails_before_timeout(self):\n        future = Future()\n        self.io_loop.add_timeout(\n            datetime.timedelta(seconds=0.1),\n            lambda: future.set_exception(ZeroDivisionError()))\n        with self.assertRaises(ZeroDivisionError):\n            yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                   future, io_loop=self.io_loop)\n\n    @gen_test\n    def test_already_resolved(self):\n        future = Future()\n        future.set_result('asdf')\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                        future, io_loop=self.io_loop)\n        self.assertEqual(result, 'asdf')\n\n    @unittest.skipIf(futures is None, 'futures module not present')\n    @gen_test\n    def test_timeout_concurrent_future(self):\n        with futures.ThreadPoolExecutor(1) as executor:\n            with self.assertRaises(gen.TimeoutError):\n                yield gen.with_timeout(self.io_loop.time(),\n                                       executor.submit(time.sleep, 0.1))\n\n    @unittest.skipIf(futures is None, 'futures module not present')\n    @gen_test\n    def test_completed_concurrent_future(self):\n        with futures.ThreadPoolExecutor(1) as executor:\n            yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                   executor.submit(lambda: None))\n\n\nclass WaitIteratorTest(AsyncTestCase):\n    @gen_test\n    def test_empty_iterator(self):\n        g = gen.WaitIterator()\n        self.assertTrue(g.done(), 'empty generator iterated')\n\n        with self.assertRaises(ValueError):\n            g = gen.WaitIterator(False, bar=False)\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n    @gen_test\n    def test_already_done(self):\n        f1 = Future()\n        f2 = Future()\n        f3 = Future()\n        f1.set_result(24)\n        f2.set_result(42)\n        f3.set_result(84)\n\n        g = gen.WaitIterator(f1, f2, f3)\n        i = 0\n        while not g.done():\n            r = yield g.next()\n            # Order is not guaranteed, but the current implementation\n            # preserves ordering of already-done Futures.\n            if i == 0:\n                self.assertEqual(g.current_index, 0)\n                self.assertIs(g.current_future, f1)\n                self.assertEqual(r, 24)\n            elif i == 1:\n                self.assertEqual(g.current_index, 1)\n                self.assertIs(g.current_future, f2)\n                self.assertEqual(r, 42)\n            elif i == 2:\n                self.assertEqual(g.current_index, 2)\n                self.assertIs(g.current_future, f3)\n                self.assertEqual(r, 84)\n            i += 1\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n        dg = gen.WaitIterator(f1=f1, f2=f2)\n\n        while not dg.done():\n            dr = yield dg.next()\n            if dg.current_index == \"f1\":\n                self.assertTrue(dg.current_future == f1 and dr == 24,\n                                \"WaitIterator dict status incorrect\")\n            elif dg.current_index == \"f2\":\n                self.assertTrue(dg.current_future == f2 and dr == 42,\n                                \"WaitIterator dict status incorrect\")\n            else:\n                self.fail(\"got bad WaitIterator index {}\".format(\n                    dg.current_index))\n\n            i += 1\n\n        self.assertEqual(dg.current_index, None, \"bad nil current index\")\n        self.assertEqual(dg.current_future, None, \"bad nil current future\")\n\n    def finish_coroutines(self, iteration, futures):\n        if iteration == 3:\n            futures[2].set_result(24)\n        elif iteration == 5:\n            futures[0].set_exception(ZeroDivisionError())\n        elif iteration == 8:\n            futures[1].set_result(42)\n            futures[3].set_result(84)\n\n        if iteration < 8:\n            self.io_loop.add_callback(self.finish_coroutines, iteration + 1, futures)\n\n    @gen_test\n    def test_iterator(self):\n        futures = [Future(), Future(), Future(), Future()]\n\n        self.finish_coroutines(0, futures)\n\n        g = gen.WaitIterator(*futures)\n\n        i = 0\n        while not g.done():\n            try:\n                r = yield g.next()\n            except ZeroDivisionError:\n                self.assertIs(g.current_future, futures[0],\n                              'exception future invalid')\n            else:\n                if i == 0:\n                    self.assertEqual(r, 24, 'iterator value incorrect')\n                    self.assertEqual(g.current_index, 2, 'wrong index')\n                elif i == 2:\n                    self.assertEqual(r, 42, 'iterator value incorrect')\n                    self.assertEqual(g.current_index, 1, 'wrong index')\n                elif i == 3:\n                    self.assertEqual(r, 84, 'iterator value incorrect')\n                    self.assertEqual(g.current_index, 3, 'wrong index')\n            i += 1\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "tornado/test/gen_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "31acadd8",
                "new_commit_hash": "15876d59",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/gen_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/gen_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 844,
                            "length": 6
                        },
                        "new_range": {
                            "start": 844,
                            "length": 29
                        },
                        "section": "class GenCoroutineTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        yield gen.sleep(0.01)",
                                "type": "context"
                            },
                            {
                                "content": "        self.finished = True",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @skipBefore33",
                                "type": "added"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "added"
                            },
                            {
                                "content": "    def test_py3_leak_exception_context(self):",
                                "type": "added"
                            },
                            {
                                "content": "        class LeakedException(Exception):",
                                "type": "added"
                            },
                            {
                                "content": "            pass",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        @gen.coroutine",
                                "type": "added"
                            },
                            {
                                "content": "        def inner(iteration):",
                                "type": "added"
                            },
                            {
                                "content": "            raise LeakedException(iteration)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        try:",
                                "type": "added"
                            },
                            {
                                "content": "            yield inner(1)",
                                "type": "added"
                            },
                            {
                                "content": "        except LeakedException as e:",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEqual(str(e), \"1\")",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertIsNone(e.__context__)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        try:",
                                "type": "added"
                            },
                            {
                                "content": "            yield inner(2)",
                                "type": "added"
                            },
                            {
                                "content": "        except LeakedException as e:",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEqual(str(e), \"2\")",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertIsNone(e.__context__)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        self.finished = True",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class GenSequenceHandler(RequestHandler):",
                                "type": "context"
                            },
                            {
                                "content": "    @asynchronous",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenCoroutineTest",
                            "content": "class GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        # Note that this test and the following are for behavior that is\n        # not really supported any more:  coroutines no longer create a\n        # stack context automatically; but one is created after the first\n        # YieldPoint (i.e. not a Future).\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_moment(self):\n        calls = []\n\n        @gen.coroutine\n        def f(name, yieldable):\n            for i in range(5):\n                calls.append(name)\n                yield yieldable\n        # First, confirm the behavior without moment: each coroutine\n        # monopolizes the event loop until it finishes.\n        immediate = Future()\n        immediate.set_result(None)\n        yield [f('a', immediate), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'aaaaabbbbb')\n\n        # With moment, they take turns.\n        calls = []\n        yield [f('a', gen.moment), f('b', gen.moment)]\n        self.assertEqual(''.join(calls), 'ababababab')\n        self.finished = True\n\n        calls = []\n        yield [f('a', gen.moment), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'abbbbbaaaa')\n\n    @gen_test\n    def test_sleep(self):\n        yield gen.sleep(0.01)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_py3_leak_exception_context(self):\n        class LeakedException(Exception):\n            pass\n\n        @gen.coroutine\n        def inner(iteration):\n            raise LeakedException(iteration)\n\n        try:\n            yield inner(1)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"1\")\n            self.assertIsNone(e.__context__)\n\n        try:\n            yield inner(2)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"2\")\n            self.assertIsNone(e.__context__)\n\n        self.finished = True",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 603,
                            "end_lineno": 869,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenCoroutineTest.test_py3_leak_exception_context",
                            "content": "class GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        # Note that this test and the following are for behavior that is\n        # not really supported any more:  coroutines no longer create a\n        # stack context automatically; but one is created after the first\n        # YieldPoint (i.e. not a Future).\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_moment(self):\n        calls = []\n\n        @gen.coroutine\n        def f(name, yieldable):\n            for i in range(5):\n                calls.append(name)\n                yield yieldable\n        # First, confirm the behavior without moment: each coroutine\n        # monopolizes the event loop until it finishes.\n        immediate = Future()\n        immediate.set_result(None)\n        yield [f('a', immediate), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'aaaaabbbbb')\n\n        # With moment, they take turns.\n        calls = []\n        yield [f('a', gen.moment), f('b', gen.moment)]\n        self.assertEqual(''.join(calls), 'ababababab')\n        self.finished = True\n\n        calls = []\n        yield [f('a', gen.moment), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'abbbbbaaaa')\n\n    @gen_test\n    def test_sleep(self):\n        yield gen.sleep(0.01)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_py3_leak_exception_context(self):\n        class LeakedException(Exception):\n            pass\n\n        @gen.coroutine\n        def inner(iteration):\n            raise LeakedException(iteration)\n\n        try:\n            yield inner(1)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"1\")\n            self.assertIsNone(e.__context__)\n\n        try:\n            yield inner(2)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"2\")\n            self.assertIsNone(e.__context__)\n\n        self.finished = True",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 849,
                            "end_lineno": 869,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenCoroutineTest",
                                "content": "class GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        # Note that this test and the following are for behavior that is\n        # not really supported any more:  coroutines no longer create a\n        # stack context automatically; but one is created after the first\n        # YieldPoint (i.e. not a Future).\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_moment(self):\n        calls = []\n\n        @gen.coroutine\n        def f(name, yieldable):\n            for i in range(5):\n                calls.append(name)\n                yield yieldable\n        # First, confirm the behavior without moment: each coroutine\n        # monopolizes the event loop until it finishes.\n        immediate = Future()\n        immediate.set_result(None)\n        yield [f('a', immediate), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'aaaaabbbbb')\n\n        # With moment, they take turns.\n        calls = []\n        yield [f('a', gen.moment), f('b', gen.moment)]\n        self.assertEqual(''.join(calls), 'ababababab')\n        self.finished = True\n\n        calls = []\n        yield [f('a', gen.moment), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'abbbbbaaaa')\n\n    @gen_test\n    def test_sleep(self):\n        yield gen.sleep(0.01)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_py3_leak_exception_context(self):\n        class LeakedException(Exception):\n            pass\n\n        @gen.coroutine\n        def inner(iteration):\n            raise LeakedException(iteration)\n\n        try:\n            yield inner(1)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"1\")\n            self.assertIsNone(e.__context__)\n\n        try:\n            yield inner(2)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"2\")\n            self.assertIsNone(e.__context__)\n\n        self.finished = True",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 603,
                                "end_lineno": 869,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "a015429def80caeed9944a6450095483cc58e870^",
    "new_commit_hash": "a015429def80caeed9944a6450095483cc58e870",
    "commit_message": "Merge pull request #1333 from carlsverre/master\n\nCoroutine exception __context__ leak in python 3",
    "commit_date": "2015-02-12T18:06:51-05:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "a015429def80caeed9944a6450095483cc58e870",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport datetime\nimport functools\nimport sys\nimport textwrap\nimport time\nimport platform\nimport weakref\n\nfrom tornado.concurrent import return_future, Future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler, asynchronous, HTTPError\n\nfrom tornado import gen\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\nskipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')\nskipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython',\n                                 'Not CPython implementation')\n\n\nclass GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_with_arg_tuple(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback((1, 2)))((3, 4))\n            res = yield gen.Wait((1, 2))\n            self.assertEqual((3, 4), res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_reuse_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_key_mismatch_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Wait((2, 3))\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_leaked_callback_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.engine\n        def f():\n            yield (1, 2)\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_dict(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield dict(foo=gen.Wait(\"k1\"), bar=gen.Wait(\"k2\"))\n            self.assertEqual(results, dict(foo=\"v1\", bar=\"v2\"))\n            self.stop()\n        self.run_gen(f)\n\n    # The following tests explicitly run with both gen.Multi\n    # and gen.multi_future (Task returns a Future, so it can be used\n    # with either).\n    def test_multi_yieldpoint_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.Multi([\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ])\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_yieldpoint_dict_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.Multi(dict(\n                foo=gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                bar=gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ))\n            self.assertEqual(responses, dict(foo=\"v1\", bar=\"v2\"))\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_future_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future([\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ])\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_future_dict_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future(dict(\n                foo=gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                bar=gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ))\n            self.assertEqual(responses, dict(foo=\"v1\", bar=\"v2\"))\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_multi_empty(self):\n        # Empty lists or dicts should return the same type.\n        x = yield []\n        self.assertTrue(isinstance(x, list))\n        y = yield {}\n        self.assertTrue(isinstance(y, dict))\n\n    @gen_test\n    def test_multi_mixed_types(self):\n        # A YieldPoint (Wait) and Future (Task) can be combined\n        # (and use the YieldPoint codepath)\n        (yield gen.Callback(\"k1\"))(\"v1\")\n        responses = yield [gen.Wait(\"k1\"),\n                           gen.Task(self.delay_callback, 3, arg=\"v2\")]\n        self.assertEqual(responses, [\"v1\", \"v2\"])\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    @gen_test\n    def test_multi_dict_future(self):\n        results = yield dict(foo=self.async_future(1), bar=self.async_future(2))\n        self.assertEqual(results, dict(foo=1, bar=2))\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        def _stack_depth():\n            head = stack_context._state.contexts[1]\n            length = 0\n\n            while head is not None:\n                length += 1\n                head = head.old_contexts[1]\n\n            return length\n\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n\n            stack_increase = _stack_depth() - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = _stack_depth()\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value_tuple(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return (1, 2)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    @skipNotCPython\n    def test_task_refcounting(self):\n        # On CPython, tasks and their arguments should be released immediately\n        # without waiting for garbage collection.\n        @gen.engine\n        def f():\n            class Foo(object):\n                pass\n            arg = Foo()\n            self.arg_ref = weakref.ref(arg)\n            task = gen.Task(self.io_loop.add_callback, arg=arg)\n            self.task_ref = weakref.ref(task)\n            yield task\n            self.stop()\n\n        self.run_gen(f)\n        self.assertIs(self.arg_ref(), None)\n        self.assertIs(self.task_ref(), None)\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        # Note that this test and the following are for behavior that is\n        # not really supported any more:  coroutines no longer create a\n        # stack context automatically; but one is created after the first\n        # YieldPoint (i.e. not a Future).\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            (yield gen.Callback(1))()\n            yield gen.Wait(1)\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_moment(self):\n        calls = []\n\n        @gen.coroutine\n        def f(name, yieldable):\n            for i in range(5):\n                calls.append(name)\n                yield yieldable\n        # First, confirm the behavior without moment: each coroutine\n        # monopolizes the event loop until it finishes.\n        immediate = Future()\n        immediate.set_result(None)\n        yield [f('a', immediate), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'aaaaabbbbb')\n\n        # With moment, they take turns.\n        calls = []\n        yield [f('a', gen.moment), f('b', gen.moment)]\n        self.assertEqual(''.join(calls), 'ababababab')\n        self.finished = True\n\n        calls = []\n        yield [f('a', gen.moment), f('b', immediate)]\n        self.assertEqual(''.join(calls), 'abbbbbaaaa')\n\n    @gen_test\n    def test_sleep(self):\n        yield gen.sleep(0.01)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_py3_leak_exception_context(self):\n        class LeakedException(Exception):\n            pass\n\n        @gen.coroutine\n        def inner(iteration):\n            raise LeakedException(iteration)\n\n        try:\n            yield inner(1)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"1\")\n            self.assertIsNone(e.__context__)\n\n        try:\n            yield inner(2)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"2\")\n            self.assertIsNone(e.__context__)\n\n        self.finished = True\n\nclass GenSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")\n\n\nclass GenTaskHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        client = AsyncHTTPClient(io_loop=io_loop)\n        response = yield gen.Task(client.fetch, self.get_argument('url'))\n        response.rethrow()\n        self.finish(b\"got response: \" + response.body)\n\n\nclass GenExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenCoroutineExceptionHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenYieldExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        # Test the interaction of the two stack_contexts.\n\n        def fail_task(callback):\n            io_loop.add_callback(lambda: 1 / 0)\n        try:\n            yield gen.Task(fail_task)\n            raise Exception(\"did not get expected exception\")\n        except ZeroDivisionError:\n            self.finish('ok')\n\n\nclass UndecoratedCoroutinesHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        self.chunks = []\n        yield gen.Task(IOLoop.current().add_callback)\n        self.chunks.append('1')\n\n    @gen.coroutine\n    def get(self):\n        self.chunks.append('2')\n        yield gen.Task(IOLoop.current().add_callback)\n        self.chunks.append('3')\n        yield gen.Task(IOLoop.current().add_callback)\n        self.write(''.join(self.chunks))\n\n\nclass AsyncPrepareErrorHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        yield gen.Task(IOLoop.current().add_callback)\n        raise HTTPError(403)\n\n    def get(self):\n        self.finish('ok')\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n            ('/undecorated_coroutine', UndecoratedCoroutinesHandler),\n            ('/async_prepare_error', AsyncPrepareErrorHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\n\n    def test_undecorated_coroutines(self):\n        response = self.fetch('/undecorated_coroutine')\n        self.assertEqual(response.body, b'123')\n\n    def test_async_prepare_error_handler(self):\n        response = self.fetch('/async_prepare_error')\n        self.assertEqual(response.code, 403)\n\n\nclass WithTimeoutTest(AsyncTestCase):\n    @gen_test\n    def test_timeout(self):\n        with self.assertRaises(gen.TimeoutError):\n            yield gen.with_timeout(datetime.timedelta(seconds=0.1),\n                                   Future())\n\n    @gen_test\n    def test_completes_before_timeout(self):\n        future = Future()\n        self.io_loop.add_timeout(datetime.timedelta(seconds=0.1),\n                                 lambda: future.set_result('asdf'))\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                        future, io_loop=self.io_loop)\n        self.assertEqual(result, 'asdf')\n\n    @gen_test\n    def test_fails_before_timeout(self):\n        future = Future()\n        self.io_loop.add_timeout(\n            datetime.timedelta(seconds=0.1),\n            lambda: future.set_exception(ZeroDivisionError()))\n        with self.assertRaises(ZeroDivisionError):\n            yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                   future, io_loop=self.io_loop)\n\n    @gen_test\n    def test_already_resolved(self):\n        future = Future()\n        future.set_result('asdf')\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                        future, io_loop=self.io_loop)\n        self.assertEqual(result, 'asdf')\n\n    @unittest.skipIf(futures is None, 'futures module not present')\n    @gen_test\n    def test_timeout_concurrent_future(self):\n        with futures.ThreadPoolExecutor(1) as executor:\n            with self.assertRaises(gen.TimeoutError):\n                yield gen.with_timeout(self.io_loop.time(),\n                                       executor.submit(time.sleep, 0.1))\n\n    @unittest.skipIf(futures is None, 'futures module not present')\n    @gen_test\n    def test_completed_concurrent_future(self):\n        with futures.ThreadPoolExecutor(1) as executor:\n            yield gen.with_timeout(datetime.timedelta(seconds=3600),\n                                   executor.submit(lambda: None))\n\n\nclass WaitIteratorTest(AsyncTestCase):\n    @gen_test\n    def test_empty_iterator(self):\n        g = gen.WaitIterator()\n        self.assertTrue(g.done(), 'empty generator iterated')\n\n        with self.assertRaises(ValueError):\n            g = gen.WaitIterator(False, bar=False)\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n    @gen_test\n    def test_already_done(self):\n        f1 = Future()\n        f2 = Future()\n        f3 = Future()\n        f1.set_result(24)\n        f2.set_result(42)\n        f3.set_result(84)\n\n        g = gen.WaitIterator(f1, f2, f3)\n        i = 0\n        while not g.done():\n            r = yield g.next()\n            # Order is not guaranteed, but the current implementation\n            # preserves ordering of already-done Futures.\n            if i == 0:\n                self.assertEqual(g.current_index, 0)\n                self.assertIs(g.current_future, f1)\n                self.assertEqual(r, 24)\n            elif i == 1:\n                self.assertEqual(g.current_index, 1)\n                self.assertIs(g.current_future, f2)\n                self.assertEqual(r, 42)\n            elif i == 2:\n                self.assertEqual(g.current_index, 2)\n                self.assertIs(g.current_future, f3)\n                self.assertEqual(r, 84)\n            i += 1\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n        dg = gen.WaitIterator(f1=f1, f2=f2)\n\n        while not dg.done():\n            dr = yield dg.next()\n            if dg.current_index == \"f1\":\n                self.assertTrue(dg.current_future == f1 and dr == 24,\n                                \"WaitIterator dict status incorrect\")\n            elif dg.current_index == \"f2\":\n                self.assertTrue(dg.current_future == f2 and dr == 42,\n                                \"WaitIterator dict status incorrect\")\n            else:\n                self.fail(\"got bad WaitIterator index {}\".format(\n                    dg.current_index))\n\n            i += 1\n\n        self.assertEqual(dg.current_index, None, \"bad nil current index\")\n        self.assertEqual(dg.current_future, None, \"bad nil current future\")\n\n    def finish_coroutines(self, iteration, futures):\n        if iteration == 3:\n            futures[2].set_result(24)\n        elif iteration == 5:\n            futures[0].set_exception(ZeroDivisionError())\n        elif iteration == 8:\n            futures[1].set_result(42)\n            futures[3].set_result(84)\n\n        if iteration < 8:\n            self.io_loop.add_callback(self.finish_coroutines, iteration + 1, futures)\n\n    @gen_test\n    def test_iterator(self):\n        futures = [Future(), Future(), Future(), Future()]\n\n        self.finish_coroutines(0, futures)\n\n        g = gen.WaitIterator(*futures)\n\n        i = 0\n        while not g.done():\n            try:\n                r = yield g.next()\n            except ZeroDivisionError:\n                self.assertIs(g.current_future, futures[0],\n                              'exception future invalid')\n            else:\n                if i == 0:\n                    self.assertEqual(r, 24, 'iterator value incorrect')\n                    self.assertEqual(g.current_index, 2, 'wrong index')\n                elif i == 2:\n                    self.assertEqual(r, 42, 'iterator value incorrect')\n                    self.assertEqual(g.current_index, 1, 'wrong index')\n                elif i == 3:\n                    self.assertEqual(r, 84, 'iterator value incorrect')\n                    self.assertEqual(g.current_index, 3, 'wrong index')\n            i += 1\n\nif __name__ == '__main__':\n    unittest.main()\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 2 packages in 827ms\nPrepared 1 package in 1.28s\nInstalled 2 packages in 1ms\n + certifi==2024.12.14\n + tornado==4.2.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870)\nResolved 29 packages in 21ms\nInstalled 29 packages in 52ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870\n......................................................................................\ncollected 86 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_early_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return_no_value\nPASSED r2e_tests.test_1::GenCoroutineTest::test_moment\nPASSED r2e_tests.test_1::GenCoroutineTest::test_pass_callback\nPASSED r2e_tests.test_1::GenCoroutineTest::test_py3_leak_exception_context\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sleep\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return_no_value\nPASSED r2e_tests.test_1::GenEngineTest::test_arguments\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_future\nPASSED r2e_tests.test_1::GenEngineTest::test_inline_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_ioloop_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_multi\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_dict\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_dict_future\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_empty\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future_dict_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_mixed_types\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_performance\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_yieldpoint_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_yieldpoint_dict_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_no_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_orphaned_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_parallel_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_raise_after_stop\nPASSED r2e_tests.test_1::GenEngineTest::test_resume_after_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak_exception\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_task\nPASSED r2e_tests.test_1::GenEngineTest::test_task_refcounting\nPASSED r2e_tests.test_1::GenEngineTest::test_task_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_all\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg_tuple\nPASSED r2e_tests.test_1::GenWebTest::test_async_prepare_error_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_unfinished_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_task_handler\nPASSED r2e_tests.test_1::GenWebTest::test_undecorated_coroutines\nPASSED r2e_tests.test_1::GenWebTest::test_yield_exception_handler\nPASSED r2e_tests.test_1::WaitIteratorTest::test_already_done\nPASSED r2e_tests.test_1::WaitIteratorTest::test_empty_iterator\nPASSED r2e_tests.test_1::WaitIteratorTest::test_iterator\nPASSED r2e_tests.test_1::WithTimeoutTest::test_already_resolved\nPASSED r2e_tests.test_1::WithTimeoutTest::test_completed_concurrent_future\nPASSED r2e_tests.test_1::WithTimeoutTest::test_completes_before_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_fails_before_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_timeout_concurrent_future\n=================== 86 passed in 0.46s ===================\n",
    "new_commit_res_stderr": "WARNING:tornado.access:403 GET /async_prepare_error (127.0.0.1) 0.41ms\nERROR:tornado.access:500 GET /coroutine_exception (127.0.0.1) 0.32ms\nERROR:tornado.access:500 GET /exception (127.0.0.1) 0.28ms\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870\n......................................................................................\ncollected 87 items\n\n=================================== FAILURES ===================================\n__________ GenCoroutineTest.test_py3_leak_exception_context __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/r2e_tests/test_1.py\", line 858, in test_py3_leak_exception_context\n    yield inner(1)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/gen.py\", line 828, in run\n    value = future.result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/concurrent.py\", line 211, in result\n    raise_exc_info(self._exc_info)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/gen.py\", line 214, in wrapper\n    result = func(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/r2e_tests/test_1.py\", line 855, in inner\n    raise LeakedException(iteration)\nr2e_tests.test_1.GenCoroutineTest.test_py3_leak_exception_context.<locals>.LeakedException: 1\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/r2e_tests/test_1.py\", line 864, in test_py3_leak_exception_context\n    yield inner(2)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/gen.py\", line 828, in run\n    value = future.result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/concurrent.py\", line 211, in result\n    raise_exc_info(self._exc_info)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/gen.py\", line 214, in wrapper\n    result = func(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/r2e_tests/test_1.py\", line 855, in inner\n    raise LeakedException(iteration)\nr2e_tests.test_1.GenCoroutineTest.test_py3_leak_exception_context.<locals>.LeakedException: 2\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/testing.py\", line 120, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/testing.py\", line 501, in post_coroutine\n    return self.io_loop.run_sync(\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/ioloop.py\", line 428, in run_sync\n    return future_cell[0].result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/concurrent.py\", line 211, in result\n    raise_exc_info(self._exc_info)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/tornado/gen.py\", line 831, in run\n    yielded = self.gen.throw(*sys.exc_info())\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/r2e_tests/test_1.py\", line 867, in test_py3_leak_exception_context\n    self.assertIsNone(e.__context__)\nAssertionError: LeakedException(1) is not None\n__________ GenCoroutineTest.test_py3_leak_exception_context __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 595, in run\n    self._callTearDown()\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 553, in _callTearDown\n    self.tearDown()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_a015429def80caeed9944a6450095483cc58e870/r2e_tests/test_1.py\", line 613, in tearDown\n    assert self.finished\nAssertionError\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_early_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return_no_value\nPASSED r2e_tests.test_1::GenCoroutineTest::test_moment\nPASSED r2e_tests.test_1::GenCoroutineTest::test_pass_callback\nFAILED r2e_tests.test_1::GenCoroutineTest::test_py3_leak_exception_context\nFAILED r2e_tests.test_1::GenCoroutineTest::test_py3_leak_exception_context\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sleep\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return_no_value\nPASSED r2e_tests.test_1::GenEngineTest::test_arguments\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_future\nPASSED r2e_tests.test_1::GenEngineTest::test_inline_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_ioloop_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_multi\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_dict\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_dict_future\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_empty\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future_dict_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_mixed_types\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_performance\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_yieldpoint_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_yieldpoint_dict_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_no_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_orphaned_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_parallel_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_raise_after_stop\nPASSED r2e_tests.test_1::GenEngineTest::test_resume_after_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak_exception\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_task\nPASSED r2e_tests.test_1::GenEngineTest::test_task_refcounting\nPASSED r2e_tests.test_1::GenEngineTest::test_task_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_all\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg_tuple\nPASSED r2e_tests.test_1::GenWebTest::test_async_prepare_error_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_unfinished_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_task_handler\nPASSED r2e_tests.test_1::GenWebTest::test_undecorated_coroutines\nPASSED r2e_tests.test_1::GenWebTest::test_yield_exception_handler\nPASSED r2e_tests.test_1::WaitIteratorTest::test_already_done\nPASSED r2e_tests.test_1::WaitIteratorTest::test_empty_iterator\nPASSED r2e_tests.test_1::WaitIteratorTest::test_iterator\nPASSED r2e_tests.test_1::WithTimeoutTest::test_already_resolved\nPASSED r2e_tests.test_1::WithTimeoutTest::test_completed_concurrent_future\nPASSED r2e_tests.test_1::WithTimeoutTest::test_completes_before_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_fails_before_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_timeout_concurrent_future\n=================== 2 failed, 85 passed in 0.46s ===================\n",
    "old_commit_res_stderr": "WARNING:tornado.access:403 GET /async_prepare_error (127.0.0.1) 0.32ms\nERROR:tornado.access:500 GET /coroutine_exception (127.0.0.1) 0.32ms\nERROR:tornado.access:500 GET /exception (127.0.0.1) 0.33ms\n"
}
tornado/gen.py tornado/test/gen_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Coroutine Exceptions Leak `__context__` Attribute in Python 3

**Description:**
When an exception is raised within a coroutine, the exception's `__context__` attribute unexpectedly retains context information instead of being cleared. This leakage can interfere with exception handling and debugging processes.

**Example Code:**
```python
import tornado.gen
from tornado.testing import AsyncTestCase

class CoroutineExceptionTest(AsyncTestCase):
    @tornado.gen.coroutine
    def test_exception_context_leak(self):
        class SampleException(Exception):
            pass

        @tornado.gen.coroutine
        def inner():
            raise SampleException("Test exception")

        try:
            yield inner()
        except SampleException as e:
            print(e.__context__)  # Unexpectedly retains context
```

**Expected Behavior:**
After catching the exception, `e.__context__` should be `None`, indicating no retained context.

**Actual Behavior:**
`e.__context__` retains context information instead of being `None`, leading to a context leak.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/gen.py
"""``tornado.gen`` is a generator-based interface to make it easier to
work in an asynchronous environment.  Code using the ``gen`` module
is technically asynchronous, but it is written as a single generator
instead of a collection of separate functions.

For example, the following asynchronous handler:

.. testcode::

    class AsyncHandler(RequestHandler):
        @asynchronous
        def get(self):
            http_client = AsyncHTTPClient()
            http_client.fetch("http://example.com",
                              callback=self.on_fetch)

        def on_fetch(self, response):
            do_something_with_response(response)
            self.render("template.html")

.. testoutput::
   :hide:

could be written with ``gen`` as:

.. testcode::

    class GenAsyncHandler(RequestHandler):
        @gen.coroutine
        def get(self):
            http_client = AsyncHTTPClient()
            response = yield http_client.fetch("http://example.com")
            do_something_with_response(response)
            self.render("template.html")

.. testoutput::
   :hide:

Most asynchronous functions in Tornado return a `.Future`;
yielding this object returns its `~.Future.result`.

You can also yield a list or dict of ``Futures``, which will be
started at the same time and run in parallel; a list or dict of results will
be returned when they are all finished:

.. testcode::

    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response1, response2 = yield [http_client.fetch(url1),
                                      http_client.fetch(url2)]
        response_dict = yield dict(response3=http_client.fetch(url3),
                                   response4=http_client.fetch(url4))
        response3 = response_dict['response3']
        response4 = response_dict['response4']

.. testoutput::
   :hide:

If the `~functools.singledispatch` library is available (standard in
Python 3.4, available via the `singledispatch
<https://pypi.python.org/pypi/singledispatch>`_ package on older
versions), additional types of objects may be yielded. Tornado includes
support for ``asyncio.Future`` and Twisted's ``Deferred`` class when
``tornado.platform.asyncio`` and ``tornado.platform.twisted`` are imported.
See the `convert_yielded` function to extend this mechanism.

.. versionchanged:: 3.2
   Dict support added.

.. versionchanged:: 4.1
   Support added for yielding ``asyncio`` Futures and Twisted Deferreds
   via ``singledispatch``.

"""
from __future__ import absolute_import, division, print_function, with_statement

import collections
import functools
import itertools
import sys
import types
import weakref

from tornado.concurrent import Future, TracebackFuture, is_future, chain_future
from tornado.ioloop import IOLoop
from tornado.log import app_log
from tornado import stack_context

try:
    from functools import singledispatch  # py34+
except ImportError as e:
    try:
        from singledispatch import singledispatch  # backport
    except ImportError:
        singledispatch = None


class KeyReuseError(Exception):
    pass


class UnknownKeyError(Exception):
    pass


class LeakedCallbackError(Exception):
    pass


class BadYieldError(Exception):
    pass


class ReturnValueIgnoredError(Exception):
    pass


class TimeoutError(Exception):
    """Exception raised by ``with_timeout``."""


def engine(func):
    """Callback-oriented decorator for asynchronous generators.

    This is an older interface; for new code that does not need to be
    compatible with versions of Tornado older than 3.0 the
    `coroutine` decorator is recommended instead.

    This decorator is similar to `coroutine`, except it does not
    return a `.Future` and the ``callback`` argument is not treated
    specially.

    In most cases, functions decorated with `engine` should take
    a ``callback`` argument and invoke it with their result when
    they are finished.  One notable exception is the
    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,
    which use ``self.finish()`` in place of a callback argument.
    """
    func = _make_coroutine_wrapper(func, replace_callback=False)

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        future = func(*args, **kwargs)

        def final_callback(future):
            if future.result() is not None:
                raise ReturnValueIgnoredError(
                    "@gen.engine functions cannot return values: %r" %
                    (future.result(),))
        # The engine interface doesn't give us any way to return
        # errors but to raise them into the stack context.
        # Save the stack context here to use when the Future has resolved.
        future.add_done_callback(stack_context.wrap(final_callback))
    return wrapper


def coroutine(func, replace_callback=True):
    """Decorator for asynchronous generators.

    Any generator that yields objects from this module must be wrapped
    in either this decorator or `engine`.

    Coroutines may "return" by raising the special exception
    `Return(value) <Return>`.  In Python 3.3+, it is also possible for
    the function to simply use the ``return value`` statement (prior to
    Python 3.3 generators were not allowed to also return values).
    In all versions of Python a coroutine that simply wishes to exit
    early may use the ``return`` statement without a value.

    Functions with this decorator return a `.Future`.  Additionally,
    they may be called with a ``callback`` keyword argument, which
    will be invoked with the future's result when it resolves.  If the
    coroutine fails, the callback will not be run and an exception
    will be raised into the surrounding `.StackContext`.  The
    ``callback`` argument is not visible inside the decorated
    function; it is handled by the decorator itself.

    From the caller's perspective, ``@gen.coroutine`` is similar to
    the combination of ``@return_future`` and ``@gen.engine``.

    .. warning::

       When exceptions occur inside a coroutine, the exception
       information will be stored in the `.Future` object. You must
       examine the result of the `.Future` object, or the exception
       may go unnoticed by your code. This means yielding the function
       if called from another coroutine, using something like
       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`
       to `.IOLoop.add_future`.

    """
    return _make_coroutine_wrapper(func, replace_callback=True)


def _make_coroutine_wrapper(func, replace_callback):
    """The inner workings of ``@gen.coroutine`` and ``@gen.engine``.

    The two decorators differ in their treatment of the ``callback``
    argument, so we cannot simply implement ``@engine`` in terms of
    ``@coroutine``.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        future = TracebackFuture()

        if replace_callback and 'callback' in kwargs:
            callback = kwargs.pop('callback')
            IOLoop.current().add_future(
                future, lambda future: callback(future.result()))

        try:
            result = func(*args, **kwargs)
        except (Return, StopIteration) as e:
            result = getattr(e, 'value', None)
        except Exception:
            future.set_exc_info(sys.exc_info())
            return future
        else:
            if isinstance(result, types.GeneratorType):
                # Inline the first iteration of Runner.run.  This lets us
                # avoid the cost of creating a Runner when the coroutine
                # never actually yields, which in turn allows us to
                # use "optional" coroutines in critical path code without
                # performance penalty for the synchronous case.
                try:
                    orig_stack_contexts = stack_context._state.contexts
                    yielded = next(result)
                    if stack_context._state.contexts is not orig_stack_contexts:
                        yielded = TracebackFuture()
                        yielded.set_exception(
                            stack_context.StackContextInconsistentError(
                                'stack_context inconsistency (probably caused '
                                'by yield within a "with StackContext" block)'))
                except (StopIteration, Return) as e:
                    future.set_result(getattr(e, 'value', None))
                except Exception:
                    future.set_exc_info(sys.exc_info())
                else:
                    Runner(result, future, yielded)
                try:
                    return future
                finally:
                    # Subtle memory optimization: if next() raised an exception,
                    # the future's exc_info contains a traceback which
                    # includes this stack frame.  This creates a cycle,
                    # which will be collected at the next full GC but has
                    # been shown to greatly increase memory usage of
                    # benchmarks (relative to the refcount-based scheme
                    # used in the absence of cycles).  We can avoid the
                    # cycle by clearing the local variable after we return it.
                    future = None
        future.set_result(result)
        return future
    return wrapper


class Return(Exception):
    """Special exception to return a value from a `coroutine`.

    If this exception is raised, its value argument is used as the
    result of the coroutine::

        @gen.coroutine
        def fetch_json(url):
            response = yield AsyncHTTPClient().fetch(url)
            raise gen.Return(json_decode(response.body))

    In Python 3.3, this exception is no longer necessary: the ``return``
    statement can be used directly to return a value (previously
    ``yield`` and ``return`` with a value could not be combined in the
    same function).

    By analogy with the return statement, the value argument is optional,
    but it is never necessary to ``raise gen.Return()``.  The ``return``
    statement can be used with no arguments instead.
    """
    def __init__(self, value=None):
        super(Return, self).__init__()
        self.value = value


class WaitIterator(object):
    """Provides an iterator to yield the results of futures as they finish.

    Yielding a set of futures like this:

    ``results = yield [future1, future2]``

    pauses the coroutine until both ``future1`` and ``future2``
    return, and then restarts the coroutine with the results of both
    futures. If either future is an exception, the expression will
    raise that exception and all the results will be lost.

    If you need to get the result of each future as soon as possible,
    or if you need the result of some futures even if others produce
    errors, you can use ``WaitIterator``::

      wait_iterator = gen.WaitIterator(future1, future2)
      while not wait_iterator.done():
          try:
              result = yield wait_iterator.next()
          except Exception as e:
              print("Error {} from {}".format(e, wait_iterator.current_future))
          else:
              print("Result {} recieved from {} at {}".format(
                  result, wait_iterator.current_future,
                  wait_iterator.current_index))

    Because results are returned as soon as they are available the
    output from the iterator *will not be in the same order as the
    input arguments*. If you need to know which future produced the
    current result, you can use the attributes
    ``WaitIterator.current_future``, or ``WaitIterator.current_index``
    to get the index of the future from the input list. (if keyword
    arguments were used in the construction of the `WaitIterator`,
    ``current_index`` will use the corresponding keyword).

    .. versionadded:: 4.1
    """
    def __init__(self, *args, **kwargs):
        if args and kwargs:
            raise ValueError(
                "You must provide args or kwargs, not both")

        if kwargs:
            self._unfinished = dict((f, k) for (k, f) in kwargs.items())
            futures = list(kwargs.values())
        else:
            self._unfinished = dict((f, i) for (i, f) in enumerate(args))
            futures = args

        self._finished = collections.deque()
        self.current_index = self.current_future = None
        self._running_future = None

        self_ref = weakref.ref(self)
        for future in futures:
            future.add_done_callback(functools.partial(
                self._done_callback, self_ref))

    def done(self):
        """Returns True if this iterator has no more results."""
        if self._finished or self._unfinished:
            return False
        # Clear the 'current' values when iteration is done.
        self.current_index = self.current_future = None
        return True

    def next(self):
        """Returns a `.Future` that will yield the next available result.

        Note that this `.Future` will not be the same object as any of
        the inputs.
        """
        self._running_future = TracebackFuture()

        if self._finished:
            self._return_result(self._finished.popleft())

        return self._running_future

    @staticmethod
    def _done_callback(self_ref, done):
        self = self_ref()
        if self is not None:
            if self._running_future and not self._running_future.done():
                self._return_result(done)
            else:
                self._finished.append(done)

    def _return_result(self, done):
        """Called set the returned future's state that of the future
        we yielded, and set the current future for the iterator.
        """
        chain_future(done, self._running_future)

        self.current_future = done
        self.current_index = self._unfinished.pop(done)


class YieldPoint(object):
    """Base class for objects that may be yielded from the generator.

    .. deprecated:: 4.0
       Use `Futures <.Future>` instead.
    """
    def start(self, runner):
        """Called by the runner after the generator has yielded.

        No other methods will be called on this object before ``start``.
        """
        raise NotImplementedError()

    def is_ready(self):
        """Called by the runner to determine whether to resume the generator.

        Returns a boolean; may be called more than once.
        """
        raise NotImplementedError()

    def get_result(self):
        """Returns the value to use as the result of the yield expression.

        This method will only be called once, and only after `is_ready`
        has returned true.
        """
        raise NotImplementedError()


class Callback(YieldPoint):
    """Returns a callable object that will allow a matching `Wait` to proceed.

    The key may be any value suitable for use as a dictionary key, and is
    used to match ``Callbacks`` to their corresponding ``Waits``.  The key
    must be unique among outstanding callbacks within a single run of the
    generator function, but may be reused across different runs of the same
    function (so constants generally work fine).

    The callback may be called with zero or one arguments; if an argument
    is given it will be returned by `Wait`.

    .. deprecated:: 4.0
       Use `Futures <.Future>` instead.
    """
    def __init__(self, key):
        self.key = key

    def start(self, runner):
        self.runner = runner
        runner.register_callback(self.key)

    def is_ready(self):
        return True

    def get_result(self):
        return self.runner.result_callback(self.key)


class Wait(YieldPoint):
    """Returns the argument passed to the result of a previous `Callback`.

    .. deprecated:: 4.0
       Use `Futures <.Future>` instead.
    """
    def __init__(self, key):
        self.key = key

    def start(self, runner):
        self.runner = runner

    def is_ready(self):
        return self.runner.is_ready(self.key)

    def get_result(self):
        return self.runner.pop_result(self.key)


class WaitAll(YieldPoint):
    """Returns the results of multiple previous `Callbacks <Callback>`.

    The argument is a sequence of `Callback` keys, and the result is
    a list of results in the same order.

    `WaitAll` is equivalent to yielding a list of `Wait` objects.

    .. deprecated:: 4.0
       Use `Futures <.Future>` instead.
    """
    def __init__(self, keys):
        self.keys = keys

    def start(self, runner):
        self.runner = runner

    def is_ready(self):
        return all(self.runner.is_ready(key) for key in self.keys)

    def get_result(self):
        return [self.runner.pop_result(key) for key in self.keys]


def Task(func, *args, **kwargs):
    """Adapts a callback-based asynchronous function for use in coroutines.

    Takes a function (and optional additional arguments) and runs it with
    those arguments plus a ``callback`` keyword argument.  The argument passed
    to the callback is returned as the result of the yield expression.

    .. versionchanged:: 4.0
       ``gen.Task`` is now a function that returns a `.Future`, instead of
       a subclass of `YieldPoint`.  It still behaves the same way when
       yielded.
    """
    future = Future()

    def handle_exception(typ, value, tb):
        if future.done():
            return False
        future.set_exc_info((typ, value, tb))
        return True

    def set_result(result):
        if future.done():
            return
        future.set_result(result)
    with stack_context.ExceptionStackContext(handle_exception):
        func(*args, callback=_argument_adapter(set_result), **kwargs)
    return future


class YieldFuture(YieldPoint):
    def __init__(self, future, io_loop=None):
        """Adapts a `.Future` to the `YieldPoint` interface.

        .. versionchanged:: 4.1
           The ``io_loop`` argument is deprecated.
        """
        self.future = future
        self.io_loop = io_loop or IOLoop.current()

    def start(self, runner):
        if not self.future.done():
            self.runner = runner
            self.key = object()
            runner.register_callback(self.key)
            self.io_loop.add_future(self.future, runner.result_callback(self.key))
        else:
            self.runner = None
            self.result = self.future.result()

    def is_ready(self):
        if self.runner is not None:
            return self.runner.is_ready(self.key)
        else:
            return True

    def get_result(self):
        if self.runner is not None:
            return self.runner.pop_result(self.key).result()
        else:
            return self.result


class Multi(YieldPoint):
    """Runs multiple asynchronous operations in parallel.

    Takes a list of ``YieldPoints`` or ``Futures`` and returns a list of
    their responses.  It is not necessary to call `Multi` explicitly,
    since the engine will do so automatically when the generator yields
    a list of ``YieldPoints`` or a mixture of ``YieldPoints`` and ``Futures``.

    Instead of a list, the argument may also be a dictionary whose values are
    Futures, in which case a parallel dictionary is returned mapping the same
    keys to their results.
    """
    def __init__(self, children):
        self.keys = None
        if isinstance(children, dict):
            self.keys = list(children.keys())
            children = children.values()
        self.children = []
        for i in children:
            if is_future(i):
                i = YieldFuture(i)
            self.children.append(i)
        assert all(isinstance(i, YieldPoint) for i in self.children)
        self.unfinished_children = set(self.children)

    def start(self, runner):
        for i in self.children:
            i.start(runner)

    def is_ready(self):
        finished = list(itertools.takewhile(
            lambda i: i.is_ready(), self.unfinished_children))
        self.unfinished_children.difference_update(finished)
        return not self.unfinished_children

    def get_result(self):
        result = (i.get_result() for i in self.children)
        if self.keys is not None:
            return dict(zip(self.keys, result))
        else:
            return list(result)


def multi_future(children):
    """Wait for multiple asynchronous futures in parallel.

    Takes a list of ``Futures`` (but *not* other ``YieldPoints``) and returns
    a new Future that resolves when all the other Futures are done.
    If all the ``Futures`` succeeded, the returned Future's result is a list
    of their results.  If any failed, the returned Future raises the exception
    of the first one to fail.

    Instead of a list, the argument may also be a dictionary whose values are
    Futures, in which case a parallel dictionary is returned mapping the same
    keys to their results.

    It is not necessary to call `multi_future` explcitly, since the engine will
    do so automatically when the generator yields a list of `Futures`.
    This function is faster than the `Multi` `YieldPoint` because it does not
    require the creation of a stack context.

    .. versionadded:: 4.0
    """
    if isinstance(children, dict):
        keys = list(children.keys())
        children = children.values()
    else:
        keys = None
    assert all(is_future(i) for i in children)
    unfinished_children = set(children)

    future = Future()
    if not children:
        future.set_result({} if keys is not None else [])

    def callback(f):
        unfinished_children.remove(f)
        if not unfinished_children:
            try:
                result_list = [i.result() for i in children]
            except Exception:
                future.set_exc_info(sys.exc_info())
            else:
                if keys is not None:
                    future.set_result(dict(zip(keys, result_list)))
                else:
                    future.set_result(result_list)
    for f in children:
        f.add_done_callback(callback)
    return future


def maybe_future(x):
    """Converts ``x`` into a `.Future`.

    If ``x`` is already a `.Future`, it is simply returned; otherwise
    it is wrapped in a new `.Future`.  This is suitable for use as
    ``result = yield gen.maybe_future(f())`` when you don't know whether
    ``f()`` returns a `.Future` or not.
    """
    if is_future(x):
        return x
    else:
        fut = Future()
        fut.set_result(x)
        return fut


def with_timeout(timeout, future, io_loop=None, quiet_exceptions=()):
    """Wraps a `.Future` in a timeout.

    Raises `TimeoutError` if the input future does not complete before
    ``timeout``, which may be specified in any form allowed by
    `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
    relative to `.IOLoop.time`)

    If the wrapped `.Future` fails after it has timed out, the exception
    will be logged unless it is of a type contained in ``quiet_exceptions``
    (which may be an exception type or a sequence of types).

    Currently only supports Futures, not other `YieldPoint` classes.

    .. versionadded:: 4.0

    .. versionchanged:: 4.1
       Added the ``quiet_exceptions`` argument and the logging of unhandled
       exceptions.
    """
    # TODO: allow yield points in addition to futures?
    # Tricky to do with stack_context semantics.
    #
    # It's tempting to optimize this by cancelling the input future on timeout
    # instead of creating a new one, but A) we can't know if we are the only
    # one waiting on the input future, so cancelling it might disrupt other
    # callers and B) concurrent futures can only be cancelled while they are
    # in the queue, so cancellation cannot reliably bound our waiting time.
    result = Future()
    chain_future(future, result)
    if io_loop is None:
        io_loop = IOLoop.current()

    def error_callback(future):
        try:
            future.result()
        except Exception as e:
            if not isinstance(e, quiet_exceptions):
                app_log.error("Exception in Future %r after timeout",
                              future, exc_info=True)

    def timeout_callback():
        result.set_exception(TimeoutError("Timeout"))
        # In case the wrapped future goes on to fail, log it.
        future.add_done_callback(error_callback)
    timeout_handle = io_loop.add_timeout(
        timeout, timeout_callback)
    if isinstance(future, Future):
        # We know this future will resolve on the IOLoop, so we don't
        # need the extra thread-safety of IOLoop.add_future (and we also
        # don't care about StackContext here.
        future.add_done_callback(
            lambda future: io_loop.remove_timeout(timeout_handle))
    else:
        # concurrent.futures.Futures may resolve on any thread, so we
        # need to route them back to the IOLoop.
        io_loop.add_future(
            future, lambda future: io_loop.remove_timeout(timeout_handle))
    return result


def sleep(duration):
    """Return a `.Future` that resolves after the given number of seconds.

    When used with ``yield`` in a coroutine, this is a non-blocking
    analogue to `time.sleep` (which should not be used in coroutines
    because it is blocking)::

        yield gen.sleep(0.5)

    Note that calling this function on its own does nothing; you must
    wait on the `.Future` it returns (usually by yielding it).

    .. versionadded:: 4.1
    """
    f = Future()
    IOLoop.current().call_later(duration, lambda: f.set_result(None))
    return f


_null_future = Future()
_null_future.set_result(None)

moment = Future()
moment.__doc__ = \
    """A special object which may be yielded to allow the IOLoop to run for
one iteration.

This is not needed in normal use but it can be helpful in long-running
coroutines that are likely to yield Futures that are ready instantly.

Usage: ``yield gen.moment``

.. versionadded:: 4.0
"""
moment.set_result(None)


class Runner(object):
    """Internal implementation of `tornado.gen.engine`.

    Maintains information about pending callbacks and their results.

    The results of the generator are stored in ``result_future`` (a
    `.TracebackFuture`)
    """
    def __init__(self, gen, result_future, first_yielded):
        self.gen = gen
        self.result_future = result_future
        self.future = _null_future
        self.yield_point = None
        self.pending_callbacks = None
        self.results = None
        self.running = False
        self.finished = False
        self.had_exception = False
        self.io_loop = IOLoop.current()
        # For efficiency, we do not create a stack context until we
        # reach a YieldPoint (stack contexts are required for the historical
        # semantics of YieldPoints, but not for Futures).  When we have
        # done so, this field will be set and must be called at the end
        # of the coroutine.
        self.stack_context_deactivate = None
        if self.handle_yield(first_yielded):
            self.run()

    def register_callback(self, key):
        """Adds ``key`` to the list of callbacks."""
        if self.pending_callbacks is None:
            # Lazily initialize the old-style YieldPoint data structures.
            self.pending_callbacks = set()
            self.results = {}
        if key in self.pending_callbacks:
            raise KeyReuseError("key %r is already pending" % (key,))
        self.pending_callbacks.add(key)

    def is_ready(self, key):
        """Returns true if a result is available for ``key``."""
        if self.pending_callbacks is None or key not in self.pending_callbacks:
            raise UnknownKeyError("key %r is not pending" % (key,))
        return key in self.results

    def set_result(self, key, result):
        """Sets the result for ``key`` and attempts to resume the generator."""
        self.results[key] = result
        if self.yield_point is not None and self.yield_point.is_ready():
            try:
                self.future.set_result(self.yield_point.get_result())
            except:
                self.future.set_exc_info(sys.exc_info())
            self.yield_point = None
            self.run()

    def pop_result(self, key):
        """Returns the result for ``key`` and unregisters it."""
        self.pending_callbacks.remove(key)
        return self.results.pop(key)

    def run(self):
        """Starts or resumes the generator, running until it reaches a
        yield point that is not ready.
        """
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                future = self.future
                if not future.done():
                    return
                self.future = None
                try:
                    orig_stack_contexts = stack_context._state.contexts
                    try:
                        value = future.result()
                    except Exception:
                        self.had_exception = True
                        yielded = self.gen.throw(*sys.exc_info())
                    else:
                        yielded = self.gen.send(value)
                    if stack_context._state.contexts is not orig_stack_contexts:
                        self.gen.throw(
                            stack_context.StackContextInconsistentError(
                                'stack_context inconsistency (probably caused '
                                'by yield within a "with StackContext" block)'))
                except (StopIteration, Return) as e:
                    self.finished = True
                    self.future = _null_future
                    if self.pending_callbacks and not self.had_exception:
                        # If we ran cleanly without waiting on all callbacks
                        # raise an error (really more of a warning).  If we
                        # had an exception then some callbacks may have been
                        # orphaned, so skip the check in that case.
                        raise LeakedCallbackError(
                            "finished without waiting for callbacks %r" %
                            self.pending_callbacks)
                    self.result_future.set_result(getattr(e, 'value', None))
                    self.result_future = None
                    self._deactivate_stack_context()
                    return
                except Exception:
                    self.finished = True
                    self.future = _null_future
                    self.result_future.set_exc_info(sys.exc_info())
                    self.result_future = None
                    self._deactivate_stack_context()
                    return
                if not self.handle_yield(yielded):
                    return
        finally:
            self.running = False

    def handle_yield(self, yielded):
        # Lists containing YieldPoints require stack contexts;
        # other lists are handled via multi_future in convert_yielded.
        if (isinstance(yielded, list) and
                any(isinstance(f, YieldPoint) for f in yielded)):
            yielded = Multi(yielded)
        elif (isinstance(yielded, dict) and
              any(isinstance(f, YieldPoint) for f in yielded.values())):
            yielded = Multi(yielded)

        if isinstance(yielded, YieldPoint):
            # YieldPoints are too closely coupled to the Runner to go
            # through the generic convert_yielded mechanism.
            self.future = TracebackFuture()

            def start_yield_point():
                try:
                    yielded.start(self)
                    if yielded.is_ready():
                        self.future.set_result(
                            yielded.get_result())
                    else:
                        self.yield_point = yielded
                except Exception:
                    self.future = TracebackFuture()
                    self.future.set_exc_info(sys.exc_info())

            if self.stack_context_deactivate is None:
                # Start a stack context if this is the first
                # YieldPoint we've seen.
                with stack_context.ExceptionStackContext(
                        self.handle_exception) as deactivate:
                    self.stack_context_deactivate = deactivate

                    def cb():
                        start_yield_point()
                        self.run()
                    self.io_loop.add_callback(cb)
                    return False
            else:
                start_yield_point()
        else:
            try:
                self.future = convert_yielded(yielded)
            except BadYieldError:
                self.future = TracebackFuture()
                self.future.set_exc_info(sys.exc_info())

        if not self.future.done() or self.future is moment:
            self.io_loop.add_future(
                self.future, lambda f: self.run())
            return False
        return True

    def result_callback(self, key):
        return stack_context.wrap(_argument_adapter(
            functools.partial(self.set_result, key)))

    def handle_exception(self, typ, value, tb):
        if not self.running and not self.finished:
            self.future = TracebackFuture()
            self.future.set_exc_info((typ, value, tb))
            self.run()
            return True
        else:
            return False

    def _deactivate_stack_context(self):
        if self.stack_context_deactivate is not None:
            self.stack_context_deactivate()
            self.stack_context_deactivate = None

Arguments = collections.namedtuple('Arguments', ['args', 'kwargs'])


def _argument_adapter(callback):
    """Returns a function that when invoked runs ``callback`` with one arg.

    If the function returned by this function is called with exactly
    one argument, that argument is passed to ``callback``.  Otherwise
    the args tuple and kwargs dict are wrapped in an `Arguments` object.
    """
    def wrapper(*args, **kwargs):
        if kwargs or len(args) > 1:
            callback(Arguments(args, kwargs))
        elif args:
            callback(args[0])
        else:
            callback(None)
    return wrapper


def convert_yielded(yielded):
    """Convert a yielded object into a `.Future`.

    The default implementation accepts lists, dictionaries, and Futures.

    If the `~functools.singledispatch` library is available, this function
    may be extended to support additional types. For example::

        @convert_yielded.register(asyncio.Future)
        def _(asyncio_future):
            return tornado.platform.asyncio.to_tornado_future(asyncio_future)

    .. versionadded:: 4.1
    """
    # Lists and dicts containing YieldPoints were handled separately
    # via Multi().
    if isinstance(yielded, (list, dict)):
        return multi_future(yielded)
    elif is_future(yielded):
        return yielded
    else:
        raise BadYieldError("yielded unknown object %r" % (yielded,))

if singledispatch is not None:
    convert_yielded = singledispatch(convert_yielded)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** Coroutine Exceptions Leak `__context__` Attribute in Python 3

**Description:**
When an exception is raised within a coroutine, the exception's `__context__` attribute unexpectedly retains context information instead of being cleared. This leakage can interfere with exception handling and debugging processes.

**Example Code:**
```python
import tornado.gen
from tornado.testing import AsyncTestCase

class CoroutineExceptionTest(AsyncTestCase):
    @tornado.gen.coroutine
    def test_exception_context_leak(self):
        class SampleException(Exception):
            pass

        @tornado.gen.coroutine
        def inner():
            raise SampleException("Test exception")

        try:
            yield inner()
        except SampleException as e:
            print(e.__context__)  # Unexpectedly retains context
```

**Expected Behavior:**
After catching the exception, `e.__context__` should be `None`, indicating no retained context.

**Actual Behavior:**
`e.__context__` retains context information instead of being `None`, leading to a context leak.

[/ISSUE]
{
    "GenCoroutineTest.test_async_early_return": "PASSED",
    "GenCoroutineTest.test_async_gen_return": "PASSED",
    "GenCoroutineTest.test_async_raise": "PASSED",
    "GenCoroutineTest.test_async_return": "PASSED",
    "GenCoroutineTest.test_async_return_no_value": "PASSED",
    "GenCoroutineTest.test_moment": "PASSED",
    "GenCoroutineTest.test_pass_callback": "PASSED",
    "GenCoroutineTest.test_py3_leak_exception_context": "PASSED",
    "GenCoroutineTest.test_replace_context_exception": "PASSED",
    "GenCoroutineTest.test_replace_yieldpoint_exception": "PASSED",
    "GenCoroutineTest.test_sleep": "PASSED",
    "GenCoroutineTest.test_swallow_context_exception": "PASSED",
    "GenCoroutineTest.test_swallow_yieldpoint_exception": "PASSED",
    "GenCoroutineTest.test_sync_gen_return": "PASSED",
    "GenCoroutineTest.test_sync_raise": "PASSED",
    "GenCoroutineTest.test_sync_return": "PASSED",
    "GenCoroutineTest.test_sync_return_no_value": "PASSED",
    "GenEngineTest.test_arguments": "PASSED",
    "GenEngineTest.test_async_raise_return": "PASSED",
    "GenEngineTest.test_async_raise_return_value": "PASSED",
    "GenEngineTest.test_async_raise_return_value_tuple": "PASSED",
    "GenEngineTest.test_bogus_yield": "PASSED",
    "GenEngineTest.test_bogus_yield_tuple": "PASSED",
    "GenEngineTest.test_exception_in_task_phase1": "PASSED",
    "GenEngineTest.test_exception_in_task_phase2": "PASSED",
    "GenEngineTest.test_exception_in_yield": "PASSED",
    "GenEngineTest.test_exception_phase1": "PASSED",
    "GenEngineTest.test_exception_phase2": "PASSED",
    "GenEngineTest.test_future": "PASSED",
    "GenEngineTest.test_inline_cb": "PASSED",
    "GenEngineTest.test_ioloop_cb": "PASSED",
    "GenEngineTest.test_key_mismatch": "PASSED",
    "GenEngineTest.test_key_mismatch_tuple": "PASSED",
    "GenEngineTest.test_key_reuse": "PASSED",
    "GenEngineTest.test_key_reuse_tuple": "PASSED",
    "GenEngineTest.test_leaked_callback": "PASSED",
    "GenEngineTest.test_leaked_callback_tuple": "PASSED",
    "GenEngineTest.test_multi": "PASSED",
    "GenEngineTest.test_multi_dict": "PASSED",
    "GenEngineTest.test_multi_dict_future": "PASSED",
    "GenEngineTest.test_multi_empty": "PASSED",
    "GenEngineTest.test_multi_future": "PASSED",
    "GenEngineTest.test_multi_future_delayed": "PASSED",
    "GenEngineTest.test_multi_future_dict_delayed": "PASSED",
    "GenEngineTest.test_multi_mixed_types": "PASSED",
    "GenEngineTest.test_multi_performance": "PASSED",
    "GenEngineTest.test_multi_yieldpoint_delayed": "PASSED",
    "GenEngineTest.test_multi_yieldpoint_dict_delayed": "PASSED",
    "GenEngineTest.test_no_yield": "PASSED",
    "GenEngineTest.test_orphaned_callback": "PASSED",
    "GenEngineTest.test_parallel_callback": "PASSED",
    "GenEngineTest.test_raise_after_stop": "PASSED",
    "GenEngineTest.test_resume_after_exception_in_yield": "PASSED",
    "GenEngineTest.test_return_value": "PASSED",
    "GenEngineTest.test_return_value_tuple": "PASSED",
    "GenEngineTest.test_reuse": "PASSED",
    "GenEngineTest.test_stack_context_leak": "PASSED",
    "GenEngineTest.test_stack_context_leak_exception": "PASSED",
    "GenEngineTest.test_sync_raise_return": "PASSED",
    "GenEngineTest.test_sync_raise_return_value": "PASSED",
    "GenEngineTest.test_sync_raise_return_value_tuple": "PASSED",
    "GenEngineTest.test_task": "PASSED",
    "GenEngineTest.test_task_refcounting": "PASSED",
    "GenEngineTest.test_task_transfer_stack_context": "PASSED",
    "GenEngineTest.test_wait_all": "PASSED",
    "GenEngineTest.test_wait_transfer_stack_context": "PASSED",
    "GenEngineTest.test_with_arg": "PASSED",
    "GenEngineTest.test_with_arg_tuple": "PASSED",
    "GenWebTest.test_async_prepare_error_handler": "PASSED",
    "GenWebTest.test_coroutine_exception_handler": "PASSED",
    "GenWebTest.test_coroutine_sequence_handler": "PASSED",
    "GenWebTest.test_coroutine_unfinished_sequence_handler": "PASSED",
    "GenWebTest.test_exception_handler": "PASSED",
    "GenWebTest.test_sequence_handler": "PASSED",
    "GenWebTest.test_task_handler": "PASSED",
    "GenWebTest.test_undecorated_coroutines": "PASSED",
    "GenWebTest.test_yield_exception_handler": "PASSED",
    "WaitIteratorTest.test_already_done": "PASSED",
    "WaitIteratorTest.test_empty_iterator": "PASSED",
    "WaitIteratorTest.test_iterator": "PASSED",
    "WithTimeoutTest.test_already_resolved": "PASSED",
    "WithTimeoutTest.test_completed_concurrent_future": "PASSED",
    "WithTimeoutTest.test_completes_before_timeout": "PASSED",
    "WithTimeoutTest.test_fails_before_timeout": "PASSED",
    "WithTimeoutTest.test_timeout": "PASSED",
    "WithTimeoutTest.test_timeout_concurrent_future": "PASSED"
}
diff --git a/tornado/gen.py b/tornado/gen.py
index 3d87d717..b405b2f7 100644
--- a/tornado/gen.py
+++ b/tornado/gen.py
@@ -824,13 +824,20 @@ class Runner(object):
                 self.future = None
                 try:
                     orig_stack_contexts = stack_context._state.contexts
+                    exc_info = None
+
                     try:
                         value = future.result()
                     except Exception:
                         self.had_exception = True
-                        yielded = self.gen.throw(*sys.exc_info())
+                        exc_info = sys.exc_info()
+
+                    if exc_info is not None:
+                        yielded = self.gen.throw(*exc_info)
+                        exc_info = None
                     else:
                         yielded = self.gen.send(value)
+
                     if stack_context._state.contexts is not orig_stack_contexts:
                         self.gen.throw(
                             stack_context.StackContextInconsistentError(

{"tornado/gen.py": "\"\"\"``tornado.gen`` is a generator-based interface to make it easier to\nwork in an asynchronous environment.  Code using the ``gen`` module\nis technically asynchronous, but it is written as a single generator\ninstead of a collection of separate functions.\n\nFor example, the following asynchronous handler:\n\n.. testcode::\n\n    class AsyncHandler(RequestHandler):\n        @asynchronous\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=self.on_fetch)\n\n        def on_fetch(self, response):\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n.. testoutput::\n   :hide:\n\ncould be written with ``gen`` as:\n\n.. testcode::\n\n    class GenAsyncHandler(RequestHandler):\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield http_client.fetch(\"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n.. testoutput::\n   :hide:\n\nMost asynchronous functions in Tornado return a `.Future`;\nyielding this object returns its `~.Future.result`.\n\nYou can also yield a list or dict of ``Futures``, which will be\nstarted at the same time and run in parallel; a list or dict of results will\nbe returned when they are all finished:\n\n.. testcode::\n\n    @gen.coroutine\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [http_client.fetch(url1),\n                                      http_client.fetch(url2)]\n        response_dict = yield dict(response3=http_client.fetch(url3),\n                                   response4=http_client.fetch(url4))\n        response3 = response_dict['response3']\n        response4 = response_dict['response4']\n\n.. testoutput::\n   :hide:\n\nIf the `~functools.singledispatch` library is available (standard in\nPython 3.4, available via the `singledispatch\n<https://pypi.python.org/pypi/singledispatch>`_ package on older\nversions), additional types of objects may be yielded. Tornado includes\nsupport for ``asyncio.Future`` and Twisted's ``Deferred`` class when\n``tornado.platform.asyncio`` and ``tornado.platform.twisted`` are imported.\nSee the `convert_yielded` function to extend this mechanism.\n\n.. versionchanged:: 3.2\n   Dict support added.\n\n.. versionchanged:: 4.1\n   Support added for yielding ``asyncio`` Futures and Twisted Deferreds\n   via ``singledispatch``.\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport functools\nimport itertools\nimport sys\nimport types\nimport weakref\n\nfrom tornado.concurrent import Future, TracebackFuture, is_future, chain_future\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import app_log\nfrom tornado import stack_context\n\ntry:\n    from functools import singledispatch  # py34+\nexcept ImportError as e:\n    try:\n        from singledispatch import singledispatch  # backport\n    except ImportError:\n        singledispatch = None\n\n\nclass KeyReuseError(Exception):\n    pass\n\n\nclass UnknownKeyError(Exception):\n    pass\n\n\nclass LeakedCallbackError(Exception):\n    pass\n\n\nclass BadYieldError(Exception):\n    pass\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n\nclass TimeoutError(Exception):\n    \"\"\"Exception raised by ``with_timeout``.\"\"\"\n\n\ndef engine(func):\n    \"\"\"Callback-oriented decorator for asynchronous generators.\n\n    This is an older interface; for new code that does not need to be\n    compatible with versions of Tornado older than 3.0 the\n    `coroutine` decorator is recommended instead.\n\n    This decorator is similar to `coroutine`, except it does not\n    return a `.Future` and the ``callback`` argument is not treated\n    specially.\n\n    In most cases, functions decorated with `engine` should take\n    a ``callback`` argument and invoke it with their result when\n    they are finished.  One notable exception is the\n    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,\n    which use ``self.finish()`` in place of a callback argument.\n    \"\"\"\n    func = _make_coroutine_wrapper(func, replace_callback=False)\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        future = func(*args, **kwargs)\n\n        def final_callback(future):\n            if future.result() is not None:\n                raise ReturnValueIgnoredError(\n                    \"@gen.engine functions cannot return values: %r\" %\n                    (future.result(),))\n        # The engine interface doesn't give us any way to return\n        # errors but to raise them into the stack context.\n        # Save the stack context here to use when the Future has resolved.\n        future.add_done_callback(stack_context.wrap(final_callback))\n    return wrapper\n\n\ndef coroutine(func, replace_callback=True):\n    \"\"\"Decorator for asynchronous generators.\n\n    Any generator that yields objects from this module must be wrapped\n    in either this decorator or `engine`.\n\n    Coroutines may \"return\" by raising the special exception\n    `Return(value) <Return>`.  In Python 3.3+, it is also possible for\n    the function to simply use the ``return value`` statement (prior to\n    Python 3.3 generators were not allowed to also return values).\n    In all versions of Python a coroutine that simply wishes to exit\n    early may use the ``return`` statement without a value.\n\n    Functions with this decorator return a `.Future`.  Additionally,\n    they may be called with a ``callback`` keyword argument, which\n    will be invoked with the future's result when it resolves.  If the\n    coroutine fails, the callback will not be run and an exception\n    will be raised into the surrounding `.StackContext`.  The\n    ``callback`` argument is not visible inside the decorated\n    function; it is handled by the decorator itself.\n\n    From the caller's perspective, ``@gen.coroutine`` is similar to\n    the combination of ``@return_future`` and ``@gen.engine``.\n\n    .. warning::\n\n       When exceptions occur inside a coroutine, the exception\n       information will be stored in the `.Future` object. You must\n       examine the result of the `.Future` object, or the exception\n       may go unnoticed by your code. This means yielding the function\n       if called from another coroutine, using something like\n       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`\n       to `.IOLoop.add_future`.\n\n    \"\"\"\n    return _make_coroutine_wrapper(func, replace_callback=True)\n\n\ndef _make_coroutine_wrapper(func, replace_callback):\n    \"\"\"The inner workings of ``@gen.coroutine`` and ``@gen.engine``.\n\n    The two decorators differ in their treatment of the ``callback``\n    argument, so we cannot simply implement ``@engine`` in terms of\n    ``@coroutine``.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        future = TracebackFuture()\n\n        if replace_callback and 'callback' in kwargs:\n            callback = kwargs.pop('callback')\n            IOLoop.current().add_future(\n                future, lambda future: callback(future.result()))\n\n        try:\n            result = func(*args, **kwargs)\n        except (Return, StopIteration) as e:\n            result = getattr(e, 'value', None)\n        except Exception:\n            future.set_exc_info(sys.exc_info())\n            return future\n        else:\n            if isinstance(result, types.GeneratorType):\n                # Inline the first iteration of Runner.run.  This lets us\n                # avoid the cost of creating a Runner when the coroutine\n                # never actually yields, which in turn allows us to\n                # use \"optional\" coroutines in critical path code without\n                # performance penalty for the synchronous case.\n                try:\n                    orig_stack_contexts = stack_context._state.contexts\n                    yielded = next(result)\n                    if stack_context._state.contexts is not orig_stack_contexts:\n                        yielded = TracebackFuture()\n                        yielded.set_exception(\n                            stack_context.StackContextInconsistentError(\n                                'stack_context inconsistency (probably caused '\n                                'by yield within a \"with StackContext\" block)'))\n                except (StopIteration, Return) as e:\n                    future.set_result(getattr(e, 'value', None))\n                except Exception:\n                    future.set_exc_info(sys.exc_info())\n                else:\n                    Runner(result, future, yielded)\n                try:\n                    return future\n                finally:\n                    # Subtle memory optimization: if next() raised an exception,\n                    # the future's exc_info contains a traceback which\n                    # includes this stack frame.  This creates a cycle,\n                    # which will be collected at the next full GC but has\n                    # been shown to greatly increase memory usage of\n                    # benchmarks (relative to the refcount-based scheme\n                    # used in the absence of cycles).  We can avoid the\n                    # cycle by clearing the local variable after we return it.\n                    future = None\n        future.set_result(result)\n        return future\n    return wrapper\n\n\nclass Return(Exception):\n    \"\"\"Special exception to return a value from a `coroutine`.\n\n    If this exception is raised, its value argument is used as the\n    result of the coroutine::\n\n        @gen.coroutine\n        def fetch_json(url):\n            response = yield AsyncHTTPClient().fetch(url)\n            raise gen.Return(json_decode(response.body))\n\n    In Python 3.3, this exception is no longer necessary: the ``return``\n    statement can be used directly to return a value (previously\n    ``yield`` and ``return`` with a value could not be combined in the\n    same function).\n\n    By analogy with the return statement, the value argument is optional,\n    but it is never necessary to ``raise gen.Return()``.  The ``return``\n    statement can be used with no arguments instead.\n    \"\"\"\n    def __init__(self, value=None):\n        super(Return, self).__init__()\n        self.value = value\n\n\nclass WaitIterator(object):\n    \"\"\"Provides an iterator to yield the results of futures as they finish.\n\n    Yielding a set of futures like this:\n\n    ``results = yield [future1, future2]``\n\n    pauses the coroutine until both ``future1`` and ``future2``\n    return, and then restarts the coroutine with the results of both\n    futures. If either future is an exception, the expression will\n    raise that exception and all the results will be lost.\n\n    If you need to get the result of each future as soon as possible,\n    or if you need the result of some futures even if others produce\n    errors, you can use ``WaitIterator``::\n\n      wait_iterator = gen.WaitIterator(future1, future2)\n      while not wait_iterator.done():\n          try:\n              result = yield wait_iterator.next()\n          except Exception as e:\n              print(\"Error {} from {}\".format(e, wait_iterator.current_future))\n          else:\n              print(\"Result {} recieved from {} at {}\".format(\n                  result, wait_iterator.current_future,\n                  wait_iterator.current_index))\n\n    Because results are returned as soon as they are available the\n    output from the iterator *will not be in the same order as the\n    input arguments*. If you need to know which future produced the\n    current result, you can use the attributes\n    ``WaitIterator.current_future``, or ``WaitIterator.current_index``\n    to get the index of the future from the input list. (if keyword\n    arguments were used in the construction of the `WaitIterator`,\n    ``current_index`` will use the corresponding keyword).\n\n    .. versionadded:: 4.1\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        if args and kwargs:\n            raise ValueError(\n                \"You must provide args or kwargs, not both\")\n\n        if kwargs:\n            self._unfinished = dict((f, k) for (k, f) in kwargs.items())\n            futures = list(kwargs.values())\n        else:\n            self._unfinished = dict((f, i) for (i, f) in enumerate(args))\n            futures = args\n\n        self._finished = collections.deque()\n        self.current_index = self.current_future = None\n        self._running_future = None\n\n        self_ref = weakref.ref(self)\n        for future in futures:\n            future.add_done_callback(functools.partial(\n                self._done_callback, self_ref))\n\n    def done(self):\n        \"\"\"Returns True if this iterator has no more results.\"\"\"\n        if self._finished or self._unfinished:\n            return False\n        # Clear the 'current' values when iteration is done.\n        self.current_index = self.current_future = None\n        return True\n\n    def next(self):\n        \"\"\"Returns a `.Future` that will yield the next available result.\n\n        Note that this `.Future` will not be the same object as any of\n        the inputs.\n        \"\"\"\n        self._running_future = TracebackFuture()\n\n        if self._finished:\n            self._return_result(self._finished.popleft())\n\n        return self._running_future\n\n    @staticmethod\n    def _done_callback(self_ref, done):\n        self = self_ref()\n        if self is not None:\n            if self._running_future and not self._running_future.done():\n                self._return_result(done)\n            else:\n                self._finished.append(done)\n\n    def _return_result(self, done):\n        \"\"\"Called set the returned future's state that of the future\n        we yielded, and set the current future for the iterator.\n        \"\"\"\n        chain_future(done, self._running_future)\n\n        self.current_future = done\n        self.current_index = self._unfinished.pop(done)\n\n\nclass YieldPoint(object):\n    \"\"\"Base class for objects that may be yielded from the generator.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def start(self, runner):\n        \"\"\"Called by the runner after the generator has yielded.\n\n        No other methods will be called on this object before ``start``.\n        \"\"\"\n        raise NotImplementedError()\n\n    def is_ready(self):\n        \"\"\"Called by the runner to determine whether to resume the generator.\n\n        Returns a boolean; may be called more than once.\n        \"\"\"\n        raise NotImplementedError()\n\n    def get_result(self):\n        \"\"\"Returns the value to use as the result of the yield expression.\n\n        This method will only be called once, and only after `is_ready`\n        has returned true.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass Callback(YieldPoint):\n    \"\"\"Returns a callable object that will allow a matching `Wait` to proceed.\n\n    The key may be any value suitable for use as a dictionary key, and is\n    used to match ``Callbacks`` to their corresponding ``Waits``.  The key\n    must be unique among outstanding callbacks within a single run of the\n    generator function, but may be reused across different runs of the same\n    function (so constants generally work fine).\n\n    The callback may be called with zero or one arguments; if an argument\n    is given it will be returned by `Wait`.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n        runner.register_callback(self.key)\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return self.runner.result_callback(self.key)\n\n\nclass Wait(YieldPoint):\n    \"\"\"Returns the argument passed to the result of a previous `Callback`.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key)\n\n\nclass WaitAll(YieldPoint):\n    \"\"\"Returns the results of multiple previous `Callbacks <Callback>`.\n\n    The argument is a sequence of `Callback` keys, and the result is\n    a list of results in the same order.\n\n    `WaitAll` is equivalent to yielding a list of `Wait` objects.\n\n    .. deprecated:: 4.0\n       Use `Futures <.Future>` instead.\n    \"\"\"\n    def __init__(self, keys):\n        self.keys = keys\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return all(self.runner.is_ready(key) for key in self.keys)\n\n    def get_result(self):\n        return [self.runner.pop_result(key) for key in self.keys]\n\n\ndef Task(func, *args, **kwargs):\n    \"\"\"Adapts a callback-based asynchronous function for use in coroutines.\n\n    Takes a function (and optional additional arguments) and runs it with\n    those arguments plus a ``callback`` keyword argument.  The argument passed\n    to the callback is returned as the result of the yield expression.\n\n    .. versionchanged:: 4.0\n       ``gen.Task`` is now a function that returns a `.Future`, instead of\n       a subclass of `YieldPoint`.  It still behaves the same way when\n       yielded.\n    \"\"\"\n    future = Future()\n\n    def handle_exception(typ, value, tb):\n        if future.done():\n            return False\n        future.set_exc_info((typ, value, tb))\n        return True\n\n    def set_result(result):\n        if future.done():\n            return\n        future.set_result(result)\n    with stack_context.ExceptionStackContext(handle_exception):\n        func(*args, callback=_argument_adapter(set_result), **kwargs)\n    return future\n\n\nclass YieldFuture(YieldPoint):\n    def __init__(self, future, io_loop=None):\n        \"\"\"Adapts a `.Future` to the `YieldPoint` interface.\n\n        .. versionchanged:: 4.1\n           The ``io_loop`` argument is deprecated.\n        \"\"\"\n        self.future = future\n        self.io_loop = io_loop or IOLoop.current()\n\n    def start(self, runner):\n        if not self.future.done():\n            self.runner = runner\n            self.key = object()\n            runner.register_callback(self.key)\n            self.io_loop.add_future(self.future, runner.result_callback(self.key))\n        else:\n            self.runner = None\n            self.result = self.future.result()\n\n    def is_ready(self):\n        if self.runner is not None:\n            return self.runner.is_ready(self.key)\n        else:\n            return True\n\n    def get_result(self):\n        if self.runner is not None:\n            return self.runner.pop_result(self.key).result()\n        else:\n            return self.result\n\n\nclass Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``YieldPoints`` or ``Futures`` and returns a list of\n    their responses.  It is not necessary to call `Multi` explicitly,\n    since the engine will do so automatically when the generator yields\n    a list of ``YieldPoints`` or a mixture of ``YieldPoints`` and ``Futures``.\n\n    Instead of a list, the argument may also be a dictionary whose values are\n    Futures, in which case a parallel dictionary is returned mapping the same\n    keys to their results.\n    \"\"\"\n    def __init__(self, children):\n        self.keys = None\n        if isinstance(children, dict):\n            self.keys = list(children.keys())\n            children = children.values()\n        self.children = []\n        for i in children:\n            if is_future(i):\n                i = YieldFuture(i)\n            self.children.append(i)\n        assert all(isinstance(i, YieldPoint) for i in self.children)\n        self.unfinished_children = set(self.children)\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        finished = list(itertools.takewhile(\n            lambda i: i.is_ready(), self.unfinished_children))\n        self.unfinished_children.difference_update(finished)\n        return not self.unfinished_children\n\n    def get_result(self):\n        result = (i.get_result() for i in self.children)\n        if self.keys is not None:\n            return dict(zip(self.keys, result))\n        else:\n            return list(result)\n\n\ndef multi_future(children):\n    \"\"\"Wait for multiple asynchronous futures in parallel.\n\n    Takes a list of ``Futures`` (but *not* other ``YieldPoints``) and returns\n    a new Future that resolves when all the other Futures are done.\n    If all the ``Futures`` succeeded, the returned Future's result is a list\n    of their results.  If any failed, the returned Future raises the exception\n    of the first one to fail.\n\n    Instead of a list, the argument may also be a dictionary whose values are\n    Futures, in which case a parallel dictionary is returned mapping the same\n    keys to their results.\n\n    It is not necessary to call `multi_future` explcitly, since the engine will\n    do so automatically when the generator yields a list of `Futures`.\n    This function is faster than the `Multi` `YieldPoint` because it does not\n    require the creation of a stack context.\n\n    .. versionadded:: 4.0\n    \"\"\"\n    if isinstance(children, dict):\n        keys = list(children.keys())\n        children = children.values()\n    else:\n        keys = None\n    assert all(is_future(i) for i in children)\n    unfinished_children = set(children)\n\n    future = Future()\n    if not children:\n        future.set_result({} if keys is not None else [])\n\n    def callback(f):\n        unfinished_children.remove(f)\n        if not unfinished_children:\n            try:\n                result_list = [i.result() for i in children]\n            except Exception:\n                future.set_exc_info(sys.exc_info())\n            else:\n                if keys is not None:\n                    future.set_result(dict(zip(keys, result_list)))\n                else:\n                    future.set_result(result_list)\n    for f in children:\n        f.add_done_callback(callback)\n    return future\n\n\ndef maybe_future(x):\n    \"\"\"Converts ``x`` into a `.Future`.\n\n    If ``x`` is already a `.Future`, it is simply returned; otherwise\n    it is wrapped in a new `.Future`.  This is suitable for use as\n    ``result = yield gen.maybe_future(f())`` when you don't know whether\n    ``f()`` returns a `.Future` or not.\n    \"\"\"\n    if is_future(x):\n        return x\n    else:\n        fut = Future()\n        fut.set_result(x)\n        return fut\n\n\ndef with_timeout(timeout, future, io_loop=None, quiet_exceptions=()):\n    \"\"\"Wraps a `.Future` in a timeout.\n\n    Raises `TimeoutError` if the input future does not complete before\n    ``timeout``, which may be specified in any form allowed by\n    `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time\n    relative to `.IOLoop.time`)\n\n    If the wrapped `.Future` fails after it has timed out, the exception\n    will be logged unless it is of a type contained in ``quiet_exceptions``\n    (which may be an exception type or a sequence of types).\n\n    Currently only supports Futures, not other `YieldPoint` classes.\n\n    .. versionadded:: 4.0\n\n    .. versionchanged:: 4.1\n       Added the ``quiet_exceptions`` argument and the logging of unhandled\n       exceptions.\n    \"\"\"\n    # TODO: allow yield points in addition to futures?\n    # Tricky to do with stack_context semantics.\n    #\n    # It's tempting to optimize this by cancelling the input future on timeout\n    # instead of creating a new one, but A) we can't know if we are the only\n    # one waiting on the input future, so cancelling it might disrupt other\n    # callers and B) concurrent futures can only be cancelled while they are\n    # in the queue, so cancellation cannot reliably bound our waiting time.\n    result = Future()\n    chain_future(future, result)\n    if io_loop is None:\n        io_loop = IOLoop.current()\n\n    def error_callback(future):\n        try:\n            future.result()\n        except Exception as e:\n            if not isinstance(e, quiet_exceptions):\n                app_log.error(\"Exception in Future %r after timeout\",\n                              future, exc_info=True)\n\n    def timeout_callback():\n        result.set_exception(TimeoutError(\"Timeout\"))\n        # In case the wrapped future goes on to fail, log it.\n        future.add_done_callback(error_callback)\n    timeout_handle = io_loop.add_timeout(\n        timeout, timeout_callback)\n    if isinstance(future, Future):\n        # We know this future will resolve on the IOLoop, so we don't\n        # need the extra thread-safety of IOLoop.add_future (and we also\n        # don't care about StackContext here.\n        future.add_done_callback(\n            lambda future: io_loop.remove_timeout(timeout_handle))\n    else:\n        # concurrent.futures.Futures may resolve on any thread, so we\n        # need to route them back to the IOLoop.\n        io_loop.add_future(\n            future, lambda future: io_loop.remove_timeout(timeout_handle))\n    return result\n\n\ndef sleep(duration):\n    \"\"\"Return a `.Future` that resolves after the given number of seconds.\n\n    When used with ``yield`` in a coroutine, this is a non-blocking\n    analogue to `time.sleep` (which should not be used in coroutines\n    because it is blocking)::\n\n        yield gen.sleep(0.5)\n\n    Note that calling this function on its own does nothing; you must\n    wait on the `.Future` it returns (usually by yielding it).\n\n    .. versionadded:: 4.1\n    \"\"\"\n    f = Future()\n    IOLoop.current().call_later(duration, lambda: f.set_result(None))\n    return f\n\n\n_null_future = Future()\n_null_future.set_result(None)\n\nmoment = Future()\nmoment.__doc__ = \\\n    \"\"\"A special object which may be yielded to allow the IOLoop to run for\none iteration.\n\nThis is not needed in normal use but it can be helpful in long-running\ncoroutines that are likely to yield Futures that are ready instantly.\n\nUsage: ``yield gen.moment``\n\n.. versionadded:: 4.0\n\"\"\"\nmoment.set_result(None)\n\n\nclass Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.TracebackFuture`)\n    \"\"\"\n    def __init__(self, gen, result_future, first_yielded):\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future\n        self.yield_point = None\n        self.pending_callbacks = None\n        self.results = None\n        self.running = False\n        self.finished = False\n        self.had_exception = False\n        self.io_loop = IOLoop.current()\n        # For efficiency, we do not create a stack context until we\n        # reach a YieldPoint (stack contexts are required for the historical\n        # semantics of YieldPoints, but not for Futures).  When we have\n        # done so, this field will be set and must be called at the end\n        # of the coroutine.\n        self.stack_context_deactivate = None\n        if self.handle_yield(first_yielded):\n            self.run()\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if self.pending_callbacks is None:\n            # Lazily initialize the old-style YieldPoint data structures.\n            self.pending_callbacks = set()\n            self.results = {}\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if self.pending_callbacks is None or key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        if self.yield_point is not None and self.yield_point.is_ready():\n            try:\n                self.future.set_result(self.yield_point.get_result())\n            except:\n                self.future.set_exc_info(sys.exc_info())\n            self.yield_point = None\n            self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    orig_stack_contexts = stack_context._state.contexts\n                    try:\n                        value = future.result()\n                    except Exception:\n                        self.had_exception = True\n                        yielded = self.gen.throw(*sys.exc_info())\n                    else:\n                        yielded = self.gen.send(value)\n                    if stack_context._state.contexts is not orig_stack_contexts:\n                        self.gen.throw(\n                            stack_context.StackContextInconsistentError(\n                                'stack_context inconsistency (probably caused '\n                                'by yield within a \"with StackContext\" block)'))\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.result_future.set_result(getattr(e, 'value', None))\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    self.result_future.set_exc_info(sys.exc_info())\n                    self.result_future = None\n                    self._deactivate_stack_context()\n                    return\n                if not self.handle_yield(yielded):\n                    return\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded):\n        # Lists containing YieldPoints require stack contexts;\n        # other lists are handled via multi_future in convert_yielded.\n        if (isinstance(yielded, list) and\n                any(isinstance(f, YieldPoint) for f in yielded)):\n            yielded = Multi(yielded)\n        elif (isinstance(yielded, dict) and\n              any(isinstance(f, YieldPoint) for f in yielded.values())):\n            yielded = Multi(yielded)\n\n        if isinstance(yielded, YieldPoint):\n            # YieldPoints are too closely coupled to the Runner to go\n            # through the generic convert_yielded mechanism.\n            self.future = TracebackFuture()\n\n            def start_yield_point():\n                try:\n                    yielded.start(self)\n                    if yielded.is_ready():\n                        self.future.set_result(\n                            yielded.get_result())\n                    else:\n                        self.yield_point = yielded\n                except Exception:\n                    self.future = TracebackFuture()\n                    self.future.set_exc_info(sys.exc_info())\n\n            if self.stack_context_deactivate is None:\n                # Start a stack context if this is the first\n                # YieldPoint we've seen.\n                with stack_context.ExceptionStackContext(\n                        self.handle_exception) as deactivate:\n                    self.stack_context_deactivate = deactivate\n\n                    def cb():\n                        start_yield_point()\n                        self.run()\n                    self.io_loop.add_callback(cb)\n                    return False\n            else:\n                start_yield_point()\n        else:\n            try:\n                self.future = convert_yielded(yielded)\n            except BadYieldError:\n                self.future = TracebackFuture()\n                self.future.set_exc_info(sys.exc_info())\n\n        if not self.future.done() or self.future is moment:\n            self.io_loop.add_future(\n                self.future, lambda f: self.run())\n            return False\n        return True\n\n    def result_callback(self, key):\n        return stack_context.wrap(_argument_adapter(\n            functools.partial(self.set_result, key)))\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.future = TracebackFuture()\n            self.future.set_exc_info((typ, value, tb))\n            self.run()\n            return True\n        else:\n            return False\n\n    def _deactivate_stack_context(self):\n        if self.stack_context_deactivate is not None:\n            self.stack_context_deactivate()\n            self.stack_context_deactivate = None\n\nArguments = collections.namedtuple('Arguments', ['args', 'kwargs'])\n\n\ndef _argument_adapter(callback):\n    \"\"\"Returns a function that when invoked runs ``callback`` with one arg.\n\n    If the function returned by this function is called with exactly\n    one argument, that argument is passed to ``callback``.  Otherwise\n    the args tuple and kwargs dict are wrapped in an `Arguments` object.\n    \"\"\"\n    def wrapper(*args, **kwargs):\n        if kwargs or len(args) > 1:\n            callback(Arguments(args, kwargs))\n        elif args:\n            callback(args[0])\n        else:\n            callback(None)\n    return wrapper\n\n\ndef convert_yielded(yielded):\n    \"\"\"Convert a yielded object into a `.Future`.\n\n    The default implementation accepts lists, dictionaries, and Futures.\n\n    If the `~functools.singledispatch` library is available, this function\n    may be extended to support additional types. For example::\n\n        @convert_yielded.register(asyncio.Future)\n        def _(asyncio_future):\n            return tornado.platform.asyncio.to_tornado_future(asyncio_future)\n\n    .. versionadded:: 4.1\n    \"\"\"\n    # Lists and dicts containing YieldPoints were handled separately\n    # via Multi().\n    if isinstance(yielded, (list, dict)):\n        return multi_future(yielded)\n    elif is_future(yielded):\n        return yielded\n    else:\n        raise BadYieldError(\"yielded unknown object %r\" % (yielded,))\n\nif singledispatch is not None:\n    convert_yielded = singledispatch(convert_yielded)\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Coroutine Exceptions Leak `__context__` Attribute in Python 3

**Description:**
When an exception is raised within a coroutine, the exception's `__context__` attribute unexpectedly retains context information instead of being cleared. This leakage can interfere with exception handling and debugging processes.

**Example Code:**
```python
import tornado.gen
from tornado.testing import AsyncTestCase

class CoroutineExceptionTest(AsyncTestCase):
    @tornado.gen.coroutine
    def test_exception_context_leak(self):
        class SampleException(Exception):
            pass

        @tornado.gen.coroutine
        def inner():
            raise SampleException("Test exception")

        try:
            yield inner()
        except SampleException as e:
            print(e.__context__)  # Unexpectedly retains context
```

**Expected Behavior:**
After catching the exception, `e.__context__` should be `None`, indicating no retained context.

**Actual Behavior:**
`e.__context__` retains context information instead of being `None`, leading to a context leak.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/gen.py
"""``tornado.gen`` is a generator-based interface to make it easier to
work in an asynchronous environment.  Code using the ``gen`` module
is technically asynchronous, but it is written as a single generator
instead of a collection of separate functions.

For example, the following asynchronous handler:

.. testcode::

    class AsyncHandler(RequestHandler):
        @asynchronous
        def get(self):
            http_client = AsyncHTTPClient()
            http_client.fetch("http://example.com",
                              callback=self.on_fetch)

        def on_fetch(self, response):
            do_something_with_response(response)
            self.render("template.html")

.. testoutput::
   :hide:

could be written with ``gen`` as:

.. testcode::

    class GenAsyncHandler(RequestHandler):
        @gen.coroutine
        def get(self):
            http_client = AsyncHTTPClient()
            response = yield http_client.fetch("http://example.com")
            do_something_with_response(response)
            self.render("template.html")

.. testoutput::
   :hide:

Most asynchronous functions in Tornado return a `.Future`;
yielding this object returns its `~.Future.result`.

You can also yield a list or dict of ``Futures``, which will be
started at the same time and run in parallel; a list or dict of results will
be returned when they are all finished:

.. testcode::

    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response1, response2 = yield [http_client.fetch(url1),
                                      http_client.fetch(url2)]
        response_dict = yield dict(response3=http_client.fetch(url3),
                                   response4=http_client.fetch(url4))
        response3 = response_dict['response3']
        response4 = response_dict['response4']

.. testoutput::
   :hide:

If the `~functools.singledispatch` library is available (standard in
Python 3.4, available via the `singledispatch
<https://pypi.python.org/pypi/singledispatch>`_ package on older
versions), additional types of objects may be yielded. Tornado includes
support for ``asyncio.Future`` and Twisted's ``Deferred`` class when
``tornado.platform.asyncio`` and ``tornado.platform.twisted`` are imported.
See the `convert_yielded` function to extend this mechanism.

.. versionchanged:: 3.2
   Dict support added.

.. versionchanged:: 4.1
   Support added for yielding ``asyncio`` Futures and Twisted Deferreds
   via ``singledispatch``.

"""
from __future__ import absolute_import, division, print_function, with_statement

import collections
import functools
import itertools
import sys
import types
import weakref

from tornado.concurrent import Future, TracebackFuture, is_future, chain_future
from tornado.ioloop import IOLoop
from tornado.log import app_log
from tornado import stack_context

try:
    from functools import singledispatch  # py34+
except ImportError as e:
    try:
        from singledispatch import singledispatch  # backport
    except ImportError:
        singledispatch = None


class KeyReuseError(Exception):
    pass


class UnknownKeyError(Exception):
    pass


class LeakedCallbackError(Exception):
    pass


class BadYieldError(Exception):
    pass


class ReturnValueIgnoredError(Exception):
    pass


class TimeoutError(Exception):
    """Exception raised by ``with_timeout``."""


def engine(func):
    """Callback-oriented decorator for asynchronous generators.

    This is an older interface; for new code that does not need to be
    compatible with versions of Tornado older than 3.0 the
    `coroutine` decorator is recommended instead.

    This decorator is similar to `coroutine`, except it does not
    return a `.Future` and the ``callback`` argument is not treated
    specially.

    In most cases, functions decorated with `engine` should take
    a ``callback`` argument and invoke it with their result when
    they are finished.  One notable exception is the
    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,
    which use ``self.finish()`` in place of a callback argument.
    """
    func = _make_coroutine_wrapper(func, replace_callback=False)

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        future = func(*args, **kwargs)

        def final_callback(future):
            if future.result() is not None:
                raise ReturnValueIgnoredError(
                    "@gen.engine functions cannot return values: %r" %
                    (future.result(),))
        # The engine interface doesn't give us any way to return
        # errors but to raise them into the stack context.
        # Save the stack context here to use when the Future has resolved.
        future.add_done_callback(stack_context.wrap(final_callback))
    return wrapper


def coroutine(func, replace_callback=True):
    """Decorator for asynchronous generators.

    Any generator that yields objects from this module must be wrapped
    in either this decorator or `engine`.

    Coroutines may "return" by raising the special exception
    `Return(value) <Return>`.  In Python 3.3+, it is also possible for
    the function to simply use the ``return value`` statement (prior to
    Python 3.3 generators were not allowed to also return values).
    In all versions of Python a coroutine that simply wishes to exit
    early may use the ``return`` statement without a value.

    Functions with this decorator return a `.Future`.  Additionally,
    they may be called with a ``callback`` keyword argument, which
    will be invoked with the future's result when it resolves.  If the
    coroutine fails, the callback will not be run and an exception
    will be raised into the surrounding `.StackContext`.  The
    ``callback`` argument is not visible inside the decorated
    function; it is handled by the decorator itself.

    From the caller's perspective, ``@gen.coroutine`` is similar to
    the combination of ``@return_future`` and ``@gen.engine``.

    .. warning::

       When exceptions occur inside a coroutine, the exception
       information will be stored in the `.Future` object. You must
       examine the result of the `.Future` object, or the exception
       may go unnoticed by your code. This means yielding the function
       if called from another coroutine, using something like
       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`
       to `.IOLoop.add_future`.

    """
    return _make_coroutine_wrapper(func, replace_callback=True)


def _make_coroutine_wrapper(func, replace_callback):
    """The inner workings of ``@gen.coroutine`` and ``@gen.engine``.

    The two decorators differ in their treatment of the ``callback``
    argument, so we cannot simply implement ``@engine`` in terms of
    ``@coroutine``.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        future = TracebackFuture()

        if replace_callback and 'callback' in kwargs:
            callback = kwargs.pop('callback')
            IOLoop.current().add_future(
                future, lambda future: callback(future.result()))

        try:
            result = func(*args, **kwargs)
        except (Return, StopIteration) as e:
            result = getattr(e, 'value', None)
        except Exception:
            future.set_exc_info(sys.exc_info())
            return future
        else:
            if isinstance(result, types.GeneratorType):
                # Inline the first iteration of Runner.run.  This lets us
                # avoid the cost of creating a Runner when the coroutine
                # never actually yields, which in turn allows us to
                # use "optional" coroutines in critical path code without
                # performance penalty for the synchronous case.
                try:
                    orig_stack_contexts = stack_context._state.contexts
                    yielded = next(result)
                    if stack_context._state.contexts is not orig_stack_contexts:
                        yielded = TracebackFuture()
                        yielded.set_exception(
                            stack_context.StackContextInconsistentError(
                                'stack_context inconsistency (probably caused '
                                'by yield within a "with StackContext" block)'))
                except (StopIteration, Return) as e:
                    future.set_result(getattr(e, 'value', None))
                except Exception:
                    future.set_exc_info(sys.exc_info())
                else:
                    Runner(result, future, yielded)
                try:
                    return future
                finally:
                    # Subtle memory optimization: if next() raised an exception,
                    # the future's exc_info contains a traceback which
                    # includes this stack frame.  This creates a cycle,
                    # which will be collected at the next full GC but has
                    # been shown to greatly increase memory usage of
                    # benchmarks (relative to the refcount-based scheme
                    # used in the absence of cycles).  We can avoid the
                    # cycle by clearing the local variable after we return it.
                    future = None
        future.set_result(result)
        return future
    return wrapper


class Return(Exception):
    """Special exception to return a value from a `coroutine`.

    If this exception is raised, its value argument is used as the
    result of the coroutine::

        @gen.coroutine
        def fetch_json(url):
            response = yield AsyncHTTPClient().fetch(url)
            raise gen.Return(json_decode(response.body))

    In Python 3.3, this exception is no longer necessary: the ``return``
    statement can be used directly to return a value (previously
    ``yield`` and ``return`` with a value could not be combined in the
    same function).

    By analogy with the return statement, the value argument is optional,
    but it is never necessary to ``raise gen.Return()``.  The ``return``
    statement can be used with no arguments instead.
    """
    def __init__(self, value=None):
        super(Return, self).__init__()
        self.value = value


class WaitIterator(object):
    """Provides an iterator to yield the results of futures as they finish.

    Yielding a set of futures like this:

    ``results = yield [future1, future2]``

    pauses the coroutine until both ``future1`` and ``future2``
    return, and then restarts the coroutine with the results of both
    futures. If either future is an exception, the expression will
    raise that exception and all the results will be lost.

    If you need to get the result of each future as soon as possible,
    or if you need the result of some futures even if others produce
    errors, you can use ``WaitIterator``::

      wait_iterator = gen.WaitIterator(future1, future2)
      while not wait_iterator.done():
          try:
              result = yield wait_iterator.next()
          except Exception as e:
              print("Error {} from {}".format(e, wait_iterator.current_future))
          else:
              print("Result {} recieved from {} at {}".format(
                  result, wait_iterator.current_future,
                  wait_iterator.current_index))

    Because results are returned as soon as they are available the
    output from the iterator *will not be in the same order as the
    input arguments*. If you need to know which future produced the
    current result, you can use the attributes
    ``WaitIterator.current_future``, or ``WaitIterator.current_index``
    to get the index of the future from the input list. (if keyword
    arguments were used in the construction of the `WaitIterator`,
    ``current_index`` will use the corresponding keyword).

    .. versionadded:: 4.1
    """
    def __init__(self, *args, **kwargs):
        if args and kwargs:
            raise ValueError(
                "You must provide args or kwargs, not both")

        if kwargs:
            self._unfinished = dict((f, k) for (k, f) in kwargs.items())
            futures = list(kwargs.values())
        else:
            self._unfinished = dict((f, i) for (i, f) in enumerate(args))
            futures = args

        self._finished = collections.deque()
        self.current_index = self.current_future = None
        self._running_future = None

        self_ref = weakref.ref(self)
        for future in futures:
            future.add_done_callback(functools.partial(
                self._done_callback, self_ref))

    def done(self):
        """Returns True if this iterator has no more results."""
        if self._finished or self._unfinished:
            return False
        # Clear the 'current' values when iteration is done.
        self.current_index = self.current_future = None
        return True

    def next(self):
        """Returns a `.Future` that will yield the next available result.

        Note that this `.Future` will not be the same object as any of
        the inputs.
        """
        self._running_future = TracebackFuture()

        if self._finished:
            self._return_result(self._finished.popleft())

        return self._running_future

    @staticmethod
    def _done_callback(self_ref, done):
        self = self_ref()
        if self is not None:
            if self._running_future and not self._running_future.done():
                self._return_result(done)
            else:
                self._finished.append(done)

    def _return_result(self, done):
        """Called set the returned future's state that of the future
        we yielded, and set the current future for the iterator.
        """
        chain_future(done, self._running_future)

        self.current_future = done
        self.current_index = self._unfinished.pop(done)


class YieldPoint(object):
    """Base class for objects that may be yielded from the generator.

    .. deprecated:: 4.0
       Use `Futures <.Future>` instead.
    """
    def start(self, runner):
        """Called by the runner after the generator has yielded.

        No other methods will be called on this object before ``start``.
        """
        raise NotImplementedError()

    def is_ready(self):
        """Called by the runner to determine whether to resume the generator.

        Returns a boolean; may be called more than once.
        """
        raise NotImplementedError()

    def get_result(self):
        """Returns the value to use as the result of the yield expression.

        This method will only be called once, and only after `is_ready`
        has returned true.
        """
        raise NotImplementedError()


class Callback(YieldPoint):
    """Returns a callable object that will allow a matching `Wait` to proceed.

    The key may be any value suitable for use as a dictionary key, and is
    used to match ``Callbacks`` to their corresponding ``Waits``.  The key
    must be unique among outstanding callbacks within a single run of the
    generator function, but may be reused across different runs of the same
    function (so constants generally work fine).

    The callback may be called with zero or one arguments; if an argument
    is given it will be returned by `Wait`.

    .. deprecated:: 4.0
       Use `Futures <.Future>` instead.
    """
    def __init__(self, key):
        self.key = key

    def start(self, runner):
        self.runner = runner
        runner.register_callback(self.key)

    def is_ready(self):
        return True

    def get_result(self):
        return self.runner.result_callback(self.key)


class Wait(YieldPoint):
    """Returns the argument passed to the result of a previous `Callback`.

    .. deprecated:: 4.0
       Use `Futures <.Future>` instead.
    """
    def __init__(self, key):
        self.key = key

    def start(self, runner):
        self.runner = runner

    def is_ready(self):
        return self.runner.is_ready(self.key)

    def get_result(self):
        return self.runner.pop_result(self.key)


class WaitAll(YieldPoint):
    """Returns the results of multiple previous `Callbacks <Callback>`.

    The argument is a sequence of `Callback` keys, and the result is
    a list of results in the same order.

    `WaitAll` is equivalent to yielding a list of `Wait` objects.

    .. deprecated:: 4.0
       Use `Futures <.Future>` instead.
    """
    def __init__(self, keys):
        self.keys = keys

    def start(self, runner):
        self.runner = runner

    def is_ready(self):
        return all(self.runner.is_ready(key) for key in self.keys)

    def get_result(self):
        return [self.runner.pop_result(key) for key in self.keys]


def Task(func, *args, **kwargs):
    """Adapts a callback-based asynchronous function for use in coroutines.

    Takes a function (and optional additional arguments) and runs it with
    those arguments plus a ``callback`` keyword argument.  The argument passed
    to the callback is returned as the result of the yield expression.

    .. versionchanged:: 4.0
       ``gen.Task`` is now a function that returns a `.Future`, instead of
       a subclass of `YieldPoint`.  It still behaves the same way when
       yielded.
    """
    future = Future()

    def handle_exception(typ, value, tb):
        if future.done():
            return False
        future.set_exc_info((typ, value, tb))
        return True

    def set_result(result):
        if future.done():
            return
        future.set_result(result)
    with stack_context.ExceptionStackContext(handle_exception):
        func(*args, callback=_argument_adapter(set_result), **kwargs)
    return future


class YieldFuture(YieldPoint):
    def __init__(self, future, io_loop=None):
        """Adapts a `.Future` to the `YieldPoint` interface.

        .. versionchanged:: 4.1
           The ``io_loop`` argument is deprecated.
        """
        self.future = future
        self.io_loop = io_loop or IOLoop.current()

    def start(self, runner):
        if not self.future.done():
            self.runner = runner
            self.key = object()
            runner.register_callback(self.key)
            self.io_loop.add_future(self.future, runner.result_callback(self.key))
        else:
            self.runner = None
            self.result = self.future.result()

    def is_ready(self):
        if self.runner is not None:
            return self.runner.is_ready(self.key)
        else:
            return True

    def get_result(self):
        if self.runner is not None:
            return self.runner.pop_result(self.key).result()
        else:
            return self.result


class Multi(YieldPoint):
    """Runs multiple asynchronous operations in parallel.

    Takes a list of ``YieldPoints`` or ``Futures`` and returns a list of
    their responses.  It is not necessary to call `Multi` explicitly,
    since the engine will do so automatically when the generator yields
    a list of ``YieldPoints`` or a mixture of ``YieldPoints`` and ``Futures``.

    Instead of a list, the argument may also be a dictionary whose values are
    Futures, in which case a parallel dictionary is returned mapping the same
    keys to their results.
    """
    def __init__(self, children):
        self.keys = None
        if isinstance(children, dict):
            self.keys = list(children.keys())
            children = children.values()
        self.children = []
        for i in children:
            if is_future(i):
                i = YieldFuture(i)
            self.children.append(i)
        assert all(isinstance(i, YieldPoint) for i in self.children)
        self.unfinished_children = set(self.children)

    def start(self, runner):
        for i in self.children:
            i.start(runner)

    def is_ready(self):
        finished = list(itertools.takewhile(
            lambda i: i.is_ready(), self.unfinished_children))
        self.unfinished_children.difference_update(finished)
        return not self.unfinished_children

    def get_result(self):
        result = (i.get_result() for i in self.children)
        if self.keys is not None:
            return dict(zip(self.keys, result))
        else:
            return list(result)


def multi_future(children):
    """Wait for multiple asynchronous futures in parallel.

    Takes a list of ``Futures`` (but *not* other ``YieldPoints``) and returns
    a new Future that resolves when all the other Futures are done.
    If all the ``Futures`` succeeded, the returned Future's result is a list
    of their results.  If any failed, the returned Future raises the exception
    of the first one to fail.

    Instead of a list, the argument may also be a dictionary whose values are
    Futures, in which case a parallel dictionary is returned mapping the same
    keys to their results.

    It is not necessary to call `multi_future` explcitly, since the engine will
    do so automatically when the generator yields a list of `Futures`.
    This function is faster than the `Multi` `YieldPoint` because it does not
    require the creation of a stack context.

    .. versionadded:: 4.0
    """
    if isinstance(children, dict):
        keys = list(children.keys())
        children = children.values()
    else:
        keys = None
    assert all(is_future(i) for i in children)
    unfinished_children = set(children)

    future = Future()
    if not children:
        future.set_result({} if keys is not None else [])

    def callback(f):
        unfinished_children.remove(f)
        if not unfinished_children:
            try:
                result_list = [i.result() for i in children]
            except Exception:
                future.set_exc_info(sys.exc_info())
            else:
                if keys is not None:
                    future.set_result(dict(zip(keys, result_list)))
                else:
                    future.set_result(result_list)
    for f in children:
        f.add_done_callback(callback)
    return future


def maybe_future(x):
    """Converts ``x`` into a `.Future`.

    If ``x`` is already a `.Future`, it is simply returned; otherwise
    it is wrapped in a new `.Future`.  This is suitable for use as
    ``result = yield gen.maybe_future(f())`` when you don't know whether
    ``f()`` returns a `.Future` or not.
    """
    if is_future(x):
        return x
    else:
        fut = Future()
        fut.set_result(x)
        return fut


def with_timeout(timeout, future, io_loop=None, quiet_exceptions=()):
    """Wraps a `.Future` in a timeout.

    Raises `TimeoutError` if the input future does not complete before
    ``timeout``, which may be specified in any form allowed by
    `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
    relative to `.IOLoop.time`)

    If the wrapped `.Future` fails after it has timed out, the exception
    will be logged unless it is of a type contained in ``quiet_exceptions``
    (which may be an exception type or a sequence of types).

    Currently only supports Futures, not other `YieldPoint` classes.

    .. versionadded:: 4.0

    .. versionchanged:: 4.1
       Added the ``quiet_exceptions`` argument and the logging of unhandled
       exceptions.
    """
    # TODO: allow yield points in addition to futures?
    # Tricky to do with stack_context semantics.
    #
    # It's tempting to optimize this by cancelling the input future on timeout
    # instead of creating a new one, but A) we can't know if we are the only
    # one waiting on the input future, so cancelling it might disrupt other
    # callers and B) concurrent futures can only be cancelled while they are
    # in the queue, so cancellation cannot reliably bound our waiting time.
    result = Future()
    chain_future(future, result)
    if io_loop is None:
        io_loop = IOLoop.current()

    def error_callback(future):
        try:
            future.result()
        except Exception as e:
            if not isinstance(e, quiet_exceptions):
                app_log.error("Exception in Future %r after timeout",
                              future, exc_info=True)

    def timeout_callback():
        result.set_exception(TimeoutError("Timeout"))
        # In case the wrapped future goes on to fail, log it.
        future.add_done_callback(error_callback)
    timeout_handle = io_loop.add_timeout(
        timeout, timeout_callback)
    if isinstance(future, Future):
        # We know this future will resolve on the IOLoop, so we don't
        # need the extra thread-safety of IOLoop.add_future (and we also
        # don't care about StackContext here.
        future.add_done_callback(
            lambda future: io_loop.remove_timeout(timeout_handle))
    else:
        # concurrent.futures.Futures may resolve on any thread, so we
        # need to route them back to the IOLoop.
        io_loop.add_future(
            future, lambda future: io_loop.remove_timeout(timeout_handle))
    return result


def sleep(duration):
    """Return a `.Future` that resolves after the given number of seconds.

    When used with ``yield`` in a coroutine, this is a non-blocking
    analogue to `time.sleep` (which should not be used in coroutines
    because it is blocking)::

        yield gen.sleep(0.5)

    Note that calling this function on its own does nothing; you must
    wait on the `.Future` it returns (usually by yielding it).

    .. versionadded:: 4.1
    """
    f = Future()
    IOLoop.current().call_later(duration, lambda: f.set_result(None))
    return f


_null_future = Future()
_null_future.set_result(None)

moment = Future()
moment.__doc__ = \
    """A special object which may be yielded to allow the IOLoop to run for
one iteration.

This is not needed in normal use but it can be helpful in long-running
coroutines that are likely to yield Futures that are ready instantly.

Usage: ``yield gen.moment``

.. versionadded:: 4.0
"""
moment.set_result(None)


class Runner(object):
    """Internal implementation of `tornado.gen.engine`.

    Maintains information about pending callbacks and their results.

    The results of the generator are stored in ``result_future`` (a
    `.TracebackFuture`)
    """
    def __init__(self, gen, result_future, first_yielded):
        self.gen = gen
        self.result_future = result_future
        self.future = _null_future
        self.yield_point = None
        self.pending_callbacks = None
        self.results = None
        self.running = False
        self.finished = False
        self.had_exception = False
        self.io_loop = IOLoop.current()
        # For efficiency, we do not create a stack context until we
        # reach a YieldPoint (stack contexts are required for the historical
        # semantics of YieldPoints, but not for Futures).  When we have
        # done so, this field will be set and must be called at the end
        # of the coroutine.
        self.stack_context_deactivate = None
        if self.handle_yield(first_yielded):
            self.run()

    def register_callback(self, key):
        """Adds ``key`` to the list of callbacks."""
        if self.pending_callbacks is None:
            # Lazily initialize the old-style YieldPoint data structures.
            self.pending_callbacks = set()
            self.results = {}
        if key in self.pending_callbacks:
            raise KeyReuseError("key %r is already pending" % (key,))
        self.pending_callbacks.add(key)

    def is_ready(self, key):
        """Returns true if a result is available for ``key``."""
        if self.pending_callbacks is None or key not in self.pending_callbacks:
            raise UnknownKeyError("key %r is not pending" % (key,))
        return key in self.results

    def set_result(self, key, result):
        """Sets the result for ``key`` and attempts to resume the generator."""
        self.results[key] = result
        if self.yield_point is not None and self.yield_point.is_ready():
            try:
                self.future.set_result(self.yield_point.get_result())
            except:
                self.future.set_exc_info(sys.exc_info())
            self.yield_point = None
            self.run()

    def pop_result(self, key):
        """Returns the result for ``key`` and unregisters it."""
        self.pending_callbacks.remove(key)
        return self.results.pop(key)

    def run(self):
        """Starts or resumes the generator, running until it reaches a
        yield point that is not ready.
        """
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                future = self.future
                if not future.done():
                    return
                self.future = None
                try:
                    orig_stack_contexts = stack_context._state.contexts
                    try:
                        value = future.result()
                    except Exception:
                        self.had_exception = True
                        yielded = self.gen.throw(*sys.exc_info())
                    else:
                        yielded = self.gen.send(value)
                    if stack_context._state.contexts is not orig_stack_contexts:
                        self.gen.throw(
                            stack_context.StackContextInconsistentError(
                                'stack_context inconsistency (probably caused '
                                'by yield within a "with StackContext" block)'))
                except (StopIteration, Return) as e:
                    self.finished = True
                    self.future = _null_future
                    if self.pending_callbacks and not self.had_exception:
                        # If we ran cleanly without waiting on all callbacks
                        # raise an error (really more of a warning).  If we
                        # had an exception then some callbacks may have been
                        # orphaned, so skip the check in that case.
                        raise LeakedCallbackError(
                            "finished without waiting for callbacks %r" %
                            self.pending_callbacks)
                    self.result_future.set_result(getattr(e, 'value', None))
                    self.result_future = None
                    self._deactivate_stack_context()
                    return
                except Exception:
                    self.finished = True
                    self.future = _null_future
                    self.result_future.set_exc_info(sys.exc_info())
                    self.result_future = None
                    self._deactivate_stack_context()
                    return
                if not self.handle_yield(yielded):
                    return
        finally:
            self.running = False

    def handle_yield(self, yielded):
        # Lists containing YieldPoints require stack contexts;
        # other lists are handled via multi_future in convert_yielded.
        if (isinstance(yielded, list) and
                any(isinstance(f, YieldPoint) for f in yielded)):
            yielded = Multi(yielded)
        elif (isinstance(yielded, dict) and
              any(isinstance(f, YieldPoint) for f in yielded.values())):
            yielded = Multi(yielded)

        if isinstance(yielded, YieldPoint):
            # YieldPoints are too closely coupled to the Runner to go
            # through the generic convert_yielded mechanism.
            self.future = TracebackFuture()

            def start_yield_point():
                try:
                    yielded.start(self)
                    if yielded.is_ready():
                        self.future.set_result(
                            yielded.get_result())
                    else:
                        self.yield_point = yielded
                except Exception:
                    self.future = TracebackFuture()
                    self.future.set_exc_info(sys.exc_info())

            if self.stack_context_deactivate is None:
                # Start a stack context if this is the first
                # YieldPoint we've seen.
                with stack_context.ExceptionStackContext(
                        self.handle_exception) as deactivate:
                    self.stack_context_deactivate = deactivate

                    def cb():
                        start_yield_point()
                        self.run()
                    self.io_loop.add_callback(cb)
                    return False
            else:
                start_yield_point()
        else:
            try:
                self.future = convert_yielded(yielded)
            except BadYieldError:
                self.future = TracebackFuture()
                self.future.set_exc_info(sys.exc_info())

        if not self.future.done() or self.future is moment:
            self.io_loop.add_future(
                self.future, lambda f: self.run())
            return False
        return True

    def result_callback(self, key):
        return stack_context.wrap(_argument_adapter(
            functools.partial(self.set_result, key)))

    def handle_exception(self, typ, value, tb):
        if not self.running and not self.finished:
            self.future = TracebackFuture()
            self.future.set_exc_info((typ, value, tb))
            self.run()
            return True
        else:
            return False

    def _deactivate_stack_context(self):
        if self.stack_context_deactivate is not None:
            self.stack_context_deactivate()
            self.stack_context_deactivate = None

Arguments = collections.namedtuple('Arguments', ['args', 'kwargs'])


def _argument_adapter(callback):
    """Returns a function that when invoked runs ``callback`` with one arg.

    If the function returned by this function is called with exactly
    one argument, that argument is passed to ``callback``.  Otherwise
    the args tuple and kwargs dict are wrapped in an `Arguments` object.
    """
    def wrapper(*args, **kwargs):
        if kwargs or len(args) > 1:
            callback(Arguments(args, kwargs))
        elif args:
            callback(args[0])
        else:
            callback(None)
    return wrapper


def convert_yielded(yielded):
    """Convert a yielded object into a `.Future`.

    The default implementation accepts lists, dictionaries, and Futures.

    If the `~functools.singledispatch` library is available, this function
    may be extended to support additional types. For example::

        @convert_yielded.register(asyncio.Future)
        def _(asyncio_future):
            return tornado.platform.asyncio.to_tornado_future(asyncio_future)

    .. versionadded:: 4.1
    """
    # Lists and dicts containing YieldPoints were handled separately
    # via Multi().
    if isinstance(yielded, (list, dict)):
        return multi_future(yielded)
    elif is_future(yielded):
        return yielded
    else:
        raise BadYieldError("yielded unknown object %r" % (yielded,))

if singledispatch is not None:
    convert_yielded = singledispatch(convert_yielded)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user