{
    "file_diffs": [
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport functools\nimport sys\n\nfrom tornado.stack_context import ExceptionStackContext, wrap\nfrom tornado.util import raise_exc_info, ArgReplacer\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\nclass _DummyFuture(object):\n    def __init__(self):\n        self._done = False\n        self._result = None\n        self._exception = None\n        self._callbacks = []\n\n    def cancel(self):\n        return False\n\n    def cancelled(self):\n        return False\n\n    def running(self):\n        return not self._done\n\n    def done(self):\n        return self._done\n\n    def result(self, timeout=None):\n        self._check_done()\n        if self._exception:\n            raise self._exception\n        return self._result\n\n    def exception(self, timeout=None):\n        self._check_done()\n        if self._exception:\n            return self._exception\n        else:\n            return None\n\n    def add_done_callback(self, fn):\n        if self._done:\n            fn(self)\n        else:\n            self._callbacks.append(fn)\n\n    def set_result(self, result):\n        self._result = result\n        self._set_done()\n\n    def set_exception(self, exception):\n        self._exception = exception\n        self._set_done()\n\n    def _check_done(self):\n        if not self._done:\n            raise Exception(\"DummyFuture does not support blocking for results\")\n\n    def _set_done(self):\n        self._done = True\n        for cb in self._callbacks:\n            # TODO: error handling\n            cb(self)\n        self._callbacks = None\n\nif futures is None:\n    Future = _DummyFuture\nelse:\n    Future = futures.Future\n\n\nclass DummyExecutor(object):\n    def submit(self, fn, *args, **kwargs):\n        future = Future()\n        try:\n            future.set_result(fn(*args, **kwargs))\n        except Exception as e:\n            future.set_exception(e)\n        return future\n\ndummy_executor = DummyExecutor()\n\n\ndef run_on_executor(fn):\n    @functools.wraps(fn)\n    def wrapper(self, *args, **kwargs):\n        callback = kwargs.pop(\"callback\", None)\n        future = self.executor.submit(fn, self, *args, **kwargs)\n        if callback:\n            self.io_loop.add_future(future,\n                                    lambda future: callback(future.result()))\n        return future\n    return wrapper\n\n\ndef return_future(f):\n    \"\"\"Decorator to make a function that returns via callback return a `Future`.\n\n    The wrapped function should take a ``callback`` keyword argument\n    and invoke it with one argument when it has finished.  To signal failure,\n    the function can simply raise an exception (which will be\n    captured by the `stack_context` and passed along to the `Future`).\n\n    From the caller's perspective, the callback argument is optional.\n    If one is given, it will be invoked when the function is complete\n    with `Future.result()` as an argument.  If the function fails,\n    the callback will not be run and an exception will be raised into\n    the surrounding `StackContext`.\n\n    If no callback is given, the caller should use the `Future` to\n    wait for the function to complete (perhaps by yielding it in a\n    `gen.engine` function, or passing it to `IOLoop.add_future`).\n\n    Usage::\n        @return_future\n        def future_func(arg1, arg2, callback):\n            # Do stuff (possibly asynchronous)\n            callback(result)\n\n        @gen.engine\n        def caller(callback):\n            yield future_func(arg1, arg2)\n            callback()\n\n    Note that ``@return_future`` and ``@gen.engine`` can be applied to the\n    same function, provided ``@return_future`` appears first.  However,\n    consider using ``@gen.coroutine`` instead of this combination.\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = Future()\n        callback, args, kwargs = replacer.replace(future.set_result,\n                                                  args, kwargs)\n\n        def handle_error(typ, value, tb):\n            future.set_exception(value)\n            return True\n        exc_info = None\n        with ExceptionStackContext(handle_error):\n            try:\n                result = f(*args, **kwargs)\n                if result is not None:\n                    raise ReturnValueIgnoredError(\n                        \"@return_future should not be used with functions \"\n                        \"that return values\")\n            except:\n                exc_info = sys.exc_info()\n                raise\n        if exc_info is not None:\n            # If the initial synchronous part of f() raised an exception,\n            # go ahead and raise it to the caller directly without waiting\n            # for them to inspect the Future.\n            raise_exc_info(exc_info)\n\n        # If the caller passed in a callback, schedule it to be called\n        # when the future resolves.  It is important that this happens\n        # just before we return the future, or else we risk confusing\n        # stack contexts with multiple exceptions (one here with the\n        # immediate exception, and again when the future resolves and\n        # the callback triggers its exception by calling future.result()).\n        if callback is not None:\n            def run_callback(future):\n                callback(future.result())\n            future.add_done_callback(wrap(run_callback))\n        return future\n    return wrapper\n\ndef chain_future(a, b):\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``.\n    \"\"\"\n    def copy(future):\n        assert future is a\n        if a.exception() is not None:\n            b.set_exception(a.exception())\n        else:\n            b.set_result(a.result())\n    a.add_done_callback(copy)\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport functools\nimport sys\n\nfrom tornado.stack_context import ExceptionStackContext, wrap\nfrom tornado.util import raise_exc_info, ArgReplacer\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\nclass _DummyFuture(object):\n    def __init__(self):\n        self._done = False\n        self._result = None\n        self._exception = None\n        self._callbacks = []\n\n    def cancel(self):\n        return False\n\n    def cancelled(self):\n        return False\n\n    def running(self):\n        return not self._done\n\n    def done(self):\n        return self._done\n\n    def result(self, timeout=None):\n        self._check_done()\n        if self._exception:\n            raise self._exception\n        return self._result\n\n    def exception(self, timeout=None):\n        self._check_done()\n        if self._exception:\n            return self._exception\n        else:\n            return None\n\n    def add_done_callback(self, fn):\n        if self._done:\n            fn(self)\n        else:\n            self._callbacks.append(fn)\n\n    def set_result(self, result):\n        self._result = result\n        self._set_done()\n\n    def set_exception(self, exception):\n        self._exception = exception\n        self._set_done()\n\n    def _check_done(self):\n        if not self._done:\n            raise Exception(\"DummyFuture does not support blocking for results\")\n\n    def _set_done(self):\n        self._done = True\n        for cb in self._callbacks:\n            # TODO: error handling\n            cb(self)\n        self._callbacks = None\n\nif futures is None:\n    Future = _DummyFuture\nelse:\n    Future = futures.Future\n\n\nclass DummyExecutor(object):\n    def submit(self, fn, *args, **kwargs):\n        future = Future()\n        try:\n            future.set_result(fn(*args, **kwargs))\n        except Exception as e:\n            future.set_exception(e)\n        return future\n\ndummy_executor = DummyExecutor()\n\n\ndef run_on_executor(fn):\n    @functools.wraps(fn)\n    def wrapper(self, *args, **kwargs):\n        callback = kwargs.pop(\"callback\", None)\n        future = self.executor.submit(fn, self, *args, **kwargs)\n        if callback:\n            self.io_loop.add_future(future,\n                                    lambda future: callback(future.result()))\n        return future\n    return wrapper\n\n\ndef return_future(f):\n    \"\"\"Decorator to make a function that returns via callback return a `Future`.\n\n    The wrapped function should take a ``callback`` keyword argument\n    and invoke it with one argument when it has finished.  To signal failure,\n    the function can simply raise an exception (which will be\n    captured by the `stack_context` and passed along to the `Future`).\n\n    From the caller's perspective, the callback argument is optional.\n    If one is given, it will be invoked when the function is complete\n    with `Future.result()` as an argument.  If the function fails,\n    the callback will not be run and an exception will be raised into\n    the surrounding `StackContext`.\n\n    If no callback is given, the caller should use the `Future` to\n    wait for the function to complete (perhaps by yielding it in a\n    `gen.engine` function, or passing it to `IOLoop.add_future`).\n\n    Usage::\n        @return_future\n        def future_func(arg1, arg2, callback):\n            # Do stuff (possibly asynchronous)\n            callback(result)\n\n        @gen.engine\n        def caller(callback):\n            yield future_func(arg1, arg2)\n            callback()\n\n    Note that ``@return_future`` and ``@gen.engine`` can be applied to the\n    same function, provided ``@return_future`` appears first.  However,\n    consider using ``@gen.coroutine`` instead of this combination.\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = Future()\n        callback, args, kwargs = replacer.replace(\n            lambda value=None: future.set_result(value),\n            args, kwargs)\n\n        def handle_error(typ, value, tb):\n            future.set_exception(value)\n            return True\n        exc_info = None\n        with ExceptionStackContext(handle_error):\n            try:\n                result = f(*args, **kwargs)\n                if result is not None:\n                    raise ReturnValueIgnoredError(\n                        \"@return_future should not be used with functions \"\n                        \"that return values\")\n            except:\n                exc_info = sys.exc_info()\n                raise\n        if exc_info is not None:\n            # If the initial synchronous part of f() raised an exception,\n            # go ahead and raise it to the caller directly without waiting\n            # for them to inspect the Future.\n            raise_exc_info(exc_info)\n\n        # If the caller passed in a callback, schedule it to be called\n        # when the future resolves.  It is important that this happens\n        # just before we return the future, or else we risk confusing\n        # stack contexts with multiple exceptions (one here with the\n        # immediate exception, and again when the future resolves and\n        # the callback triggers its exception by calling future.result()).\n        if callback is not None:\n            def run_callback(future):\n                callback(future.result())\n            future.add_done_callback(wrap(run_callback))\n        return future\n    return wrapper\n\ndef chain_future(a, b):\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``.\n    \"\"\"\n    def copy(future):\n        assert future is a\n        if a.exception() is not None:\n            b.set_exception(a.exception())\n        else:\n            b.set_result(a.result())\n    a.add_done_callback(copy)\n",
            "header": {
                "file": {
                    "path": "tornado/concurrent.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "c92bda0b",
                "new_commit_hash": "2b2d06a3",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/concurrent.py"
            },
            "plus_file": {
                "path": "b/tornado/concurrent.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 153,
                            "length": 8
                        },
                        "new_range": {
                            "start": 153,
                            "length": 9
                        },
                        "section": "def return_future(f):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    @functools.wraps(f)",
                                "type": "context"
                            },
                            {
                                "content": "    def wrapper(*args, **kwargs):",
                                "type": "context"
                            },
                            {
                                "content": "        future = Future()",
                                "type": "context"
                            },
                            {
                                "content": "        callback, args, kwargs = replacer.replace(future.set_result,",
                                "type": "deleted"
                            },
                            {
                                "content": "                                                  args, kwargs)",
                                "type": "deleted"
                            },
                            {
                                "content": "        callback, args, kwargs = replacer.replace(",
                                "type": "added"
                            },
                            {
                                "content": "            lambda value=None: future.set_result(value),",
                                "type": "added"
                            },
                            {
                                "content": "            args, kwargs)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        def handle_error(typ, value, tb):",
                                "type": "context"
                            },
                            {
                                "content": "            future.set_exception(value)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/concurrent.py",
                            "type": "function",
                            "name": "return_future",
                            "content": "def return_future(f):\n    \"\"\"Decorator to make a function that returns via callback return a `Future`.\n\n    The wrapped function should take a ``callback`` keyword argument\n    and invoke it with one argument when it has finished.  To signal failure,\n    the function can simply raise an exception (which will be\n    captured by the `stack_context` and passed along to the `Future`).\n\n    From the caller's perspective, the callback argument is optional.\n    If one is given, it will be invoked when the function is complete\n    with `Future.result()` as an argument.  If the function fails,\n    the callback will not be run and an exception will be raised into\n    the surrounding `StackContext`.\n\n    If no callback is given, the caller should use the `Future` to\n    wait for the function to complete (perhaps by yielding it in a\n    `gen.engine` function, or passing it to `IOLoop.add_future`).\n\n    Usage::\n        @return_future\n        def future_func(arg1, arg2, callback):\n            # Do stuff (possibly asynchronous)\n            callback(result)\n\n        @gen.engine\n        def caller(callback):\n            yield future_func(arg1, arg2)\n            callback()\n\n    Note that ``@return_future`` and ``@gen.engine`` can be applied to the\n    same function, provided ``@return_future`` appears first.  However,\n    consider using ``@gen.coroutine`` instead of this combination.\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = Future()\n        callback, args, kwargs = replacer.replace(future.set_result,\n                                                  args, kwargs)\n\n        def handle_error(typ, value, tb):\n            future.set_exception(value)\n            return True\n        exc_info = None\n        with ExceptionStackContext(handle_error):\n            try:\n                result = f(*args, **kwargs)\n                if result is not None:\n                    raise ReturnValueIgnoredError(\n                        \"@return_future should not be used with functions \"\n                        \"that return values\")\n            except:\n                exc_info = sys.exc_info()\n                raise\n        if exc_info is not None:\n            # If the initial synchronous part of f() raised an exception,\n            # go ahead and raise it to the caller directly without waiting\n            # for them to inspect the Future.\n            raise_exc_info(exc_info)\n\n        # If the caller passed in a callback, schedule it to be called\n        # when the future resolves.  It is important that this happens\n        # just before we return the future, or else we risk confusing\n        # stack contexts with multiple exceptions (one here with the\n        # immediate exception, and again when the future resolves and\n        # the callback triggers its exception by calling future.result()).\n        if callback is not None:\n            def run_callback(future):\n                callback(future.result())\n            future.add_done_callback(wrap(run_callback))\n        return future\n    return wrapper",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 119,
                            "end_lineno": 190,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport logging\nimport re\nimport socket\n\nfrom tornado.concurrent import Future, return_future, ReturnValueIgnoredError\nfrom tornado.escape import utf8, to_unicode\nfrom tornado import gen\nfrom tornado.iostream import IOStream\nfrom tornado import stack_context\nfrom tornado.tcpserver import TCPServer\nfrom tornado.testing import AsyncTestCase, LogTrapTestCase, bind_unused_port, gen_test\n\n\nclass ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n# The following series of classes demonstrate and test various styles\n# of use, with and without generators and futures.\nclass CapServer(TCPServer):\n    def handle_stream(self, stream, address):\n        logging.info(\"handle_stream\")\n        self.stream = stream\n        self.stream.read_until(b\"\\n\", self.handle_read)\n\n    def handle_read(self, data):\n        logging.info(\"handle_read\")\n        data = to_unicode(data)\n        if data == data.upper():\n            self.stream.write(b\"error\\talready capitalized\\n\")\n        else:\n            # data already has \\n\n            self.stream.write(utf8(\"ok\\t%s\" % data.upper()))\n        self.stream.close()\n\n\nclass CapError(Exception):\n    pass\n\n\nclass BaseCapClient(object):\n    def __init__(self, port, io_loop):\n        self.port = port\n        self.io_loop = io_loop\n\n    def process_response(self, data):\n        status, message = re.match('(.*)\\t(.*)\\n', to_unicode(data)).groups()\n        if status == 'ok':\n            return message\n        else:\n            raise CapError(message)\n\n\nclass ManualCapClient(BaseCapClient):\n    def capitalize(self, request_data, callback=None):\n        logging.info(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket(), io_loop=self.io_loop)\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.future = Future()\n        if callback is not None:\n            self.future.add_done_callback(\n                stack_context.wrap(lambda future: callback(future.result())))\n        return self.future\n\n    def handle_connect(self):\n        logging.info(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.info(\"handle_read\")\n        self.stream.close()\n        try:\n            self.future.set_result(self.process_response(data))\n        except CapError as e:\n            self.future.set_exception(e)\n\n\nclass DecoratorCapClient(BaseCapClient):\n    @return_future\n    def capitalize(self, request_data, callback):\n        logging.info(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket(), io_loop=self.io_loop)\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.callback = callback\n\n    def handle_connect(self):\n        logging.info(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.info(\"handle_read\")\n        self.stream.close()\n        self.callback(self.process_response(data))\n\n\nclass GeneratorCapClient(BaseCapClient):\n    @return_future\n    @gen.engine\n    def capitalize(self, request_data, callback):\n        logging.info('capitalize')\n        stream = IOStream(socket.socket(), io_loop=self.io_loop)\n        logging.info('connecting')\n        yield gen.Task(stream.connect, ('127.0.0.1', self.port))\n        stream.write(utf8(request_data + '\\n'))\n        logging.info('reading')\n        data = yield gen.Task(stream.read_until, b'\\n')\n        logging.info('returning')\n        stream.close()\n        callback(self.process_response(data))\n\n\nclass ClientTestMixin(object):\n    def setUp(self):\n        super(ClientTestMixin, self).setUp()\n        self.server = CapServer(io_loop=self.io_loop)\n        sock, port = bind_unused_port()\n        self.server.add_sockets([sock])\n        self.client = self.client_class(io_loop=self.io_loop, port=port)\n\n    def tearDown(self):\n        self.server.stop()\n        super(ClientTestMixin, self).tearDown()\n\n    def test_callback(self):\n        self.client.capitalize(\"hello\", callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, \"HELLO\")\n\n    def test_callback_error(self):\n        self.client.capitalize(\"HELLO\", callback=self.stop)\n        self.assertRaisesRegexp(CapError, \"already capitalized\", self.wait)\n\n    def test_future(self):\n        future = self.client.capitalize(\"hello\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertEqual(future.result(), \"HELLO\")\n\n    def test_future_error(self):\n        future = self.client.capitalize(\"HELLO\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertRaisesRegexp(CapError, \"already capitalized\", future.result)\n\n    def test_generator(self):\n        @gen.engine\n        def f():\n            result = yield self.client.capitalize(\"hello\")\n            self.assertEqual(result, \"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n    def test_generator_error(self):\n        @gen.engine\n        def f():\n            with self.assertRaisesRegexp(CapError, \"already capitalized\"):\n                yield self.client.capitalize(\"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n\nclass ManualClientTest(ClientTestMixin, AsyncTestCase, LogTrapTestCase):\n    client_class = ManualCapClient\n\n\nclass DecoratorClientTest(ClientTestMixin, AsyncTestCase, LogTrapTestCase):\n    client_class = DecoratorCapClient\n\n\nclass GeneratorClientTest(ClientTestMixin, AsyncTestCase, LogTrapTestCase):\n    client_class = GeneratorCapClient\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport logging\nimport re\nimport socket\n\nfrom tornado.concurrent import Future, return_future, ReturnValueIgnoredError\nfrom tornado.escape import utf8, to_unicode\nfrom tornado import gen\nfrom tornado.iostream import IOStream\nfrom tornado import stack_context\nfrom tornado.tcpserver import TCPServer\nfrom tornado.testing import AsyncTestCase, LogTrapTestCase, bind_unused_port, gen_test\n\n\nclass ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n# The following series of classes demonstrate and test various styles\n# of use, with and without generators and futures.\nclass CapServer(TCPServer):\n    def handle_stream(self, stream, address):\n        logging.info(\"handle_stream\")\n        self.stream = stream\n        self.stream.read_until(b\"\\n\", self.handle_read)\n\n    def handle_read(self, data):\n        logging.info(\"handle_read\")\n        data = to_unicode(data)\n        if data == data.upper():\n            self.stream.write(b\"error\\talready capitalized\\n\")\n        else:\n            # data already has \\n\n            self.stream.write(utf8(\"ok\\t%s\" % data.upper()))\n        self.stream.close()\n\n\nclass CapError(Exception):\n    pass\n\n\nclass BaseCapClient(object):\n    def __init__(self, port, io_loop):\n        self.port = port\n        self.io_loop = io_loop\n\n    def process_response(self, data):\n        status, message = re.match('(.*)\\t(.*)\\n', to_unicode(data)).groups()\n        if status == 'ok':\n            return message\n        else:\n            raise CapError(message)\n\n\nclass ManualCapClient(BaseCapClient):\n    def capitalize(self, request_data, callback=None):\n        logging.info(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket(), io_loop=self.io_loop)\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.future = Future()\n        if callback is not None:\n            self.future.add_done_callback(\n                stack_context.wrap(lambda future: callback(future.result())))\n        return self.future\n\n    def handle_connect(self):\n        logging.info(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.info(\"handle_read\")\n        self.stream.close()\n        try:\n            self.future.set_result(self.process_response(data))\n        except CapError as e:\n            self.future.set_exception(e)\n\n\nclass DecoratorCapClient(BaseCapClient):\n    @return_future\n    def capitalize(self, request_data, callback):\n        logging.info(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket(), io_loop=self.io_loop)\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.callback = callback\n\n    def handle_connect(self):\n        logging.info(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.info(\"handle_read\")\n        self.stream.close()\n        self.callback(self.process_response(data))\n\n\nclass GeneratorCapClient(BaseCapClient):\n    @return_future\n    @gen.engine\n    def capitalize(self, request_data, callback):\n        logging.info('capitalize')\n        stream = IOStream(socket.socket(), io_loop=self.io_loop)\n        logging.info('connecting')\n        yield gen.Task(stream.connect, ('127.0.0.1', self.port))\n        stream.write(utf8(request_data + '\\n'))\n        logging.info('reading')\n        data = yield gen.Task(stream.read_until, b'\\n')\n        logging.info('returning')\n        stream.close()\n        callback(self.process_response(data))\n\n\nclass ClientTestMixin(object):\n    def setUp(self):\n        super(ClientTestMixin, self).setUp()\n        self.server = CapServer(io_loop=self.io_loop)\n        sock, port = bind_unused_port()\n        self.server.add_sockets([sock])\n        self.client = self.client_class(io_loop=self.io_loop, port=port)\n\n    def tearDown(self):\n        self.server.stop()\n        super(ClientTestMixin, self).tearDown()\n\n    def test_callback(self):\n        self.client.capitalize(\"hello\", callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, \"HELLO\")\n\n    def test_callback_error(self):\n        self.client.capitalize(\"HELLO\", callback=self.stop)\n        self.assertRaisesRegexp(CapError, \"already capitalized\", self.wait)\n\n    def test_future(self):\n        future = self.client.capitalize(\"hello\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertEqual(future.result(), \"HELLO\")\n\n    def test_future_error(self):\n        future = self.client.capitalize(\"HELLO\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertRaisesRegexp(CapError, \"already capitalized\", future.result)\n\n    def test_generator(self):\n        @gen.engine\n        def f():\n            result = yield self.client.capitalize(\"hello\")\n            self.assertEqual(result, \"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n    def test_generator_error(self):\n        @gen.engine\n        def f():\n            with self.assertRaisesRegexp(CapError, \"already capitalized\"):\n                yield self.client.capitalize(\"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n\nclass ManualClientTest(ClientTestMixin, AsyncTestCase, LogTrapTestCase):\n    client_class = ManualCapClient\n\n\nclass DecoratorClientTest(ClientTestMixin, AsyncTestCase, LogTrapTestCase):\n    client_class = DecoratorCapClient\n\n\nclass GeneratorClientTest(ClientTestMixin, AsyncTestCase, LogTrapTestCase):\n    client_class = GeneratorCapClient\n",
            "header": {
                "file": {
                    "path": "tornado/test/concurrent_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "8e758404",
                "new_commit_hash": "4e5380e8",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/concurrent_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/concurrent_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 52,
                            "length": 6
                        },
                        "new_range": {
                            "start": 52,
                            "length": 10
                        },
                        "section": "class ReturnFutureTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        # implementations the last event prior to callback resolution wins.",
                                "type": "context"
                            },
                            {
                                "content": "        return 42",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @return_future",
                                "type": "added"
                            },
                            {
                                "content": "    def no_result_future(self, callback):",
                                "type": "added"
                            },
                            {
                                "content": "        callback()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_immediate_failure(self):",
                                "type": "context"
                            },
                            {
                                "content": "        with self.assertRaises(ZeroDivisionError):",
                                "type": "context"
                            },
                            {
                                "content": "            # The caller sees the error just like a normal function.",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/concurrent_test.py",
                            "type": "class",
                            "name": "ReturnFutureTest",
                            "content": "class ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 31,
                            "end_lineno": 136,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/concurrent_test.py",
                            "type": "method",
                            "name": "ReturnFutureTest.no_result_future",
                            "content": "class ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 56,
                            "end_lineno": 57,
                            "parent": {
                                "file_name": "tornado/test/concurrent_test.py",
                                "type": "class",
                                "name": "ReturnFutureTest",
                                "content": "class ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 31,
                                "end_lineno": 136,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 126,
                            "length": 6
                        },
                        "new_range": {
                            "start": 130,
                            "length": 11
                        },
                        "section": "class ReturnFutureTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        # when we wait.",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertRaises(ZeroDivisionError, self.wait)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_no_result_future(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.no_result_future(self.stop)",
                                "type": "added"
                            },
                            {
                                "content": "        result = self.wait()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIs(result, None)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "# The following series of classes demonstrate and test various styles",
                                "type": "context"
                            },
                            {
                                "content": "# of use, with and without generators and futures.",
                                "type": "context"
                            },
                            {
                                "content": "class CapServer(TCPServer):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/concurrent_test.py",
                            "type": "class",
                            "name": "ReturnFutureTest",
                            "content": "class ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 31,
                            "end_lineno": 136,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/concurrent_test.py",
                            "type": "method",
                            "name": "ReturnFutureTest.test_no_result_future",
                            "content": "class ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 133,
                            "end_lineno": 136,
                            "parent": {
                                "file_name": "tornado/test/concurrent_test.py",
                                "type": "class",
                                "name": "ReturnFutureTest",
                                "content": "class ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 31,
                                "end_lineno": 136,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "94a5a4027210d082115f96308fd5527cb82b6e33^",
    "new_commit_hash": "94a5a4027210d082115f96308fd5527cb82b6e33",
    "commit_message": "Allow the callback in @return_future to be run with no arguments.",
    "commit_date": "2013-03-03T19:29:39-05:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "94a5a4027210d082115f96308fd5527cb82b6e33",
    "test_file_codes": [
        "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport logging\nimport re\nimport socket\n\nfrom tornado.concurrent import Future, return_future, ReturnValueIgnoredError\nfrom tornado.escape import utf8, to_unicode\nfrom tornado import gen\nfrom tornado.iostream import IOStream\nfrom tornado import stack_context\nfrom tornado.tcpserver import TCPServer\nfrom tornado.testing import AsyncTestCase, LogTrapTestCase, bind_unused_port, gen_test\n\n\nclass ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n# The following series of classes demonstrate and test various styles\n# of use, with and without generators and futures.\nclass CapServer(TCPServer):\n    def handle_stream(self, stream, address):\n        logging.info(\"handle_stream\")\n        self.stream = stream\n        self.stream.read_until(b\"\\n\", self.handle_read)\n\n    def handle_read(self, data):\n        logging.info(\"handle_read\")\n        data = to_unicode(data)\n        if data == data.upper():\n            self.stream.write(b\"error\\talready capitalized\\n\")\n        else:\n            # data already has \\n\n            self.stream.write(utf8(\"ok\\t%s\" % data.upper()))\n        self.stream.close()\n\n\nclass CapError(Exception):\n    pass\n\n\nclass BaseCapClient(object):\n    def __init__(self, port, io_loop):\n        self.port = port\n        self.io_loop = io_loop\n\n    def process_response(self, data):\n        status, message = re.match('(.*)\\t(.*)\\n', to_unicode(data)).groups()\n        if status == 'ok':\n            return message\n        else:\n            raise CapError(message)\n\n\nclass ManualCapClient(BaseCapClient):\n    def capitalize(self, request_data, callback=None):\n        logging.info(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket(), io_loop=self.io_loop)\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.future = Future()\n        if callback is not None:\n            self.future.add_done_callback(\n                stack_context.wrap(lambda future: callback(future.result())))\n        return self.future\n\n    def handle_connect(self):\n        logging.info(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.info(\"handle_read\")\n        self.stream.close()\n        try:\n            self.future.set_result(self.process_response(data))\n        except CapError as e:\n            self.future.set_exception(e)\n\n\nclass DecoratorCapClient(BaseCapClient):\n    @return_future\n    def capitalize(self, request_data, callback):\n        logging.info(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket(), io_loop=self.io_loop)\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.callback = callback\n\n    def handle_connect(self):\n        logging.info(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.info(\"handle_read\")\n        self.stream.close()\n        self.callback(self.process_response(data))\n\n\nclass GeneratorCapClient(BaseCapClient):\n    @return_future\n    @gen.engine\n    def capitalize(self, request_data, callback):\n        logging.info('capitalize')\n        stream = IOStream(socket.socket(), io_loop=self.io_loop)\n        logging.info('connecting')\n        yield gen.Task(stream.connect, ('127.0.0.1', self.port))\n        stream.write(utf8(request_data + '\\n'))\n        logging.info('reading')\n        data = yield gen.Task(stream.read_until, b'\\n')\n        logging.info('returning')\n        stream.close()\n        callback(self.process_response(data))\n\n\nclass ClientTestMixin(object):\n    def setUp(self):\n        super(ClientTestMixin, self).setUp()\n        self.server = CapServer(io_loop=self.io_loop)\n        sock, port = bind_unused_port()\n        self.server.add_sockets([sock])\n        self.client = self.client_class(io_loop=self.io_loop, port=port)\n\n    def tearDown(self):\n        self.server.stop()\n        super(ClientTestMixin, self).tearDown()\n\n    def test_callback(self):\n        self.client.capitalize(\"hello\", callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, \"HELLO\")\n\n    def test_callback_error(self):\n        self.client.capitalize(\"HELLO\", callback=self.stop)\n        self.assertRaisesRegexp(CapError, \"already capitalized\", self.wait)\n\n    def test_future(self):\n        future = self.client.capitalize(\"hello\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertEqual(future.result(), \"HELLO\")\n\n    def test_future_error(self):\n        future = self.client.capitalize(\"HELLO\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertRaisesRegexp(CapError, \"already capitalized\", future.result)\n\n    def test_generator(self):\n        @gen.engine\n        def f():\n            result = yield self.client.capitalize(\"hello\")\n            self.assertEqual(result, \"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n    def test_generator_error(self):\n        @gen.engine\n        def f():\n            with self.assertRaisesRegexp(CapError, \"already capitalized\"):\n                yield self.client.capitalize(\"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n\nclass ManualClientTest(ClientTestMixin, AsyncTestCase, LogTrapTestCase):\n    client_class = ManualCapClient\n\n\nclass DecoratorClientTest(ClientTestMixin, AsyncTestCase, LogTrapTestCase):\n    client_class = DecoratorCapClient\n\n\nclass GeneratorClientTest(ClientTestMixin, AsyncTestCase, LogTrapTestCase):\n    client_class = GeneratorCapClient\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 804ms\nPrepared 1 package in 678ms\nInstalled 1 package in 1ms\n + tornado==2.4.post4 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_94a5a4027210d082115f96308fd5527cb82b6e33)\nResolved 29 packages in 16ms\nInstalled 29 packages in 54ms\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_94a5a4027210d082115f96308fd5527cb82b6e33\n...............................\ncollected 31 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::DecoratorClientTest::test_callback\nPASSED r2e_tests.test_1::DecoratorClientTest::test_callback_error\nPASSED r2e_tests.test_1::DecoratorClientTest::test_future\nPASSED r2e_tests.test_1::DecoratorClientTest::test_future_error\nPASSED r2e_tests.test_1::DecoratorClientTest::test_generator\nPASSED r2e_tests.test_1::DecoratorClientTest::test_generator_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_callback\nPASSED r2e_tests.test_1::GeneratorClientTest::test_callback_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_future\nPASSED r2e_tests.test_1::GeneratorClientTest::test_future_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_generator\nPASSED r2e_tests.test_1::GeneratorClientTest::test_generator_error\nPASSED r2e_tests.test_1::ManualClientTest::test_callback\nPASSED r2e_tests.test_1::ManualClientTest::test_callback_error\nPASSED r2e_tests.test_1::ManualClientTest::test_future\nPASSED r2e_tests.test_1::ManualClientTest::test_future_error\nPASSED r2e_tests.test_1::ManualClientTest::test_generator\nPASSED r2e_tests.test_1::ManualClientTest::test_generator_error\nPASSED r2e_tests.test_1::ReturnFutureTest::test_async_future\nPASSED r2e_tests.test_1::ReturnFutureTest::test_async_future_gen\nPASSED r2e_tests.test_1::ReturnFutureTest::test_callback_kw\nPASSED r2e_tests.test_1::ReturnFutureTest::test_callback_positional\nPASSED r2e_tests.test_1::ReturnFutureTest::test_delayed_failure\nPASSED r2e_tests.test_1::ReturnFutureTest::test_error_in_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_immediate_failure\nPASSED r2e_tests.test_1::ReturnFutureTest::test_kw_only_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_no_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_no_result_future\nPASSED r2e_tests.test_1::ReturnFutureTest::test_none_callback_kw\nPASSED r2e_tests.test_1::ReturnFutureTest::test_none_callback_pos\nPASSED r2e_tests.test_1::ReturnFutureTest::test_return_value\n=================== 31 passed in 0.07s ===================\n",
    "new_commit_res_stderr": "",
    "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_94a5a4027210d082115f96308fd5527cb82b6e33\n...............................\ncollected 31 items\n\n=================================== ERRORS =====================================\n__________ ReturnFutureTest.test_no_result_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_94a5a4027210d082115f96308fd5527cb82b6e33/r2e_tests/test_1.py\", line 134, in test_no_result_future\n    self.no_result_future(self.stop)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_94a5a4027210d082115f96308fd5527cb82b6e33/tornado/concurrent.py\", line 177, in wrapper\n    raise_exc_info(exc_info)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_94a5a4027210d082115f96308fd5527cb82b6e33/tornado/concurrent.py\", line 165, in wrapper\n    result = f(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_94a5a4027210d082115f96308fd5527cb82b6e33/r2e_tests/test_1.py\", line 57, in no_result_future\n    callback()\nTypeError: set_result() missing 1 required positional argument: 'result'\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::DecoratorClientTest::test_callback\nPASSED r2e_tests.test_1::DecoratorClientTest::test_callback_error\nPASSED r2e_tests.test_1::DecoratorClientTest::test_future\nPASSED r2e_tests.test_1::DecoratorClientTest::test_future_error\nPASSED r2e_tests.test_1::DecoratorClientTest::test_generator\nPASSED r2e_tests.test_1::DecoratorClientTest::test_generator_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_callback\nPASSED r2e_tests.test_1::GeneratorClientTest::test_callback_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_future\nPASSED r2e_tests.test_1::GeneratorClientTest::test_future_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_generator\nPASSED r2e_tests.test_1::GeneratorClientTest::test_generator_error\nPASSED r2e_tests.test_1::ManualClientTest::test_callback\nPASSED r2e_tests.test_1::ManualClientTest::test_callback_error\nPASSED r2e_tests.test_1::ManualClientTest::test_future\nPASSED r2e_tests.test_1::ManualClientTest::test_future_error\nPASSED r2e_tests.test_1::ManualClientTest::test_generator\nPASSED r2e_tests.test_1::ManualClientTest::test_generator_error\nPASSED r2e_tests.test_1::ReturnFutureTest::test_async_future\nPASSED r2e_tests.test_1::ReturnFutureTest::test_async_future_gen\nPASSED r2e_tests.test_1::ReturnFutureTest::test_callback_kw\nPASSED r2e_tests.test_1::ReturnFutureTest::test_callback_positional\nPASSED r2e_tests.test_1::ReturnFutureTest::test_delayed_failure\nPASSED r2e_tests.test_1::ReturnFutureTest::test_error_in_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_immediate_failure\nPASSED r2e_tests.test_1::ReturnFutureTest::test_kw_only_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_no_callback\nERROR r2e_tests.test_1::ReturnFutureTest::test_no_result_future\nPASSED r2e_tests.test_1::ReturnFutureTest::test_none_callback_kw\nPASSED r2e_tests.test_1::ReturnFutureTest::test_none_callback_pos\nPASSED r2e_tests.test_1::ReturnFutureTest::test_return_value\n=================== 1 error, 30 passed in 0.07s ===================\n",
    "old_commit_res_stderr": ""
}
tornado/concurrent.py tornado/test/concurrent_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Calling callback without arguments causes TypeError in `@return_future` decorated functions

**Description:**
When using the `@return_future` decorator, invoking the callback without any arguments results in a `TypeError`. This occurs because the callback expects a `result` argument, and calling it without one leads to an exception.

**Buggy Code Example:**
```python
from tornado.concurrent import return_future

@return_future
def no_result_future(callback):
    callback()  # Called without arguments
```

**Expected Behavior:**
Calling the `no_result_future` function without providing any arguments to the callback should set the future's result to `None` without raising any errors.

**Actual Behavior:**
Invoking the callback without arguments raises the following error:
```
TypeError: set_result() missing 1 required positional argument: 'result'
```

[/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/concurrent.py
#!/usr/bin/env python
#
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, with_statement

import functools
import sys

from tornado.stack_context import ExceptionStackContext, wrap
from tornado.util import raise_exc_info, ArgReplacer

try:
    from concurrent import futures
except ImportError:
    futures = None

class ReturnValueIgnoredError(Exception):
    pass

class _DummyFuture(object):
    def __init__(self):
        self._done = False
        self._result = None
        self._exception = None
        self._callbacks = []

    def cancel(self):
        return False

    def cancelled(self):
        return False

    def running(self):
        return not self._done

    def done(self):
        return self._done

    def result(self, timeout=None):
        self._check_done()
        if self._exception:
            raise self._exception
        return self._result

    def exception(self, timeout=None):
        self._check_done()
        if self._exception:
            return self._exception
        else:
            return None

    def add_done_callback(self, fn):
        if self._done:
            fn(self)
        else:
            self._callbacks.append(fn)

    def set_result(self, result):
        self._result = result
        self._set_done()

    def set_exception(self, exception):
        self._exception = exception
        self._set_done()

    def _check_done(self):
        if not self._done:
            raise Exception("DummyFuture does not support blocking for results")

    def _set_done(self):
        self._done = True
        for cb in self._callbacks:
            # TODO: error handling
            cb(self)
        self._callbacks = None

if futures is None:
    Future = _DummyFuture
else:
    Future = futures.Future


class DummyExecutor(object):
    def submit(self, fn, *args, **kwargs):
        future = Future()
        try:
            future.set_result(fn(*args, **kwargs))
        except Exception as e:
            future.set_exception(e)
        return future

dummy_executor = DummyExecutor()


def run_on_executor(fn):
    @functools.wraps(fn)
    def wrapper(self, *args, **kwargs):
        callback = kwargs.pop("callback", None)
        future = self.executor.submit(fn, self, *args, **kwargs)
        if callback:
            self.io_loop.add_future(future,
                                    lambda future: callback(future.result()))
        return future
    return wrapper


def return_future(f):
    """Decorator to make a function that returns via callback return a `Future`.

    The wrapped function should take a ``callback`` keyword argument
    and invoke it with one argument when it has finished.  To signal failure,
    the function can simply raise an exception (which will be
    captured by the `stack_context` and passed along to the `Future`).

    From the caller's perspective, the callback argument is optional.
    If one is given, it will be invoked when the function is complete
    with `Future.result()` as an argument.  If the function fails,
    the callback will not be run and an exception will be raised into
    the surrounding `StackContext`.

    If no callback is given, the caller should use the `Future` to
    wait for the function to complete (perhaps by yielding it in a
    `gen.engine` function, or passing it to `IOLoop.add_future`).

    Usage::
        @return_future
        def future_func(arg1, arg2, callback):
            # Do stuff (possibly asynchronous)
            callback(result)

        @gen.engine
        def caller(callback):
            yield future_func(arg1, arg2)
            callback()

    Note that ``@return_future`` and ``@gen.engine`` can be applied to the
    same function, provided ``@return_future`` appears first.  However,
    consider using ``@gen.coroutine`` instead of this combination.
    """
    replacer = ArgReplacer(f, 'callback')
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        future = Future()
        callback, args, kwargs = replacer.replace(future.set_result,
                                                  args, kwargs)

        def handle_error(typ, value, tb):
            future.set_exception(value)
            return True
        exc_info = None
        with ExceptionStackContext(handle_error):
            try:
                result = f(*args, **kwargs)
                if result is not None:
                    raise ReturnValueIgnoredError(
                        "@return_future should not be used with functions "
                        "that return values")
            except:
                exc_info = sys.exc_info()
                raise
        if exc_info is not None:
            # If the initial synchronous part of f() raised an exception,
            # go ahead and raise it to the caller directly without waiting
            # for them to inspect the Future.
            raise_exc_info(exc_info)

        # If the caller passed in a callback, schedule it to be called
        # when the future resolves.  It is important that this happens
        # just before we return the future, or else we risk confusing
        # stack contexts with multiple exceptions (one here with the
        # immediate exception, and again when the future resolves and
        # the callback triggers its exception by calling future.result()).
        if callback is not None:
            def run_callback(future):
                callback(future.result())
            future.add_done_callback(wrap(run_callback))
        return future
    return wrapper

def chain_future(a, b):
    """Chain two futures together so that when one completes, so does the other.

    The result (success or failure) of ``a`` will be copied to ``b``.
    """
    def copy(future):
        assert future is a
        if a.exception() is not None:
            b.set_exception(a.exception())
        else:
            b.set_result(a.result())
    a.add_done_callback(copy)

```
--- 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:** Calling callback without arguments causes TypeError in `@return_future` decorated functions

**Description:**
When using the `@return_future` decorator, invoking the callback without any arguments results in a `TypeError`. This occurs because the callback expects a `result` argument, and calling it without one leads to an exception.

**Buggy Code Example:**
```python
from tornado.concurrent import return_future

@return_future
def no_result_future(callback):
    callback()  # Called without arguments
```

**Expected Behavior:**
Calling the `no_result_future` function without providing any arguments to the callback should set the future's result to `None` without raising any errors.

**Actual Behavior:**
Invoking the callback without arguments raises the following error:
```
TypeError: set_result() missing 1 required positional argument: 'result'
```

[/ISSUE]
{
    "DecoratorClientTest.test_callback": "PASSED",
    "DecoratorClientTest.test_callback_error": "PASSED",
    "DecoratorClientTest.test_future": "PASSED",
    "DecoratorClientTest.test_future_error": "PASSED",
    "DecoratorClientTest.test_generator": "PASSED",
    "DecoratorClientTest.test_generator_error": "PASSED",
    "GeneratorClientTest.test_callback": "PASSED",
    "GeneratorClientTest.test_callback_error": "PASSED",
    "GeneratorClientTest.test_future": "PASSED",
    "GeneratorClientTest.test_future_error": "PASSED",
    "GeneratorClientTest.test_generator": "PASSED",
    "GeneratorClientTest.test_generator_error": "PASSED",
    "ManualClientTest.test_callback": "PASSED",
    "ManualClientTest.test_callback_error": "PASSED",
    "ManualClientTest.test_future": "PASSED",
    "ManualClientTest.test_future_error": "PASSED",
    "ManualClientTest.test_generator": "PASSED",
    "ManualClientTest.test_generator_error": "PASSED",
    "ReturnFutureTest.test_async_future": "PASSED",
    "ReturnFutureTest.test_async_future_gen": "PASSED",
    "ReturnFutureTest.test_callback_kw": "PASSED",
    "ReturnFutureTest.test_callback_positional": "PASSED",
    "ReturnFutureTest.test_delayed_failure": "PASSED",
    "ReturnFutureTest.test_error_in_callback": "PASSED",
    "ReturnFutureTest.test_immediate_failure": "PASSED",
    "ReturnFutureTest.test_kw_only_callback": "PASSED",
    "ReturnFutureTest.test_no_callback": "PASSED",
    "ReturnFutureTest.test_no_result_future": "PASSED",
    "ReturnFutureTest.test_none_callback_kw": "PASSED",
    "ReturnFutureTest.test_none_callback_pos": "PASSED",
    "ReturnFutureTest.test_return_value": "PASSED"
}
diff --git a/tornado/concurrent.py b/tornado/concurrent.py
index c92bda0b..2b2d06a3 100644
--- a/tornado/concurrent.py
+++ b/tornado/concurrent.py
@@ -153,8 +153,9 @@ def return_future(f):
     @functools.wraps(f)
     def wrapper(*args, **kwargs):
         future = Future()
-        callback, args, kwargs = replacer.replace(future.set_result,
-                                                  args, kwargs)
+        callback, args, kwargs = replacer.replace(
+            lambda value=None: future.set_result(value),
+            args, kwargs)
 
         def handle_error(typ, value, tb):
             future.set_exception(value)

{"tornado/concurrent.py": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport functools\nimport sys\n\nfrom tornado.stack_context import ExceptionStackContext, wrap\nfrom tornado.util import raise_exc_info, ArgReplacer\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\nclass _DummyFuture(object):\n    def __init__(self):\n        self._done = False\n        self._result = None\n        self._exception = None\n        self._callbacks = []\n\n    def cancel(self):\n        return False\n\n    def cancelled(self):\n        return False\n\n    def running(self):\n        return not self._done\n\n    def done(self):\n        return self._done\n\n    def result(self, timeout=None):\n        self._check_done()\n        if self._exception:\n            raise self._exception\n        return self._result\n\n    def exception(self, timeout=None):\n        self._check_done()\n        if self._exception:\n            return self._exception\n        else:\n            return None\n\n    def add_done_callback(self, fn):\n        if self._done:\n            fn(self)\n        else:\n            self._callbacks.append(fn)\n\n    def set_result(self, result):\n        self._result = result\n        self._set_done()\n\n    def set_exception(self, exception):\n        self._exception = exception\n        self._set_done()\n\n    def _check_done(self):\n        if not self._done:\n            raise Exception(\"DummyFuture does not support blocking for results\")\n\n    def _set_done(self):\n        self._done = True\n        for cb in self._callbacks:\n            # TODO: error handling\n            cb(self)\n        self._callbacks = None\n\nif futures is None:\n    Future = _DummyFuture\nelse:\n    Future = futures.Future\n\n\nclass DummyExecutor(object):\n    def submit(self, fn, *args, **kwargs):\n        future = Future()\n        try:\n            future.set_result(fn(*args, **kwargs))\n        except Exception as e:\n            future.set_exception(e)\n        return future\n\ndummy_executor = DummyExecutor()\n\n\ndef run_on_executor(fn):\n    @functools.wraps(fn)\n    def wrapper(self, *args, **kwargs):\n        callback = kwargs.pop(\"callback\", None)\n        future = self.executor.submit(fn, self, *args, **kwargs)\n        if callback:\n            self.io_loop.add_future(future,\n                                    lambda future: callback(future.result()))\n        return future\n    return wrapper\n\n\ndef return_future(f):\n    \"\"\"Decorator to make a function that returns via callback return a `Future`.\n\n    The wrapped function should take a ``callback`` keyword argument\n    and invoke it with one argument when it has finished.  To signal failure,\n    the function can simply raise an exception (which will be\n    captured by the `stack_context` and passed along to the `Future`).\n\n    From the caller's perspective, the callback argument is optional.\n    If one is given, it will be invoked when the function is complete\n    with `Future.result()` as an argument.  If the function fails,\n    the callback will not be run and an exception will be raised into\n    the surrounding `StackContext`.\n\n    If no callback is given, the caller should use the `Future` to\n    wait for the function to complete (perhaps by yielding it in a\n    `gen.engine` function, or passing it to `IOLoop.add_future`).\n\n    Usage::\n        @return_future\n        def future_func(arg1, arg2, callback):\n            # Do stuff (possibly asynchronous)\n            callback(result)\n\n        @gen.engine\n        def caller(callback):\n            yield future_func(arg1, arg2)\n            callback()\n\n    Note that ``@return_future`` and ``@gen.engine`` can be applied to the\n    same function, provided ``@return_future`` appears first.  However,\n    consider using ``@gen.coroutine`` instead of this combination.\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = Future()\n        callback, args, kwargs = replacer.replace(future.set_result,\n                                                  args, kwargs)\n\n        def handle_error(typ, value, tb):\n            future.set_exception(value)\n            return True\n        exc_info = None\n        with ExceptionStackContext(handle_error):\n            try:\n                result = f(*args, **kwargs)\n                if result is not None:\n                    raise ReturnValueIgnoredError(\n                        \"@return_future should not be used with functions \"\n                        \"that return values\")\n            except:\n                exc_info = sys.exc_info()\n                raise\n        if exc_info is not None:\n            # If the initial synchronous part of f() raised an exception,\n            # go ahead and raise it to the caller directly without waiting\n            # for them to inspect the Future.\n            raise_exc_info(exc_info)\n\n        # If the caller passed in a callback, schedule it to be called\n        # when the future resolves.  It is important that this happens\n        # just before we return the future, or else we risk confusing\n        # stack contexts with multiple exceptions (one here with the\n        # immediate exception, and again when the future resolves and\n        # the callback triggers its exception by calling future.result()).\n        if callback is not None:\n            def run_callback(future):\n                callback(future.result())\n            future.add_done_callback(wrap(run_callback))\n        return future\n    return wrapper\n\ndef chain_future(a, b):\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``.\n    \"\"\"\n    def copy(future):\n        assert future is a\n        if a.exception() is not None:\n            b.set_exception(a.exception())\n        else:\n            b.set_result(a.result())\n    a.add_done_callback(copy)\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:** Calling callback without arguments causes TypeError in `@return_future` decorated functions

**Description:**
When using the `@return_future` decorator, invoking the callback without any arguments results in a `TypeError`. This occurs because the callback expects a `result` argument, and calling it without one leads to an exception.

**Buggy Code Example:**
```python
from tornado.concurrent import return_future

@return_future
def no_result_future(callback):
    callback()  # Called without arguments
```

**Expected Behavior:**
Calling the `no_result_future` function without providing any arguments to the callback should set the future's result to `None` without raising any errors.

**Actual Behavior:**
Invoking the callback without arguments raises the following error:
```
TypeError: set_result() missing 1 required positional argument: 'result'
```

[/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/concurrent.py
#!/usr/bin/env python
#
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, with_statement

import functools
import sys

from tornado.stack_context import ExceptionStackContext, wrap
from tornado.util import raise_exc_info, ArgReplacer

try:
    from concurrent import futures
except ImportError:
    futures = None

class ReturnValueIgnoredError(Exception):
    pass

class _DummyFuture(object):
    def __init__(self):
        self._done = False
        self._result = None
        self._exception = None
        self._callbacks = []

    def cancel(self):
        return False

    def cancelled(self):
        return False

    def running(self):
        return not self._done

    def done(self):
        return self._done

    def result(self, timeout=None):
        self._check_done()
        if self._exception:
            raise self._exception
        return self._result

    def exception(self, timeout=None):
        self._check_done()
        if self._exception:
            return self._exception
        else:
            return None

    def add_done_callback(self, fn):
        if self._done:
            fn(self)
        else:
            self._callbacks.append(fn)

    def set_result(self, result):
        self._result = result
        self._set_done()

    def set_exception(self, exception):
        self._exception = exception
        self._set_done()

    def _check_done(self):
        if not self._done:
            raise Exception("DummyFuture does not support blocking for results")

    def _set_done(self):
        self._done = True
        for cb in self._callbacks:
            # TODO: error handling
            cb(self)
        self._callbacks = None

if futures is None:
    Future = _DummyFuture
else:
    Future = futures.Future


class DummyExecutor(object):
    def submit(self, fn, *args, **kwargs):
        future = Future()
        try:
            future.set_result(fn(*args, **kwargs))
        except Exception as e:
            future.set_exception(e)
        return future

dummy_executor = DummyExecutor()


def run_on_executor(fn):
    @functools.wraps(fn)
    def wrapper(self, *args, **kwargs):
        callback = kwargs.pop("callback", None)
        future = self.executor.submit(fn, self, *args, **kwargs)
        if callback:
            self.io_loop.add_future(future,
                                    lambda future: callback(future.result()))
        return future
    return wrapper


def return_future(f):
    """Decorator to make a function that returns via callback return a `Future`.

    The wrapped function should take a ``callback`` keyword argument
    and invoke it with one argument when it has finished.  To signal failure,
    the function can simply raise an exception (which will be
    captured by the `stack_context` and passed along to the `Future`).

    From the caller's perspective, the callback argument is optional.
    If one is given, it will be invoked when the function is complete
    with `Future.result()` as an argument.  If the function fails,
    the callback will not be run and an exception will be raised into
    the surrounding `StackContext`.

    If no callback is given, the caller should use the `Future` to
    wait for the function to complete (perhaps by yielding it in a
    `gen.engine` function, or passing it to `IOLoop.add_future`).

    Usage::
        @return_future
        def future_func(arg1, arg2, callback):
            # Do stuff (possibly asynchronous)
            callback(result)

        @gen.engine
        def caller(callback):
            yield future_func(arg1, arg2)
            callback()

    Note that ``@return_future`` and ``@gen.engine`` can be applied to the
    same function, provided ``@return_future`` appears first.  However,
    consider using ``@gen.coroutine`` instead of this combination.
    """
    replacer = ArgReplacer(f, 'callback')
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        future = Future()
        callback, args, kwargs = replacer.replace(future.set_result,
                                                  args, kwargs)

        def handle_error(typ, value, tb):
            future.set_exception(value)
            return True
        exc_info = None
        with ExceptionStackContext(handle_error):
            try:
                result = f(*args, **kwargs)
                if result is not None:
                    raise ReturnValueIgnoredError(
                        "@return_future should not be used with functions "
                        "that return values")
            except:
                exc_info = sys.exc_info()
                raise
        if exc_info is not None:
            # If the initial synchronous part of f() raised an exception,
            # go ahead and raise it to the caller directly without waiting
            # for them to inspect the Future.
            raise_exc_info(exc_info)

        # If the caller passed in a callback, schedule it to be called
        # when the future resolves.  It is important that this happens
        # just before we return the future, or else we risk confusing
        # stack contexts with multiple exceptions (one here with the
        # immediate exception, and again when the future resolves and
        # the callback triggers its exception by calling future.result()).
        if callback is not None:
            def run_callback(future):
                callback(future.result())
            future.add_done_callback(wrap(run_callback))
        return future
    return wrapper

def chain_future(a, b):
    """Chain two futures together so that when one completes, so does the other.

    The result (success or failure) of ``a`` will be copied to ``b``.
    """
    def copy(future):
        assert future is a
        if a.exception() is not None:
            b.set_exception(a.exception())
        else:
            b.set_result(a.result())
    a.add_done_callback(copy)

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