{
    "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    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\ncould be written with ``gen`` as::\n\n    class GenAsyncHandler(RequestHandler):\n        @asynchronous\n        @gen.engine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield gen.Task(http_client.fetch, \"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n`Task` works with any function that takes a ``callback`` keyword\nargument.  You can also yield a list of ``Tasks``, which will be\nstarted at the same time and run in parallel; a list of results will\nbe returned when they are all finished::\n\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [gen.Task(http_client.fetch, url1),\n                                      gen.Task(http_client.fetch, url2)]\n\nFor more complicated interfaces, `Task` can be split into two parts:\n`Callback` and `Wait`::\n\n    class GenAsyncHandler2(RequestHandler):\n        @asynchronous\n        @gen.engine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=(yield gen.Callback(\"key\"))\n            response = yield gen.Wait(\"key\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\nThe ``key`` argument to `Callback` and `Wait` allows for multiple\nasynchronous operations to be started at different times and proceed\nin parallel: yield several callbacks with different keys, then wait\nfor them once all the async operations have started.\n\nThe result of a `Wait` or `Task` yield expression depends on how the callback\nwas run.  If it was called with no arguments, the result is ``None``.  If\nit was called with one argument, the result is that argument.  If it was\ncalled with more than one argument or any keyword arguments, the result\nis an `Arguments` object, which is a named tuple ``(args, kwargs)``.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport functools\nimport sys\nimport types\n\nfrom tornado.concurrent import Future\nfrom tornado.ioloop import IOLoop\nfrom tornado.stack_context import ExceptionStackContext\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\ndef engine(func):\n    \"\"\"Decorator for asynchronous generators.\n\n    Any generator that yields objects from this module must be wrapped\n    in this decorator.  The decorator only works on functions that are\n    already asynchronous.  For `~tornado.web.RequestHandler`\n    ``get``/``post``/etc methods, this means that both the\n    `tornado.web.asynchronous` and `tornado.gen.engine` decorators\n    must be used (for proper exception handling, ``asynchronous``\n    should come before ``gen.engine``).  In most other cases, it means\n    that it doesn't make sense to use ``gen.engine`` on functions that\n    don't already take a callback argument.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        runner = None\n\n        def handle_exception(typ, value, tb):\n            # if the function throws an exception before its first \"yield\"\n            # (or is not a generator at all), the Runner won't exist yet.\n            # However, in that case we haven't reached anything asynchronous\n            # yet, so we can just let the exception propagate.\n            if runner is not None:\n                return runner.handle_exception(typ, value, tb)\n            return False\n        with ExceptionStackContext(handle_exception) as deactivate:\n            gen = func(*args, **kwargs)\n            if isinstance(gen, types.GeneratorType):\n                runner = Runner(gen, deactivate)\n                runner.run()\n                return\n            assert gen is None, gen\n            deactivate()\n            # no yield, so we're done\n    return wrapper\n\n\nclass YieldPoint(object):\n    \"\"\"Base class for objects that may be yielded from the generator.\"\"\"\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    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    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`.\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    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\nclass Task(YieldPoint):\n    \"\"\"Runs a single asynchronous operation.\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    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique\n    key generated automatically)::\n\n        result = yield gen.Task(func, args)\n\n        func(args, callback=(yield gen.Callback(key)))\n        result = yield gen.Wait(key)\n    \"\"\"\n    def __init__(self, func, *args, **kwargs):\n        assert \"callback\" not in kwargs\n        self.args = args\n        self.kwargs = kwargs\n        self.func = func\n\n    def start(self, runner):\n        self.runner = runner\n        self.key = object()\n        runner.register_callback(self.key)\n        self.kwargs[\"callback\"] = runner.result_callback(self.key)\n        self.func(*self.args, **self.kwargs)\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 YieldFuture(YieldPoint):\n    def __init__(self, future, io_loop=None):\n        self.future = future\n        self.io_loop = io_loop or IOLoop.current()\n\n    def start(self, runner):\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\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).result()\n\n\nclass Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``Tasks`` or other ``YieldPoints`` 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``.\n    \"\"\"\n    def __init__(self, children):\n        assert all(isinstance(i, YieldPoint) for i in children)\n        self.children = children\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        return all(i.is_ready() for i in self.children)\n\n    def get_result(self):\n        return [i.get_result() for i in self.children]\n\n\nclass _NullYieldPoint(YieldPoint):\n    def start(self, runner):\n        pass\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return 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    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\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 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        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                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except StopIteration:\n                    self.finished = True\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.final_callback()\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                if isinstance(yielded, Future):\n                    # TODO: lists of futures\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\"yielded unknown object %r\" % yielded),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return inner\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False\n\nArguments = collections.namedtuple('Arguments', ['args', 'kwargs'])\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    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\ncould be written with ``gen`` as::\n\n    class GenAsyncHandler(RequestHandler):\n        @asynchronous\n        @gen.engine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield gen.Task(http_client.fetch, \"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n`Task` works with any function that takes a ``callback`` keyword\nargument.  You can also yield a list of ``Tasks``, which will be\nstarted at the same time and run in parallel; a list of results will\nbe returned when they are all finished::\n\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [gen.Task(http_client.fetch, url1),\n                                      gen.Task(http_client.fetch, url2)]\n\nFor more complicated interfaces, `Task` can be split into two parts:\n`Callback` and `Wait`::\n\n    class GenAsyncHandler2(RequestHandler):\n        @asynchronous\n        @gen.engine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=(yield gen.Callback(\"key\"))\n            response = yield gen.Wait(\"key\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\nThe ``key`` argument to `Callback` and `Wait` allows for multiple\nasynchronous operations to be started at different times and proceed\nin parallel: yield several callbacks with different keys, then wait\nfor them once all the async operations have started.\n\nThe result of a `Wait` or `Task` yield expression depends on how the callback\nwas run.  If it was called with no arguments, the result is ``None``.  If\nit was called with one argument, the result is that argument.  If it was\ncalled with more than one argument or any keyword arguments, the result\nis an `Arguments` object, which is a named tuple ``(args, kwargs)``.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport functools\nimport sys\nimport types\n\nfrom tornado.concurrent import Future\nfrom tornado.ioloop import IOLoop\nfrom tornado.stack_context import ExceptionStackContext\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\ndef engine(func):\n    \"\"\"Decorator for asynchronous generators.\n\n    Any generator that yields objects from this module must be wrapped\n    in this decorator.  The decorator only works on functions that are\n    already asynchronous.  For `~tornado.web.RequestHandler`\n    ``get``/``post``/etc methods, this means that both the\n    `tornado.web.asynchronous` and `tornado.gen.engine` decorators\n    must be used (for proper exception handling, ``asynchronous``\n    should come before ``gen.engine``).  In most other cases, it means\n    that it doesn't make sense to use ``gen.engine`` on functions that\n    don't already take a callback argument.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        runner = None\n\n        def handle_exception(typ, value, tb):\n            # if the function throws an exception before its first \"yield\"\n            # (or is not a generator at all), the Runner won't exist yet.\n            # However, in that case we haven't reached anything asynchronous\n            # yet, so we can just let the exception propagate.\n            if runner is not None:\n                return runner.handle_exception(typ, value, tb)\n            return False\n        with ExceptionStackContext(handle_exception) as deactivate:\n            gen = func(*args, **kwargs)\n            if isinstance(gen, types.GeneratorType):\n                runner = Runner(gen, deactivate)\n                runner.run()\n                return\n            assert gen is None, gen\n            deactivate()\n            # no yield, so we're done\n    return wrapper\n\n\nclass YieldPoint(object):\n    \"\"\"Base class for objects that may be yielded from the generator.\"\"\"\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    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    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`.\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    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\nclass Task(YieldPoint):\n    \"\"\"Runs a single asynchronous operation.\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    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique\n    key generated automatically)::\n\n        result = yield gen.Task(func, args)\n\n        func(args, callback=(yield gen.Callback(key)))\n        result = yield gen.Wait(key)\n    \"\"\"\n    def __init__(self, func, *args, **kwargs):\n        assert \"callback\" not in kwargs\n        self.args = args\n        self.kwargs = kwargs\n        self.func = func\n\n    def start(self, runner):\n        self.runner = runner\n        self.key = object()\n        runner.register_callback(self.key)\n        self.kwargs[\"callback\"] = runner.result_callback(self.key)\n        self.func(*self.args, **self.kwargs)\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 YieldFuture(YieldPoint):\n    def __init__(self, future, io_loop=None):\n        self.future = future\n        self.io_loop = io_loop or IOLoop.current()\n\n    def start(self, runner):\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\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).result()\n\n\nclass Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``Tasks`` or other ``YieldPoints`` 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``.\n    \"\"\"\n    def __init__(self, children):\n        self.children = []\n        for i in children:\n            if isinstance(i, Future):\n                i = YieldFuture(i)\n            self.children.append(i)\n        assert all(isinstance(i, YieldPoint) for i in 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        return all(i.is_ready() for i in self.children)\n\n    def get_result(self):\n        return [i.get_result() for i in self.children]\n\n\nclass _NullYieldPoint(YieldPoint):\n    def start(self, runner):\n        pass\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return 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    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\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 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        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                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except StopIteration:\n                    self.finished = True\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.final_callback()\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\"yielded unknown object %r\" % yielded),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return inner\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False\n\nArguments = collections.namedtuple('Arguments', ['args', 'kwargs'])\n",
            "header": {
                "file": {
                    "path": "tornado/gen.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "320f7da6",
                "new_commit_hash": "e309bf3c",
                "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": 276,
                            "length": 8
                        },
                        "new_range": {
                            "start": 276,
                            "length": 12
                        },
                        "section": "class Multi(YieldPoint):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    a list of ``YieldPoints``.",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    def __init__(self, children):",
                                "type": "context"
                            },
                            {
                                "content": "        assert all(isinstance(i, YieldPoint) for i in children)",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.children = children",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.children = []",
                                "type": "added"
                            },
                            {
                                "content": "        for i in children:",
                                "type": "added"
                            },
                            {
                                "content": "            if isinstance(i, Future):",
                                "type": "added"
                            },
                            {
                                "content": "                i = YieldFuture(i)",
                                "type": "added"
                            },
                            {
                                "content": "            self.children.append(i)",
                                "type": "added"
                            },
                            {
                                "content": "        assert all(isinstance(i, YieldPoint) for i in self.children)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def start(self, runner):",
                                "type": "context"
                            },
                            {
                                "content": "        for i in self.children:",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/gen.py",
                            "type": "method",
                            "name": "Multi.__init__",
                            "content": "class Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``Tasks`` or other ``YieldPoints`` 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``.\n    \"\"\"\n    def __init__(self, children):\n        assert all(isinstance(i, YieldPoint) for i in children)\n        self.children = children\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        return all(i.is_ready() for i in self.children)\n\n    def get_result(self):\n        return [i.get_result() for i in self.children]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 278,
                            "end_lineno": 280,
                            "parent": {
                                "file_name": "tornado/gen.py",
                                "type": "class",
                                "name": "Multi",
                                "content": "class Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``Tasks`` or other ``YieldPoints`` 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``.\n    \"\"\"\n    def __init__(self, children):\n        assert all(isinstance(i, YieldPoint) for i in children)\n        self.children = children\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        return all(i.is_ready() for i in self.children)\n\n    def get_result(self):\n        return [i.get_result() for i in self.children]",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 270,
                                "end_lineno": 290,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/gen.py",
                            "type": "class",
                            "name": "Multi",
                            "content": "class Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``Tasks`` or other ``YieldPoints`` 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``.\n    \"\"\"\n    def __init__(self, children):\n        assert all(isinstance(i, YieldPoint) for i in children)\n        self.children = children\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        return all(i.is_ready() for i in self.children)\n\n    def get_result(self):\n        return [i.get_result() for i in self.children]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 270,
                            "end_lineno": 290,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 383,
                            "length": 8
                        },
                        "new_range": {
                            "start": 387,
                            "length": 7
                        },
                        "section": "class Runner(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                    raise",
                                "type": "context"
                            },
                            {
                                "content": "                if isinstance(yielded, list):",
                                "type": "context"
                            },
                            {
                                "content": "                    yielded = Multi(yielded)",
                                "type": "context"
                            },
                            {
                                "content": "                if isinstance(yielded, Future):",
                                "type": "deleted"
                            },
                            {
                                "content": "                    # TODO: lists of futures",
                                "type": "deleted"
                            },
                            {
                                "content": "                elif isinstance(yielded, Future):",
                                "type": "added"
                            },
                            {
                                "content": "                    yielded = YieldFuture(yielded)",
                                "type": "context"
                            },
                            {
                                "content": "                if isinstance(yielded, YieldPoint):",
                                "type": "context"
                            },
                            {
                                "content": "                    self.yield_point = yielded",
                                "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    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\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 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        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                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except StopIteration:\n                    self.finished = True\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.final_callback()\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                if isinstance(yielded, Future):\n                    # TODO: lists of futures\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\"yielded unknown object %r\" % yielded),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return inner\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 344,
                            "end_lineno": 398,
                            "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    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\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 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        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                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except StopIteration:\n                    self.finished = True\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.final_callback()\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                if isinstance(yielded, Future):\n                    # TODO: lists of futures\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\"yielded unknown object %r\" % yielded),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return inner\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 304,
                                "end_lineno": 417,
                                "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    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\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 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        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                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except StopIteration:\n                    self.finished = True\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.final_callback()\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                if isinstance(yielded, Future):\n                    # TODO: lists of futures\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\"yielded unknown object %r\" % yielded),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return inner\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 304,
                            "end_lineno": 417,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function, with_statement\nimport functools\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.log import app_log\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog\nfrom tornado.web import Application, RequestHandler, asynchronous\n\nfrom tornado import gen\n\n\nclass GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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    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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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_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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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\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 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 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 GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/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_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport functools\nfrom tornado.concurrent import return_future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.log import app_log\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.web import Application, RequestHandler, asynchronous\n\nfrom tornado import gen\n\n\n\nclass GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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\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 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 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 GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/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_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\n",
            "header": {
                "file": {
                    "path": "tornado/test/gen_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "7249a3ad",
                "new_commit_hash": "ad531077",
                "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": 1,
                            "length": 14
                        },
                        "new_range": {
                            "start": 1,
                            "length": 17
                        },
                        "section": ""
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "from __future__ import absolute_import, division, print_function, with_statement",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "import functools",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.concurrent import return_future",
                                "type": "added"
                            },
                            {
                                "content": "from tornado.escape import url_escape",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.httpclient import AsyncHTTPClient",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.log import app_log",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog",
                                "type": "deleted"
                            },
                            {
                                "content": "from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test",
                                "type": "added"
                            },
                            {
                                "content": "from tornado.web import Application, RequestHandler, asynchronous",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from tornado import gen",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class GenTest(AsyncTestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    def run_gen(self, f):",
                                "type": "context"
                            },
                            {
                                "content": "        f()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 8,
                            "end_lineno": 8,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.concurrent import return_future",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 4,
                            "end_lineno": 4,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 6,
                            "end_lineno": 6,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 22,
                            "length": 6
                        },
                        "new_range": {
                            "start": 25,
                            "length": 10
                        },
                        "section": "class GenTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            self.io_loop.add_callback(functools.partial(",
                                "type": "context"
                            },
                            {
                                "content": "                self.delay_callback, iterations - 1, callback, arg))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @return_future",
                                "type": "added"
                            },
                            {
                                "content": "    def async_future(self, result, callback):",
                                "type": "added"
                            },
                            {
                                "content": "        self.io_loop.add_callback(callback, result)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_no_yield(self):",
                                "type": "context"
                            },
                            {
                                "content": "        @gen.engine",
                                "type": "context"
                            },
                            {
                                "content": "        def f():",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenTest",
                            "content": "class GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 15,
                            "end_lineno": 309,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenTest.async_future",
                            "content": "class GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 29,
                            "end_lineno": 30,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenTest",
                                "content": "class GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 15,
                                "end_lineno": 309,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 220,
                            "length": 6
                        },
                        "new_range": {
                            "start": 227,
                            "length": 16
                        },
                        "section": "class GenTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            self.stop()",
                                "type": "context"
                            },
                            {
                                "content": "        self.run_gen(f)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "added"
                            },
                            {
                                "content": "    def test_future(self):",
                                "type": "added"
                            },
                            {
                                "content": "        result = yield self.async_future(1)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(result, 1)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "added"
                            },
                            {
                                "content": "    def test_multi_future(self):",
                                "type": "added"
                            },
                            {
                                "content": "        results = yield [self.async_future(1), self.async_future(2)]",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(results, [1, 2])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_arguments(self):",
                                "type": "context"
                            },
                            {
                                "content": "        @gen.engine",
                                "type": "context"
                            },
                            {
                                "content": "        def f():",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenTest",
                            "content": "class GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 15,
                            "end_lineno": 309,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenTest.test_multi_future",
                            "content": "class GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 236,
                            "end_lineno": 238,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenTest",
                                "content": "class GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 15,
                                "end_lineno": 309,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenTest.test_future",
                            "content": "class GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 231,
                            "end_lineno": 233,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenTest",
                                "content": "class GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 15,
                                "end_lineno": 309,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "34edd2e8020b42cd16c3dc9a8c0417b9fae1e6d4^",
    "new_commit_hash": "34edd2e8020b42cd16c3dc9a8c0417b9fae1e6d4",
    "commit_message": "Support lists of futures in @gen.engine.",
    "commit_date": "2013-01-27T18:07:21-05:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "34edd2e8020b42cd16c3dc9a8c0417b9fae1e6d4",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function, with_statement\n\nimport functools\nfrom tornado.concurrent import return_future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.log import app_log\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.web import Application, RequestHandler, asynchronous\n\nfrom tornado import gen\n\n\n\nclass GenTest(AsyncTestCase):\n    def run_gen(self, f):\n        f()\n        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_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_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_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_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_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_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\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    @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    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        from tornado import stack_context\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            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 test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        from tornado import stack_context\n\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\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 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 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 GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/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_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\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 1 package in 862ms\nPrepared 1 package in 912ms\nInstalled 1 package in 0.72ms\n + tornado==2.4.post2 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_34edd2e8020b42cd16c3dc9a8c0417b9fae1e6d4)\nResolved 29 packages in 13ms\nInstalled 29 packages in 110ms\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_34edd2e8020b42cd16c3dc9a8c0417b9fae1e6d4\n..............................\ncollected 30 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::GenTest::test_arguments\nPASSED r2e_tests.test_1::GenTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenTest::test_exception_in_task_phase1\nPASSED r2e_tests.test_1::GenTest::test_exception_in_task_phase2\nPASSED r2e_tests.test_1::GenTest::test_exception_in_yield\nPASSED r2e_tests.test_1::GenTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenTest::test_future\nPASSED r2e_tests.test_1::GenTest::test_inline_cb\nPASSED r2e_tests.test_1::GenTest::test_ioloop_cb\nPASSED r2e_tests.test_1::GenTest::test_key_mismatch\nPASSED r2e_tests.test_1::GenTest::test_key_reuse\nPASSED r2e_tests.test_1::GenTest::test_leaked_callback\nPASSED r2e_tests.test_1::GenTest::test_multi\nPASSED r2e_tests.test_1::GenTest::test_multi_delayed\nPASSED r2e_tests.test_1::GenTest::test_multi_future\nPASSED r2e_tests.test_1::GenTest::test_no_yield\nPASSED r2e_tests.test_1::GenTest::test_orphaned_callback\nPASSED r2e_tests.test_1::GenTest::test_parallel_callback\nPASSED r2e_tests.test_1::GenTest::test_resume_after_exception_in_yield\nPASSED r2e_tests.test_1::GenTest::test_reuse\nPASSED r2e_tests.test_1::GenTest::test_stack_context_leak\nPASSED r2e_tests.test_1::GenTest::test_stack_context_leak_exception\nPASSED r2e_tests.test_1::GenTest::test_task\nPASSED r2e_tests.test_1::GenTest::test_wait_all\nPASSED r2e_tests.test_1::GenTest::test_with_arg\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_yield_exception_handler\n=================== 30 passed in 0.02s ===================\n",
    "new_commit_res_stderr": "ERROR:tornado.access:500 GET /exception (127.0.0.1) 0.45ms\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_34edd2e8020b42cd16c3dc9a8c0417b9fae1e6d4\n..............................\ncollected 30 items\n\n=================================== FAILURES ===================================\n__________ GenTest.test_multi_future __________\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_34edd2e8020b42cd16c3dc9a8c0417b9fae1e6d4/tornado/testing.py\", line 383, in wrapper\n    runner.run()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_34edd2e8020b42cd16c3dc9a8c0417b9fae1e6d4/tornado/gen.py\", line 385, in run\n    yielded = Multi(yielded)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_34edd2e8020b42cd16c3dc9a8c0417b9fae1e6d4/tornado/gen.py\", line 279, in __init__\n    assert all(isinstance(i, YieldPoint) for i in children)\nAssertionError\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::GenTest::test_arguments\nPASSED r2e_tests.test_1::GenTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenTest::test_exception_in_task_phase1\nPASSED r2e_tests.test_1::GenTest::test_exception_in_task_phase2\nPASSED r2e_tests.test_1::GenTest::test_exception_in_yield\nPASSED r2e_tests.test_1::GenTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenTest::test_future\nPASSED r2e_tests.test_1::GenTest::test_inline_cb\nPASSED r2e_tests.test_1::GenTest::test_ioloop_cb\nPASSED r2e_tests.test_1::GenTest::test_key_mismatch\nPASSED r2e_tests.test_1::GenTest::test_key_reuse\nPASSED r2e_tests.test_1::GenTest::test_leaked_callback\nPASSED r2e_tests.test_1::GenTest::test_multi\nPASSED r2e_tests.test_1::GenTest::test_multi_delayed\nFAILED r2e_tests.test_1::GenTest::test_multi_future\nPASSED r2e_tests.test_1::GenTest::test_no_yield\nPASSED r2e_tests.test_1::GenTest::test_orphaned_callback\nPASSED r2e_tests.test_1::GenTest::test_parallel_callback\nPASSED r2e_tests.test_1::GenTest::test_resume_after_exception_in_yield\nPASSED r2e_tests.test_1::GenTest::test_reuse\nPASSED r2e_tests.test_1::GenTest::test_stack_context_leak\nPASSED r2e_tests.test_1::GenTest::test_stack_context_leak_exception\nPASSED r2e_tests.test_1::GenTest::test_task\nPASSED r2e_tests.test_1::GenTest::test_wait_all\nPASSED r2e_tests.test_1::GenTest::test_with_arg\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_yield_exception_handler\n=================== 1 failed, 29 passed in 0.02s ===================\n",
    "old_commit_res_stderr": "ERROR:tornado.access:500 GET /exception (127.0.0.1) 0.65ms\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:** Yielding a List of Futures in `@gen.engine` Causes AssertionError

**Description:**
When yielding a list of `Future` objects within a function decorated with `@gen.engine`, an `AssertionError` is raised because the engine expects all yielded items to be instances of `YieldPoint`.

**Example Code:**
```python
from tornado.gen import engine, Future

@engine
def fetch_data():
    future1 = Future()
    future2 = Future()
    results = yield [future1, future2]
    # process results
```

**Expected Behavior:**
The `@gen.engine` decorator should handle a list of `Future` objects by waiting for all of them to complete and returning their results as a list.

**Actual Behavior:**
An `AssertionError` is raised with the message:
```
AssertionError
```

[/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::

    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")

could be written with ``gen`` as::

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

`Task` works with any function that takes a ``callback`` keyword
argument.  You can also yield a list of ``Tasks``, which will be
started at the same time and run in parallel; a list of results will
be returned when they are all finished::

    def get(self):
        http_client = AsyncHTTPClient()
        response1, response2 = yield [gen.Task(http_client.fetch, url1),
                                      gen.Task(http_client.fetch, url2)]

For more complicated interfaces, `Task` can be split into two parts:
`Callback` and `Wait`::

    class GenAsyncHandler2(RequestHandler):
        @asynchronous
        @gen.engine
        def get(self):
            http_client = AsyncHTTPClient()
            http_client.fetch("http://example.com",
                              callback=(yield gen.Callback("key"))
            response = yield gen.Wait("key")
            do_something_with_response(response)
            self.render("template.html")

The ``key`` argument to `Callback` and `Wait` allows for multiple
asynchronous operations to be started at different times and proceed
in parallel: yield several callbacks with different keys, then wait
for them once all the async operations have started.

The result of a `Wait` or `Task` yield expression depends on how the callback
was run.  If it was called with no arguments, the result is ``None``.  If
it was called with one argument, the result is that argument.  If it was
called with more than one argument or any keyword arguments, the result
is an `Arguments` object, which is a named tuple ``(args, kwargs)``.
"""
from __future__ import absolute_import, division, print_function, with_statement

import collections
import functools
import sys
import types

from tornado.concurrent import Future
from tornado.ioloop import IOLoop
from tornado.stack_context import ExceptionStackContext


class KeyReuseError(Exception):
    pass


class UnknownKeyError(Exception):
    pass


class LeakedCallbackError(Exception):
    pass


class BadYieldError(Exception):
    pass


def engine(func):
    """Decorator for asynchronous generators.

    Any generator that yields objects from this module must be wrapped
    in this decorator.  The decorator only works on functions that are
    already asynchronous.  For `~tornado.web.RequestHandler`
    ``get``/``post``/etc methods, this means that both the
    `tornado.web.asynchronous` and `tornado.gen.engine` decorators
    must be used (for proper exception handling, ``asynchronous``
    should come before ``gen.engine``).  In most other cases, it means
    that it doesn't make sense to use ``gen.engine`` on functions that
    don't already take a callback argument.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        runner = None

        def handle_exception(typ, value, tb):
            # if the function throws an exception before its first "yield"
            # (or is not a generator at all), the Runner won't exist yet.
            # However, in that case we haven't reached anything asynchronous
            # yet, so we can just let the exception propagate.
            if runner is not None:
                return runner.handle_exception(typ, value, tb)
            return False
        with ExceptionStackContext(handle_exception) as deactivate:
            gen = func(*args, **kwargs)
            if isinstance(gen, types.GeneratorType):
                runner = Runner(gen, deactivate)
                runner.run()
                return
            assert gen is None, gen
            deactivate()
            # no yield, so we're done
    return wrapper


class YieldPoint(object):
    """Base class for objects that may be yielded from the generator."""
    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`.
    """
    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`."""
    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`.

    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.
    """
    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]


class Task(YieldPoint):
    """Runs a single asynchronous operation.

    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.

    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique
    key generated automatically)::

        result = yield gen.Task(func, args)

        func(args, callback=(yield gen.Callback(key)))
        result = yield gen.Wait(key)
    """
    def __init__(self, func, *args, **kwargs):
        assert "callback" not in kwargs
        self.args = args
        self.kwargs = kwargs
        self.func = func

    def start(self, runner):
        self.runner = runner
        self.key = object()
        runner.register_callback(self.key)
        self.kwargs["callback"] = runner.result_callback(self.key)
        self.func(*self.args, **self.kwargs)

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

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


class YieldFuture(YieldPoint):
    def __init__(self, future, io_loop=None):
        self.future = future
        self.io_loop = io_loop or IOLoop.current()

    def start(self, runner):
        self.runner = runner
        self.key = object()
        runner.register_callback(self.key)
        self.io_loop.add_future(self.future, runner.result_callback(self.key))

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

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


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

    Takes a list of ``Tasks`` or other ``YieldPoints`` 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``.
    """
    def __init__(self, children):
        assert all(isinstance(i, YieldPoint) for i in children)
        self.children = children

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

    def is_ready(self):
        return all(i.is_ready() for i in self.children)

    def get_result(self):
        return [i.get_result() for i in self.children]


class _NullYieldPoint(YieldPoint):
    def start(self, runner):
        pass

    def is_ready(self):
        return True

    def get_result(self):
        return None


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

    Maintains information about pending callbacks and their results.

    ``final_callback`` is run after the generator exits.
    """
    def __init__(self, gen, final_callback):
        self.gen = gen
        self.final_callback = final_callback
        self.yield_point = _NullYieldPoint()
        self.pending_callbacks = set()
        self.results = {}
        self.running = False
        self.finished = False
        self.exc_info = None
        self.had_exception = False

    def register_callback(self, key):
        """Adds ``key`` to the list of callbacks."""
        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 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
        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:
                if self.exc_info is None:
                    try:
                        if not self.yield_point.is_ready():
                            return
                        next = self.yield_point.get_result()
                    except Exception:
                        self.exc_info = sys.exc_info()
                try:
                    if self.exc_info is not None:
                        self.had_exception = True
                        exc_info = self.exc_info
                        self.exc_info = None
                        yielded = self.gen.throw(*exc_info)
                    else:
                        yielded = self.gen.send(next)
                except StopIteration:
                    self.finished = True
                    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.final_callback()
                    self.final_callback = None
                    return
                except Exception:
                    self.finished = True
                    raise
                if isinstance(yielded, list):
                    yielded = Multi(yielded)
                if isinstance(yielded, Future):
                    # TODO: lists of futures
                    yielded = YieldFuture(yielded)
                if isinstance(yielded, YieldPoint):
                    self.yield_point = yielded
                    try:
                        self.yield_point.start(self)
                    except Exception:
                        self.exc_info = sys.exc_info()
                else:
                    self.exc_info = (BadYieldError("yielded unknown object %r" % yielded),)
        finally:
            self.running = False

    def result_callback(self, key):
        def inner(*args, **kwargs):
            if kwargs or len(args) > 1:
                result = Arguments(args, kwargs)
            elif args:
                result = args[0]
            else:
                result = None
            self.set_result(key, result)
        return inner

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

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

```
--- 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:** Yielding a List of Futures in `@gen.engine` Causes AssertionError

**Description:**
When yielding a list of `Future` objects within a function decorated with `@gen.engine`, an `AssertionError` is raised because the engine expects all yielded items to be instances of `YieldPoint`.

**Example Code:**
```python
from tornado.gen import engine, Future

@engine
def fetch_data():
    future1 = Future()
    future2 = Future()
    results = yield [future1, future2]
    # process results
```

**Expected Behavior:**
The `@gen.engine` decorator should handle a list of `Future` objects by waiting for all of them to complete and returning their results as a list.

**Actual Behavior:**
An `AssertionError` is raised with the message:
```
AssertionError
```

[/ISSUE]
{
    "GenTest.test_arguments": "PASSED",
    "GenTest.test_bogus_yield": "PASSED",
    "GenTest.test_exception_in_task_phase1": "PASSED",
    "GenTest.test_exception_in_task_phase2": "PASSED",
    "GenTest.test_exception_in_yield": "PASSED",
    "GenTest.test_exception_phase1": "PASSED",
    "GenTest.test_exception_phase2": "PASSED",
    "GenTest.test_future": "PASSED",
    "GenTest.test_inline_cb": "PASSED",
    "GenTest.test_ioloop_cb": "PASSED",
    "GenTest.test_key_mismatch": "PASSED",
    "GenTest.test_key_reuse": "PASSED",
    "GenTest.test_leaked_callback": "PASSED",
    "GenTest.test_multi": "PASSED",
    "GenTest.test_multi_delayed": "PASSED",
    "GenTest.test_multi_future": "PASSED",
    "GenTest.test_no_yield": "PASSED",
    "GenTest.test_orphaned_callback": "PASSED",
    "GenTest.test_parallel_callback": "PASSED",
    "GenTest.test_resume_after_exception_in_yield": "PASSED",
    "GenTest.test_reuse": "PASSED",
    "GenTest.test_stack_context_leak": "PASSED",
    "GenTest.test_stack_context_leak_exception": "PASSED",
    "GenTest.test_task": "PASSED",
    "GenTest.test_wait_all": "PASSED",
    "GenTest.test_with_arg": "PASSED",
    "GenWebTest.test_exception_handler": "PASSED",
    "GenWebTest.test_sequence_handler": "PASSED",
    "GenWebTest.test_task_handler": "PASSED",
    "GenWebTest.test_yield_exception_handler": "PASSED"
}
diff --git a/tornado/gen.py b/tornado/gen.py
index 320f7da6..e309bf3c 100644
--- a/tornado/gen.py
+++ b/tornado/gen.py
@@ -276,8 +276,12 @@ class Multi(YieldPoint):
     a list of ``YieldPoints``.
     """
     def __init__(self, children):
-        assert all(isinstance(i, YieldPoint) for i in children)
-        self.children = children
+        self.children = []
+        for i in children:
+            if isinstance(i, Future):
+                i = YieldFuture(i)
+            self.children.append(i)
+        assert all(isinstance(i, YieldPoint) for i in self.children)
 
     def start(self, runner):
         for i in self.children:
@@ -383,8 +387,7 @@ class Runner(object):
                     raise
                 if isinstance(yielded, list):
                     yielded = Multi(yielded)
-                if isinstance(yielded, Future):
-                    # TODO: lists of futures
+                elif isinstance(yielded, Future):
                     yielded = YieldFuture(yielded)
                 if isinstance(yielded, YieldPoint):
                     self.yield_point = yielded

{"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    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\ncould be written with ``gen`` as::\n\n    class GenAsyncHandler(RequestHandler):\n        @asynchronous\n        @gen.engine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield gen.Task(http_client.fetch, \"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n`Task` works with any function that takes a ``callback`` keyword\nargument.  You can also yield a list of ``Tasks``, which will be\nstarted at the same time and run in parallel; a list of results will\nbe returned when they are all finished::\n\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [gen.Task(http_client.fetch, url1),\n                                      gen.Task(http_client.fetch, url2)]\n\nFor more complicated interfaces, `Task` can be split into two parts:\n`Callback` and `Wait`::\n\n    class GenAsyncHandler2(RequestHandler):\n        @asynchronous\n        @gen.engine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=(yield gen.Callback(\"key\"))\n            response = yield gen.Wait(\"key\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\nThe ``key`` argument to `Callback` and `Wait` allows for multiple\nasynchronous operations to be started at different times and proceed\nin parallel: yield several callbacks with different keys, then wait\nfor them once all the async operations have started.\n\nThe result of a `Wait` or `Task` yield expression depends on how the callback\nwas run.  If it was called with no arguments, the result is ``None``.  If\nit was called with one argument, the result is that argument.  If it was\ncalled with more than one argument or any keyword arguments, the result\nis an `Arguments` object, which is a named tuple ``(args, kwargs)``.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport functools\nimport sys\nimport types\n\nfrom tornado.concurrent import Future\nfrom tornado.ioloop import IOLoop\nfrom tornado.stack_context import ExceptionStackContext\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\ndef engine(func):\n    \"\"\"Decorator for asynchronous generators.\n\n    Any generator that yields objects from this module must be wrapped\n    in this decorator.  The decorator only works on functions that are\n    already asynchronous.  For `~tornado.web.RequestHandler`\n    ``get``/``post``/etc methods, this means that both the\n    `tornado.web.asynchronous` and `tornado.gen.engine` decorators\n    must be used (for proper exception handling, ``asynchronous``\n    should come before ``gen.engine``).  In most other cases, it means\n    that it doesn't make sense to use ``gen.engine`` on functions that\n    don't already take a callback argument.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        runner = None\n\n        def handle_exception(typ, value, tb):\n            # if the function throws an exception before its first \"yield\"\n            # (or is not a generator at all), the Runner won't exist yet.\n            # However, in that case we haven't reached anything asynchronous\n            # yet, so we can just let the exception propagate.\n            if runner is not None:\n                return runner.handle_exception(typ, value, tb)\n            return False\n        with ExceptionStackContext(handle_exception) as deactivate:\n            gen = func(*args, **kwargs)\n            if isinstance(gen, types.GeneratorType):\n                runner = Runner(gen, deactivate)\n                runner.run()\n                return\n            assert gen is None, gen\n            deactivate()\n            # no yield, so we're done\n    return wrapper\n\n\nclass YieldPoint(object):\n    \"\"\"Base class for objects that may be yielded from the generator.\"\"\"\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    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    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`.\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    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\nclass Task(YieldPoint):\n    \"\"\"Runs a single asynchronous operation.\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    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique\n    key generated automatically)::\n\n        result = yield gen.Task(func, args)\n\n        func(args, callback=(yield gen.Callback(key)))\n        result = yield gen.Wait(key)\n    \"\"\"\n    def __init__(self, func, *args, **kwargs):\n        assert \"callback\" not in kwargs\n        self.args = args\n        self.kwargs = kwargs\n        self.func = func\n\n    def start(self, runner):\n        self.runner = runner\n        self.key = object()\n        runner.register_callback(self.key)\n        self.kwargs[\"callback\"] = runner.result_callback(self.key)\n        self.func(*self.args, **self.kwargs)\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 YieldFuture(YieldPoint):\n    def __init__(self, future, io_loop=None):\n        self.future = future\n        self.io_loop = io_loop or IOLoop.current()\n\n    def start(self, runner):\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\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).result()\n\n\nclass Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``Tasks`` or other ``YieldPoints`` 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``.\n    \"\"\"\n    def __init__(self, children):\n        assert all(isinstance(i, YieldPoint) for i in children)\n        self.children = children\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        return all(i.is_ready() for i in self.children)\n\n    def get_result(self):\n        return [i.get_result() for i in self.children]\n\n\nclass _NullYieldPoint(YieldPoint):\n    def start(self, runner):\n        pass\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return 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    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\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 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        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                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except StopIteration:\n                    self.finished = True\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.final_callback()\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                if isinstance(yielded, Future):\n                    # TODO: lists of futures\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\"yielded unknown object %r\" % yielded),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return inner\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False\n\nArguments = collections.namedtuple('Arguments', ['args', 'kwargs'])\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:** Yielding a List of Futures in `@gen.engine` Causes AssertionError

**Description:**
When yielding a list of `Future` objects within a function decorated with `@gen.engine`, an `AssertionError` is raised because the engine expects all yielded items to be instances of `YieldPoint`.

**Example Code:**
```python
from tornado.gen import engine, Future

@engine
def fetch_data():
    future1 = Future()
    future2 = Future()
    results = yield [future1, future2]
    # process results
```

**Expected Behavior:**
The `@gen.engine` decorator should handle a list of `Future` objects by waiting for all of them to complete and returning their results as a list.

**Actual Behavior:**
An `AssertionError` is raised with the message:
```
AssertionError
```

[/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::

    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")

could be written with ``gen`` as::

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

`Task` works with any function that takes a ``callback`` keyword
argument.  You can also yield a list of ``Tasks``, which will be
started at the same time and run in parallel; a list of results will
be returned when they are all finished::

    def get(self):
        http_client = AsyncHTTPClient()
        response1, response2 = yield [gen.Task(http_client.fetch, url1),
                                      gen.Task(http_client.fetch, url2)]

For more complicated interfaces, `Task` can be split into two parts:
`Callback` and `Wait`::

    class GenAsyncHandler2(RequestHandler):
        @asynchronous
        @gen.engine
        def get(self):
            http_client = AsyncHTTPClient()
            http_client.fetch("http://example.com",
                              callback=(yield gen.Callback("key"))
            response = yield gen.Wait("key")
            do_something_with_response(response)
            self.render("template.html")

The ``key`` argument to `Callback` and `Wait` allows for multiple
asynchronous operations to be started at different times and proceed
in parallel: yield several callbacks with different keys, then wait
for them once all the async operations have started.

The result of a `Wait` or `Task` yield expression depends on how the callback
was run.  If it was called with no arguments, the result is ``None``.  If
it was called with one argument, the result is that argument.  If it was
called with more than one argument or any keyword arguments, the result
is an `Arguments` object, which is a named tuple ``(args, kwargs)``.
"""
from __future__ import absolute_import, division, print_function, with_statement

import collections
import functools
import sys
import types

from tornado.concurrent import Future
from tornado.ioloop import IOLoop
from tornado.stack_context import ExceptionStackContext


class KeyReuseError(Exception):
    pass


class UnknownKeyError(Exception):
    pass


class LeakedCallbackError(Exception):
    pass


class BadYieldError(Exception):
    pass


def engine(func):
    """Decorator for asynchronous generators.

    Any generator that yields objects from this module must be wrapped
    in this decorator.  The decorator only works on functions that are
    already asynchronous.  For `~tornado.web.RequestHandler`
    ``get``/``post``/etc methods, this means that both the
    `tornado.web.asynchronous` and `tornado.gen.engine` decorators
    must be used (for proper exception handling, ``asynchronous``
    should come before ``gen.engine``).  In most other cases, it means
    that it doesn't make sense to use ``gen.engine`` on functions that
    don't already take a callback argument.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        runner = None

        def handle_exception(typ, value, tb):
            # if the function throws an exception before its first "yield"
            # (or is not a generator at all), the Runner won't exist yet.
            # However, in that case we haven't reached anything asynchronous
            # yet, so we can just let the exception propagate.
            if runner is not None:
                return runner.handle_exception(typ, value, tb)
            return False
        with ExceptionStackContext(handle_exception) as deactivate:
            gen = func(*args, **kwargs)
            if isinstance(gen, types.GeneratorType):
                runner = Runner(gen, deactivate)
                runner.run()
                return
            assert gen is None, gen
            deactivate()
            # no yield, so we're done
    return wrapper


class YieldPoint(object):
    """Base class for objects that may be yielded from the generator."""
    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`.
    """
    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`."""
    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`.

    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.
    """
    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]


class Task(YieldPoint):
    """Runs a single asynchronous operation.

    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.

    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique
    key generated automatically)::

        result = yield gen.Task(func, args)

        func(args, callback=(yield gen.Callback(key)))
        result = yield gen.Wait(key)
    """
    def __init__(self, func, *args, **kwargs):
        assert "callback" not in kwargs
        self.args = args
        self.kwargs = kwargs
        self.func = func

    def start(self, runner):
        self.runner = runner
        self.key = object()
        runner.register_callback(self.key)
        self.kwargs["callback"] = runner.result_callback(self.key)
        self.func(*self.args, **self.kwargs)

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

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


class YieldFuture(YieldPoint):
    def __init__(self, future, io_loop=None):
        self.future = future
        self.io_loop = io_loop or IOLoop.current()

    def start(self, runner):
        self.runner = runner
        self.key = object()
        runner.register_callback(self.key)
        self.io_loop.add_future(self.future, runner.result_callback(self.key))

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

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


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

    Takes a list of ``Tasks`` or other ``YieldPoints`` 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``.
    """
    def __init__(self, children):
        assert all(isinstance(i, YieldPoint) for i in children)
        self.children = children

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

    def is_ready(self):
        return all(i.is_ready() for i in self.children)

    def get_result(self):
        return [i.get_result() for i in self.children]


class _NullYieldPoint(YieldPoint):
    def start(self, runner):
        pass

    def is_ready(self):
        return True

    def get_result(self):
        return None


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

    Maintains information about pending callbacks and their results.

    ``final_callback`` is run after the generator exits.
    """
    def __init__(self, gen, final_callback):
        self.gen = gen
        self.final_callback = final_callback
        self.yield_point = _NullYieldPoint()
        self.pending_callbacks = set()
        self.results = {}
        self.running = False
        self.finished = False
        self.exc_info = None
        self.had_exception = False

    def register_callback(self, key):
        """Adds ``key`` to the list of callbacks."""
        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 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
        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:
                if self.exc_info is None:
                    try:
                        if not self.yield_point.is_ready():
                            return
                        next = self.yield_point.get_result()
                    except Exception:
                        self.exc_info = sys.exc_info()
                try:
                    if self.exc_info is not None:
                        self.had_exception = True
                        exc_info = self.exc_info
                        self.exc_info = None
                        yielded = self.gen.throw(*exc_info)
                    else:
                        yielded = self.gen.send(next)
                except StopIteration:
                    self.finished = True
                    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.final_callback()
                    self.final_callback = None
                    return
                except Exception:
                    self.finished = True
                    raise
                if isinstance(yielded, list):
                    yielded = Multi(yielded)
                if isinstance(yielded, Future):
                    # TODO: lists of futures
                    yielded = YieldFuture(yielded)
                if isinstance(yielded, YieldPoint):
                    self.yield_point = yielded
                    try:
                        self.yield_point.start(self)
                    except Exception:
                        self.exc_info = sys.exc_info()
                else:
                    self.exc_info = (BadYieldError("yielded unknown object %r" % yielded),)
        finally:
            self.running = False

    def result_callback(self, key):
        def inner(*args, **kwargs):
            if kwargs or len(args) > 1:
                result = Arguments(args, kwargs)
            elif args:
                result = args[0]
            else:
                result = None
            self.set_result(key, result)
        return inner

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

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

```
--- 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