{
    "file_diffs": [
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function\n\nfrom tornado import gen, ioloop\nfrom tornado.log import app_log\nfrom tornado.test.util import unittest, skipBefore35, exec_test\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, bind_unused_port, gen_test, ExpectLog\nfrom tornado.web import Application\nimport contextlib\nimport os\nimport platform\nimport traceback\nimport warnings\n\n\n@contextlib.contextmanager\ndef set_environ(name, value):\n    old_value = os.environ.get(name)\n    os.environ[name] = value\n\n    try:\n        yield\n    finally:\n        if old_value is None:\n            del os.environ[name]\n        else:\n            os.environ[name] = old_value\n\n\nclass AsyncTestCaseTest(AsyncTestCase):\n    def test_exception_in_callback(self):\n        self.io_loop.add_callback(lambda: 1 / 0)\n        try:\n            self.wait()\n            self.fail(\"did not get expected exception\")\n        except ZeroDivisionError:\n            pass\n\n    def test_wait_timeout(self):\n        time = self.io_loop.time\n\n        # Accept default 5-second timeout, no error\n        self.io_loop.add_timeout(time() + 0.01, self.stop)\n        self.wait()\n\n        # Timeout passed to wait()\n        self.io_loop.add_timeout(time() + 1, self.stop)\n        with self.assertRaises(self.failureException):\n            self.wait(timeout=0.01)\n\n        # Timeout set with environment variable\n        self.io_loop.add_timeout(time() + 1, self.stop)\n        with set_environ('ASYNC_TEST_TIMEOUT', '0.01'):\n            with self.assertRaises(self.failureException):\n                self.wait()\n\n    def test_subsequent_wait_calls(self):\n        \"\"\"\n        This test makes sure that a second call to wait()\n        clears the first timeout.\n        \"\"\"\n        self.io_loop.add_timeout(self.io_loop.time() + 0.00, self.stop)\n        self.wait(timeout=0.02)\n        self.io_loop.add_timeout(self.io_loop.time() + 0.03, self.stop)\n        self.wait(timeout=0.15)\n\n    def test_multiple_errors(self):\n        def fail(message):\n            raise Exception(message)\n        self.io_loop.add_callback(lambda: fail(\"error one\"))\n        self.io_loop.add_callback(lambda: fail(\"error two\"))\n        # The first error gets raised; the second gets logged.\n        with ExpectLog(app_log, \"multiple unhandled exceptions\"):\n            with self.assertRaises(Exception) as cm:\n                self.wait()\n        self.assertEqual(str(cm.exception), \"error one\")\n\n\nclass AsyncHTTPTestCaseTest(AsyncHTTPTestCase):\n    @classmethod\n    def setUpClass(cls):\n        super(AsyncHTTPTestCaseTest, cls).setUpClass()\n        # An unused port is bound so we can make requests upon it without\n        # impacting a real local web server.\n        cls.external_sock, cls.external_port = bind_unused_port()\n\n    def get_app(self):\n        return Application()\n\n    def test_fetch_segment(self):\n        path = '/path'\n        response = self.fetch(path)\n        self.assertEqual(response.request.url, self.get_url(path))\n\n    def test_fetch_full_http_url(self):\n        path = 'http://localhost:%d/path' % self.external_port\n\n        response = self.fetch(path, request_timeout=0.1)\n        self.assertEqual(response.request.url, path)\n\n    def test_fetch_full_https_url(self):\n        path = 'https://localhost:%d/path' % self.external_port\n\n        response = self.fetch(path, request_timeout=0.1)\n        self.assertEqual(response.request.url, path)\n\n    @classmethod\n    def tearDownClass(cls):\n        cls.external_sock.close()\n        super(AsyncHTTPTestCaseTest, cls).tearDownClass()\n\n\nclass AsyncTestCaseWrapperTest(unittest.TestCase):\n    def test_undecorated_generator(self):\n        class Test(AsyncTestCase):\n            def test_gen(self):\n                yield\n        test = Test('test_gen')\n        result = unittest.TestResult()\n        test.run(result)\n        self.assertEqual(len(result.errors), 1)\n        self.assertIn(\"should be decorated\", result.errors[0][1])\n\n    @skipBefore35\n    @unittest.skipIf(platform.python_implementation() == 'PyPy',\n                     'pypy destructor warnings cannot be silenced')\n    def test_undecorated_coroutine(self):\n        namespace = exec_test(globals(), locals(), \"\"\"\n        class Test(AsyncTestCase):\n            async def test_coro(self):\n                pass\n        \"\"\")\n\n        test_class = namespace['Test']\n        test = test_class('test_coro')\n        result = unittest.TestResult()\n\n        # Silence \"RuntimeWarning: coroutine 'test_coro' was never awaited\".\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore')\n            test.run(result)\n\n        self.assertEqual(len(result.errors), 1)\n        self.assertIn(\"should be decorated\", result.errors[0][1])\n\n    def test_undecorated_generator_with_skip(self):\n        class Test(AsyncTestCase):\n            @unittest.skip(\"don't run this\")\n            def test_gen(self):\n                yield\n        test = Test('test_gen')\n        result = unittest.TestResult()\n        test.run(result)\n        self.assertEqual(len(result.errors), 0)\n        self.assertEqual(len(result.skipped), 1)\n\n    def test_other_return(self):\n        class Test(AsyncTestCase):\n            def test_other_return(self):\n                return 42\n        test = Test('test_other_return')\n        result = unittest.TestResult()\n        test.run(result)\n        self.assertEqual(len(result.errors), 1)\n        self.assertIn(\"Return value from test method ignored\", result.errors[0][1])\n\n\nclass SetUpTearDownTest(unittest.TestCase):\n    def test_set_up_tear_down(self):\n        \"\"\"\n        This test makes sure that AsyncTestCase calls super methods for\n        setUp and tearDown.\n\n        InheritBoth is a subclass of both AsyncTestCase and\n        SetUpTearDown, with the ordering so that the super of\n        AsyncTestCase will be SetUpTearDown.\n        \"\"\"\n        events = []\n        result = unittest.TestResult()\n\n        class SetUpTearDown(unittest.TestCase):\n            def setUp(self):\n                events.append('setUp')\n\n            def tearDown(self):\n                events.append('tearDown')\n\n        class InheritBoth(AsyncTestCase, SetUpTearDown):\n            def test(self):\n                events.append('test')\n\n        InheritBoth('test').run(result)\n        expected = ['setUp', 'test', 'tearDown']\n        self.assertEqual(expected, events)\n\n\nclass GenTest(AsyncTestCase):\n    def setUp(self):\n        super(GenTest, self).setUp()\n        self.finished = False\n\n    def tearDown(self):\n        self.assertTrue(self.finished)\n        super(GenTest, self).tearDown()\n\n    @gen_test\n    def test_sync(self):\n        self.finished = True\n\n    @gen_test\n    def test_async(self):\n        yield gen.moment\n        self.finished = True\n\n    def test_timeout(self):\n        # Set a short timeout and exceed it.\n        @gen_test(timeout=0.1)\n        def test(self):\n            yield gen.sleep(1)\n\n        # This can't use assertRaises because we need to inspect the\n        # exc_info triple (and not just the exception object)\n        try:\n            test(self)\n            self.fail(\"did not get expected exception\")\n        except ioloop.TimeoutError:\n            # The stack trace should blame the add_timeout line, not just\n            # unrelated IOLoop/testing internals.\n            self.assertIn(\n                \"gen.sleep(1)\",\n                traceback.format_exc())\n\n        self.finished = True\n\n    def test_no_timeout(self):\n        # A test that does not exceed its timeout should succeed.\n        @gen_test(timeout=1)\n        def test(self):\n            yield gen.sleep(0.1)\n\n        test(self)\n        self.finished = True\n\n    def test_timeout_environment_variable(self):\n        @gen_test(timeout=0.5)\n        def test_long_timeout(self):\n            yield gen.sleep(0.25)\n\n        # Uses provided timeout of 0.5 seconds, doesn't time out.\n        with set_environ('ASYNC_TEST_TIMEOUT', '0.1'):\n            test_long_timeout(self)\n\n        self.finished = True\n\n    def test_no_timeout_environment_variable(self):\n        @gen_test(timeout=0.01)\n        def test_short_timeout(self):\n            yield gen.sleep(1)\n\n        # Uses environment-variable timeout of 0.1, times out.\n        with set_environ('ASYNC_TEST_TIMEOUT', '0.1'):\n            with self.assertRaises(ioloop.TimeoutError):\n                test_short_timeout(self)\n\n        self.finished = True\n\n    def test_with_method_args(self):\n        @gen_test\n        def test_with_args(self, *args):\n            self.assertEqual(args, ('test',))\n            yield gen.moment\n\n        test_with_args(self, 'test')\n        self.finished = True\n\n    def test_with_method_kwargs(self):\n        @gen_test\n        def test_with_kwargs(self, **kwargs):\n            self.assertDictEqual(kwargs, {'test': 'test'})\n            yield gen.moment\n\n        test_with_kwargs(self, test='test')\n        self.finished = True\n\n    @skipBefore35\n    def test_native_coroutine(self):\n        namespace = exec_test(globals(), locals(), \"\"\"\n        @gen_test\n        async def test(self):\n            self.finished = True\n        \"\"\")\n\n        namespace['test'](self)\n\n    @skipBefore35\n    def test_native_coroutine_timeout(self):\n        # Set a short timeout and exceed it.\n        namespace = exec_test(globals(), locals(), \"\"\"\n        @gen_test(timeout=0.1)\n        async def test(self):\n            await gen.sleep(1)\n        \"\"\")\n\n        try:\n            namespace['test'](self)\n            self.fail(\"did not get expected exception\")\n        except ioloop.TimeoutError:\n            self.finished = True\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function\n\nfrom tornado import gen, ioloop\nfrom tornado.log import app_log\nfrom tornado.test.util import unittest, skipBefore35, exec_test\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, bind_unused_port, gen_test, ExpectLog\nfrom tornado.web import Application\nimport contextlib\nimport os\nimport platform\nimport traceback\nimport warnings\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\n\n@contextlib.contextmanager\ndef set_environ(name, value):\n    old_value = os.environ.get(name)\n    os.environ[name] = value\n\n    try:\n        yield\n    finally:\n        if old_value is None:\n            del os.environ[name]\n        else:\n            os.environ[name] = old_value\n\n\nclass AsyncTestCaseTest(AsyncTestCase):\n    def test_exception_in_callback(self):\n        self.io_loop.add_callback(lambda: 1 / 0)\n        try:\n            self.wait()\n            self.fail(\"did not get expected exception\")\n        except ZeroDivisionError:\n            pass\n\n    def test_wait_timeout(self):\n        time = self.io_loop.time\n\n        # Accept default 5-second timeout, no error\n        self.io_loop.add_timeout(time() + 0.01, self.stop)\n        self.wait()\n\n        # Timeout passed to wait()\n        self.io_loop.add_timeout(time() + 1, self.stop)\n        with self.assertRaises(self.failureException):\n            self.wait(timeout=0.01)\n\n        # Timeout set with environment variable\n        self.io_loop.add_timeout(time() + 1, self.stop)\n        with set_environ('ASYNC_TEST_TIMEOUT', '0.01'):\n            with self.assertRaises(self.failureException):\n                self.wait()\n\n    def test_subsequent_wait_calls(self):\n        \"\"\"\n        This test makes sure that a second call to wait()\n        clears the first timeout.\n        \"\"\"\n        self.io_loop.add_timeout(self.io_loop.time() + 0.00, self.stop)\n        self.wait(timeout=0.02)\n        self.io_loop.add_timeout(self.io_loop.time() + 0.03, self.stop)\n        self.wait(timeout=0.15)\n\n    def test_multiple_errors(self):\n        def fail(message):\n            raise Exception(message)\n        self.io_loop.add_callback(lambda: fail(\"error one\"))\n        self.io_loop.add_callback(lambda: fail(\"error two\"))\n        # The first error gets raised; the second gets logged.\n        with ExpectLog(app_log, \"multiple unhandled exceptions\"):\n            with self.assertRaises(Exception) as cm:\n                self.wait()\n        self.assertEqual(str(cm.exception), \"error one\")\n\n\nclass AsyncHTTPTestCaseTest(AsyncHTTPTestCase):\n    @classmethod\n    def setUpClass(cls):\n        super(AsyncHTTPTestCaseTest, cls).setUpClass()\n        # An unused port is bound so we can make requests upon it without\n        # impacting a real local web server.\n        cls.external_sock, cls.external_port = bind_unused_port()\n\n    def get_app(self):\n        return Application()\n\n    def test_fetch_segment(self):\n        path = '/path'\n        response = self.fetch(path)\n        self.assertEqual(response.request.url, self.get_url(path))\n\n    def test_fetch_full_http_url(self):\n        path = 'http://localhost:%d/path' % self.external_port\n\n        response = self.fetch(path, request_timeout=0.1)\n        self.assertEqual(response.request.url, path)\n\n    def test_fetch_full_https_url(self):\n        path = 'https://localhost:%d/path' % self.external_port\n\n        response = self.fetch(path, request_timeout=0.1)\n        self.assertEqual(response.request.url, path)\n\n    @classmethod\n    def tearDownClass(cls):\n        cls.external_sock.close()\n        super(AsyncHTTPTestCaseTest, cls).tearDownClass()\n\n\nclass AsyncTestCaseWrapperTest(unittest.TestCase):\n    def test_undecorated_generator(self):\n        class Test(AsyncTestCase):\n            def test_gen(self):\n                yield\n        test = Test('test_gen')\n        result = unittest.TestResult()\n        test.run(result)\n        self.assertEqual(len(result.errors), 1)\n        self.assertIn(\"should be decorated\", result.errors[0][1])\n\n    @skipBefore35\n    @unittest.skipIf(platform.python_implementation() == 'PyPy',\n                     'pypy destructor warnings cannot be silenced')\n    def test_undecorated_coroutine(self):\n        namespace = exec_test(globals(), locals(), \"\"\"\n        class Test(AsyncTestCase):\n            async def test_coro(self):\n                pass\n        \"\"\")\n\n        test_class = namespace['Test']\n        test = test_class('test_coro')\n        result = unittest.TestResult()\n\n        # Silence \"RuntimeWarning: coroutine 'test_coro' was never awaited\".\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore')\n            test.run(result)\n\n        self.assertEqual(len(result.errors), 1)\n        self.assertIn(\"should be decorated\", result.errors[0][1])\n\n    def test_undecorated_generator_with_skip(self):\n        class Test(AsyncTestCase):\n            @unittest.skip(\"don't run this\")\n            def test_gen(self):\n                yield\n        test = Test('test_gen')\n        result = unittest.TestResult()\n        test.run(result)\n        self.assertEqual(len(result.errors), 0)\n        self.assertEqual(len(result.skipped), 1)\n\n    def test_other_return(self):\n        class Test(AsyncTestCase):\n            def test_other_return(self):\n                return 42\n        test = Test('test_other_return')\n        result = unittest.TestResult()\n        test.run(result)\n        self.assertEqual(len(result.errors), 1)\n        self.assertIn(\"Return value from test method ignored\", result.errors[0][1])\n\n\nclass SetUpTearDownTest(unittest.TestCase):\n    def test_set_up_tear_down(self):\n        \"\"\"\n        This test makes sure that AsyncTestCase calls super methods for\n        setUp and tearDown.\n\n        InheritBoth is a subclass of both AsyncTestCase and\n        SetUpTearDown, with the ordering so that the super of\n        AsyncTestCase will be SetUpTearDown.\n        \"\"\"\n        events = []\n        result = unittest.TestResult()\n\n        class SetUpTearDown(unittest.TestCase):\n            def setUp(self):\n                events.append('setUp')\n\n            def tearDown(self):\n                events.append('tearDown')\n\n        class InheritBoth(AsyncTestCase, SetUpTearDown):\n            def test(self):\n                events.append('test')\n\n        InheritBoth('test').run(result)\n        expected = ['setUp', 'test', 'tearDown']\n        self.assertEqual(expected, events)\n\n\nclass GenTest(AsyncTestCase):\n    def setUp(self):\n        super(GenTest, self).setUp()\n        self.finished = False\n\n    def tearDown(self):\n        self.assertTrue(self.finished)\n        super(GenTest, self).tearDown()\n\n    @gen_test\n    def test_sync(self):\n        self.finished = True\n\n    @gen_test\n    def test_async(self):\n        yield gen.moment\n        self.finished = True\n\n    def test_timeout(self):\n        # Set a short timeout and exceed it.\n        @gen_test(timeout=0.1)\n        def test(self):\n            yield gen.sleep(1)\n\n        # This can't use assertRaises because we need to inspect the\n        # exc_info triple (and not just the exception object)\n        try:\n            test(self)\n            self.fail(\"did not get expected exception\")\n        except ioloop.TimeoutError:\n            # The stack trace should blame the add_timeout line, not just\n            # unrelated IOLoop/testing internals.\n            self.assertIn(\n                \"gen.sleep(1)\",\n                traceback.format_exc())\n\n        self.finished = True\n\n    def test_no_timeout(self):\n        # A test that does not exceed its timeout should succeed.\n        @gen_test(timeout=1)\n        def test(self):\n            yield gen.sleep(0.1)\n\n        test(self)\n        self.finished = True\n\n    def test_timeout_environment_variable(self):\n        @gen_test(timeout=0.5)\n        def test_long_timeout(self):\n            yield gen.sleep(0.25)\n\n        # Uses provided timeout of 0.5 seconds, doesn't time out.\n        with set_environ('ASYNC_TEST_TIMEOUT', '0.1'):\n            test_long_timeout(self)\n\n        self.finished = True\n\n    def test_no_timeout_environment_variable(self):\n        @gen_test(timeout=0.01)\n        def test_short_timeout(self):\n            yield gen.sleep(1)\n\n        # Uses environment-variable timeout of 0.1, times out.\n        with set_environ('ASYNC_TEST_TIMEOUT', '0.1'):\n            with self.assertRaises(ioloop.TimeoutError):\n                test_short_timeout(self)\n\n        self.finished = True\n\n    def test_with_method_args(self):\n        @gen_test\n        def test_with_args(self, *args):\n            self.assertEqual(args, ('test',))\n            yield gen.moment\n\n        test_with_args(self, 'test')\n        self.finished = True\n\n    def test_with_method_kwargs(self):\n        @gen_test\n        def test_with_kwargs(self, **kwargs):\n            self.assertDictEqual(kwargs, {'test': 'test'})\n            yield gen.moment\n\n        test_with_kwargs(self, test='test')\n        self.finished = True\n\n    @skipBefore35\n    def test_native_coroutine(self):\n        namespace = exec_test(globals(), locals(), \"\"\"\n        @gen_test\n        async def test(self):\n            self.finished = True\n        \"\"\")\n\n        namespace['test'](self)\n\n    @skipBefore35\n    def test_native_coroutine_timeout(self):\n        # Set a short timeout and exceed it.\n        namespace = exec_test(globals(), locals(), \"\"\"\n        @gen_test(timeout=0.1)\n        async def test(self):\n            await gen.sleep(1)\n        \"\"\")\n\n        try:\n            namespace['test'](self)\n            self.fail(\"did not get expected exception\")\n        except ioloop.TimeoutError:\n            self.finished = True\n\n\n@unittest.skipIf(asyncio is None, \"asyncio module not present\")\nclass GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "tornado/test/testing_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "9905c927",
                "new_commit_hash": "37449466",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/testing_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/testing_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 11,
                            "length": 6
                        },
                        "new_range": {
                            "start": 11,
                            "length": 11
                        },
                        "section": "import platform"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import traceback",
                                "type": "context"
                            },
                            {
                                "content": "import warnings",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "try:",
                                "type": "added"
                            },
                            {
                                "content": "    import asyncio",
                                "type": "added"
                            },
                            {
                                "content": "except ImportError:",
                                "type": "added"
                            },
                            {
                                "content": "    asyncio = None",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "@contextlib.contextmanager",
                                "type": "context"
                            },
                            {
                                "content": "def set_environ(name, value):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/testing_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "try:\n    import asyncio\nexcept ImportError:\n    asyncio = None",
                            "ast_type_str": "Try",
                            "start_lineno": 14,
                            "end_lineno": 17,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 307,
                            "length": 5
                        },
                        "new_range": {
                            "start": 312,
                            "length": 30
                        },
                        "section": "class GenTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            self.finished = True",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "@unittest.skipIf(asyncio is None, \"asyncio module not present\")",
                                "type": "added"
                            },
                            {
                                "content": "class GetNewIOLoopTest(AsyncTestCase):",
                                "type": "added"
                            },
                            {
                                "content": "    def get_new_ioloop(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # Use the current loop instead of creating a new one here.",
                                "type": "added"
                            },
                            {
                                "content": "        return ioloop.IOLoop.current()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def setUp(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # This simulates the effect of an asyncio test harness like",
                                "type": "added"
                            },
                            {
                                "content": "        # pytest-asyncio.",
                                "type": "added"
                            },
                            {
                                "content": "        self.orig_loop = asyncio.get_event_loop()",
                                "type": "added"
                            },
                            {
                                "content": "        self.new_loop = asyncio.new_event_loop()",
                                "type": "added"
                            },
                            {
                                "content": "        asyncio.set_event_loop(self.new_loop)",
                                "type": "added"
                            },
                            {
                                "content": "        super(GetNewIOLoopTest, self).setUp()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def tearDown(self):",
                                "type": "added"
                            },
                            {
                                "content": "        super(GetNewIOLoopTest, self).tearDown()",
                                "type": "added"
                            },
                            {
                                "content": "        # AsyncTestCase must not affect the existing asyncio loop.",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertFalse(asyncio.get_event_loop().is_closed())",
                                "type": "added"
                            },
                            {
                                "content": "        asyncio.set_event_loop(self.orig_loop)",
                                "type": "added"
                            },
                            {
                                "content": "        self.new_loop.close()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_loop(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "if __name__ == '__main__':",
                                "type": "context"
                            },
                            {
                                "content": "    unittest.main()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/testing_test.py",
                            "type": "method",
                            "name": "GetNewIOLoopTest.setUp",
                            "content": "class GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 321,
                            "end_lineno": 327,
                            "parent": {
                                "file_name": "tornado/test/testing_test.py",
                                "type": "class",
                                "name": "GetNewIOLoopTest",
                                "content": "class GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 316,
                                "end_lineno": 337,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/testing_test.py",
                            "type": "method",
                            "name": "GetNewIOLoopTest.get_new_ioloop",
                            "content": "class GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 317,
                            "end_lineno": 319,
                            "parent": {
                                "file_name": "tornado/test/testing_test.py",
                                "type": "class",
                                "name": "GetNewIOLoopTest",
                                "content": "class GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 316,
                                "end_lineno": 337,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/testing_test.py",
                            "type": "class",
                            "name": "GetNewIOLoopTest",
                            "content": "class GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 316,
                            "end_lineno": 337,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/testing_test.py",
                            "type": "method",
                            "name": "GetNewIOLoopTest.tearDown",
                            "content": "class GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 329,
                            "end_lineno": 334,
                            "parent": {
                                "file_name": "tornado/test/testing_test.py",
                                "type": "class",
                                "name": "GetNewIOLoopTest",
                                "content": "class GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 316,
                                "end_lineno": 337,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/testing_test.py",
                            "type": "method",
                            "name": "GetNewIOLoopTest.test_loop",
                            "content": "class GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 336,
                            "end_lineno": 337,
                            "parent": {
                                "file_name": "tornado/test/testing_test.py",
                                "type": "class",
                                "name": "GetNewIOLoopTest",
                                "content": "class GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 316,
                                "end_lineno": 337,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "\"\"\"Support classes for automated testing.\n\n* `AsyncTestCase` and `AsyncHTTPTestCase`:  Subclasses of unittest.TestCase\n  with additional support for testing asynchronous (`.IOLoop`-based) code.\n\n* `ExpectLog`: Make test logs less spammy.\n\n* `main()`: A simple test runner (wrapper around unittest.main()) with support\n  for the tornado.autoreload module to rerun the tests when code changes.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\ntry:\n    from tornado import gen\n    from tornado.httpclient import AsyncHTTPClient\n    from tornado.httpserver import HTTPServer\n    from tornado.simple_httpclient import SimpleAsyncHTTPClient\n    from tornado.ioloop import IOLoop, TimeoutError\n    from tornado import netutil\n    from tornado.process import Subprocess\nexcept ImportError:\n    # These modules are not importable on app engine.  Parts of this module\n    # won't work, but e.g. main() will.\n    AsyncHTTPClient = None  # type: ignore\n    gen = None  # type: ignore\n    HTTPServer = None  # type: ignore\n    IOLoop = None  # type: ignore\n    netutil = None  # type: ignore\n    SimpleAsyncHTTPClient = None  # type: ignore\n    Subprocess = None  # type: ignore\nfrom tornado.log import app_log\nfrom tornado.stack_context import ExceptionStackContext\nfrom tornado.util import raise_exc_info, basestring_type, PY3\nimport functools\nimport inspect\nimport logging\nimport os\nimport re\nimport signal\nimport socket\nimport sys\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\n\ntry:\n    from collections.abc import Generator as GeneratorType  # type: ignore\nexcept ImportError:\n    from types import GeneratorType  # type: ignore\n\nif sys.version_info >= (3, 5):\n    iscoroutine = inspect.iscoroutine  # type: ignore\n    iscoroutinefunction = inspect.iscoroutinefunction  # type: ignore\nelse:\n    iscoroutine = iscoroutinefunction = lambda f: False\n\n# Tornado's own test suite requires the updated unittest module\n# (either py27+ or unittest2) so tornado.test.util enforces\n# this requirement, but for other users of tornado.testing we want\n# to allow the older version if unitest2 is not available.\nif PY3:\n    # On python 3, mixing unittest2 and unittest (including doctest)\n    # doesn't seem to work, so always use unittest.\n    import unittest\nelse:\n    # On python 2, prefer unittest2 when available.\n    try:\n        import unittest2 as unittest  # type: ignore\n    except ImportError:\n        import unittest  # type: ignore\n\n\ndef bind_unused_port(reuse_port=False):\n    \"\"\"Binds a server socket to an available port on localhost.\n\n    Returns a tuple (socket, port).\n\n    .. versionchanged:: 4.4\n       Always binds to ``127.0.0.1`` without resolving the name\n       ``localhost``.\n    \"\"\"\n    sock = netutil.bind_sockets(None, '127.0.0.1', family=socket.AF_INET,\n                                reuse_port=reuse_port)[0]\n    port = sock.getsockname()[1]\n    return sock, port\n\n\ndef get_async_test_timeout():\n    \"\"\"Get the global timeout setting for async tests.\n\n    Returns a float, the timeout in seconds.\n\n    .. versionadded:: 3.1\n    \"\"\"\n    try:\n        return float(os.environ.get('ASYNC_TEST_TIMEOUT'))\n    except (ValueError, TypeError):\n        return 5\n\n\nclass _TestMethodWrapper(object):\n    \"\"\"Wraps a test method to raise an error if it returns a value.\n\n    This is mainly used to detect undecorated generators (if a test\n    method yields it must use a decorator to consume the generator),\n    but will also detect other kinds of return values (these are not\n    necessarily errors, but we alert anyway since there is no good\n    reason to return a value from a test).\n    \"\"\"\n    def __init__(self, orig_method):\n        self.orig_method = orig_method\n\n    def __call__(self, *args, **kwargs):\n        result = self.orig_method(*args, **kwargs)\n        if isinstance(result, GeneratorType) or iscoroutine(result):\n            raise TypeError(\"Generator and coroutine test methods should be\"\n                            \" decorated with tornado.testing.gen_test\")\n        elif result is not None:\n            raise ValueError(\"Return value from test method ignored: %r\" %\n                             result)\n\n    def __getattr__(self, name):\n        \"\"\"Proxy all unknown attributes to the original method.\n\n        This is important for some of the decorators in the `unittest`\n        module, such as `unittest.skipIf`.\n        \"\"\"\n        return getattr(self.orig_method, name)\n\n\nclass AsyncTestCase(unittest.TestCase):\n    \"\"\"`~unittest.TestCase` subclass for testing `.IOLoop`-based\n    asynchronous code.\n\n    The unittest framework is synchronous, so the test must be\n    complete by the time the test method returns.  This means that\n    asynchronous code cannot be used in quite the same way as usual.\n    To write test functions that use the same ``yield``-based patterns\n    used with the `tornado.gen` module, decorate your test methods\n    with `tornado.testing.gen_test` instead of\n    `tornado.gen.coroutine`.  This class also provides the `stop()`\n    and `wait()` methods for a more manual style of testing.  The test\n    method itself must call ``self.wait()``, and asynchronous\n    callbacks should call ``self.stop()`` to signal completion.\n\n    By default, a new `.IOLoop` is constructed for each test and is available\n    as ``self.io_loop``.  If the code being tested requires a\n    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.\n\n    The `.IOLoop`'s ``start`` and ``stop`` methods should not be\n    called directly.  Instead, use `self.stop <stop>` and `self.wait\n    <wait>`.  Arguments passed to ``self.stop`` are returned from\n    ``self.wait``.  It is possible to have multiple ``wait``/``stop``\n    cycles in the same test.\n\n    Example::\n\n        # This test uses coroutine style.\n        class MyTestCase(AsyncTestCase):\n            @tornado.testing.gen_test\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                response = yield client.fetch(\"http://www.tornadoweb.org\")\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses argument passing between self.stop and self.wait.\n        class MyTestCase2(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.stop)\n                response = self.wait()\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses an explicit callback-based style.\n        class MyTestCase3(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.handle_fetch)\n                self.wait()\n\n            def handle_fetch(self, response):\n                # Test contents of response (failures and exceptions here\n                # will cause self.wait() to throw an exception and end the\n                # test).\n                # Exceptions thrown here are magically propagated to\n                # self.wait() in test_http_fetch() via stack_context.\n                self.assertIn(\"FriendFeed\", response.body)\n                self.stop()\n    \"\"\"\n    def __init__(self, methodName='runTest'):\n        super(AsyncTestCase, self).__init__(methodName)\n        self.__stopped = False\n        self.__running = False\n        self.__failure = None\n        self.__stop_args = None\n        self.__timeout = None\n\n        # It's easy to forget the @gen_test decorator, but if you do\n        # the test will silently be ignored because nothing will consume\n        # the generator.  Replace the test method with a wrapper that will\n        # make sure it's not an undecorated generator.\n        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))\n\n    def setUp(self):\n        super(AsyncTestCase, self).setUp()\n        self.io_loop = self.get_new_ioloop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        # Clean up Subprocess, so it can be used again with a new ioloop.\n        Subprocess.uninitialize()\n        self.io_loop.clear_current()\n        # Try to clean up any file descriptors left open in the ioloop.\n        # This avoids leaks, especially when tests are run repeatedly\n        # in the same process with autoreload (because curl does not\n        # set FD_CLOEXEC on its file descriptors)\n        self.io_loop.close(all_fds=True)\n        super(AsyncTestCase, self).tearDown()\n        # In case an exception escaped or the StackContext caught an exception\n        # when there wasn't a wait() to re-raise it, do so here.\n        # This is our last chance to raise an exception in a way that the\n        # unittest machinery understands.\n        self.__rethrow()\n\n    def get_new_ioloop(self):\n        \"\"\"Creates a new `.IOLoop` for this test.  May be overridden in\n        subclasses for tests that require a specific `.IOLoop` (usually\n        the singleton `.IOLoop.instance()`).\n        \"\"\"\n        return IOLoop()\n\n    def _handle_exception(self, typ, value, tb):\n        if self.__failure is None:\n            self.__failure = (typ, value, tb)\n        else:\n            app_log.error(\"multiple unhandled exceptions in test\",\n                          exc_info=(typ, value, tb))\n        self.stop()\n        return True\n\n    def __rethrow(self):\n        if self.__failure is not None:\n            failure = self.__failure\n            self.__failure = None\n            raise_exc_info(failure)\n\n    def run(self, result=None):\n        with ExceptionStackContext(self._handle_exception):\n            super(AsyncTestCase, self).run(result)\n        # As a last resort, if an exception escaped super.run() and wasn't\n        # re-raised in tearDown, raise it here.  This will cause the\n        # unittest run to fail messily, but that's better than silently\n        # ignoring an error.\n        self.__rethrow()\n\n    def stop(self, _arg=None, **kwargs):\n        \"\"\"Stops the `.IOLoop`, causing one pending (or future) call to `wait()`\n        to return.\n\n        Keyword arguments or a single positional argument passed to `stop()` are\n        saved and will be returned by `wait()`.\n        \"\"\"\n        assert _arg is None or not kwargs\n        self.__stop_args = kwargs or _arg\n        if self.__running:\n            self.io_loop.stop()\n            self.__running = False\n        self.__stopped = True\n\n    def wait(self, condition=None, timeout=None):\n        \"\"\"Runs the `.IOLoop` until stop is called or timeout has passed.\n\n        In the event of a timeout, an exception will be thrown. The\n        default timeout is 5 seconds; it may be overridden with a\n        ``timeout`` keyword argument or globally with the\n        ``ASYNC_TEST_TIMEOUT`` environment variable.\n\n        If ``condition`` is not None, the `.IOLoop` will be restarted\n        after `stop()` until ``condition()`` returns true.\n\n        .. versionchanged:: 3.1\n           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.\n        \"\"\"\n        if timeout is None:\n            timeout = get_async_test_timeout()\n\n        if not self.__stopped:\n            if timeout:\n                def timeout_func():\n                    try:\n                        raise self.failureException(\n                            'Async operation timed out after %s seconds' %\n                            timeout)\n                    except Exception:\n                        self.__failure = sys.exc_info()\n                    self.stop()\n                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,\n                                                          timeout_func)\n            while True:\n                self.__running = True\n                self.io_loop.start()\n                if (self.__failure is not None or\n                        condition is None or condition()):\n                    break\n            if self.__timeout is not None:\n                self.io_loop.remove_timeout(self.__timeout)\n                self.__timeout = None\n        assert self.__stopped\n        self.__stopped = False\n        self.__rethrow()\n        result = self.__stop_args\n        self.__stop_args = None\n        return result\n\n\nclass AsyncHTTPTestCase(AsyncTestCase):\n    \"\"\"A test case that starts up an HTTP server.\n\n    Subclasses must override `get_app()`, which returns the\n    `tornado.web.Application` (or other `.HTTPServer` callback) to be tested.\n    Tests will typically use the provided ``self.http_client`` to fetch\n    URLs from this server.\n\n    Example, assuming the \"Hello, world\" example from the user guide is in\n    ``hello.py``::\n\n        import hello\n\n        class TestHelloApp(AsyncHTTPTestCase):\n            def get_app(self):\n                return hello.make_app()\n\n            def test_homepage(self):\n                response = self.fetch('/')\n                self.assertEqual(response.code, 200)\n                self.assertEqual(response.body, 'Hello, world')\n\n    That call to ``self.fetch()`` is equivalent to ::\n\n        self.http_client.fetch(self.get_url('/'), self.stop)\n        response = self.wait()\n\n    which illustrates how AsyncTestCase can turn an asynchronous operation,\n    like ``http_client.fetch()``, into a synchronous operation. If you need\n    to do other asynchronous operations in tests, you'll probably need to use\n    ``stop()`` and ``wait()`` yourself.\n    \"\"\"\n    def setUp(self):\n        super(AsyncHTTPTestCase, self).setUp()\n        sock, port = bind_unused_port()\n        self.__port = port\n\n        self.http_client = self.get_http_client()\n        self._app = self.get_app()\n        self.http_server = self.get_http_server()\n        self.http_server.add_sockets([sock])\n\n    def get_http_client(self):\n        return AsyncHTTPClient()\n\n    def get_http_server(self):\n        return HTTPServer(self._app, **self.get_httpserver_options())\n\n    def get_app(self):\n        \"\"\"Should be overridden by subclasses to return a\n        `tornado.web.Application` or other `.HTTPServer` callback.\n        \"\"\"\n        raise NotImplementedError()\n\n    def fetch(self, path, **kwargs):\n        \"\"\"Convenience method to synchronously fetch a URL.\n\n        The given path will be appended to the local server's host and\n        port.  Any additional kwargs will be passed directly to\n        `.AsyncHTTPClient.fetch` (and so could be used to pass\n        ``method=\"POST\"``, ``body=\"...\"``, etc).\n\n        If the path begins with http:// or https://, it will be treated as a\n        full URL and will be fetched as-is.\n\n        .. versionchanged:: 5.0\n           Added support for absolute URLs.\n        \"\"\"\n        if path.lower().startswith(('http://', 'https://')):\n            self.http_client.fetch(path, self.stop, **kwargs)\n        else:\n            self.http_client.fetch(self.get_url(path), self.stop, **kwargs)\n        return self.wait()\n\n    def get_httpserver_options(self):\n        \"\"\"May be overridden by subclasses to return additional\n        keyword arguments for the server.\n        \"\"\"\n        return {}\n\n    def get_http_port(self):\n        \"\"\"Returns the port used by the server.\n\n        A new port is chosen for each test.\n        \"\"\"\n        return self.__port\n\n    def get_protocol(self):\n        return 'http'\n\n    def get_url(self, path):\n        \"\"\"Returns an absolute url for the given path on the test server.\"\"\"\n        return '%s://127.0.0.1:%s%s' % (self.get_protocol(),\n                                        self.get_http_port(), path)\n\n    def tearDown(self):\n        self.http_server.stop()\n        self.io_loop.run_sync(self.http_server.close_all_connections,\n                              timeout=get_async_test_timeout())\n        self.http_client.close()\n        super(AsyncHTTPTestCase, self).tearDown()\n\n\nclass AsyncHTTPSTestCase(AsyncHTTPTestCase):\n    \"\"\"A test case that starts an HTTPS server.\n\n    Interface is generally the same as `AsyncHTTPTestCase`.\n    \"\"\"\n    def get_http_client(self):\n        return AsyncHTTPClient(force_instance=True,\n                               defaults=dict(validate_cert=False))\n\n    def get_httpserver_options(self):\n        return dict(ssl_options=self.get_ssl_options())\n\n    def get_ssl_options(self):\n        \"\"\"May be overridden by subclasses to select SSL options.\n\n        By default includes a self-signed testing certificate.\n        \"\"\"\n        # Testing keys were generated with:\n        # openssl req -new -keyout tornado/test/test.key \\\n        #                     -out tornado/test/test.crt -nodes -days 3650 -x509\n        module_dir = os.path.dirname(__file__)\n        return dict(\n            certfile=os.path.join(module_dir, 'test', 'test.crt'),\n            keyfile=os.path.join(module_dir, 'test', 'test.key'))\n\n    def get_protocol(self):\n        return 'https'\n\n\ndef gen_test(func=None, timeout=None):\n    \"\"\"Testing equivalent of ``@gen.coroutine``, to be applied to test methods.\n\n    ``@gen.coroutine`` cannot be used on tests because the `.IOLoop` is not\n    already running.  ``@gen_test`` should be applied to test methods\n    on subclasses of `AsyncTestCase`.\n\n    Example::\n\n        class MyTest(AsyncHTTPTestCase):\n            @gen_test\n            def test_something(self):\n                response = yield self.http_client.fetch(self.get_url('/'))\n\n    By default, ``@gen_test`` times out after 5 seconds. The timeout may be\n    overridden globally with the ``ASYNC_TEST_TIMEOUT`` environment variable,\n    or for each test with the ``timeout`` keyword argument::\n\n        class MyTest(AsyncHTTPTestCase):\n            @gen_test(timeout=10)\n            def test_something_slow(self):\n                response = yield self.http_client.fetch(self.get_url('/'))\n\n    Note that ``@gen_test`` is incompatible with `AsyncTestCase.stop`,\n    `AsyncTestCase.wait`, and `AsyncHTTPTestCase.fetch`. Use ``yield\n    self.http_client.fetch(self.get_url())`` as shown above instead.\n\n    .. versionadded:: 3.1\n       The ``timeout`` argument and ``ASYNC_TEST_TIMEOUT`` environment\n       variable.\n\n    .. versionchanged:: 4.0\n       The wrapper now passes along ``*args, **kwargs`` so it can be used\n       on functions with arguments.\n\n    \"\"\"\n    if timeout is None:\n        timeout = get_async_test_timeout()\n\n    def wrap(f):\n        # Stack up several decorators to allow us to access the generator\n        # object itself.  In the innermost wrapper, we capture the generator\n        # and save it in an attribute of self.  Next, we run the wrapped\n        # function through @gen.coroutine.  Finally, the coroutine is\n        # wrapped again to make it synchronous with run_sync.\n        #\n        # This is a good case study arguing for either some sort of\n        # extensibility in the gen decorators or cancellation support.\n        @functools.wraps(f)\n        def pre_coroutine(self, *args, **kwargs):\n            result = f(self, *args, **kwargs)\n            if isinstance(result, GeneratorType) or iscoroutine(result):\n                self._test_generator = result\n            else:\n                self._test_generator = None\n            return result\n\n        if iscoroutinefunction(f):\n            coro = pre_coroutine\n        else:\n            coro = gen.coroutine(pre_coroutine)\n\n        @functools.wraps(coro)\n        def post_coroutine(self, *args, **kwargs):\n            try:\n                return self.io_loop.run_sync(\n                    functools.partial(coro, self, *args, **kwargs),\n                    timeout=timeout)\n            except TimeoutError as e:\n                # run_sync raises an error with an unhelpful traceback.\n                # If the underlying generator is still running, we can throw the\n                # exception back into it so the stack trace is replaced by the\n                # point where the test is stopped. The only reason the generator\n                # would not be running would be if it were cancelled, which means\n                # a native coroutine, so we can rely on the cr_running attribute.\n                if getattr(self._test_generator, 'cr_running', True):\n                    self._test_generator.throw(e)\n                    # In case the test contains an overly broad except\n                    # clause, we may get back here.\n                # Coroutine was stopped or didn't raise a useful stack trace,\n                # so re-raise the original exception which is better than nothing.\n                raise\n        return post_coroutine\n\n    if func is not None:\n        # Used like:\n        #     @gen_test\n        #     def f(self):\n        #         pass\n        return wrap(func)\n    else:\n        # Used like @gen_test(timeout=10)\n        return wrap\n\n\n# Without this attribute, nosetests will try to run gen_test as a test\n# anywhere it is imported.\ngen_test.__test__ = False  # type: ignore\n\n\nclass ExpectLog(logging.Filter):\n    \"\"\"Context manager to capture and suppress expected log output.\n\n    Useful to make tests of error conditions less noisy, while still\n    leaving unexpected log entries visible.  *Not thread safe.*\n\n    The attribute ``logged_stack`` is set to true if any exception\n    stack trace was logged.\n\n    Usage::\n\n        with ExpectLog('tornado.application', \"Uncaught exception\"):\n            error_response = self.fetch(\"/some_page\")\n\n    .. versionchanged:: 4.3\n       Added the ``logged_stack`` attribute.\n    \"\"\"\n    def __init__(self, logger, regex, required=True):\n        \"\"\"Constructs an ExpectLog context manager.\n\n        :param logger: Logger object (or name of logger) to watch.  Pass\n            an empty string to watch the root logger.\n        :param regex: Regular expression to match.  Any log entries on\n            the specified logger that match this regex will be suppressed.\n        :param required: If true, an exception will be raised if the end of\n            the ``with`` statement is reached without matching any log entries.\n        \"\"\"\n        if isinstance(logger, basestring_type):\n            logger = logging.getLogger(logger)\n        self.logger = logger\n        self.regex = re.compile(regex)\n        self.required = required\n        self.matched = False\n        self.logged_stack = False\n\n    def filter(self, record):\n        if record.exc_info:\n            self.logged_stack = True\n        message = record.getMessage()\n        if self.regex.match(message):\n            self.matched = True\n            return False\n        return True\n\n    def __enter__(self):\n        self.logger.addFilter(self)\n        return self\n\n    def __exit__(self, typ, value, tb):\n        self.logger.removeFilter(self)\n        if not typ and self.required and not self.matched:\n            raise Exception(\"did not get expected log message\")\n\n\ndef main(**kwargs):\n    \"\"\"A simple test runner.\n\n    This test runner is essentially equivalent to `unittest.main` from\n    the standard library, but adds support for tornado-style option\n    parsing and log formatting. It is *not* necessary to use this\n    `main` function to run tests using `AsyncTestCase`; these tests\n    are self-contained and can run with any test runner.\n\n    The easiest way to run a test is via the command line::\n\n        python -m tornado.testing tornado.test.stack_context_test\n\n    See the standard library unittest module for ways in which tests can\n    be specified.\n\n    Projects with many tests may wish to define a test script like\n    ``tornado/test/runtests.py``.  This script should define a method\n    ``all()`` which returns a test suite and then call\n    `tornado.testing.main()`.  Note that even when a test script is\n    used, the ``all()`` test suite may be overridden by naming a\n    single test on the command line::\n\n        # Runs all tests\n        python -m tornado.test.runtests\n        # Runs one test\n        python -m tornado.test.runtests tornado.test.stack_context_test\n\n    Additional keyword arguments passed through to ``unittest.main()``.\n    For example, use ``tornado.testing.main(verbosity=2)``\n    to show many test details as they are run.\n    See http://docs.python.org/library/unittest.html#unittest.main\n    for full argument list.\n\n    .. versionchanged:: 5.0\n\n       This function produces no output of its own; only that produced\n       by the `unittest` module (Previously it would add a PASS or FAIL\n       log message).\n    \"\"\"\n    from tornado.options import define, options, parse_command_line\n\n    define('exception_on_interrupt', type=bool, default=True,\n           help=(\"If true (default), ctrl-c raises a KeyboardInterrupt \"\n                 \"exception.  This prints a stack trace but cannot interrupt \"\n                 \"certain operations.  If false, the process is more reliably \"\n                 \"killed, but does not print a stack trace.\"))\n\n    # support the same options as unittest's command-line interface\n    define('verbose', type=bool)\n    define('quiet', type=bool)\n    define('failfast', type=bool)\n    define('catch', type=bool)\n    define('buffer', type=bool)\n\n    argv = [sys.argv[0]] + parse_command_line(sys.argv)\n\n    if not options.exception_on_interrupt:\n        signal.signal(signal.SIGINT, signal.SIG_DFL)\n\n    if options.verbose is not None:\n        kwargs['verbosity'] = 2\n    if options.quiet is not None:\n        kwargs['verbosity'] = 0\n    if options.failfast is not None:\n        kwargs['failfast'] = True\n    if options.catch is not None:\n        kwargs['catchbreak'] = True\n    if options.buffer is not None:\n        kwargs['buffer'] = True\n\n    if __name__ == '__main__' and len(argv) == 1:\n        print(\"No tests specified\", file=sys.stderr)\n        sys.exit(1)\n    # In order to be able to run tests by their fully-qualified name\n    # on the command line without importing all tests here,\n    # module must be set to None.  Python 3.2's unittest.main ignores\n    # defaultTest if no module is given (it tries to do its own\n    # test discovery, which is incompatible with auto2to3), so don't\n    # set module if we're not asking for a specific test.\n    if len(argv) > 1:\n        unittest.main(module=None, argv=argv, **kwargs)\n    else:\n        unittest.main(defaultTest=\"all\", argv=argv, **kwargs)\n\n\nif __name__ == '__main__':\n    main()\n",
            "new_file_content": "\"\"\"Support classes for automated testing.\n\n* `AsyncTestCase` and `AsyncHTTPTestCase`:  Subclasses of unittest.TestCase\n  with additional support for testing asynchronous (`.IOLoop`-based) code.\n\n* `ExpectLog`: Make test logs less spammy.\n\n* `main()`: A simple test runner (wrapper around unittest.main()) with support\n  for the tornado.autoreload module to rerun the tests when code changes.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\ntry:\n    from tornado import gen\n    from tornado.httpclient import AsyncHTTPClient\n    from tornado.httpserver import HTTPServer\n    from tornado.simple_httpclient import SimpleAsyncHTTPClient\n    from tornado.ioloop import IOLoop, TimeoutError\n    from tornado import netutil\n    from tornado.process import Subprocess\nexcept ImportError:\n    # These modules are not importable on app engine.  Parts of this module\n    # won't work, but e.g. main() will.\n    AsyncHTTPClient = None  # type: ignore\n    gen = None  # type: ignore\n    HTTPServer = None  # type: ignore\n    IOLoop = None  # type: ignore\n    netutil = None  # type: ignore\n    SimpleAsyncHTTPClient = None  # type: ignore\n    Subprocess = None  # type: ignore\nfrom tornado.log import app_log\nfrom tornado.stack_context import ExceptionStackContext\nfrom tornado.util import raise_exc_info, basestring_type, PY3\nimport functools\nimport inspect\nimport logging\nimport os\nimport re\nimport signal\nimport socket\nimport sys\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\n\ntry:\n    from collections.abc import Generator as GeneratorType  # type: ignore\nexcept ImportError:\n    from types import GeneratorType  # type: ignore\n\nif sys.version_info >= (3, 5):\n    iscoroutine = inspect.iscoroutine  # type: ignore\n    iscoroutinefunction = inspect.iscoroutinefunction  # type: ignore\nelse:\n    iscoroutine = iscoroutinefunction = lambda f: False\n\n# Tornado's own test suite requires the updated unittest module\n# (either py27+ or unittest2) so tornado.test.util enforces\n# this requirement, but for other users of tornado.testing we want\n# to allow the older version if unitest2 is not available.\nif PY3:\n    # On python 3, mixing unittest2 and unittest (including doctest)\n    # doesn't seem to work, so always use unittest.\n    import unittest\nelse:\n    # On python 2, prefer unittest2 when available.\n    try:\n        import unittest2 as unittest  # type: ignore\n    except ImportError:\n        import unittest  # type: ignore\n\n\nif asyncio is None:\n    _NON_OWNED_IOLOOPS = ()\nelse:\n    import tornado.platform.asyncio\n    _NON_OWNED_IOLOOPS = tornado.platform.asyncio.AsyncIOMainLoop\n\ndef bind_unused_port(reuse_port=False):\n    \"\"\"Binds a server socket to an available port on localhost.\n\n    Returns a tuple (socket, port).\n\n    .. versionchanged:: 4.4\n       Always binds to ``127.0.0.1`` without resolving the name\n       ``localhost``.\n    \"\"\"\n    sock = netutil.bind_sockets(None, '127.0.0.1', family=socket.AF_INET,\n                                reuse_port=reuse_port)[0]\n    port = sock.getsockname()[1]\n    return sock, port\n\n\ndef get_async_test_timeout():\n    \"\"\"Get the global timeout setting for async tests.\n\n    Returns a float, the timeout in seconds.\n\n    .. versionadded:: 3.1\n    \"\"\"\n    try:\n        return float(os.environ.get('ASYNC_TEST_TIMEOUT'))\n    except (ValueError, TypeError):\n        return 5\n\n\nclass _TestMethodWrapper(object):\n    \"\"\"Wraps a test method to raise an error if it returns a value.\n\n    This is mainly used to detect undecorated generators (if a test\n    method yields it must use a decorator to consume the generator),\n    but will also detect other kinds of return values (these are not\n    necessarily errors, but we alert anyway since there is no good\n    reason to return a value from a test).\n    \"\"\"\n    def __init__(self, orig_method):\n        self.orig_method = orig_method\n\n    def __call__(self, *args, **kwargs):\n        result = self.orig_method(*args, **kwargs)\n        if isinstance(result, GeneratorType) or iscoroutine(result):\n            raise TypeError(\"Generator and coroutine test methods should be\"\n                            \" decorated with tornado.testing.gen_test\")\n        elif result is not None:\n            raise ValueError(\"Return value from test method ignored: %r\" %\n                             result)\n\n    def __getattr__(self, name):\n        \"\"\"Proxy all unknown attributes to the original method.\n\n        This is important for some of the decorators in the `unittest`\n        module, such as `unittest.skipIf`.\n        \"\"\"\n        return getattr(self.orig_method, name)\n\n\nclass AsyncTestCase(unittest.TestCase):\n    \"\"\"`~unittest.TestCase` subclass for testing `.IOLoop`-based\n    asynchronous code.\n\n    The unittest framework is synchronous, so the test must be\n    complete by the time the test method returns.  This means that\n    asynchronous code cannot be used in quite the same way as usual.\n    To write test functions that use the same ``yield``-based patterns\n    used with the `tornado.gen` module, decorate your test methods\n    with `tornado.testing.gen_test` instead of\n    `tornado.gen.coroutine`.  This class also provides the `stop()`\n    and `wait()` methods for a more manual style of testing.  The test\n    method itself must call ``self.wait()``, and asynchronous\n    callbacks should call ``self.stop()`` to signal completion.\n\n    By default, a new `.IOLoop` is constructed for each test and is available\n    as ``self.io_loop``.  If the code being tested requires a\n    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.\n\n    The `.IOLoop`'s ``start`` and ``stop`` methods should not be\n    called directly.  Instead, use `self.stop <stop>` and `self.wait\n    <wait>`.  Arguments passed to ``self.stop`` are returned from\n    ``self.wait``.  It is possible to have multiple ``wait``/``stop``\n    cycles in the same test.\n\n    Example::\n\n        # This test uses coroutine style.\n        class MyTestCase(AsyncTestCase):\n            @tornado.testing.gen_test\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                response = yield client.fetch(\"http://www.tornadoweb.org\")\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses argument passing between self.stop and self.wait.\n        class MyTestCase2(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.stop)\n                response = self.wait()\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses an explicit callback-based style.\n        class MyTestCase3(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.handle_fetch)\n                self.wait()\n\n            def handle_fetch(self, response):\n                # Test contents of response (failures and exceptions here\n                # will cause self.wait() to throw an exception and end the\n                # test).\n                # Exceptions thrown here are magically propagated to\n                # self.wait() in test_http_fetch() via stack_context.\n                self.assertIn(\"FriendFeed\", response.body)\n                self.stop()\n    \"\"\"\n    def __init__(self, methodName='runTest'):\n        super(AsyncTestCase, self).__init__(methodName)\n        self.__stopped = False\n        self.__running = False\n        self.__failure = None\n        self.__stop_args = None\n        self.__timeout = None\n\n        # It's easy to forget the @gen_test decorator, but if you do\n        # the test will silently be ignored because nothing will consume\n        # the generator.  Replace the test method with a wrapper that will\n        # make sure it's not an undecorated generator.\n        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))\n\n    def setUp(self):\n        super(AsyncTestCase, self).setUp()\n        self.io_loop = self.get_new_ioloop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        # Clean up Subprocess, so it can be used again with a new ioloop.\n        Subprocess.uninitialize()\n        self.io_loop.clear_current()\n        if not isinstance(self.io_loop, _NON_OWNED_IOLOOPS):\n            # Try to clean up any file descriptors left open in the ioloop.\n            # This avoids leaks, especially when tests are run repeatedly\n            # in the same process with autoreload (because curl does not\n            # set FD_CLOEXEC on its file descriptors)\n            self.io_loop.close(all_fds=True)\n        super(AsyncTestCase, self).tearDown()\n        # In case an exception escaped or the StackContext caught an exception\n        # when there wasn't a wait() to re-raise it, do so here.\n        # This is our last chance to raise an exception in a way that the\n        # unittest machinery understands.\n        self.__rethrow()\n\n    def get_new_ioloop(self):\n        \"\"\"Returns the `.IOLoop` to use for this test.\n\n        By default, a new `.IOLoop` is created for each test.\n        Subclasses may override this method to return\n        `.IOLoop.current()` if it is not appropriate to use a new\n        `.IOLoop` in each tests (for example, if there are global\n        singletons using the default `.IOLoop`) or if a per-test event\n        loop is being provided by another system (such as\n        ``pytest-asyncio``).\n        \"\"\"\n        return IOLoop()\n\n    def _handle_exception(self, typ, value, tb):\n        if self.__failure is None:\n            self.__failure = (typ, value, tb)\n        else:\n            app_log.error(\"multiple unhandled exceptions in test\",\n                          exc_info=(typ, value, tb))\n        self.stop()\n        return True\n\n    def __rethrow(self):\n        if self.__failure is not None:\n            failure = self.__failure\n            self.__failure = None\n            raise_exc_info(failure)\n\n    def run(self, result=None):\n        with ExceptionStackContext(self._handle_exception):\n            super(AsyncTestCase, self).run(result)\n        # As a last resort, if an exception escaped super.run() and wasn't\n        # re-raised in tearDown, raise it here.  This will cause the\n        # unittest run to fail messily, but that's better than silently\n        # ignoring an error.\n        self.__rethrow()\n\n    def stop(self, _arg=None, **kwargs):\n        \"\"\"Stops the `.IOLoop`, causing one pending (or future) call to `wait()`\n        to return.\n\n        Keyword arguments or a single positional argument passed to `stop()` are\n        saved and will be returned by `wait()`.\n        \"\"\"\n        assert _arg is None or not kwargs\n        self.__stop_args = kwargs or _arg\n        if self.__running:\n            self.io_loop.stop()\n            self.__running = False\n        self.__stopped = True\n\n    def wait(self, condition=None, timeout=None):\n        \"\"\"Runs the `.IOLoop` until stop is called or timeout has passed.\n\n        In the event of a timeout, an exception will be thrown. The\n        default timeout is 5 seconds; it may be overridden with a\n        ``timeout`` keyword argument or globally with the\n        ``ASYNC_TEST_TIMEOUT`` environment variable.\n\n        If ``condition`` is not None, the `.IOLoop` will be restarted\n        after `stop()` until ``condition()`` returns true.\n\n        .. versionchanged:: 3.1\n           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.\n        \"\"\"\n        if timeout is None:\n            timeout = get_async_test_timeout()\n\n        if not self.__stopped:\n            if timeout:\n                def timeout_func():\n                    try:\n                        raise self.failureException(\n                            'Async operation timed out after %s seconds' %\n                            timeout)\n                    except Exception:\n                        self.__failure = sys.exc_info()\n                    self.stop()\n                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,\n                                                          timeout_func)\n            while True:\n                self.__running = True\n                self.io_loop.start()\n                if (self.__failure is not None or\n                        condition is None or condition()):\n                    break\n            if self.__timeout is not None:\n                self.io_loop.remove_timeout(self.__timeout)\n                self.__timeout = None\n        assert self.__stopped\n        self.__stopped = False\n        self.__rethrow()\n        result = self.__stop_args\n        self.__stop_args = None\n        return result\n\n\nclass AsyncHTTPTestCase(AsyncTestCase):\n    \"\"\"A test case that starts up an HTTP server.\n\n    Subclasses must override `get_app()`, which returns the\n    `tornado.web.Application` (or other `.HTTPServer` callback) to be tested.\n    Tests will typically use the provided ``self.http_client`` to fetch\n    URLs from this server.\n\n    Example, assuming the \"Hello, world\" example from the user guide is in\n    ``hello.py``::\n\n        import hello\n\n        class TestHelloApp(AsyncHTTPTestCase):\n            def get_app(self):\n                return hello.make_app()\n\n            def test_homepage(self):\n                response = self.fetch('/')\n                self.assertEqual(response.code, 200)\n                self.assertEqual(response.body, 'Hello, world')\n\n    That call to ``self.fetch()`` is equivalent to ::\n\n        self.http_client.fetch(self.get_url('/'), self.stop)\n        response = self.wait()\n\n    which illustrates how AsyncTestCase can turn an asynchronous operation,\n    like ``http_client.fetch()``, into a synchronous operation. If you need\n    to do other asynchronous operations in tests, you'll probably need to use\n    ``stop()`` and ``wait()`` yourself.\n    \"\"\"\n    def setUp(self):\n        super(AsyncHTTPTestCase, self).setUp()\n        sock, port = bind_unused_port()\n        self.__port = port\n\n        self.http_client = self.get_http_client()\n        self._app = self.get_app()\n        self.http_server = self.get_http_server()\n        self.http_server.add_sockets([sock])\n\n    def get_http_client(self):\n        return AsyncHTTPClient()\n\n    def get_http_server(self):\n        return HTTPServer(self._app, **self.get_httpserver_options())\n\n    def get_app(self):\n        \"\"\"Should be overridden by subclasses to return a\n        `tornado.web.Application` or other `.HTTPServer` callback.\n        \"\"\"\n        raise NotImplementedError()\n\n    def fetch(self, path, **kwargs):\n        \"\"\"Convenience method to synchronously fetch a URL.\n\n        The given path will be appended to the local server's host and\n        port.  Any additional kwargs will be passed directly to\n        `.AsyncHTTPClient.fetch` (and so could be used to pass\n        ``method=\"POST\"``, ``body=\"...\"``, etc).\n\n        If the path begins with http:// or https://, it will be treated as a\n        full URL and will be fetched as-is.\n\n        .. versionchanged:: 5.0\n           Added support for absolute URLs.\n        \"\"\"\n        if path.lower().startswith(('http://', 'https://')):\n            self.http_client.fetch(path, self.stop, **kwargs)\n        else:\n            self.http_client.fetch(self.get_url(path), self.stop, **kwargs)\n        return self.wait()\n\n    def get_httpserver_options(self):\n        \"\"\"May be overridden by subclasses to return additional\n        keyword arguments for the server.\n        \"\"\"\n        return {}\n\n    def get_http_port(self):\n        \"\"\"Returns the port used by the server.\n\n        A new port is chosen for each test.\n        \"\"\"\n        return self.__port\n\n    def get_protocol(self):\n        return 'http'\n\n    def get_url(self, path):\n        \"\"\"Returns an absolute url for the given path on the test server.\"\"\"\n        return '%s://127.0.0.1:%s%s' % (self.get_protocol(),\n                                        self.get_http_port(), path)\n\n    def tearDown(self):\n        self.http_server.stop()\n        self.io_loop.run_sync(self.http_server.close_all_connections,\n                              timeout=get_async_test_timeout())\n        self.http_client.close()\n        super(AsyncHTTPTestCase, self).tearDown()\n\n\nclass AsyncHTTPSTestCase(AsyncHTTPTestCase):\n    \"\"\"A test case that starts an HTTPS server.\n\n    Interface is generally the same as `AsyncHTTPTestCase`.\n    \"\"\"\n    def get_http_client(self):\n        return AsyncHTTPClient(force_instance=True,\n                               defaults=dict(validate_cert=False))\n\n    def get_httpserver_options(self):\n        return dict(ssl_options=self.get_ssl_options())\n\n    def get_ssl_options(self):\n        \"\"\"May be overridden by subclasses to select SSL options.\n\n        By default includes a self-signed testing certificate.\n        \"\"\"\n        # Testing keys were generated with:\n        # openssl req -new -keyout tornado/test/test.key \\\n        #                     -out tornado/test/test.crt -nodes -days 3650 -x509\n        module_dir = os.path.dirname(__file__)\n        return dict(\n            certfile=os.path.join(module_dir, 'test', 'test.crt'),\n            keyfile=os.path.join(module_dir, 'test', 'test.key'))\n\n    def get_protocol(self):\n        return 'https'\n\n\ndef gen_test(func=None, timeout=None):\n    \"\"\"Testing equivalent of ``@gen.coroutine``, to be applied to test methods.\n\n    ``@gen.coroutine`` cannot be used on tests because the `.IOLoop` is not\n    already running.  ``@gen_test`` should be applied to test methods\n    on subclasses of `AsyncTestCase`.\n\n    Example::\n\n        class MyTest(AsyncHTTPTestCase):\n            @gen_test\n            def test_something(self):\n                response = yield self.http_client.fetch(self.get_url('/'))\n\n    By default, ``@gen_test`` times out after 5 seconds. The timeout may be\n    overridden globally with the ``ASYNC_TEST_TIMEOUT`` environment variable,\n    or for each test with the ``timeout`` keyword argument::\n\n        class MyTest(AsyncHTTPTestCase):\n            @gen_test(timeout=10)\n            def test_something_slow(self):\n                response = yield self.http_client.fetch(self.get_url('/'))\n\n    Note that ``@gen_test`` is incompatible with `AsyncTestCase.stop`,\n    `AsyncTestCase.wait`, and `AsyncHTTPTestCase.fetch`. Use ``yield\n    self.http_client.fetch(self.get_url())`` as shown above instead.\n\n    .. versionadded:: 3.1\n       The ``timeout`` argument and ``ASYNC_TEST_TIMEOUT`` environment\n       variable.\n\n    .. versionchanged:: 4.0\n       The wrapper now passes along ``*args, **kwargs`` so it can be used\n       on functions with arguments.\n\n    \"\"\"\n    if timeout is None:\n        timeout = get_async_test_timeout()\n\n    def wrap(f):\n        # Stack up several decorators to allow us to access the generator\n        # object itself.  In the innermost wrapper, we capture the generator\n        # and save it in an attribute of self.  Next, we run the wrapped\n        # function through @gen.coroutine.  Finally, the coroutine is\n        # wrapped again to make it synchronous with run_sync.\n        #\n        # This is a good case study arguing for either some sort of\n        # extensibility in the gen decorators or cancellation support.\n        @functools.wraps(f)\n        def pre_coroutine(self, *args, **kwargs):\n            result = f(self, *args, **kwargs)\n            if isinstance(result, GeneratorType) or iscoroutine(result):\n                self._test_generator = result\n            else:\n                self._test_generator = None\n            return result\n\n        if iscoroutinefunction(f):\n            coro = pre_coroutine\n        else:\n            coro = gen.coroutine(pre_coroutine)\n\n        @functools.wraps(coro)\n        def post_coroutine(self, *args, **kwargs):\n            try:\n                return self.io_loop.run_sync(\n                    functools.partial(coro, self, *args, **kwargs),\n                    timeout=timeout)\n            except TimeoutError as e:\n                # run_sync raises an error with an unhelpful traceback.\n                # If the underlying generator is still running, we can throw the\n                # exception back into it so the stack trace is replaced by the\n                # point where the test is stopped. The only reason the generator\n                # would not be running would be if it were cancelled, which means\n                # a native coroutine, so we can rely on the cr_running attribute.\n                if getattr(self._test_generator, 'cr_running', True):\n                    self._test_generator.throw(e)\n                    # In case the test contains an overly broad except\n                    # clause, we may get back here.\n                # Coroutine was stopped or didn't raise a useful stack trace,\n                # so re-raise the original exception which is better than nothing.\n                raise\n        return post_coroutine\n\n    if func is not None:\n        # Used like:\n        #     @gen_test\n        #     def f(self):\n        #         pass\n        return wrap(func)\n    else:\n        # Used like @gen_test(timeout=10)\n        return wrap\n\n\n# Without this attribute, nosetests will try to run gen_test as a test\n# anywhere it is imported.\ngen_test.__test__ = False  # type: ignore\n\n\nclass ExpectLog(logging.Filter):\n    \"\"\"Context manager to capture and suppress expected log output.\n\n    Useful to make tests of error conditions less noisy, while still\n    leaving unexpected log entries visible.  *Not thread safe.*\n\n    The attribute ``logged_stack`` is set to true if any exception\n    stack trace was logged.\n\n    Usage::\n\n        with ExpectLog('tornado.application', \"Uncaught exception\"):\n            error_response = self.fetch(\"/some_page\")\n\n    .. versionchanged:: 4.3\n       Added the ``logged_stack`` attribute.\n    \"\"\"\n    def __init__(self, logger, regex, required=True):\n        \"\"\"Constructs an ExpectLog context manager.\n\n        :param logger: Logger object (or name of logger) to watch.  Pass\n            an empty string to watch the root logger.\n        :param regex: Regular expression to match.  Any log entries on\n            the specified logger that match this regex will be suppressed.\n        :param required: If true, an exception will be raised if the end of\n            the ``with`` statement is reached without matching any log entries.\n        \"\"\"\n        if isinstance(logger, basestring_type):\n            logger = logging.getLogger(logger)\n        self.logger = logger\n        self.regex = re.compile(regex)\n        self.required = required\n        self.matched = False\n        self.logged_stack = False\n\n    def filter(self, record):\n        if record.exc_info:\n            self.logged_stack = True\n        message = record.getMessage()\n        if self.regex.match(message):\n            self.matched = True\n            return False\n        return True\n\n    def __enter__(self):\n        self.logger.addFilter(self)\n        return self\n\n    def __exit__(self, typ, value, tb):\n        self.logger.removeFilter(self)\n        if not typ and self.required and not self.matched:\n            raise Exception(\"did not get expected log message\")\n\n\ndef main(**kwargs):\n    \"\"\"A simple test runner.\n\n    This test runner is essentially equivalent to `unittest.main` from\n    the standard library, but adds support for tornado-style option\n    parsing and log formatting. It is *not* necessary to use this\n    `main` function to run tests using `AsyncTestCase`; these tests\n    are self-contained and can run with any test runner.\n\n    The easiest way to run a test is via the command line::\n\n        python -m tornado.testing tornado.test.stack_context_test\n\n    See the standard library unittest module for ways in which tests can\n    be specified.\n\n    Projects with many tests may wish to define a test script like\n    ``tornado/test/runtests.py``.  This script should define a method\n    ``all()`` which returns a test suite and then call\n    `tornado.testing.main()`.  Note that even when a test script is\n    used, the ``all()`` test suite may be overridden by naming a\n    single test on the command line::\n\n        # Runs all tests\n        python -m tornado.test.runtests\n        # Runs one test\n        python -m tornado.test.runtests tornado.test.stack_context_test\n\n    Additional keyword arguments passed through to ``unittest.main()``.\n    For example, use ``tornado.testing.main(verbosity=2)``\n    to show many test details as they are run.\n    See http://docs.python.org/library/unittest.html#unittest.main\n    for full argument list.\n\n    .. versionchanged:: 5.0\n\n       This function produces no output of its own; only that produced\n       by the `unittest` module (Previously it would add a PASS or FAIL\n       log message).\n    \"\"\"\n    from tornado.options import define, options, parse_command_line\n\n    define('exception_on_interrupt', type=bool, default=True,\n           help=(\"If true (default), ctrl-c raises a KeyboardInterrupt \"\n                 \"exception.  This prints a stack trace but cannot interrupt \"\n                 \"certain operations.  If false, the process is more reliably \"\n                 \"killed, but does not print a stack trace.\"))\n\n    # support the same options as unittest's command-line interface\n    define('verbose', type=bool)\n    define('quiet', type=bool)\n    define('failfast', type=bool)\n    define('catch', type=bool)\n    define('buffer', type=bool)\n\n    argv = [sys.argv[0]] + parse_command_line(sys.argv)\n\n    if not options.exception_on_interrupt:\n        signal.signal(signal.SIGINT, signal.SIG_DFL)\n\n    if options.verbose is not None:\n        kwargs['verbosity'] = 2\n    if options.quiet is not None:\n        kwargs['verbosity'] = 0\n    if options.failfast is not None:\n        kwargs['failfast'] = True\n    if options.catch is not None:\n        kwargs['catchbreak'] = True\n    if options.buffer is not None:\n        kwargs['buffer'] = True\n\n    if __name__ == '__main__' and len(argv) == 1:\n        print(\"No tests specified\", file=sys.stderr)\n        sys.exit(1)\n    # In order to be able to run tests by their fully-qualified name\n    # on the command line without importing all tests here,\n    # module must be set to None.  Python 3.2's unittest.main ignores\n    # defaultTest if no module is given (it tries to do its own\n    # test discovery, which is incompatible with auto2to3), so don't\n    # set module if we're not asking for a specific test.\n    if len(argv) > 1:\n        unittest.main(module=None, argv=argv, **kwargs)\n    else:\n        unittest.main(defaultTest=\"all\", argv=argv, **kwargs)\n\n\nif __name__ == '__main__':\n    main()\n",
            "header": {
                "file": {
                    "path": "tornado/testing.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "400dd3e4",
                "new_commit_hash": "19bc5a94",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/testing.py"
            },
            "plus_file": {
                "path": "b/tornado/testing.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 74,
                            "length": 6
                        },
                        "new_range": {
                            "start": 74,
                            "length": 12
                        },
                        "section": "else:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        import unittest  # type: ignore",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "if asyncio is None:",
                                "type": "added"
                            },
                            {
                                "content": "    _NON_OWNED_IOLOOPS = ()",
                                "type": "added"
                            },
                            {
                                "content": "else:",
                                "type": "added"
                            },
                            {
                                "content": "    import tornado.platform.asyncio",
                                "type": "added"
                            },
                            {
                                "content": "    _NON_OWNED_IOLOOPS = tornado.platform.asyncio.AsyncIOMainLoop",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "def bind_unused_port(reuse_port=False):",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"Binds a server socket to an available port on localhost.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/testing.py",
                            "type": "statement",
                            "name": "",
                            "content": "if asyncio is None:\n    _NON_OWNED_IOLOOPS = ()\nelse:\n    import tornado.platform.asyncio\n    _NON_OWNED_IOLOOPS = tornado.platform.asyncio.AsyncIOMainLoop",
                            "ast_type_str": "If",
                            "start_lineno": 77,
                            "end_lineno": 81,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 216,
                            "length": 11
                        },
                        "new_range": {
                            "start": 222,
                            "length": 12
                        },
                        "section": "class AsyncTestCase(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        # Clean up Subprocess, so it can be used again with a new ioloop.",
                                "type": "context"
                            },
                            {
                                "content": "        Subprocess.uninitialize()",
                                "type": "context"
                            },
                            {
                                "content": "        self.io_loop.clear_current()",
                                "type": "context"
                            },
                            {
                                "content": "        # Try to clean up any file descriptors left open in the ioloop.",
                                "type": "deleted"
                            },
                            {
                                "content": "        # This avoids leaks, especially when tests are run repeatedly",
                                "type": "deleted"
                            },
                            {
                                "content": "        # in the same process with autoreload (because curl does not",
                                "type": "deleted"
                            },
                            {
                                "content": "        # set FD_CLOEXEC on its file descriptors)",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.io_loop.close(all_fds=True)",
                                "type": "deleted"
                            },
                            {
                                "content": "        if not isinstance(self.io_loop, _NON_OWNED_IOLOOPS):",
                                "type": "added"
                            },
                            {
                                "content": "            # Try to clean up any file descriptors left open in the ioloop.",
                                "type": "added"
                            },
                            {
                                "content": "            # This avoids leaks, especially when tests are run repeatedly",
                                "type": "added"
                            },
                            {
                                "content": "            # in the same process with autoreload (because curl does not",
                                "type": "added"
                            },
                            {
                                "content": "            # set FD_CLOEXEC on its file descriptors)",
                                "type": "added"
                            },
                            {
                                "content": "            self.io_loop.close(all_fds=True)",
                                "type": "added"
                            },
                            {
                                "content": "        super(AsyncTestCase, self).tearDown()",
                                "type": "context"
                            },
                            {
                                "content": "        # In case an exception escaped or the StackContext caught an exception",
                                "type": "context"
                            },
                            {
                                "content": "        # when there wasn't a wait() to re-raise it, do so here.",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/testing.py",
                            "type": "method",
                            "name": "AsyncTestCase.tearDown",
                            "content": "class AsyncTestCase(unittest.TestCase):\n    \"\"\"`~unittest.TestCase` subclass for testing `.IOLoop`-based\n    asynchronous code.\n\n    The unittest framework is synchronous, so the test must be\n    complete by the time the test method returns.  This means that\n    asynchronous code cannot be used in quite the same way as usual.\n    To write test functions that use the same ``yield``-based patterns\n    used with the `tornado.gen` module, decorate your test methods\n    with `tornado.testing.gen_test` instead of\n    `tornado.gen.coroutine`.  This class also provides the `stop()`\n    and `wait()` methods for a more manual style of testing.  The test\n    method itself must call ``self.wait()``, and asynchronous\n    callbacks should call ``self.stop()`` to signal completion.\n\n    By default, a new `.IOLoop` is constructed for each test and is available\n    as ``self.io_loop``.  If the code being tested requires a\n    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.\n\n    The `.IOLoop`'s ``start`` and ``stop`` methods should not be\n    called directly.  Instead, use `self.stop <stop>` and `self.wait\n    <wait>`.  Arguments passed to ``self.stop`` are returned from\n    ``self.wait``.  It is possible to have multiple ``wait``/``stop``\n    cycles in the same test.\n\n    Example::\n\n        # This test uses coroutine style.\n        class MyTestCase(AsyncTestCase):\n            @tornado.testing.gen_test\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                response = yield client.fetch(\"http://www.tornadoweb.org\")\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses argument passing between self.stop and self.wait.\n        class MyTestCase2(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.stop)\n                response = self.wait()\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses an explicit callback-based style.\n        class MyTestCase3(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.handle_fetch)\n                self.wait()\n\n            def handle_fetch(self, response):\n                # Test contents of response (failures and exceptions here\n                # will cause self.wait() to throw an exception and end the\n                # test).\n                # Exceptions thrown here are magically propagated to\n                # self.wait() in test_http_fetch() via stack_context.\n                self.assertIn(\"FriendFeed\", response.body)\n                self.stop()\n    \"\"\"\n    def __init__(self, methodName='runTest'):\n        super(AsyncTestCase, self).__init__(methodName)\n        self.__stopped = False\n        self.__running = False\n        self.__failure = None\n        self.__stop_args = None\n        self.__timeout = None\n\n        # It's easy to forget the @gen_test decorator, but if you do\n        # the test will silently be ignored because nothing will consume\n        # the generator.  Replace the test method with a wrapper that will\n        # make sure it's not an undecorated generator.\n        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))\n\n    def setUp(self):\n        super(AsyncTestCase, self).setUp()\n        self.io_loop = self.get_new_ioloop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        # Clean up Subprocess, so it can be used again with a new ioloop.\n        Subprocess.uninitialize()\n        self.io_loop.clear_current()\n        # Try to clean up any file descriptors left open in the ioloop.\n        # This avoids leaks, especially when tests are run repeatedly\n        # in the same process with autoreload (because curl does not\n        # set FD_CLOEXEC on its file descriptors)\n        self.io_loop.close(all_fds=True)\n        super(AsyncTestCase, self).tearDown()\n        # In case an exception escaped or the StackContext caught an exception\n        # when there wasn't a wait() to re-raise it, do so here.\n        # This is our last chance to raise an exception in a way that the\n        # unittest machinery understands.\n        self.__rethrow()\n\n    def get_new_ioloop(self):\n        \"\"\"Creates a new `.IOLoop` for this test.  May be overridden in\n        subclasses for tests that require a specific `.IOLoop` (usually\n        the singleton `.IOLoop.instance()`).\n        \"\"\"\n        return IOLoop()\n\n    def _handle_exception(self, typ, value, tb):\n        if self.__failure is None:\n            self.__failure = (typ, value, tb)\n        else:\n            app_log.error(\"multiple unhandled exceptions in test\",\n                          exc_info=(typ, value, tb))\n        self.stop()\n        return True\n\n    def __rethrow(self):\n        if self.__failure is not None:\n            failure = self.__failure\n            self.__failure = None\n            raise_exc_info(failure)\n\n    def run(self, result=None):\n        with ExceptionStackContext(self._handle_exception):\n            super(AsyncTestCase, self).run(result)\n        # As a last resort, if an exception escaped super.run() and wasn't\n        # re-raised in tearDown, raise it here.  This will cause the\n        # unittest run to fail messily, but that's better than silently\n        # ignoring an error.\n        self.__rethrow()\n\n    def stop(self, _arg=None, **kwargs):\n        \"\"\"Stops the `.IOLoop`, causing one pending (or future) call to `wait()`\n        to return.\n\n        Keyword arguments or a single positional argument passed to `stop()` are\n        saved and will be returned by `wait()`.\n        \"\"\"\n        assert _arg is None or not kwargs\n        self.__stop_args = kwargs or _arg\n        if self.__running:\n            self.io_loop.stop()\n            self.__running = False\n        self.__stopped = True\n\n    def wait(self, condition=None, timeout=None):\n        \"\"\"Runs the `.IOLoop` until stop is called or timeout has passed.\n\n        In the event of a timeout, an exception will be thrown. The\n        default timeout is 5 seconds; it may be overridden with a\n        ``timeout`` keyword argument or globally with the\n        ``ASYNC_TEST_TIMEOUT`` environment variable.\n\n        If ``condition`` is not None, the `.IOLoop` will be restarted\n        after `stop()` until ``condition()`` returns true.\n\n        .. versionchanged:: 3.1\n           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.\n        \"\"\"\n        if timeout is None:\n            timeout = get_async_test_timeout()\n\n        if not self.__stopped:\n            if timeout:\n                def timeout_func():\n                    try:\n                        raise self.failureException(\n                            'Async operation timed out after %s seconds' %\n                            timeout)\n                    except Exception:\n                        self.__failure = sys.exc_info()\n                    self.stop()\n                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,\n                                                          timeout_func)\n            while True:\n                self.__running = True\n                self.io_loop.start()\n                if (self.__failure is not None or\n                        condition is None or condition()):\n                    break\n            if self.__timeout is not None:\n                self.io_loop.remove_timeout(self.__timeout)\n                self.__timeout = None\n        assert self.__stopped\n        self.__stopped = False\n        self.__rethrow()\n        result = self.__stop_args\n        self.__stop_args = None\n        return result",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 215,
                            "end_lineno": 229,
                            "parent": {
                                "file_name": "tornado/testing.py",
                                "type": "class",
                                "name": "AsyncTestCase",
                                "content": "class AsyncTestCase(unittest.TestCase):\n    \"\"\"`~unittest.TestCase` subclass for testing `.IOLoop`-based\n    asynchronous code.\n\n    The unittest framework is synchronous, so the test must be\n    complete by the time the test method returns.  This means that\n    asynchronous code cannot be used in quite the same way as usual.\n    To write test functions that use the same ``yield``-based patterns\n    used with the `tornado.gen` module, decorate your test methods\n    with `tornado.testing.gen_test` instead of\n    `tornado.gen.coroutine`.  This class also provides the `stop()`\n    and `wait()` methods for a more manual style of testing.  The test\n    method itself must call ``self.wait()``, and asynchronous\n    callbacks should call ``self.stop()`` to signal completion.\n\n    By default, a new `.IOLoop` is constructed for each test and is available\n    as ``self.io_loop``.  If the code being tested requires a\n    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.\n\n    The `.IOLoop`'s ``start`` and ``stop`` methods should not be\n    called directly.  Instead, use `self.stop <stop>` and `self.wait\n    <wait>`.  Arguments passed to ``self.stop`` are returned from\n    ``self.wait``.  It is possible to have multiple ``wait``/``stop``\n    cycles in the same test.\n\n    Example::\n\n        # This test uses coroutine style.\n        class MyTestCase(AsyncTestCase):\n            @tornado.testing.gen_test\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                response = yield client.fetch(\"http://www.tornadoweb.org\")\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses argument passing between self.stop and self.wait.\n        class MyTestCase2(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.stop)\n                response = self.wait()\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses an explicit callback-based style.\n        class MyTestCase3(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.handle_fetch)\n                self.wait()\n\n            def handle_fetch(self, response):\n                # Test contents of response (failures and exceptions here\n                # will cause self.wait() to throw an exception and end the\n                # test).\n                # Exceptions thrown here are magically propagated to\n                # self.wait() in test_http_fetch() via stack_context.\n                self.assertIn(\"FriendFeed\", response.body)\n                self.stop()\n    \"\"\"\n    def __init__(self, methodName='runTest'):\n        super(AsyncTestCase, self).__init__(methodName)\n        self.__stopped = False\n        self.__running = False\n        self.__failure = None\n        self.__stop_args = None\n        self.__timeout = None\n\n        # It's easy to forget the @gen_test decorator, but if you do\n        # the test will silently be ignored because nothing will consume\n        # the generator.  Replace the test method with a wrapper that will\n        # make sure it's not an undecorated generator.\n        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))\n\n    def setUp(self):\n        super(AsyncTestCase, self).setUp()\n        self.io_loop = self.get_new_ioloop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        # Clean up Subprocess, so it can be used again with a new ioloop.\n        Subprocess.uninitialize()\n        self.io_loop.clear_current()\n        # Try to clean up any file descriptors left open in the ioloop.\n        # This avoids leaks, especially when tests are run repeatedly\n        # in the same process with autoreload (because curl does not\n        # set FD_CLOEXEC on its file descriptors)\n        self.io_loop.close(all_fds=True)\n        super(AsyncTestCase, self).tearDown()\n        # In case an exception escaped or the StackContext caught an exception\n        # when there wasn't a wait() to re-raise it, do so here.\n        # This is our last chance to raise an exception in a way that the\n        # unittest machinery understands.\n        self.__rethrow()\n\n    def get_new_ioloop(self):\n        \"\"\"Creates a new `.IOLoop` for this test.  May be overridden in\n        subclasses for tests that require a specific `.IOLoop` (usually\n        the singleton `.IOLoop.instance()`).\n        \"\"\"\n        return IOLoop()\n\n    def _handle_exception(self, typ, value, tb):\n        if self.__failure is None:\n            self.__failure = (typ, value, tb)\n        else:\n            app_log.error(\"multiple unhandled exceptions in test\",\n                          exc_info=(typ, value, tb))\n        self.stop()\n        return True\n\n    def __rethrow(self):\n        if self.__failure is not None:\n            failure = self.__failure\n            self.__failure = None\n            raise_exc_info(failure)\n\n    def run(self, result=None):\n        with ExceptionStackContext(self._handle_exception):\n            super(AsyncTestCase, self).run(result)\n        # As a last resort, if an exception escaped super.run() and wasn't\n        # re-raised in tearDown, raise it here.  This will cause the\n        # unittest run to fail messily, but that's better than silently\n        # ignoring an error.\n        self.__rethrow()\n\n    def stop(self, _arg=None, **kwargs):\n        \"\"\"Stops the `.IOLoop`, causing one pending (or future) call to `wait()`\n        to return.\n\n        Keyword arguments or a single positional argument passed to `stop()` are\n        saved and will be returned by `wait()`.\n        \"\"\"\n        assert _arg is None or not kwargs\n        self.__stop_args = kwargs or _arg\n        if self.__running:\n            self.io_loop.stop()\n            self.__running = False\n        self.__stopped = True\n\n    def wait(self, condition=None, timeout=None):\n        \"\"\"Runs the `.IOLoop` until stop is called or timeout has passed.\n\n        In the event of a timeout, an exception will be thrown. The\n        default timeout is 5 seconds; it may be overridden with a\n        ``timeout`` keyword argument or globally with the\n        ``ASYNC_TEST_TIMEOUT`` environment variable.\n\n        If ``condition`` is not None, the `.IOLoop` will be restarted\n        after `stop()` until ``condition()`` returns true.\n\n        .. versionchanged:: 3.1\n           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.\n        \"\"\"\n        if timeout is None:\n            timeout = get_async_test_timeout()\n\n        if not self.__stopped:\n            if timeout:\n                def timeout_func():\n                    try:\n                        raise self.failureException(\n                            'Async operation timed out after %s seconds' %\n                            timeout)\n                    except Exception:\n                        self.__failure = sys.exc_info()\n                    self.stop()\n                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,\n                                                          timeout_func)\n            while True:\n                self.__running = True\n                self.io_loop.start()\n                if (self.__failure is not None or\n                        condition is None or condition()):\n                    break\n            if self.__timeout is not None:\n                self.io_loop.remove_timeout(self.__timeout)\n                self.__timeout = None\n        assert self.__stopped\n        self.__stopped = False\n        self.__rethrow()\n        result = self.__stop_args\n        self.__stop_args = None\n        return result",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 135,
                                "end_lineno": 319,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/testing.py",
                            "type": "class",
                            "name": "AsyncTestCase",
                            "content": "class AsyncTestCase(unittest.TestCase):\n    \"\"\"`~unittest.TestCase` subclass for testing `.IOLoop`-based\n    asynchronous code.\n\n    The unittest framework is synchronous, so the test must be\n    complete by the time the test method returns.  This means that\n    asynchronous code cannot be used in quite the same way as usual.\n    To write test functions that use the same ``yield``-based patterns\n    used with the `tornado.gen` module, decorate your test methods\n    with `tornado.testing.gen_test` instead of\n    `tornado.gen.coroutine`.  This class also provides the `stop()`\n    and `wait()` methods for a more manual style of testing.  The test\n    method itself must call ``self.wait()``, and asynchronous\n    callbacks should call ``self.stop()`` to signal completion.\n\n    By default, a new `.IOLoop` is constructed for each test and is available\n    as ``self.io_loop``.  If the code being tested requires a\n    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.\n\n    The `.IOLoop`'s ``start`` and ``stop`` methods should not be\n    called directly.  Instead, use `self.stop <stop>` and `self.wait\n    <wait>`.  Arguments passed to ``self.stop`` are returned from\n    ``self.wait``.  It is possible to have multiple ``wait``/``stop``\n    cycles in the same test.\n\n    Example::\n\n        # This test uses coroutine style.\n        class MyTestCase(AsyncTestCase):\n            @tornado.testing.gen_test\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                response = yield client.fetch(\"http://www.tornadoweb.org\")\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses argument passing between self.stop and self.wait.\n        class MyTestCase2(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.stop)\n                response = self.wait()\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses an explicit callback-based style.\n        class MyTestCase3(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.handle_fetch)\n                self.wait()\n\n            def handle_fetch(self, response):\n                # Test contents of response (failures and exceptions here\n                # will cause self.wait() to throw an exception and end the\n                # test).\n                # Exceptions thrown here are magically propagated to\n                # self.wait() in test_http_fetch() via stack_context.\n                self.assertIn(\"FriendFeed\", response.body)\n                self.stop()\n    \"\"\"\n    def __init__(self, methodName='runTest'):\n        super(AsyncTestCase, self).__init__(methodName)\n        self.__stopped = False\n        self.__running = False\n        self.__failure = None\n        self.__stop_args = None\n        self.__timeout = None\n\n        # It's easy to forget the @gen_test decorator, but if you do\n        # the test will silently be ignored because nothing will consume\n        # the generator.  Replace the test method with a wrapper that will\n        # make sure it's not an undecorated generator.\n        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))\n\n    def setUp(self):\n        super(AsyncTestCase, self).setUp()\n        self.io_loop = self.get_new_ioloop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        # Clean up Subprocess, so it can be used again with a new ioloop.\n        Subprocess.uninitialize()\n        self.io_loop.clear_current()\n        # Try to clean up any file descriptors left open in the ioloop.\n        # This avoids leaks, especially when tests are run repeatedly\n        # in the same process with autoreload (because curl does not\n        # set FD_CLOEXEC on its file descriptors)\n        self.io_loop.close(all_fds=True)\n        super(AsyncTestCase, self).tearDown()\n        # In case an exception escaped or the StackContext caught an exception\n        # when there wasn't a wait() to re-raise it, do so here.\n        # This is our last chance to raise an exception in a way that the\n        # unittest machinery understands.\n        self.__rethrow()\n\n    def get_new_ioloop(self):\n        \"\"\"Creates a new `.IOLoop` for this test.  May be overridden in\n        subclasses for tests that require a specific `.IOLoop` (usually\n        the singleton `.IOLoop.instance()`).\n        \"\"\"\n        return IOLoop()\n\n    def _handle_exception(self, typ, value, tb):\n        if self.__failure is None:\n            self.__failure = (typ, value, tb)\n        else:\n            app_log.error(\"multiple unhandled exceptions in test\",\n                          exc_info=(typ, value, tb))\n        self.stop()\n        return True\n\n    def __rethrow(self):\n        if self.__failure is not None:\n            failure = self.__failure\n            self.__failure = None\n            raise_exc_info(failure)\n\n    def run(self, result=None):\n        with ExceptionStackContext(self._handle_exception):\n            super(AsyncTestCase, self).run(result)\n        # As a last resort, if an exception escaped super.run() and wasn't\n        # re-raised in tearDown, raise it here.  This will cause the\n        # unittest run to fail messily, but that's better than silently\n        # ignoring an error.\n        self.__rethrow()\n\n    def stop(self, _arg=None, **kwargs):\n        \"\"\"Stops the `.IOLoop`, causing one pending (or future) call to `wait()`\n        to return.\n\n        Keyword arguments or a single positional argument passed to `stop()` are\n        saved and will be returned by `wait()`.\n        \"\"\"\n        assert _arg is None or not kwargs\n        self.__stop_args = kwargs or _arg\n        if self.__running:\n            self.io_loop.stop()\n            self.__running = False\n        self.__stopped = True\n\n    def wait(self, condition=None, timeout=None):\n        \"\"\"Runs the `.IOLoop` until stop is called or timeout has passed.\n\n        In the event of a timeout, an exception will be thrown. The\n        default timeout is 5 seconds; it may be overridden with a\n        ``timeout`` keyword argument or globally with the\n        ``ASYNC_TEST_TIMEOUT`` environment variable.\n\n        If ``condition`` is not None, the `.IOLoop` will be restarted\n        after `stop()` until ``condition()`` returns true.\n\n        .. versionchanged:: 3.1\n           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.\n        \"\"\"\n        if timeout is None:\n            timeout = get_async_test_timeout()\n\n        if not self.__stopped:\n            if timeout:\n                def timeout_func():\n                    try:\n                        raise self.failureException(\n                            'Async operation timed out after %s seconds' %\n                            timeout)\n                    except Exception:\n                        self.__failure = sys.exc_info()\n                    self.stop()\n                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,\n                                                          timeout_func)\n            while True:\n                self.__running = True\n                self.io_loop.start()\n                if (self.__failure is not None or\n                        condition is None or condition()):\n                    break\n            if self.__timeout is not None:\n                self.io_loop.remove_timeout(self.__timeout)\n                self.__timeout = None\n        assert self.__stopped\n        self.__stopped = False\n        self.__rethrow()\n        result = self.__stop_args\n        self.__stop_args = None\n        return result",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 135,
                            "end_lineno": 319,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 229,
                            "length": 9
                        },
                        "new_range": {
                            "start": 236,
                            "length": 15
                        },
                        "section": "class AsyncTestCase(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.__rethrow()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def get_new_ioloop(self):",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"Creates a new `.IOLoop` for this test.  May be overridden in",
                                "type": "deleted"
                            },
                            {
                                "content": "        subclasses for tests that require a specific `.IOLoop` (usually",
                                "type": "deleted"
                            },
                            {
                                "content": "        the singleton `.IOLoop.instance()`).",
                                "type": "deleted"
                            },
                            {
                                "content": "        \"\"\"Returns the `.IOLoop` to use for this test.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        By default, a new `.IOLoop` is created for each test.",
                                "type": "added"
                            },
                            {
                                "content": "        Subclasses may override this method to return",
                                "type": "added"
                            },
                            {
                                "content": "        `.IOLoop.current()` if it is not appropriate to use a new",
                                "type": "added"
                            },
                            {
                                "content": "        `.IOLoop` in each tests (for example, if there are global",
                                "type": "added"
                            },
                            {
                                "content": "        singletons using the default `.IOLoop`) or if a per-test event",
                                "type": "added"
                            },
                            {
                                "content": "        loop is being provided by another system (such as",
                                "type": "added"
                            },
                            {
                                "content": "        ``pytest-asyncio``).",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "        return IOLoop()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/testing.py",
                            "type": "method",
                            "name": "AsyncTestCase.get_new_ioloop",
                            "content": "class AsyncTestCase(unittest.TestCase):\n    \"\"\"`~unittest.TestCase` subclass for testing `.IOLoop`-based\n    asynchronous code.\n\n    The unittest framework is synchronous, so the test must be\n    complete by the time the test method returns.  This means that\n    asynchronous code cannot be used in quite the same way as usual.\n    To write test functions that use the same ``yield``-based patterns\n    used with the `tornado.gen` module, decorate your test methods\n    with `tornado.testing.gen_test` instead of\n    `tornado.gen.coroutine`.  This class also provides the `stop()`\n    and `wait()` methods for a more manual style of testing.  The test\n    method itself must call ``self.wait()``, and asynchronous\n    callbacks should call ``self.stop()`` to signal completion.\n\n    By default, a new `.IOLoop` is constructed for each test and is available\n    as ``self.io_loop``.  If the code being tested requires a\n    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.\n\n    The `.IOLoop`'s ``start`` and ``stop`` methods should not be\n    called directly.  Instead, use `self.stop <stop>` and `self.wait\n    <wait>`.  Arguments passed to ``self.stop`` are returned from\n    ``self.wait``.  It is possible to have multiple ``wait``/``stop``\n    cycles in the same test.\n\n    Example::\n\n        # This test uses coroutine style.\n        class MyTestCase(AsyncTestCase):\n            @tornado.testing.gen_test\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                response = yield client.fetch(\"http://www.tornadoweb.org\")\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses argument passing between self.stop and self.wait.\n        class MyTestCase2(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.stop)\n                response = self.wait()\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses an explicit callback-based style.\n        class MyTestCase3(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.handle_fetch)\n                self.wait()\n\n            def handle_fetch(self, response):\n                # Test contents of response (failures and exceptions here\n                # will cause self.wait() to throw an exception and end the\n                # test).\n                # Exceptions thrown here are magically propagated to\n                # self.wait() in test_http_fetch() via stack_context.\n                self.assertIn(\"FriendFeed\", response.body)\n                self.stop()\n    \"\"\"\n    def __init__(self, methodName='runTest'):\n        super(AsyncTestCase, self).__init__(methodName)\n        self.__stopped = False\n        self.__running = False\n        self.__failure = None\n        self.__stop_args = None\n        self.__timeout = None\n\n        # It's easy to forget the @gen_test decorator, but if you do\n        # the test will silently be ignored because nothing will consume\n        # the generator.  Replace the test method with a wrapper that will\n        # make sure it's not an undecorated generator.\n        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))\n\n    def setUp(self):\n        super(AsyncTestCase, self).setUp()\n        self.io_loop = self.get_new_ioloop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        # Clean up Subprocess, so it can be used again with a new ioloop.\n        Subprocess.uninitialize()\n        self.io_loop.clear_current()\n        # Try to clean up any file descriptors left open in the ioloop.\n        # This avoids leaks, especially when tests are run repeatedly\n        # in the same process with autoreload (because curl does not\n        # set FD_CLOEXEC on its file descriptors)\n        self.io_loop.close(all_fds=True)\n        super(AsyncTestCase, self).tearDown()\n        # In case an exception escaped or the StackContext caught an exception\n        # when there wasn't a wait() to re-raise it, do so here.\n        # This is our last chance to raise an exception in a way that the\n        # unittest machinery understands.\n        self.__rethrow()\n\n    def get_new_ioloop(self):\n        \"\"\"Creates a new `.IOLoop` for this test.  May be overridden in\n        subclasses for tests that require a specific `.IOLoop` (usually\n        the singleton `.IOLoop.instance()`).\n        \"\"\"\n        return IOLoop()\n\n    def _handle_exception(self, typ, value, tb):\n        if self.__failure is None:\n            self.__failure = (typ, value, tb)\n        else:\n            app_log.error(\"multiple unhandled exceptions in test\",\n                          exc_info=(typ, value, tb))\n        self.stop()\n        return True\n\n    def __rethrow(self):\n        if self.__failure is not None:\n            failure = self.__failure\n            self.__failure = None\n            raise_exc_info(failure)\n\n    def run(self, result=None):\n        with ExceptionStackContext(self._handle_exception):\n            super(AsyncTestCase, self).run(result)\n        # As a last resort, if an exception escaped super.run() and wasn't\n        # re-raised in tearDown, raise it here.  This will cause the\n        # unittest run to fail messily, but that's better than silently\n        # ignoring an error.\n        self.__rethrow()\n\n    def stop(self, _arg=None, **kwargs):\n        \"\"\"Stops the `.IOLoop`, causing one pending (or future) call to `wait()`\n        to return.\n\n        Keyword arguments or a single positional argument passed to `stop()` are\n        saved and will be returned by `wait()`.\n        \"\"\"\n        assert _arg is None or not kwargs\n        self.__stop_args = kwargs or _arg\n        if self.__running:\n            self.io_loop.stop()\n            self.__running = False\n        self.__stopped = True\n\n    def wait(self, condition=None, timeout=None):\n        \"\"\"Runs the `.IOLoop` until stop is called or timeout has passed.\n\n        In the event of a timeout, an exception will be thrown. The\n        default timeout is 5 seconds; it may be overridden with a\n        ``timeout`` keyword argument or globally with the\n        ``ASYNC_TEST_TIMEOUT`` environment variable.\n\n        If ``condition`` is not None, the `.IOLoop` will be restarted\n        after `stop()` until ``condition()`` returns true.\n\n        .. versionchanged:: 3.1\n           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.\n        \"\"\"\n        if timeout is None:\n            timeout = get_async_test_timeout()\n\n        if not self.__stopped:\n            if timeout:\n                def timeout_func():\n                    try:\n                        raise self.failureException(\n                            'Async operation timed out after %s seconds' %\n                            timeout)\n                    except Exception:\n                        self.__failure = sys.exc_info()\n                    self.stop()\n                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,\n                                                          timeout_func)\n            while True:\n                self.__running = True\n                self.io_loop.start()\n                if (self.__failure is not None or\n                        condition is None or condition()):\n                    break\n            if self.__timeout is not None:\n                self.io_loop.remove_timeout(self.__timeout)\n                self.__timeout = None\n        assert self.__stopped\n        self.__stopped = False\n        self.__rethrow()\n        result = self.__stop_args\n        self.__stop_args = None\n        return result",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 231,
                            "end_lineno": 236,
                            "parent": {
                                "file_name": "tornado/testing.py",
                                "type": "class",
                                "name": "AsyncTestCase",
                                "content": "class AsyncTestCase(unittest.TestCase):\n    \"\"\"`~unittest.TestCase` subclass for testing `.IOLoop`-based\n    asynchronous code.\n\n    The unittest framework is synchronous, so the test must be\n    complete by the time the test method returns.  This means that\n    asynchronous code cannot be used in quite the same way as usual.\n    To write test functions that use the same ``yield``-based patterns\n    used with the `tornado.gen` module, decorate your test methods\n    with `tornado.testing.gen_test` instead of\n    `tornado.gen.coroutine`.  This class also provides the `stop()`\n    and `wait()` methods for a more manual style of testing.  The test\n    method itself must call ``self.wait()``, and asynchronous\n    callbacks should call ``self.stop()`` to signal completion.\n\n    By default, a new `.IOLoop` is constructed for each test and is available\n    as ``self.io_loop``.  If the code being tested requires a\n    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.\n\n    The `.IOLoop`'s ``start`` and ``stop`` methods should not be\n    called directly.  Instead, use `self.stop <stop>` and `self.wait\n    <wait>`.  Arguments passed to ``self.stop`` are returned from\n    ``self.wait``.  It is possible to have multiple ``wait``/``stop``\n    cycles in the same test.\n\n    Example::\n\n        # This test uses coroutine style.\n        class MyTestCase(AsyncTestCase):\n            @tornado.testing.gen_test\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                response = yield client.fetch(\"http://www.tornadoweb.org\")\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses argument passing between self.stop and self.wait.\n        class MyTestCase2(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.stop)\n                response = self.wait()\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses an explicit callback-based style.\n        class MyTestCase3(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.handle_fetch)\n                self.wait()\n\n            def handle_fetch(self, response):\n                # Test contents of response (failures and exceptions here\n                # will cause self.wait() to throw an exception and end the\n                # test).\n                # Exceptions thrown here are magically propagated to\n                # self.wait() in test_http_fetch() via stack_context.\n                self.assertIn(\"FriendFeed\", response.body)\n                self.stop()\n    \"\"\"\n    def __init__(self, methodName='runTest'):\n        super(AsyncTestCase, self).__init__(methodName)\n        self.__stopped = False\n        self.__running = False\n        self.__failure = None\n        self.__stop_args = None\n        self.__timeout = None\n\n        # It's easy to forget the @gen_test decorator, but if you do\n        # the test will silently be ignored because nothing will consume\n        # the generator.  Replace the test method with a wrapper that will\n        # make sure it's not an undecorated generator.\n        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))\n\n    def setUp(self):\n        super(AsyncTestCase, self).setUp()\n        self.io_loop = self.get_new_ioloop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        # Clean up Subprocess, so it can be used again with a new ioloop.\n        Subprocess.uninitialize()\n        self.io_loop.clear_current()\n        # Try to clean up any file descriptors left open in the ioloop.\n        # This avoids leaks, especially when tests are run repeatedly\n        # in the same process with autoreload (because curl does not\n        # set FD_CLOEXEC on its file descriptors)\n        self.io_loop.close(all_fds=True)\n        super(AsyncTestCase, self).tearDown()\n        # In case an exception escaped or the StackContext caught an exception\n        # when there wasn't a wait() to re-raise it, do so here.\n        # This is our last chance to raise an exception in a way that the\n        # unittest machinery understands.\n        self.__rethrow()\n\n    def get_new_ioloop(self):\n        \"\"\"Creates a new `.IOLoop` for this test.  May be overridden in\n        subclasses for tests that require a specific `.IOLoop` (usually\n        the singleton `.IOLoop.instance()`).\n        \"\"\"\n        return IOLoop()\n\n    def _handle_exception(self, typ, value, tb):\n        if self.__failure is None:\n            self.__failure = (typ, value, tb)\n        else:\n            app_log.error(\"multiple unhandled exceptions in test\",\n                          exc_info=(typ, value, tb))\n        self.stop()\n        return True\n\n    def __rethrow(self):\n        if self.__failure is not None:\n            failure = self.__failure\n            self.__failure = None\n            raise_exc_info(failure)\n\n    def run(self, result=None):\n        with ExceptionStackContext(self._handle_exception):\n            super(AsyncTestCase, self).run(result)\n        # As a last resort, if an exception escaped super.run() and wasn't\n        # re-raised in tearDown, raise it here.  This will cause the\n        # unittest run to fail messily, but that's better than silently\n        # ignoring an error.\n        self.__rethrow()\n\n    def stop(self, _arg=None, **kwargs):\n        \"\"\"Stops the `.IOLoop`, causing one pending (or future) call to `wait()`\n        to return.\n\n        Keyword arguments or a single positional argument passed to `stop()` are\n        saved and will be returned by `wait()`.\n        \"\"\"\n        assert _arg is None or not kwargs\n        self.__stop_args = kwargs or _arg\n        if self.__running:\n            self.io_loop.stop()\n            self.__running = False\n        self.__stopped = True\n\n    def wait(self, condition=None, timeout=None):\n        \"\"\"Runs the `.IOLoop` until stop is called or timeout has passed.\n\n        In the event of a timeout, an exception will be thrown. The\n        default timeout is 5 seconds; it may be overridden with a\n        ``timeout`` keyword argument or globally with the\n        ``ASYNC_TEST_TIMEOUT`` environment variable.\n\n        If ``condition`` is not None, the `.IOLoop` will be restarted\n        after `stop()` until ``condition()`` returns true.\n\n        .. versionchanged:: 3.1\n           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.\n        \"\"\"\n        if timeout is None:\n            timeout = get_async_test_timeout()\n\n        if not self.__stopped:\n            if timeout:\n                def timeout_func():\n                    try:\n                        raise self.failureException(\n                            'Async operation timed out after %s seconds' %\n                            timeout)\n                    except Exception:\n                        self.__failure = sys.exc_info()\n                    self.stop()\n                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,\n                                                          timeout_func)\n            while True:\n                self.__running = True\n                self.io_loop.start()\n                if (self.__failure is not None or\n                        condition is None or condition()):\n                    break\n            if self.__timeout is not None:\n                self.io_loop.remove_timeout(self.__timeout)\n                self.__timeout = None\n        assert self.__stopped\n        self.__stopped = False\n        self.__rethrow()\n        result = self.__stop_args\n        self.__stop_args = None\n        return result",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 135,
                                "end_lineno": 319,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/testing.py",
                            "type": "class",
                            "name": "AsyncTestCase",
                            "content": "class AsyncTestCase(unittest.TestCase):\n    \"\"\"`~unittest.TestCase` subclass for testing `.IOLoop`-based\n    asynchronous code.\n\n    The unittest framework is synchronous, so the test must be\n    complete by the time the test method returns.  This means that\n    asynchronous code cannot be used in quite the same way as usual.\n    To write test functions that use the same ``yield``-based patterns\n    used with the `tornado.gen` module, decorate your test methods\n    with `tornado.testing.gen_test` instead of\n    `tornado.gen.coroutine`.  This class also provides the `stop()`\n    and `wait()` methods for a more manual style of testing.  The test\n    method itself must call ``self.wait()``, and asynchronous\n    callbacks should call ``self.stop()`` to signal completion.\n\n    By default, a new `.IOLoop` is constructed for each test and is available\n    as ``self.io_loop``.  If the code being tested requires a\n    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.\n\n    The `.IOLoop`'s ``start`` and ``stop`` methods should not be\n    called directly.  Instead, use `self.stop <stop>` and `self.wait\n    <wait>`.  Arguments passed to ``self.stop`` are returned from\n    ``self.wait``.  It is possible to have multiple ``wait``/``stop``\n    cycles in the same test.\n\n    Example::\n\n        # This test uses coroutine style.\n        class MyTestCase(AsyncTestCase):\n            @tornado.testing.gen_test\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                response = yield client.fetch(\"http://www.tornadoweb.org\")\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses argument passing between self.stop and self.wait.\n        class MyTestCase2(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.stop)\n                response = self.wait()\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses an explicit callback-based style.\n        class MyTestCase3(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.handle_fetch)\n                self.wait()\n\n            def handle_fetch(self, response):\n                # Test contents of response (failures and exceptions here\n                # will cause self.wait() to throw an exception and end the\n                # test).\n                # Exceptions thrown here are magically propagated to\n                # self.wait() in test_http_fetch() via stack_context.\n                self.assertIn(\"FriendFeed\", response.body)\n                self.stop()\n    \"\"\"\n    def __init__(self, methodName='runTest'):\n        super(AsyncTestCase, self).__init__(methodName)\n        self.__stopped = False\n        self.__running = False\n        self.__failure = None\n        self.__stop_args = None\n        self.__timeout = None\n\n        # It's easy to forget the @gen_test decorator, but if you do\n        # the test will silently be ignored because nothing will consume\n        # the generator.  Replace the test method with a wrapper that will\n        # make sure it's not an undecorated generator.\n        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))\n\n    def setUp(self):\n        super(AsyncTestCase, self).setUp()\n        self.io_loop = self.get_new_ioloop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        # Clean up Subprocess, so it can be used again with a new ioloop.\n        Subprocess.uninitialize()\n        self.io_loop.clear_current()\n        # Try to clean up any file descriptors left open in the ioloop.\n        # This avoids leaks, especially when tests are run repeatedly\n        # in the same process with autoreload (because curl does not\n        # set FD_CLOEXEC on its file descriptors)\n        self.io_loop.close(all_fds=True)\n        super(AsyncTestCase, self).tearDown()\n        # In case an exception escaped or the StackContext caught an exception\n        # when there wasn't a wait() to re-raise it, do so here.\n        # This is our last chance to raise an exception in a way that the\n        # unittest machinery understands.\n        self.__rethrow()\n\n    def get_new_ioloop(self):\n        \"\"\"Creates a new `.IOLoop` for this test.  May be overridden in\n        subclasses for tests that require a specific `.IOLoop` (usually\n        the singleton `.IOLoop.instance()`).\n        \"\"\"\n        return IOLoop()\n\n    def _handle_exception(self, typ, value, tb):\n        if self.__failure is None:\n            self.__failure = (typ, value, tb)\n        else:\n            app_log.error(\"multiple unhandled exceptions in test\",\n                          exc_info=(typ, value, tb))\n        self.stop()\n        return True\n\n    def __rethrow(self):\n        if self.__failure is not None:\n            failure = self.__failure\n            self.__failure = None\n            raise_exc_info(failure)\n\n    def run(self, result=None):\n        with ExceptionStackContext(self._handle_exception):\n            super(AsyncTestCase, self).run(result)\n        # As a last resort, if an exception escaped super.run() and wasn't\n        # re-raised in tearDown, raise it here.  This will cause the\n        # unittest run to fail messily, but that's better than silently\n        # ignoring an error.\n        self.__rethrow()\n\n    def stop(self, _arg=None, **kwargs):\n        \"\"\"Stops the `.IOLoop`, causing one pending (or future) call to `wait()`\n        to return.\n\n        Keyword arguments or a single positional argument passed to `stop()` are\n        saved and will be returned by `wait()`.\n        \"\"\"\n        assert _arg is None or not kwargs\n        self.__stop_args = kwargs or _arg\n        if self.__running:\n            self.io_loop.stop()\n            self.__running = False\n        self.__stopped = True\n\n    def wait(self, condition=None, timeout=None):\n        \"\"\"Runs the `.IOLoop` until stop is called or timeout has passed.\n\n        In the event of a timeout, an exception will be thrown. The\n        default timeout is 5 seconds; it may be overridden with a\n        ``timeout`` keyword argument or globally with the\n        ``ASYNC_TEST_TIMEOUT`` environment variable.\n\n        If ``condition`` is not None, the `.IOLoop` will be restarted\n        after `stop()` until ``condition()`` returns true.\n\n        .. versionchanged:: 3.1\n           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.\n        \"\"\"\n        if timeout is None:\n            timeout = get_async_test_timeout()\n\n        if not self.__stopped:\n            if timeout:\n                def timeout_func():\n                    try:\n                        raise self.failureException(\n                            'Async operation timed out after %s seconds' %\n                            timeout)\n                    except Exception:\n                        self.__failure = sys.exc_info()\n                    self.stop()\n                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,\n                                                          timeout_func)\n            while True:\n                self.__running = True\n                self.io_loop.start()\n                if (self.__failure is not None or\n                        condition is None or condition()):\n                    break\n            if self.__timeout is not None:\n                self.io_loop.remove_timeout(self.__timeout)\n                self.__timeout = None\n        assert self.__stopped\n        self.__stopped = False\n        self.__rethrow()\n        result = self.__stop_args\n        self.__stop_args = None\n        return result",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 135,
                            "end_lineno": 319,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "f47d639f90bceaae27019d7949c5cea14a420293^",
    "new_commit_hash": "f47d639f90bceaae27019d7949c5cea14a420293",
    "commit_message": "testing: Don't close the event loop if we didn't create it\n\nThis improves compatibility with asyncio test frameworks like\npytest-asyncio.\n\nFixes #2324",
    "commit_date": "2018-03-25T11:50:09-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "f47d639f90bceaae27019d7949c5cea14a420293",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function\n\nfrom tornado import gen, ioloop\nfrom tornado.log import app_log\nfrom tornado.test.util import unittest, skipBefore35, exec_test\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, bind_unused_port, gen_test, ExpectLog\nfrom tornado.web import Application\nimport contextlib\nimport os\nimport platform\nimport traceback\nimport warnings\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\n\n@contextlib.contextmanager\ndef set_environ(name, value):\n    old_value = os.environ.get(name)\n    os.environ[name] = value\n\n    try:\n        yield\n    finally:\n        if old_value is None:\n            del os.environ[name]\n        else:\n            os.environ[name] = old_value\n\n\nclass AsyncTestCaseTest(AsyncTestCase):\n    def test_exception_in_callback(self):\n        self.io_loop.add_callback(lambda: 1 / 0)\n        try:\n            self.wait()\n            self.fail(\"did not get expected exception\")\n        except ZeroDivisionError:\n            pass\n\n    def test_wait_timeout(self):\n        time = self.io_loop.time\n\n        # Accept default 5-second timeout, no error\n        self.io_loop.add_timeout(time() + 0.01, self.stop)\n        self.wait()\n\n        # Timeout passed to wait()\n        self.io_loop.add_timeout(time() + 1, self.stop)\n        with self.assertRaises(self.failureException):\n            self.wait(timeout=0.01)\n\n        # Timeout set with environment variable\n        self.io_loop.add_timeout(time() + 1, self.stop)\n        with set_environ('ASYNC_TEST_TIMEOUT', '0.01'):\n            with self.assertRaises(self.failureException):\n                self.wait()\n\n    def test_subsequent_wait_calls(self):\n        \"\"\"\n        This test makes sure that a second call to wait()\n        clears the first timeout.\n        \"\"\"\n        self.io_loop.add_timeout(self.io_loop.time() + 0.00, self.stop)\n        self.wait(timeout=0.02)\n        self.io_loop.add_timeout(self.io_loop.time() + 0.03, self.stop)\n        self.wait(timeout=0.15)\n\n    def test_multiple_errors(self):\n        def fail(message):\n            raise Exception(message)\n        self.io_loop.add_callback(lambda: fail(\"error one\"))\n        self.io_loop.add_callback(lambda: fail(\"error two\"))\n        # The first error gets raised; the second gets logged.\n        with ExpectLog(app_log, \"multiple unhandled exceptions\"):\n            with self.assertRaises(Exception) as cm:\n                self.wait()\n        self.assertEqual(str(cm.exception), \"error one\")\n\n\nclass AsyncHTTPTestCaseTest(AsyncHTTPTestCase):\n    @classmethod\n    def setUpClass(cls):\n        super(AsyncHTTPTestCaseTest, cls).setUpClass()\n        # An unused port is bound so we can make requests upon it without\n        # impacting a real local web server.\n        cls.external_sock, cls.external_port = bind_unused_port()\n\n    def get_app(self):\n        return Application()\n\n    def test_fetch_segment(self):\n        path = '/path'\n        response = self.fetch(path)\n        self.assertEqual(response.request.url, self.get_url(path))\n\n    def test_fetch_full_http_url(self):\n        path = 'http://localhost:%d/path' % self.external_port\n\n        response = self.fetch(path, request_timeout=0.1)\n        self.assertEqual(response.request.url, path)\n\n    def test_fetch_full_https_url(self):\n        path = 'https://localhost:%d/path' % self.external_port\n\n        response = self.fetch(path, request_timeout=0.1)\n        self.assertEqual(response.request.url, path)\n\n    @classmethod\n    def tearDownClass(cls):\n        cls.external_sock.close()\n        super(AsyncHTTPTestCaseTest, cls).tearDownClass()\n\n\nclass AsyncTestCaseWrapperTest(unittest.TestCase):\n    def test_undecorated_generator(self):\n        class Test(AsyncTestCase):\n            def test_gen(self):\n                yield\n        test = Test('test_gen')\n        result = unittest.TestResult()\n        test.run(result)\n        self.assertEqual(len(result.errors), 1)\n        self.assertIn(\"should be decorated\", result.errors[0][1])\n\n    @skipBefore35\n    @unittest.skipIf(platform.python_implementation() == 'PyPy',\n                     'pypy destructor warnings cannot be silenced')\n    def test_undecorated_coroutine(self):\n        namespace = exec_test(globals(), locals(), \"\"\"\n        class Test(AsyncTestCase):\n            async def test_coro(self):\n                pass\n        \"\"\")\n\n        test_class = namespace['Test']\n        test = test_class('test_coro')\n        result = unittest.TestResult()\n\n        # Silence \"RuntimeWarning: coroutine 'test_coro' was never awaited\".\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore')\n            test.run(result)\n\n        self.assertEqual(len(result.errors), 1)\n        self.assertIn(\"should be decorated\", result.errors[0][1])\n\n    def test_undecorated_generator_with_skip(self):\n        class Test(AsyncTestCase):\n            @unittest.skip(\"don't run this\")\n            def test_gen(self):\n                yield\n        test = Test('test_gen')\n        result = unittest.TestResult()\n        test.run(result)\n        self.assertEqual(len(result.errors), 0)\n        self.assertEqual(len(result.skipped), 1)\n\n    def test_other_return(self):\n        class Test(AsyncTestCase):\n            def test_other_return(self):\n                return 42\n        test = Test('test_other_return')\n        result = unittest.TestResult()\n        test.run(result)\n        self.assertEqual(len(result.errors), 1)\n        self.assertIn(\"Return value from test method ignored\", result.errors[0][1])\n\n\nclass SetUpTearDownTest(unittest.TestCase):\n    def test_set_up_tear_down(self):\n        \"\"\"\n        This test makes sure that AsyncTestCase calls super methods for\n        setUp and tearDown.\n\n        InheritBoth is a subclass of both AsyncTestCase and\n        SetUpTearDown, with the ordering so that the super of\n        AsyncTestCase will be SetUpTearDown.\n        \"\"\"\n        events = []\n        result = unittest.TestResult()\n\n        class SetUpTearDown(unittest.TestCase):\n            def setUp(self):\n                events.append('setUp')\n\n            def tearDown(self):\n                events.append('tearDown')\n\n        class InheritBoth(AsyncTestCase, SetUpTearDown):\n            def test(self):\n                events.append('test')\n\n        InheritBoth('test').run(result)\n        expected = ['setUp', 'test', 'tearDown']\n        self.assertEqual(expected, events)\n\n\nclass GenTest(AsyncTestCase):\n    def setUp(self):\n        super(GenTest, self).setUp()\n        self.finished = False\n\n    def tearDown(self):\n        self.assertTrue(self.finished)\n        super(GenTest, self).tearDown()\n\n    @gen_test\n    def test_sync(self):\n        self.finished = True\n\n    @gen_test\n    def test_async(self):\n        yield gen.moment\n        self.finished = True\n\n    def test_timeout(self):\n        # Set a short timeout and exceed it.\n        @gen_test(timeout=0.1)\n        def test(self):\n            yield gen.sleep(1)\n\n        # This can't use assertRaises because we need to inspect the\n        # exc_info triple (and not just the exception object)\n        try:\n            test(self)\n            self.fail(\"did not get expected exception\")\n        except ioloop.TimeoutError:\n            # The stack trace should blame the add_timeout line, not just\n            # unrelated IOLoop/testing internals.\n            self.assertIn(\n                \"gen.sleep(1)\",\n                traceback.format_exc())\n\n        self.finished = True\n\n    def test_no_timeout(self):\n        # A test that does not exceed its timeout should succeed.\n        @gen_test(timeout=1)\n        def test(self):\n            yield gen.sleep(0.1)\n\n        test(self)\n        self.finished = True\n\n    def test_timeout_environment_variable(self):\n        @gen_test(timeout=0.5)\n        def test_long_timeout(self):\n            yield gen.sleep(0.25)\n\n        # Uses provided timeout of 0.5 seconds, doesn't time out.\n        with set_environ('ASYNC_TEST_TIMEOUT', '0.1'):\n            test_long_timeout(self)\n\n        self.finished = True\n\n    def test_no_timeout_environment_variable(self):\n        @gen_test(timeout=0.01)\n        def test_short_timeout(self):\n            yield gen.sleep(1)\n\n        # Uses environment-variable timeout of 0.1, times out.\n        with set_environ('ASYNC_TEST_TIMEOUT', '0.1'):\n            with self.assertRaises(ioloop.TimeoutError):\n                test_short_timeout(self)\n\n        self.finished = True\n\n    def test_with_method_args(self):\n        @gen_test\n        def test_with_args(self, *args):\n            self.assertEqual(args, ('test',))\n            yield gen.moment\n\n        test_with_args(self, 'test')\n        self.finished = True\n\n    def test_with_method_kwargs(self):\n        @gen_test\n        def test_with_kwargs(self, **kwargs):\n            self.assertDictEqual(kwargs, {'test': 'test'})\n            yield gen.moment\n\n        test_with_kwargs(self, test='test')\n        self.finished = True\n\n    @skipBefore35\n    def test_native_coroutine(self):\n        namespace = exec_test(globals(), locals(), \"\"\"\n        @gen_test\n        async def test(self):\n            self.finished = True\n        \"\"\")\n\n        namespace['test'](self)\n\n    @skipBefore35\n    def test_native_coroutine_timeout(self):\n        # Set a short timeout and exceed it.\n        namespace = exec_test(globals(), locals(), \"\"\"\n        @gen_test(timeout=0.1)\n        async def test(self):\n            await gen.sleep(1)\n        \"\"\")\n\n        try:\n            namespace['test'](self)\n            self.fail(\"did not get expected exception\")\n        except ioloop.TimeoutError:\n            self.finished = True\n\n\n@unittest.skipIf(asyncio is None, \"asyncio module not present\")\nclass GetNewIOLoopTest(AsyncTestCase):\n    def get_new_ioloop(self):\n        # Use the current loop instead of creating a new one here.\n        return ioloop.IOLoop.current()\n\n    def setUp(self):\n        # This simulates the effect of an asyncio test harness like\n        # pytest-asyncio.\n        self.orig_loop = asyncio.get_event_loop()\n        self.new_loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.new_loop)\n        super(GetNewIOLoopTest, self).setUp()\n\n    def tearDown(self):\n        super(GetNewIOLoopTest, self).tearDown()\n        # AsyncTestCase must not affect the existing asyncio loop.\n        self.assertFalse(asyncio.get_event_loop().is_closed())\n        asyncio.set_event_loop(self.orig_loop)\n        self.new_loop.close()\n\n    def test_loop(self):\n        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 545ms\nPrepared 1 package in 945ms\nInstalled 1 package in 1ms\n + tornado==5.1.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f47d639f90bceaae27019d7949c5cea14a420293)\nResolved 29 packages in 14ms\nInstalled 29 packages in 103ms\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_f47d639f90bceaae27019d7949c5cea14a420293\n.......................\ncollected 23 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::AsyncHTTPTestCaseTest::test_fetch_full_http_url\nPASSED r2e_tests.test_1::AsyncHTTPTestCaseTest::test_fetch_full_https_url\nPASSED r2e_tests.test_1::AsyncHTTPTestCaseTest::test_fetch_segment\nPASSED r2e_tests.test_1::AsyncTestCaseTest::test_exception_in_callback\nPASSED r2e_tests.test_1::AsyncTestCaseTest::test_multiple_errors\nPASSED r2e_tests.test_1::AsyncTestCaseTest::test_subsequent_wait_calls\nPASSED r2e_tests.test_1::AsyncTestCaseTest::test_wait_timeout\nPASSED r2e_tests.test_1::AsyncTestCaseWrapperTest::test_other_return\nPASSED r2e_tests.test_1::AsyncTestCaseWrapperTest::test_undecorated_coroutine\nPASSED r2e_tests.test_1::AsyncTestCaseWrapperTest::test_undecorated_generator\nPASSED r2e_tests.test_1::AsyncTestCaseWrapperTest::test_undecorated_generator_with_skip\nPASSED r2e_tests.test_1::GenTest::test_async\nPASSED r2e_tests.test_1::GenTest::test_native_coroutine\nPASSED r2e_tests.test_1::GenTest::test_native_coroutine_timeout\nPASSED r2e_tests.test_1::GenTest::test_no_timeout\nPASSED r2e_tests.test_1::GenTest::test_no_timeout_environment_variable\nPASSED r2e_tests.test_1::GenTest::test_sync\nPASSED r2e_tests.test_1::GenTest::test_timeout\nPASSED r2e_tests.test_1::GenTest::test_timeout_environment_variable\nPASSED r2e_tests.test_1::GenTest::test_with_method_args\nPASSED r2e_tests.test_1::GenTest::test_with_method_kwargs\nPASSED r2e_tests.test_1::GetNewIOLoopTest::test_loop\nPASSED r2e_tests.test_1::SetUpTearDownTest::test_set_up_tear_down\n=================== 23 passed in 0.84s ===================\n",
    "new_commit_res_stderr": "WARNING:tornado.access:404 GET /path (127.0.0.1) 0.36ms\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f47d639f90bceaae27019d7949c5cea14a420293\n.......................\ncollected 23 items\n\n=================================== FAILURES ===================================\n__________ GetNewIOLoopTest.test_loop __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 595, in run\n    self._callTearDown()\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 553, in _callTearDown\n    self.tearDown()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_f47d639f90bceaae27019d7949c5cea14a420293/r2e_tests/test_1.py\", line 332, in tearDown\n    self.assertFalse(asyncio.get_event_loop().is_closed())\nAssertionError: True is not false\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::AsyncHTTPTestCaseTest::test_fetch_full_http_url\nPASSED r2e_tests.test_1::AsyncHTTPTestCaseTest::test_fetch_full_https_url\nPASSED r2e_tests.test_1::AsyncHTTPTestCaseTest::test_fetch_segment\nPASSED r2e_tests.test_1::AsyncTestCaseTest::test_exception_in_callback\nPASSED r2e_tests.test_1::AsyncTestCaseTest::test_multiple_errors\nPASSED r2e_tests.test_1::AsyncTestCaseTest::test_subsequent_wait_calls\nPASSED r2e_tests.test_1::AsyncTestCaseTest::test_wait_timeout\nPASSED r2e_tests.test_1::AsyncTestCaseWrapperTest::test_other_return\nPASSED r2e_tests.test_1::AsyncTestCaseWrapperTest::test_undecorated_coroutine\nPASSED r2e_tests.test_1::AsyncTestCaseWrapperTest::test_undecorated_generator\nPASSED r2e_tests.test_1::AsyncTestCaseWrapperTest::test_undecorated_generator_with_skip\nPASSED r2e_tests.test_1::GenTest::test_async\nPASSED r2e_tests.test_1::GenTest::test_native_coroutine\nPASSED r2e_tests.test_1::GenTest::test_native_coroutine_timeout\nPASSED r2e_tests.test_1::GenTest::test_no_timeout\nPASSED r2e_tests.test_1::GenTest::test_no_timeout_environment_variable\nPASSED r2e_tests.test_1::GenTest::test_sync\nPASSED r2e_tests.test_1::GenTest::test_timeout\nPASSED r2e_tests.test_1::GenTest::test_timeout_environment_variable\nPASSED r2e_tests.test_1::GenTest::test_with_method_args\nPASSED r2e_tests.test_1::GenTest::test_with_method_kwargs\nFAILED r2e_tests.test_1::GetNewIOLoopTest::test_loop\nPASSED r2e_tests.test_1::SetUpTearDownTest::test_set_up_tear_down\n=================== 1 failed, 22 passed in 0.84s ===================\n",
    "old_commit_res_stderr": "WARNING:tornado.access:404 GET /path (127.0.0.1) 0.35ms\n"
}
tornado/test/testing_test.py tornado/testing.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title**: External Event Loop is Unexpectedly Closed, Causing Test Failures

**Description**:

When using an external asyncio event loop in tests, the event loop is closed by the testing framework even though it wasn't created within the test itself. This leads to tests failing because the loop is no longer active when the framework expects it to remain open.

**Example Buggy Code**:

```python
import asyncio
import unittest
from tornado.testing import AsyncTestCase, IOLoop

class CustomIOLoopTest(AsyncTestCase):
    def get_new_ioloop(self):
        return IOLoop.current()

    def setUp(self):
        self.orig_loop = asyncio.get_event_loop()
        self.new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.new_loop)
        super().setUp()

    def tearDown(self):
        super().tearDown()
        self.assertFalse(asyncio.get_event_loop().is_closed())
        asyncio.set_event_loop(self.orig_loop)
        self.new_loop.close()

    def test_event_loop(self):
        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)
```

**Expected Behavior**:

The external asyncio event loop provided by the test should remain open after the test completes. The testing framework should not interfere with the lifecycle of event loops that it did not create, allowing external management of the loop.

**Actual Behavior**:

The testing framework closes the external event loop, resulting in the test failing with an assertion that the event loop is closed. This disrupts tests that rely on external event loop management, causing unexpected failures.

[/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/testing.py
"""Support classes for automated testing.

* `AsyncTestCase` and `AsyncHTTPTestCase`:  Subclasses of unittest.TestCase
  with additional support for testing asynchronous (`.IOLoop`-based) code.

* `ExpectLog`: Make test logs less spammy.

* `main()`: A simple test runner (wrapper around unittest.main()) with support
  for the tornado.autoreload module to rerun the tests when code changes.
"""

from __future__ import absolute_import, division, print_function

try:
    from tornado import gen
    from tornado.httpclient import AsyncHTTPClient
    from tornado.httpserver import HTTPServer
    from tornado.simple_httpclient import SimpleAsyncHTTPClient
    from tornado.ioloop import IOLoop, TimeoutError
    from tornado import netutil
    from tornado.process import Subprocess
except ImportError:
    # These modules are not importable on app engine.  Parts of this module
    # won't work, but e.g. main() will.
    AsyncHTTPClient = None  # type: ignore
    gen = None  # type: ignore
    HTTPServer = None  # type: ignore
    IOLoop = None  # type: ignore
    netutil = None  # type: ignore
    SimpleAsyncHTTPClient = None  # type: ignore
    Subprocess = None  # type: ignore
from tornado.log import app_log
from tornado.stack_context import ExceptionStackContext
from tornado.util import raise_exc_info, basestring_type, PY3
import functools
import inspect
import logging
import os
import re
import signal
import socket
import sys

try:
    import asyncio
except ImportError:
    asyncio = None


try:
    from collections.abc import Generator as GeneratorType  # type: ignore
except ImportError:
    from types import GeneratorType  # type: ignore

if sys.version_info >= (3, 5):
    iscoroutine = inspect.iscoroutine  # type: ignore
    iscoroutinefunction = inspect.iscoroutinefunction  # type: ignore
else:
    iscoroutine = iscoroutinefunction = lambda f: False

# Tornado's own test suite requires the updated unittest module
# (either py27+ or unittest2) so tornado.test.util enforces
# this requirement, but for other users of tornado.testing we want
# to allow the older version if unitest2 is not available.
if PY3:
    # On python 3, mixing unittest2 and unittest (including doctest)
    # doesn't seem to work, so always use unittest.
    import unittest
else:
    # On python 2, prefer unittest2 when available.
    try:
        import unittest2 as unittest  # type: ignore
    except ImportError:
        import unittest  # type: ignore


def bind_unused_port(reuse_port=False):
    """Binds a server socket to an available port on localhost.

    Returns a tuple (socket, port).

    .. versionchanged:: 4.4
       Always binds to ``127.0.0.1`` without resolving the name
       ``localhost``.
    """
    sock = netutil.bind_sockets(None, '127.0.0.1', family=socket.AF_INET,
                                reuse_port=reuse_port)[0]
    port = sock.getsockname()[1]
    return sock, port


def get_async_test_timeout():
    """Get the global timeout setting for async tests.

    Returns a float, the timeout in seconds.

    .. versionadded:: 3.1
    """
    try:
        return float(os.environ.get('ASYNC_TEST_TIMEOUT'))
    except (ValueError, TypeError):
        return 5


class _TestMethodWrapper(object):
    """Wraps a test method to raise an error if it returns a value.

    This is mainly used to detect undecorated generators (if a test
    method yields it must use a decorator to consume the generator),
    but will also detect other kinds of return values (these are not
    necessarily errors, but we alert anyway since there is no good
    reason to return a value from a test).
    """
    def __init__(self, orig_method):
        self.orig_method = orig_method

    def __call__(self, *args, **kwargs):
        result = self.orig_method(*args, **kwargs)
        if isinstance(result, GeneratorType) or iscoroutine(result):
            raise TypeError("Generator and coroutine test methods should be"
                            " decorated with tornado.testing.gen_test")
        elif result is not None:
            raise ValueError("Return value from test method ignored: %r" %
                             result)

    def __getattr__(self, name):
        """Proxy all unknown attributes to the original method.

        This is important for some of the decorators in the `unittest`
        module, such as `unittest.skipIf`.
        """
        return getattr(self.orig_method, name)


class AsyncTestCase(unittest.TestCase):
    """`~unittest.TestCase` subclass for testing `.IOLoop`-based
    asynchronous code.

    The unittest framework is synchronous, so the test must be
    complete by the time the test method returns.  This means that
    asynchronous code cannot be used in quite the same way as usual.
    To write test functions that use the same ``yield``-based patterns
    used with the `tornado.gen` module, decorate your test methods
    with `tornado.testing.gen_test` instead of
    `tornado.gen.coroutine`.  This class also provides the `stop()`
    and `wait()` methods for a more manual style of testing.  The test
    method itself must call ``self.wait()``, and asynchronous
    callbacks should call ``self.stop()`` to signal completion.

    By default, a new `.IOLoop` is constructed for each test and is available
    as ``self.io_loop``.  If the code being tested requires a
    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.

    The `.IOLoop`'s ``start`` and ``stop`` methods should not be
    called directly.  Instead, use `self.stop <stop>` and `self.wait
    <wait>`.  Arguments passed to ``self.stop`` are returned from
    ``self.wait``.  It is possible to have multiple ``wait``/``stop``
    cycles in the same test.

    Example::

        # This test uses coroutine style.
        class MyTestCase(AsyncTestCase):
            @tornado.testing.gen_test
            def test_http_fetch(self):
                client = AsyncHTTPClient()
                response = yield client.fetch("http://www.tornadoweb.org")
                # Test contents of response
                self.assertIn("FriendFeed", response.body)

        # This test uses argument passing between self.stop and self.wait.
        class MyTestCase2(AsyncTestCase):
            def test_http_fetch(self):
                client = AsyncHTTPClient()
                client.fetch("http://www.tornadoweb.org/", self.stop)
                response = self.wait()
                # Test contents of response
                self.assertIn("FriendFeed", response.body)

        # This test uses an explicit callback-based style.
        class MyTestCase3(AsyncTestCase):
            def test_http_fetch(self):
                client = AsyncHTTPClient()
                client.fetch("http://www.tornadoweb.org/", self.handle_fetch)
                self.wait()

            def handle_fetch(self, response):
                # Test contents of response (failures and exceptions here
                # will cause self.wait() to throw an exception and end the
                # test).
                # Exceptions thrown here are magically propagated to
                # self.wait() in test_http_fetch() via stack_context.
                self.assertIn("FriendFeed", response.body)
                self.stop()
    """
    def __init__(self, methodName='runTest'):
        super(AsyncTestCase, self).__init__(methodName)
        self.__stopped = False
        self.__running = False
        self.__failure = None
        self.__stop_args = None
        self.__timeout = None

        # It's easy to forget the @gen_test decorator, but if you do
        # the test will silently be ignored because nothing will consume
        # the generator.  Replace the test method with a wrapper that will
        # make sure it's not an undecorated generator.
        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))

    def setUp(self):
        super(AsyncTestCase, self).setUp()
        self.io_loop = self.get_new_ioloop()
        self.io_loop.make_current()

    def tearDown(self):
        # Clean up Subprocess, so it can be used again with a new ioloop.
        Subprocess.uninitialize()
        self.io_loop.clear_current()
        # Try to clean up any file descriptors left open in the ioloop.
        # This avoids leaks, especially when tests are run repeatedly
        # in the same process with autoreload (because curl does not
        # set FD_CLOEXEC on its file descriptors)
        self.io_loop.close(all_fds=True)
        super(AsyncTestCase, self).tearDown()
        # In case an exception escaped or the StackContext caught an exception
        # when there wasn't a wait() to re-raise it, do so here.
        # This is our last chance to raise an exception in a way that the
        # unittest machinery understands.
        self.__rethrow()

    def get_new_ioloop(self):
        """Creates a new `.IOLoop` for this test.  May be overridden in
        subclasses for tests that require a specific `.IOLoop` (usually
        the singleton `.IOLoop.instance()`).
        """
        return IOLoop()

    def _handle_exception(self, typ, value, tb):
        if self.__failure is None:
            self.__failure = (typ, value, tb)
        else:
            app_log.error("multiple unhandled exceptions in test",
                          exc_info=(typ, value, tb))
        self.stop()
        return True

    def __rethrow(self):
        if self.__failure is not None:
            failure = self.__failure
            self.__failure = None
            raise_exc_info(failure)

    def run(self, result=None):
        with ExceptionStackContext(self._handle_exception):
            super(AsyncTestCase, self).run(result)
        # As a last resort, if an exception escaped super.run() and wasn't
        # re-raised in tearDown, raise it here.  This will cause the
        # unittest run to fail messily, but that's better than silently
        # ignoring an error.
        self.__rethrow()

    def stop(self, _arg=None, **kwargs):
        """Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
        to return.

        Keyword arguments or a single positional argument passed to `stop()` are
        saved and will be returned by `wait()`.
        """
        assert _arg is None or not kwargs
        self.__stop_args = kwargs or _arg
        if self.__running:
            self.io_loop.stop()
            self.__running = False
        self.__stopped = True

    def wait(self, condition=None, timeout=None):
        """Runs the `.IOLoop` until stop is called or timeout has passed.

        In the event of a timeout, an exception will be thrown. The
        default timeout is 5 seconds; it may be overridden with a
        ``timeout`` keyword argument or globally with the
        ``ASYNC_TEST_TIMEOUT`` environment variable.

        If ``condition`` is not None, the `.IOLoop` will be restarted
        after `stop()` until ``condition()`` returns true.

        .. versionchanged:: 3.1
           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.
        """
        if timeout is None:
            timeout = get_async_test_timeout()

        if not self.__stopped:
            if timeout:
                def timeout_func():
                    try:
                        raise self.failureException(
                            'Async operation timed out after %s seconds' %
                            timeout)
                    except Exception:
                        self.__failure = sys.exc_info()
                    self.stop()
                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,
                                                          timeout_func)
            while True:
                self.__running = True
                self.io_loop.start()
                if (self.__failure is not None or
                        condition is None or condition()):
                    break
            if self.__timeout is not None:
                self.io_loop.remove_timeout(self.__timeout)
                self.__timeout = None
        assert self.__stopped
        self.__stopped = False
        self.__rethrow()
        result = self.__stop_args
        self.__stop_args = None
        return result


class AsyncHTTPTestCase(AsyncTestCase):
    """A test case that starts up an HTTP server.

    Subclasses must override `get_app()`, which returns the
    `tornado.web.Application` (or other `.HTTPServer` callback) to be tested.
    Tests will typically use the provided ``self.http_client`` to fetch
    URLs from this server.

    Example, assuming the "Hello, world" example from the user guide is in
    ``hello.py``::

        import hello

        class TestHelloApp(AsyncHTTPTestCase):
            def get_app(self):
                return hello.make_app()

            def test_homepage(self):
                response = self.fetch('/')
                self.assertEqual(response.code, 200)
                self.assertEqual(response.body, 'Hello, world')

    That call to ``self.fetch()`` is equivalent to ::

        self.http_client.fetch(self.get_url('/'), self.stop)
        response = self.wait()

    which illustrates how AsyncTestCase can turn an asynchronous operation,
    like ``http_client.fetch()``, into a synchronous operation. If you need
    to do other asynchronous operations in tests, you'll probably need to use
    ``stop()`` and ``wait()`` yourself.
    """
    def setUp(self):
        super(AsyncHTTPTestCase, self).setUp()
        sock, port = bind_unused_port()
        self.__port = port

        self.http_client = self.get_http_client()
        self._app = self.get_app()
        self.http_server = self.get_http_server()
        self.http_server.add_sockets([sock])

    def get_http_client(self):
        return AsyncHTTPClient()

    def get_http_server(self):
        return HTTPServer(self._app, **self.get_httpserver_options())

    def get_app(self):
        """Should be overridden by subclasses to return a
        `tornado.web.Application` or other `.HTTPServer` callback.
        """
        raise NotImplementedError()

    def fetch(self, path, **kwargs):
        """Convenience method to synchronously fetch a URL.

        The given path will be appended to the local server's host and
        port.  Any additional kwargs will be passed directly to
        `.AsyncHTTPClient.fetch` (and so could be used to pass
        ``method="POST"``, ``body="..."``, etc).

        If the path begins with http:// or https://, it will be treated as a
        full URL and will be fetched as-is.

        .. versionchanged:: 5.0
           Added support for absolute URLs.
        """
        if path.lower().startswith(('http://', 'https://')):
            self.http_client.fetch(path, self.stop, **kwargs)
        else:
            self.http_client.fetch(self.get_url(path), self.stop, **kwargs)
        return self.wait()

    def get_httpserver_options(self):
        """May be overridden by subclasses to return additional
        keyword arguments for the server.
        """
        return {}

    def get_http_port(self):
        """Returns the port used by the server.

        A new port is chosen for each test.
        """
        return self.__port

    def get_protocol(self):
        return 'http'

    def get_url(self, path):
        """Returns an absolute url for the given path on the test server."""
        return '%s://127.0.0.1:%s%s' % (self.get_protocol(),
                                        self.get_http_port(), path)

    def tearDown(self):
        self.http_server.stop()
        self.io_loop.run_sync(self.http_server.close_all_connections,
                              timeout=get_async_test_timeout())
        self.http_client.close()
        super(AsyncHTTPTestCase, self).tearDown()


class AsyncHTTPSTestCase(AsyncHTTPTestCase):
    """A test case that starts an HTTPS server.

    Interface is generally the same as `AsyncHTTPTestCase`.
    """
    def get_http_client(self):
        return AsyncHTTPClient(force_instance=True,
                               defaults=dict(validate_cert=False))

    def get_httpserver_options(self):
        return dict(ssl_options=self.get_ssl_options())

    def get_ssl_options(self):
        """May be overridden by subclasses to select SSL options.

        By default includes a self-signed testing certificate.
        """
        # Testing keys were generated with:
        # openssl req -new -keyout tornado/test/test.key \
        #                     -out tornado/test/test.crt -nodes -days 3650 -x509
        module_dir = os.path.dirname(__file__)
        return dict(
            certfile=os.path.join(module_dir, 'test', 'test.crt'),
            keyfile=os.path.join(module_dir, 'test', 'test.key'))

    def get_protocol(self):
        return 'https'


def gen_test(func=None, timeout=None):
    """Testing equivalent of ``@gen.coroutine``, to be applied to test methods.

    ``@gen.coroutine`` cannot be used on tests because the `.IOLoop` is not
    already running.  ``@gen_test`` should be applied to test methods
    on subclasses of `AsyncTestCase`.

    Example::

        class MyTest(AsyncHTTPTestCase):
            @gen_test
            def test_something(self):
                response = yield self.http_client.fetch(self.get_url('/'))

    By default, ``@gen_test`` times out after 5 seconds. The timeout may be
    overridden globally with the ``ASYNC_TEST_TIMEOUT`` environment variable,
    or for each test with the ``timeout`` keyword argument::

        class MyTest(AsyncHTTPTestCase):
            @gen_test(timeout=10)
            def test_something_slow(self):
                response = yield self.http_client.fetch(self.get_url('/'))

    Note that ``@gen_test`` is incompatible with `AsyncTestCase.stop`,
    `AsyncTestCase.wait`, and `AsyncHTTPTestCase.fetch`. Use ``yield
    self.http_client.fetch(self.get_url())`` as shown above instead.

    .. versionadded:: 3.1
       The ``timeout`` argument and ``ASYNC_TEST_TIMEOUT`` environment
       variable.

    .. versionchanged:: 4.0
       The wrapper now passes along ``*args, **kwargs`` so it can be used
       on functions with arguments.

    """
    if timeout is None:
        timeout = get_async_test_timeout()

    def wrap(f):
        # Stack up several decorators to allow us to access the generator
        # object itself.  In the innermost wrapper, we capture the generator
        # and save it in an attribute of self.  Next, we run the wrapped
        # function through @gen.coroutine.  Finally, the coroutine is
        # wrapped again to make it synchronous with run_sync.
        #
        # This is a good case study arguing for either some sort of
        # extensibility in the gen decorators or cancellation support.
        @functools.wraps(f)
        def pre_coroutine(self, *args, **kwargs):
            result = f(self, *args, **kwargs)
            if isinstance(result, GeneratorType) or iscoroutine(result):
                self._test_generator = result
            else:
                self._test_generator = None
            return result

        if iscoroutinefunction(f):
            coro = pre_coroutine
        else:
            coro = gen.coroutine(pre_coroutine)

        @functools.wraps(coro)
        def post_coroutine(self, *args, **kwargs):
            try:
                return self.io_loop.run_sync(
                    functools.partial(coro, self, *args, **kwargs),
                    timeout=timeout)
            except TimeoutError as e:
                # run_sync raises an error with an unhelpful traceback.
                # If the underlying generator is still running, we can throw the
                # exception back into it so the stack trace is replaced by the
                # point where the test is stopped. The only reason the generator
                # would not be running would be if it were cancelled, which means
                # a native coroutine, so we can rely on the cr_running attribute.
                if getattr(self._test_generator, 'cr_running', True):
                    self._test_generator.throw(e)
                    # In case the test contains an overly broad except
                    # clause, we may get back here.
                # Coroutine was stopped or didn't raise a useful stack trace,
                # so re-raise the original exception which is better than nothing.
                raise
        return post_coroutine

    if func is not None:
        # Used like:
        #     @gen_test
        #     def f(self):
        #         pass
        return wrap(func)
    else:
        # Used like @gen_test(timeout=10)
        return wrap


# Without this attribute, nosetests will try to run gen_test as a test
# anywhere it is imported.
gen_test.__test__ = False  # type: ignore


class ExpectLog(logging.Filter):
    """Context manager to capture and suppress expected log output.

    Useful to make tests of error conditions less noisy, while still
    leaving unexpected log entries visible.  *Not thread safe.*

    The attribute ``logged_stack`` is set to true if any exception
    stack trace was logged.

    Usage::

        with ExpectLog('tornado.application', "Uncaught exception"):
            error_response = self.fetch("/some_page")

    .. versionchanged:: 4.3
       Added the ``logged_stack`` attribute.
    """
    def __init__(self, logger, regex, required=True):
        """Constructs an ExpectLog context manager.

        :param logger: Logger object (or name of logger) to watch.  Pass
            an empty string to watch the root logger.
        :param regex: Regular expression to match.  Any log entries on
            the specified logger that match this regex will be suppressed.
        :param required: If true, an exception will be raised if the end of
            the ``with`` statement is reached without matching any log entries.
        """
        if isinstance(logger, basestring_type):
            logger = logging.getLogger(logger)
        self.logger = logger
        self.regex = re.compile(regex)
        self.required = required
        self.matched = False
        self.logged_stack = False

    def filter(self, record):
        if record.exc_info:
            self.logged_stack = True
        message = record.getMessage()
        if self.regex.match(message):
            self.matched = True
            return False
        return True

    def __enter__(self):
        self.logger.addFilter(self)
        return self

    def __exit__(self, typ, value, tb):
        self.logger.removeFilter(self)
        if not typ and self.required and not self.matched:
            raise Exception("did not get expected log message")


def main(**kwargs):
    """A simple test runner.

    This test runner is essentially equivalent to `unittest.main` from
    the standard library, but adds support for tornado-style option
    parsing and log formatting. It is *not* necessary to use this
    `main` function to run tests using `AsyncTestCase`; these tests
    are self-contained and can run with any test runner.

    The easiest way to run a test is via the command line::

        python -m tornado.testing tornado.test.stack_context_test

    See the standard library unittest module for ways in which tests can
    be specified.

    Projects with many tests may wish to define a test script like
    ``tornado/test/runtests.py``.  This script should define a method
    ``all()`` which returns a test suite and then call
    `tornado.testing.main()`.  Note that even when a test script is
    used, the ``all()`` test suite may be overridden by naming a
    single test on the command line::

        # Runs all tests
        python -m tornado.test.runtests
        # Runs one test
        python -m tornado.test.runtests tornado.test.stack_context_test

    Additional keyword arguments passed through to ``unittest.main()``.
    For example, use ``tornado.testing.main(verbosity=2)``
    to show many test details as they are run.
    See http://docs.python.org/library/unittest.html#unittest.main
    for full argument list.

    .. versionchanged:: 5.0

       This function produces no output of its own; only that produced
       by the `unittest` module (Previously it would add a PASS or FAIL
       log message).
    """
    from tornado.options import define, options, parse_command_line

    define('exception_on_interrupt', type=bool, default=True,
           help=("If true (default), ctrl-c raises a KeyboardInterrupt "
                 "exception.  This prints a stack trace but cannot interrupt "
                 "certain operations.  If false, the process is more reliably "
                 "killed, but does not print a stack trace."))

    # support the same options as unittest's command-line interface
    define('verbose', type=bool)
    define('quiet', type=bool)
    define('failfast', type=bool)
    define('catch', type=bool)
    define('buffer', type=bool)

    argv = [sys.argv[0]] + parse_command_line(sys.argv)

    if not options.exception_on_interrupt:
        signal.signal(signal.SIGINT, signal.SIG_DFL)

    if options.verbose is not None:
        kwargs['verbosity'] = 2
    if options.quiet is not None:
        kwargs['verbosity'] = 0
    if options.failfast is not None:
        kwargs['failfast'] = True
    if options.catch is not None:
        kwargs['catchbreak'] = True
    if options.buffer is not None:
        kwargs['buffer'] = True

    if __name__ == '__main__' and len(argv) == 1:
        print("No tests specified", file=sys.stderr)
        sys.exit(1)
    # In order to be able to run tests by their fully-qualified name
    # on the command line without importing all tests here,
    # module must be set to None.  Python 3.2's unittest.main ignores
    # defaultTest if no module is given (it tries to do its own
    # test discovery, which is incompatible with auto2to3), so don't
    # set module if we're not asking for a specific test.
    if len(argv) > 1:
        unittest.main(module=None, argv=argv, **kwargs)
    else:
        unittest.main(defaultTest="all", argv=argv, **kwargs)


if __name__ == '__main__':
    main()

```
--- 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**: External Event Loop is Unexpectedly Closed, Causing Test Failures

**Description**:

When using an external asyncio event loop in tests, the event loop is closed by the testing framework even though it wasn't created within the test itself. This leads to tests failing because the loop is no longer active when the framework expects it to remain open.

**Example Buggy Code**:

```python
import asyncio
import unittest
from tornado.testing import AsyncTestCase, IOLoop

class CustomIOLoopTest(AsyncTestCase):
    def get_new_ioloop(self):
        return IOLoop.current()

    def setUp(self):
        self.orig_loop = asyncio.get_event_loop()
        self.new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.new_loop)
        super().setUp()

    def tearDown(self):
        super().tearDown()
        self.assertFalse(asyncio.get_event_loop().is_closed())
        asyncio.set_event_loop(self.orig_loop)
        self.new_loop.close()

    def test_event_loop(self):
        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)
```

**Expected Behavior**:

The external asyncio event loop provided by the test should remain open after the test completes. The testing framework should not interfere with the lifecycle of event loops that it did not create, allowing external management of the loop.

**Actual Behavior**:

The testing framework closes the external event loop, resulting in the test failing with an assertion that the event loop is closed. This disrupts tests that rely on external event loop management, causing unexpected failures.

[/ISSUE]
{
    "AsyncHTTPTestCaseTest.test_fetch_full_http_url": "PASSED",
    "AsyncHTTPTestCaseTest.test_fetch_full_https_url": "PASSED",
    "AsyncHTTPTestCaseTest.test_fetch_segment": "PASSED",
    "AsyncTestCaseTest.test_exception_in_callback": "PASSED",
    "AsyncTestCaseTest.test_multiple_errors": "PASSED",
    "AsyncTestCaseTest.test_subsequent_wait_calls": "PASSED",
    "AsyncTestCaseTest.test_wait_timeout": "PASSED",
    "AsyncTestCaseWrapperTest.test_other_return": "PASSED",
    "AsyncTestCaseWrapperTest.test_undecorated_coroutine": "PASSED",
    "AsyncTestCaseWrapperTest.test_undecorated_generator": "PASSED",
    "AsyncTestCaseWrapperTest.test_undecorated_generator_with_skip": "PASSED",
    "GenTest.test_async": "PASSED",
    "GenTest.test_native_coroutine": "PASSED",
    "GenTest.test_native_coroutine_timeout": "PASSED",
    "GenTest.test_no_timeout": "PASSED",
    "GenTest.test_no_timeout_environment_variable": "PASSED",
    "GenTest.test_sync": "PASSED",
    "GenTest.test_timeout": "PASSED",
    "GenTest.test_timeout_environment_variable": "PASSED",
    "GenTest.test_with_method_args": "PASSED",
    "GenTest.test_with_method_kwargs": "PASSED",
    "GetNewIOLoopTest.test_loop": "PASSED",
    "SetUpTearDownTest.test_set_up_tear_down": "PASSED"
}
diff --git a/tornado/testing.py b/tornado/testing.py
index 400dd3e4..19bc5a94 100644
--- a/tornado/testing.py
+++ b/tornado/testing.py
@@ -74,6 +74,12 @@ else:
         import unittest  # type: ignore
 
 
+if asyncio is None:
+    _NON_OWNED_IOLOOPS = ()
+else:
+    import tornado.platform.asyncio
+    _NON_OWNED_IOLOOPS = tornado.platform.asyncio.AsyncIOMainLoop
+
 def bind_unused_port(reuse_port=False):
     """Binds a server socket to an available port on localhost.
 
@@ -216,11 +222,12 @@ class AsyncTestCase(unittest.TestCase):
         # Clean up Subprocess, so it can be used again with a new ioloop.
         Subprocess.uninitialize()
         self.io_loop.clear_current()
-        # Try to clean up any file descriptors left open in the ioloop.
-        # This avoids leaks, especially when tests are run repeatedly
-        # in the same process with autoreload (because curl does not
-        # set FD_CLOEXEC on its file descriptors)
-        self.io_loop.close(all_fds=True)
+        if not isinstance(self.io_loop, _NON_OWNED_IOLOOPS):
+            # Try to clean up any file descriptors left open in the ioloop.
+            # This avoids leaks, especially when tests are run repeatedly
+            # in the same process with autoreload (because curl does not
+            # set FD_CLOEXEC on its file descriptors)
+            self.io_loop.close(all_fds=True)
         super(AsyncTestCase, self).tearDown()
         # In case an exception escaped or the StackContext caught an exception
         # when there wasn't a wait() to re-raise it, do so here.
@@ -229,9 +236,15 @@ class AsyncTestCase(unittest.TestCase):
         self.__rethrow()
 
     def get_new_ioloop(self):
-        """Creates a new `.IOLoop` for this test.  May be overridden in
-        subclasses for tests that require a specific `.IOLoop` (usually
-        the singleton `.IOLoop.instance()`).
+        """Returns the `.IOLoop` to use for this test.
+
+        By default, a new `.IOLoop` is created for each test.
+        Subclasses may override this method to return
+        `.IOLoop.current()` if it is not appropriate to use a new
+        `.IOLoop` in each tests (for example, if there are global
+        singletons using the default `.IOLoop`) or if a per-test event
+        loop is being provided by another system (such as
+        ``pytest-asyncio``).
         """
         return IOLoop()
 
 

{"tornado/testing.py": "\"\"\"Support classes for automated testing.\n\n* `AsyncTestCase` and `AsyncHTTPTestCase`:  Subclasses of unittest.TestCase\n  with additional support for testing asynchronous (`.IOLoop`-based) code.\n\n* `ExpectLog`: Make test logs less spammy.\n\n* `main()`: A simple test runner (wrapper around unittest.main()) with support\n  for the tornado.autoreload module to rerun the tests when code changes.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\ntry:\n    from tornado import gen\n    from tornado.httpclient import AsyncHTTPClient\n    from tornado.httpserver import HTTPServer\n    from tornado.simple_httpclient import SimpleAsyncHTTPClient\n    from tornado.ioloop import IOLoop, TimeoutError\n    from tornado import netutil\n    from tornado.process import Subprocess\nexcept ImportError:\n    # These modules are not importable on app engine.  Parts of this module\n    # won't work, but e.g. main() will.\n    AsyncHTTPClient = None  # type: ignore\n    gen = None  # type: ignore\n    HTTPServer = None  # type: ignore\n    IOLoop = None  # type: ignore\n    netutil = None  # type: ignore\n    SimpleAsyncHTTPClient = None  # type: ignore\n    Subprocess = None  # type: ignore\nfrom tornado.log import app_log\nfrom tornado.stack_context import ExceptionStackContext\nfrom tornado.util import raise_exc_info, basestring_type, PY3\nimport functools\nimport inspect\nimport logging\nimport os\nimport re\nimport signal\nimport socket\nimport sys\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\n\ntry:\n    from collections.abc import Generator as GeneratorType  # type: ignore\nexcept ImportError:\n    from types import GeneratorType  # type: ignore\n\nif sys.version_info >= (3, 5):\n    iscoroutine = inspect.iscoroutine  # type: ignore\n    iscoroutinefunction = inspect.iscoroutinefunction  # type: ignore\nelse:\n    iscoroutine = iscoroutinefunction = lambda f: False\n\n# Tornado's own test suite requires the updated unittest module\n# (either py27+ or unittest2) so tornado.test.util enforces\n# this requirement, but for other users of tornado.testing we want\n# to allow the older version if unitest2 is not available.\nif PY3:\n    # On python 3, mixing unittest2 and unittest (including doctest)\n    # doesn't seem to work, so always use unittest.\n    import unittest\nelse:\n    # On python 2, prefer unittest2 when available.\n    try:\n        import unittest2 as unittest  # type: ignore\n    except ImportError:\n        import unittest  # type: ignore\n\n\ndef bind_unused_port(reuse_port=False):\n    \"\"\"Binds a server socket to an available port on localhost.\n\n    Returns a tuple (socket, port).\n\n    .. versionchanged:: 4.4\n       Always binds to ``127.0.0.1`` without resolving the name\n       ``localhost``.\n    \"\"\"\n    sock = netutil.bind_sockets(None, '127.0.0.1', family=socket.AF_INET,\n                                reuse_port=reuse_port)[0]\n    port = sock.getsockname()[1]\n    return sock, port\n\n\ndef get_async_test_timeout():\n    \"\"\"Get the global timeout setting for async tests.\n\n    Returns a float, the timeout in seconds.\n\n    .. versionadded:: 3.1\n    \"\"\"\n    try:\n        return float(os.environ.get('ASYNC_TEST_TIMEOUT'))\n    except (ValueError, TypeError):\n        return 5\n\n\nclass _TestMethodWrapper(object):\n    \"\"\"Wraps a test method to raise an error if it returns a value.\n\n    This is mainly used to detect undecorated generators (if a test\n    method yields it must use a decorator to consume the generator),\n    but will also detect other kinds of return values (these are not\n    necessarily errors, but we alert anyway since there is no good\n    reason to return a value from a test).\n    \"\"\"\n    def __init__(self, orig_method):\n        self.orig_method = orig_method\n\n    def __call__(self, *args, **kwargs):\n        result = self.orig_method(*args, **kwargs)\n        if isinstance(result, GeneratorType) or iscoroutine(result):\n            raise TypeError(\"Generator and coroutine test methods should be\"\n                            \" decorated with tornado.testing.gen_test\")\n        elif result is not None:\n            raise ValueError(\"Return value from test method ignored: %r\" %\n                             result)\n\n    def __getattr__(self, name):\n        \"\"\"Proxy all unknown attributes to the original method.\n\n        This is important for some of the decorators in the `unittest`\n        module, such as `unittest.skipIf`.\n        \"\"\"\n        return getattr(self.orig_method, name)\n\n\nclass AsyncTestCase(unittest.TestCase):\n    \"\"\"`~unittest.TestCase` subclass for testing `.IOLoop`-based\n    asynchronous code.\n\n    The unittest framework is synchronous, so the test must be\n    complete by the time the test method returns.  This means that\n    asynchronous code cannot be used in quite the same way as usual.\n    To write test functions that use the same ``yield``-based patterns\n    used with the `tornado.gen` module, decorate your test methods\n    with `tornado.testing.gen_test` instead of\n    `tornado.gen.coroutine`.  This class also provides the `stop()`\n    and `wait()` methods for a more manual style of testing.  The test\n    method itself must call ``self.wait()``, and asynchronous\n    callbacks should call ``self.stop()`` to signal completion.\n\n    By default, a new `.IOLoop` is constructed for each test and is available\n    as ``self.io_loop``.  If the code being tested requires a\n    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.\n\n    The `.IOLoop`'s ``start`` and ``stop`` methods should not be\n    called directly.  Instead, use `self.stop <stop>` and `self.wait\n    <wait>`.  Arguments passed to ``self.stop`` are returned from\n    ``self.wait``.  It is possible to have multiple ``wait``/``stop``\n    cycles in the same test.\n\n    Example::\n\n        # This test uses coroutine style.\n        class MyTestCase(AsyncTestCase):\n            @tornado.testing.gen_test\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                response = yield client.fetch(\"http://www.tornadoweb.org\")\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses argument passing between self.stop and self.wait.\n        class MyTestCase2(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.stop)\n                response = self.wait()\n                # Test contents of response\n                self.assertIn(\"FriendFeed\", response.body)\n\n        # This test uses an explicit callback-based style.\n        class MyTestCase3(AsyncTestCase):\n            def test_http_fetch(self):\n                client = AsyncHTTPClient()\n                client.fetch(\"http://www.tornadoweb.org/\", self.handle_fetch)\n                self.wait()\n\n            def handle_fetch(self, response):\n                # Test contents of response (failures and exceptions here\n                # will cause self.wait() to throw an exception and end the\n                # test).\n                # Exceptions thrown here are magically propagated to\n                # self.wait() in test_http_fetch() via stack_context.\n                self.assertIn(\"FriendFeed\", response.body)\n                self.stop()\n    \"\"\"\n    def __init__(self, methodName='runTest'):\n        super(AsyncTestCase, self).__init__(methodName)\n        self.__stopped = False\n        self.__running = False\n        self.__failure = None\n        self.__stop_args = None\n        self.__timeout = None\n\n        # It's easy to forget the @gen_test decorator, but if you do\n        # the test will silently be ignored because nothing will consume\n        # the generator.  Replace the test method with a wrapper that will\n        # make sure it's not an undecorated generator.\n        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))\n\n    def setUp(self):\n        super(AsyncTestCase, self).setUp()\n        self.io_loop = self.get_new_ioloop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        # Clean up Subprocess, so it can be used again with a new ioloop.\n        Subprocess.uninitialize()\n        self.io_loop.clear_current()\n        # Try to clean up any file descriptors left open in the ioloop.\n        # This avoids leaks, especially when tests are run repeatedly\n        # in the same process with autoreload (because curl does not\n        # set FD_CLOEXEC on its file descriptors)\n        self.io_loop.close(all_fds=True)\n        super(AsyncTestCase, self).tearDown()\n        # In case an exception escaped or the StackContext caught an exception\n        # when there wasn't a wait() to re-raise it, do so here.\n        # This is our last chance to raise an exception in a way that the\n        # unittest machinery understands.\n        self.__rethrow()\n\n    def get_new_ioloop(self):\n        \"\"\"Creates a new `.IOLoop` for this test.  May be overridden in\n        subclasses for tests that require a specific `.IOLoop` (usually\n        the singleton `.IOLoop.instance()`).\n        \"\"\"\n        return IOLoop()\n\n    def _handle_exception(self, typ, value, tb):\n        if self.__failure is None:\n            self.__failure = (typ, value, tb)\n        else:\n            app_log.error(\"multiple unhandled exceptions in test\",\n                          exc_info=(typ, value, tb))\n        self.stop()\n        return True\n\n    def __rethrow(self):\n        if self.__failure is not None:\n            failure = self.__failure\n            self.__failure = None\n            raise_exc_info(failure)\n\n    def run(self, result=None):\n        with ExceptionStackContext(self._handle_exception):\n            super(AsyncTestCase, self).run(result)\n        # As a last resort, if an exception escaped super.run() and wasn't\n        # re-raised in tearDown, raise it here.  This will cause the\n        # unittest run to fail messily, but that's better than silently\n        # ignoring an error.\n        self.__rethrow()\n\n    def stop(self, _arg=None, **kwargs):\n        \"\"\"Stops the `.IOLoop`, causing one pending (or future) call to `wait()`\n        to return.\n\n        Keyword arguments or a single positional argument passed to `stop()` are\n        saved and will be returned by `wait()`.\n        \"\"\"\n        assert _arg is None or not kwargs\n        self.__stop_args = kwargs or _arg\n        if self.__running:\n            self.io_loop.stop()\n            self.__running = False\n        self.__stopped = True\n\n    def wait(self, condition=None, timeout=None):\n        \"\"\"Runs the `.IOLoop` until stop is called or timeout has passed.\n\n        In the event of a timeout, an exception will be thrown. The\n        default timeout is 5 seconds; it may be overridden with a\n        ``timeout`` keyword argument or globally with the\n        ``ASYNC_TEST_TIMEOUT`` environment variable.\n\n        If ``condition`` is not None, the `.IOLoop` will be restarted\n        after `stop()` until ``condition()`` returns true.\n\n        .. versionchanged:: 3.1\n           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.\n        \"\"\"\n        if timeout is None:\n            timeout = get_async_test_timeout()\n\n        if not self.__stopped:\n            if timeout:\n                def timeout_func():\n                    try:\n                        raise self.failureException(\n                            'Async operation timed out after %s seconds' %\n                            timeout)\n                    except Exception:\n                        self.__failure = sys.exc_info()\n                    self.stop()\n                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,\n                                                          timeout_func)\n            while True:\n                self.__running = True\n                self.io_loop.start()\n                if (self.__failure is not None or\n                        condition is None or condition()):\n                    break\n            if self.__timeout is not None:\n                self.io_loop.remove_timeout(self.__timeout)\n                self.__timeout = None\n        assert self.__stopped\n        self.__stopped = False\n        self.__rethrow()\n        result = self.__stop_args\n        self.__stop_args = None\n        return result\n\n\nclass AsyncHTTPTestCase(AsyncTestCase):\n    \"\"\"A test case that starts up an HTTP server.\n\n    Subclasses must override `get_app()`, which returns the\n    `tornado.web.Application` (or other `.HTTPServer` callback) to be tested.\n    Tests will typically use the provided ``self.http_client`` to fetch\n    URLs from this server.\n\n    Example, assuming the \"Hello, world\" example from the user guide is in\n    ``hello.py``::\n\n        import hello\n\n        class TestHelloApp(AsyncHTTPTestCase):\n            def get_app(self):\n                return hello.make_app()\n\n            def test_homepage(self):\n                response = self.fetch('/')\n                self.assertEqual(response.code, 200)\n                self.assertEqual(response.body, 'Hello, world')\n\n    That call to ``self.fetch()`` is equivalent to ::\n\n        self.http_client.fetch(self.get_url('/'), self.stop)\n        response = self.wait()\n\n    which illustrates how AsyncTestCase can turn an asynchronous operation,\n    like ``http_client.fetch()``, into a synchronous operation. If you need\n    to do other asynchronous operations in tests, you'll probably need to use\n    ``stop()`` and ``wait()`` yourself.\n    \"\"\"\n    def setUp(self):\n        super(AsyncHTTPTestCase, self).setUp()\n        sock, port = bind_unused_port()\n        self.__port = port\n\n        self.http_client = self.get_http_client()\n        self._app = self.get_app()\n        self.http_server = self.get_http_server()\n        self.http_server.add_sockets([sock])\n\n    def get_http_client(self):\n        return AsyncHTTPClient()\n\n    def get_http_server(self):\n        return HTTPServer(self._app, **self.get_httpserver_options())\n\n    def get_app(self):\n        \"\"\"Should be overridden by subclasses to return a\n        `tornado.web.Application` or other `.HTTPServer` callback.\n        \"\"\"\n        raise NotImplementedError()\n\n    def fetch(self, path, **kwargs):\n        \"\"\"Convenience method to synchronously fetch a URL.\n\n        The given path will be appended to the local server's host and\n        port.  Any additional kwargs will be passed directly to\n        `.AsyncHTTPClient.fetch` (and so could be used to pass\n        ``method=\"POST\"``, ``body=\"...\"``, etc).\n\n        If the path begins with http:// or https://, it will be treated as a\n        full URL and will be fetched as-is.\n\n        .. versionchanged:: 5.0\n           Added support for absolute URLs.\n        \"\"\"\n        if path.lower().startswith(('http://', 'https://')):\n            self.http_client.fetch(path, self.stop, **kwargs)\n        else:\n            self.http_client.fetch(self.get_url(path), self.stop, **kwargs)\n        return self.wait()\n\n    def get_httpserver_options(self):\n        \"\"\"May be overridden by subclasses to return additional\n        keyword arguments for the server.\n        \"\"\"\n        return {}\n\n    def get_http_port(self):\n        \"\"\"Returns the port used by the server.\n\n        A new port is chosen for each test.\n        \"\"\"\n        return self.__port\n\n    def get_protocol(self):\n        return 'http'\n\n    def get_url(self, path):\n        \"\"\"Returns an absolute url for the given path on the test server.\"\"\"\n        return '%s://127.0.0.1:%s%s' % (self.get_protocol(),\n                                        self.get_http_port(), path)\n\n    def tearDown(self):\n        self.http_server.stop()\n        self.io_loop.run_sync(self.http_server.close_all_connections,\n                              timeout=get_async_test_timeout())\n        self.http_client.close()\n        super(AsyncHTTPTestCase, self).tearDown()\n\n\nclass AsyncHTTPSTestCase(AsyncHTTPTestCase):\n    \"\"\"A test case that starts an HTTPS server.\n\n    Interface is generally the same as `AsyncHTTPTestCase`.\n    \"\"\"\n    def get_http_client(self):\n        return AsyncHTTPClient(force_instance=True,\n                               defaults=dict(validate_cert=False))\n\n    def get_httpserver_options(self):\n        return dict(ssl_options=self.get_ssl_options())\n\n    def get_ssl_options(self):\n        \"\"\"May be overridden by subclasses to select SSL options.\n\n        By default includes a self-signed testing certificate.\n        \"\"\"\n        # Testing keys were generated with:\n        # openssl req -new -keyout tornado/test/test.key \\\n        #                     -out tornado/test/test.crt -nodes -days 3650 -x509\n        module_dir = os.path.dirname(__file__)\n        return dict(\n            certfile=os.path.join(module_dir, 'test', 'test.crt'),\n            keyfile=os.path.join(module_dir, 'test', 'test.key'))\n\n    def get_protocol(self):\n        return 'https'\n\n\ndef gen_test(func=None, timeout=None):\n    \"\"\"Testing equivalent of ``@gen.coroutine``, to be applied to test methods.\n\n    ``@gen.coroutine`` cannot be used on tests because the `.IOLoop` is not\n    already running.  ``@gen_test`` should be applied to test methods\n    on subclasses of `AsyncTestCase`.\n\n    Example::\n\n        class MyTest(AsyncHTTPTestCase):\n            @gen_test\n            def test_something(self):\n                response = yield self.http_client.fetch(self.get_url('/'))\n\n    By default, ``@gen_test`` times out after 5 seconds. The timeout may be\n    overridden globally with the ``ASYNC_TEST_TIMEOUT`` environment variable,\n    or for each test with the ``timeout`` keyword argument::\n\n        class MyTest(AsyncHTTPTestCase):\n            @gen_test(timeout=10)\n            def test_something_slow(self):\n                response = yield self.http_client.fetch(self.get_url('/'))\n\n    Note that ``@gen_test`` is incompatible with `AsyncTestCase.stop`,\n    `AsyncTestCase.wait`, and `AsyncHTTPTestCase.fetch`. Use ``yield\n    self.http_client.fetch(self.get_url())`` as shown above instead.\n\n    .. versionadded:: 3.1\n       The ``timeout`` argument and ``ASYNC_TEST_TIMEOUT`` environment\n       variable.\n\n    .. versionchanged:: 4.0\n       The wrapper now passes along ``*args, **kwargs`` so it can be used\n       on functions with arguments.\n\n    \"\"\"\n    if timeout is None:\n        timeout = get_async_test_timeout()\n\n    def wrap(f):\n        # Stack up several decorators to allow us to access the generator\n        # object itself.  In the innermost wrapper, we capture the generator\n        # and save it in an attribute of self.  Next, we run the wrapped\n        # function through @gen.coroutine.  Finally, the coroutine is\n        # wrapped again to make it synchronous with run_sync.\n        #\n        # This is a good case study arguing for either some sort of\n        # extensibility in the gen decorators or cancellation support.\n        @functools.wraps(f)\n        def pre_coroutine(self, *args, **kwargs):\n            result = f(self, *args, **kwargs)\n            if isinstance(result, GeneratorType) or iscoroutine(result):\n                self._test_generator = result\n            else:\n                self._test_generator = None\n            return result\n\n        if iscoroutinefunction(f):\n            coro = pre_coroutine\n        else:\n            coro = gen.coroutine(pre_coroutine)\n\n        @functools.wraps(coro)\n        def post_coroutine(self, *args, **kwargs):\n            try:\n                return self.io_loop.run_sync(\n                    functools.partial(coro, self, *args, **kwargs),\n                    timeout=timeout)\n            except TimeoutError as e:\n                # run_sync raises an error with an unhelpful traceback.\n                # If the underlying generator is still running, we can throw the\n                # exception back into it so the stack trace is replaced by the\n                # point where the test is stopped. The only reason the generator\n                # would not be running would be if it were cancelled, which means\n                # a native coroutine, so we can rely on the cr_running attribute.\n                if getattr(self._test_generator, 'cr_running', True):\n                    self._test_generator.throw(e)\n                    # In case the test contains an overly broad except\n                    # clause, we may get back here.\n                # Coroutine was stopped or didn't raise a useful stack trace,\n                # so re-raise the original exception which is better than nothing.\n                raise\n        return post_coroutine\n\n    if func is not None:\n        # Used like:\n        #     @gen_test\n        #     def f(self):\n        #         pass\n        return wrap(func)\n    else:\n        # Used like @gen_test(timeout=10)\n        return wrap\n\n\n# Without this attribute, nosetests will try to run gen_test as a test\n# anywhere it is imported.\ngen_test.__test__ = False  # type: ignore\n\n\nclass ExpectLog(logging.Filter):\n    \"\"\"Context manager to capture and suppress expected log output.\n\n    Useful to make tests of error conditions less noisy, while still\n    leaving unexpected log entries visible.  *Not thread safe.*\n\n    The attribute ``logged_stack`` is set to true if any exception\n    stack trace was logged.\n\n    Usage::\n\n        with ExpectLog('tornado.application', \"Uncaught exception\"):\n            error_response = self.fetch(\"/some_page\")\n\n    .. versionchanged:: 4.3\n       Added the ``logged_stack`` attribute.\n    \"\"\"\n    def __init__(self, logger, regex, required=True):\n        \"\"\"Constructs an ExpectLog context manager.\n\n        :param logger: Logger object (or name of logger) to watch.  Pass\n            an empty string to watch the root logger.\n        :param regex: Regular expression to match.  Any log entries on\n            the specified logger that match this regex will be suppressed.\n        :param required: If true, an exception will be raised if the end of\n            the ``with`` statement is reached without matching any log entries.\n        \"\"\"\n        if isinstance(logger, basestring_type):\n            logger = logging.getLogger(logger)\n        self.logger = logger\n        self.regex = re.compile(regex)\n        self.required = required\n        self.matched = False\n        self.logged_stack = False\n\n    def filter(self, record):\n        if record.exc_info:\n            self.logged_stack = True\n        message = record.getMessage()\n        if self.regex.match(message):\n            self.matched = True\n            return False\n        return True\n\n    def __enter__(self):\n        self.logger.addFilter(self)\n        return self\n\n    def __exit__(self, typ, value, tb):\n        self.logger.removeFilter(self)\n        if not typ and self.required and not self.matched:\n            raise Exception(\"did not get expected log message\")\n\n\ndef main(**kwargs):\n    \"\"\"A simple test runner.\n\n    This test runner is essentially equivalent to `unittest.main` from\n    the standard library, but adds support for tornado-style option\n    parsing and log formatting. It is *not* necessary to use this\n    `main` function to run tests using `AsyncTestCase`; these tests\n    are self-contained and can run with any test runner.\n\n    The easiest way to run a test is via the command line::\n\n        python -m tornado.testing tornado.test.stack_context_test\n\n    See the standard library unittest module for ways in which tests can\n    be specified.\n\n    Projects with many tests may wish to define a test script like\n    ``tornado/test/runtests.py``.  This script should define a method\n    ``all()`` which returns a test suite and then call\n    `tornado.testing.main()`.  Note that even when a test script is\n    used, the ``all()`` test suite may be overridden by naming a\n    single test on the command line::\n\n        # Runs all tests\n        python -m tornado.test.runtests\n        # Runs one test\n        python -m tornado.test.runtests tornado.test.stack_context_test\n\n    Additional keyword arguments passed through to ``unittest.main()``.\n    For example, use ``tornado.testing.main(verbosity=2)``\n    to show many test details as they are run.\n    See http://docs.python.org/library/unittest.html#unittest.main\n    for full argument list.\n\n    .. versionchanged:: 5.0\n\n       This function produces no output of its own; only that produced\n       by the `unittest` module (Previously it would add a PASS or FAIL\n       log message).\n    \"\"\"\n    from tornado.options import define, options, parse_command_line\n\n    define('exception_on_interrupt', type=bool, default=True,\n           help=(\"If true (default), ctrl-c raises a KeyboardInterrupt \"\n                 \"exception.  This prints a stack trace but cannot interrupt \"\n                 \"certain operations.  If false, the process is more reliably \"\n                 \"killed, but does not print a stack trace.\"))\n\n    # support the same options as unittest's command-line interface\n    define('verbose', type=bool)\n    define('quiet', type=bool)\n    define('failfast', type=bool)\n    define('catch', type=bool)\n    define('buffer', type=bool)\n\n    argv = [sys.argv[0]] + parse_command_line(sys.argv)\n\n    if not options.exception_on_interrupt:\n        signal.signal(signal.SIGINT, signal.SIG_DFL)\n\n    if options.verbose is not None:\n        kwargs['verbosity'] = 2\n    if options.quiet is not None:\n        kwargs['verbosity'] = 0\n    if options.failfast is not None:\n        kwargs['failfast'] = True\n    if options.catch is not None:\n        kwargs['catchbreak'] = True\n    if options.buffer is not None:\n        kwargs['buffer'] = True\n\n    if __name__ == '__main__' and len(argv) == 1:\n        print(\"No tests specified\", file=sys.stderr)\n        sys.exit(1)\n    # In order to be able to run tests by their fully-qualified name\n    # on the command line without importing all tests here,\n    # module must be set to None.  Python 3.2's unittest.main ignores\n    # defaultTest if no module is given (it tries to do its own\n    # test discovery, which is incompatible with auto2to3), so don't\n    # set module if we're not asking for a specific test.\n    if len(argv) > 1:\n        unittest.main(module=None, argv=argv, **kwargs)\n    else:\n        unittest.main(defaultTest=\"all\", argv=argv, **kwargs)\n\n\nif __name__ == '__main__':\n    main()\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**: External Event Loop is Unexpectedly Closed, Causing Test Failures

**Description**:

When using an external asyncio event loop in tests, the event loop is closed by the testing framework even though it wasn't created within the test itself. This leads to tests failing because the loop is no longer active when the framework expects it to remain open.

**Example Buggy Code**:

```python
import asyncio
import unittest
from tornado.testing import AsyncTestCase, IOLoop

class CustomIOLoopTest(AsyncTestCase):
    def get_new_ioloop(self):
        return IOLoop.current()

    def setUp(self):
        self.orig_loop = asyncio.get_event_loop()
        self.new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.new_loop)
        super().setUp()

    def tearDown(self):
        super().tearDown()
        self.assertFalse(asyncio.get_event_loop().is_closed())
        asyncio.set_event_loop(self.orig_loop)
        self.new_loop.close()

    def test_event_loop(self):
        self.assertIs(self.io_loop.asyncio_loop, self.new_loop)
```

**Expected Behavior**:

The external asyncio event loop provided by the test should remain open after the test completes. The testing framework should not interfere with the lifecycle of event loops that it did not create, allowing external management of the loop.

**Actual Behavior**:

The testing framework closes the external event loop, resulting in the test failing with an assertion that the event loop is closed. This disrupts tests that rely on external event loop management, causing unexpected failures.

[/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/testing.py
"""Support classes for automated testing.

* `AsyncTestCase` and `AsyncHTTPTestCase`:  Subclasses of unittest.TestCase
  with additional support for testing asynchronous (`.IOLoop`-based) code.

* `ExpectLog`: Make test logs less spammy.

* `main()`: A simple test runner (wrapper around unittest.main()) with support
  for the tornado.autoreload module to rerun the tests when code changes.
"""

from __future__ import absolute_import, division, print_function

try:
    from tornado import gen
    from tornado.httpclient import AsyncHTTPClient
    from tornado.httpserver import HTTPServer
    from tornado.simple_httpclient import SimpleAsyncHTTPClient
    from tornado.ioloop import IOLoop, TimeoutError
    from tornado import netutil
    from tornado.process import Subprocess
except ImportError:
    # These modules are not importable on app engine.  Parts of this module
    # won't work, but e.g. main() will.
    AsyncHTTPClient = None  # type: ignore
    gen = None  # type: ignore
    HTTPServer = None  # type: ignore
    IOLoop = None  # type: ignore
    netutil = None  # type: ignore
    SimpleAsyncHTTPClient = None  # type: ignore
    Subprocess = None  # type: ignore
from tornado.log import app_log
from tornado.stack_context import ExceptionStackContext
from tornado.util import raise_exc_info, basestring_type, PY3
import functools
import inspect
import logging
import os
import re
import signal
import socket
import sys

try:
    import asyncio
except ImportError:
    asyncio = None


try:
    from collections.abc import Generator as GeneratorType  # type: ignore
except ImportError:
    from types import GeneratorType  # type: ignore

if sys.version_info >= (3, 5):
    iscoroutine = inspect.iscoroutine  # type: ignore
    iscoroutinefunction = inspect.iscoroutinefunction  # type: ignore
else:
    iscoroutine = iscoroutinefunction = lambda f: False

# Tornado's own test suite requires the updated unittest module
# (either py27+ or unittest2) so tornado.test.util enforces
# this requirement, but for other users of tornado.testing we want
# to allow the older version if unitest2 is not available.
if PY3:
    # On python 3, mixing unittest2 and unittest (including doctest)
    # doesn't seem to work, so always use unittest.
    import unittest
else:
    # On python 2, prefer unittest2 when available.
    try:
        import unittest2 as unittest  # type: ignore
    except ImportError:
        import unittest  # type: ignore


def bind_unused_port(reuse_port=False):
    """Binds a server socket to an available port on localhost.

    Returns a tuple (socket, port).

    .. versionchanged:: 4.4
       Always binds to ``127.0.0.1`` without resolving the name
       ``localhost``.
    """
    sock = netutil.bind_sockets(None, '127.0.0.1', family=socket.AF_INET,
                                reuse_port=reuse_port)[0]
    port = sock.getsockname()[1]
    return sock, port


def get_async_test_timeout():
    """Get the global timeout setting for async tests.

    Returns a float, the timeout in seconds.

    .. versionadded:: 3.1
    """
    try:
        return float(os.environ.get('ASYNC_TEST_TIMEOUT'))
    except (ValueError, TypeError):
        return 5


class _TestMethodWrapper(object):
    """Wraps a test method to raise an error if it returns a value.

    This is mainly used to detect undecorated generators (if a test
    method yields it must use a decorator to consume the generator),
    but will also detect other kinds of return values (these are not
    necessarily errors, but we alert anyway since there is no good
    reason to return a value from a test).
    """
    def __init__(self, orig_method):
        self.orig_method = orig_method

    def __call__(self, *args, **kwargs):
        result = self.orig_method(*args, **kwargs)
        if isinstance(result, GeneratorType) or iscoroutine(result):
            raise TypeError("Generator and coroutine test methods should be"
                            " decorated with tornado.testing.gen_test")
        elif result is not None:
            raise ValueError("Return value from test method ignored: %r" %
                             result)

    def __getattr__(self, name):
        """Proxy all unknown attributes to the original method.

        This is important for some of the decorators in the `unittest`
        module, such as `unittest.skipIf`.
        """
        return getattr(self.orig_method, name)


class AsyncTestCase(unittest.TestCase):
    """`~unittest.TestCase` subclass for testing `.IOLoop`-based
    asynchronous code.

    The unittest framework is synchronous, so the test must be
    complete by the time the test method returns.  This means that
    asynchronous code cannot be used in quite the same way as usual.
    To write test functions that use the same ``yield``-based patterns
    used with the `tornado.gen` module, decorate your test methods
    with `tornado.testing.gen_test` instead of
    `tornado.gen.coroutine`.  This class also provides the `stop()`
    and `wait()` methods for a more manual style of testing.  The test
    method itself must call ``self.wait()``, and asynchronous
    callbacks should call ``self.stop()`` to signal completion.

    By default, a new `.IOLoop` is constructed for each test and is available
    as ``self.io_loop``.  If the code being tested requires a
    global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.

    The `.IOLoop`'s ``start`` and ``stop`` methods should not be
    called directly.  Instead, use `self.stop <stop>` and `self.wait
    <wait>`.  Arguments passed to ``self.stop`` are returned from
    ``self.wait``.  It is possible to have multiple ``wait``/``stop``
    cycles in the same test.

    Example::

        # This test uses coroutine style.
        class MyTestCase(AsyncTestCase):
            @tornado.testing.gen_test
            def test_http_fetch(self):
                client = AsyncHTTPClient()
                response = yield client.fetch("http://www.tornadoweb.org")
                # Test contents of response
                self.assertIn("FriendFeed", response.body)

        # This test uses argument passing between self.stop and self.wait.
        class MyTestCase2(AsyncTestCase):
            def test_http_fetch(self):
                client = AsyncHTTPClient()
                client.fetch("http://www.tornadoweb.org/", self.stop)
                response = self.wait()
                # Test contents of response
                self.assertIn("FriendFeed", response.body)

        # This test uses an explicit callback-based style.
        class MyTestCase3(AsyncTestCase):
            def test_http_fetch(self):
                client = AsyncHTTPClient()
                client.fetch("http://www.tornadoweb.org/", self.handle_fetch)
                self.wait()

            def handle_fetch(self, response):
                # Test contents of response (failures and exceptions here
                # will cause self.wait() to throw an exception and end the
                # test).
                # Exceptions thrown here are magically propagated to
                # self.wait() in test_http_fetch() via stack_context.
                self.assertIn("FriendFeed", response.body)
                self.stop()
    """
    def __init__(self, methodName='runTest'):
        super(AsyncTestCase, self).__init__(methodName)
        self.__stopped = False
        self.__running = False
        self.__failure = None
        self.__stop_args = None
        self.__timeout = None

        # It's easy to forget the @gen_test decorator, but if you do
        # the test will silently be ignored because nothing will consume
        # the generator.  Replace the test method with a wrapper that will
        # make sure it's not an undecorated generator.
        setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))

    def setUp(self):
        super(AsyncTestCase, self).setUp()
        self.io_loop = self.get_new_ioloop()
        self.io_loop.make_current()

    def tearDown(self):
        # Clean up Subprocess, so it can be used again with a new ioloop.
        Subprocess.uninitialize()
        self.io_loop.clear_current()
        # Try to clean up any file descriptors left open in the ioloop.
        # This avoids leaks, especially when tests are run repeatedly
        # in the same process with autoreload (because curl does not
        # set FD_CLOEXEC on its file descriptors)
        self.io_loop.close(all_fds=True)
        super(AsyncTestCase, self).tearDown()
        # In case an exception escaped or the StackContext caught an exception
        # when there wasn't a wait() to re-raise it, do so here.
        # This is our last chance to raise an exception in a way that the
        # unittest machinery understands.
        self.__rethrow()

    def get_new_ioloop(self):
        """Creates a new `.IOLoop` for this test.  May be overridden in
        subclasses for tests that require a specific `.IOLoop` (usually
        the singleton `.IOLoop.instance()`).
        """
        return IOLoop()

    def _handle_exception(self, typ, value, tb):
        if self.__failure is None:
            self.__failure = (typ, value, tb)
        else:
            app_log.error("multiple unhandled exceptions in test",
                          exc_info=(typ, value, tb))
        self.stop()
        return True

    def __rethrow(self):
        if self.__failure is not None:
            failure = self.__failure
            self.__failure = None
            raise_exc_info(failure)

    def run(self, result=None):
        with ExceptionStackContext(self._handle_exception):
            super(AsyncTestCase, self).run(result)
        # As a last resort, if an exception escaped super.run() and wasn't
        # re-raised in tearDown, raise it here.  This will cause the
        # unittest run to fail messily, but that's better than silently
        # ignoring an error.
        self.__rethrow()

    def stop(self, _arg=None, **kwargs):
        """Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
        to return.

        Keyword arguments or a single positional argument passed to `stop()` are
        saved and will be returned by `wait()`.
        """
        assert _arg is None or not kwargs
        self.__stop_args = kwargs or _arg
        if self.__running:
            self.io_loop.stop()
            self.__running = False
        self.__stopped = True

    def wait(self, condition=None, timeout=None):
        """Runs the `.IOLoop` until stop is called or timeout has passed.

        In the event of a timeout, an exception will be thrown. The
        default timeout is 5 seconds; it may be overridden with a
        ``timeout`` keyword argument or globally with the
        ``ASYNC_TEST_TIMEOUT`` environment variable.

        If ``condition`` is not None, the `.IOLoop` will be restarted
        after `stop()` until ``condition()`` returns true.

        .. versionchanged:: 3.1
           Added the ``ASYNC_TEST_TIMEOUT`` environment variable.
        """
        if timeout is None:
            timeout = get_async_test_timeout()

        if not self.__stopped:
            if timeout:
                def timeout_func():
                    try:
                        raise self.failureException(
                            'Async operation timed out after %s seconds' %
                            timeout)
                    except Exception:
                        self.__failure = sys.exc_info()
                    self.stop()
                self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,
                                                          timeout_func)
            while True:
                self.__running = True
                self.io_loop.start()
                if (self.__failure is not None or
                        condition is None or condition()):
                    break
            if self.__timeout is not None:
                self.io_loop.remove_timeout(self.__timeout)
                self.__timeout = None
        assert self.__stopped
        self.__stopped = False
        self.__rethrow()
        result = self.__stop_args
        self.__stop_args = None
        return result


class AsyncHTTPTestCase(AsyncTestCase):
    """A test case that starts up an HTTP server.

    Subclasses must override `get_app()`, which returns the
    `tornado.web.Application` (or other `.HTTPServer` callback) to be tested.
    Tests will typically use the provided ``self.http_client`` to fetch
    URLs from this server.

    Example, assuming the "Hello, world" example from the user guide is in
    ``hello.py``::

        import hello

        class TestHelloApp(AsyncHTTPTestCase):
            def get_app(self):
                return hello.make_app()

            def test_homepage(self):
                response = self.fetch('/')
                self.assertEqual(response.code, 200)
                self.assertEqual(response.body, 'Hello, world')

    That call to ``self.fetch()`` is equivalent to ::

        self.http_client.fetch(self.get_url('/'), self.stop)
        response = self.wait()

    which illustrates how AsyncTestCase can turn an asynchronous operation,
    like ``http_client.fetch()``, into a synchronous operation. If you need
    to do other asynchronous operations in tests, you'll probably need to use
    ``stop()`` and ``wait()`` yourself.
    """
    def setUp(self):
        super(AsyncHTTPTestCase, self).setUp()
        sock, port = bind_unused_port()
        self.__port = port

        self.http_client = self.get_http_client()
        self._app = self.get_app()
        self.http_server = self.get_http_server()
        self.http_server.add_sockets([sock])

    def get_http_client(self):
        return AsyncHTTPClient()

    def get_http_server(self):
        return HTTPServer(self._app, **self.get_httpserver_options())

    def get_app(self):
        """Should be overridden by subclasses to return a
        `tornado.web.Application` or other `.HTTPServer` callback.
        """
        raise NotImplementedError()

    def fetch(self, path, **kwargs):
        """Convenience method to synchronously fetch a URL.

        The given path will be appended to the local server's host and
        port.  Any additional kwargs will be passed directly to
        `.AsyncHTTPClient.fetch` (and so could be used to pass
        ``method="POST"``, ``body="..."``, etc).

        If the path begins with http:// or https://, it will be treated as a
        full URL and will be fetched as-is.

        .. versionchanged:: 5.0
           Added support for absolute URLs.
        """
        if path.lower().startswith(('http://', 'https://')):
            self.http_client.fetch(path, self.stop, **kwargs)
        else:
            self.http_client.fetch(self.get_url(path), self.stop, **kwargs)
        return self.wait()

    def get_httpserver_options(self):
        """May be overridden by subclasses to return additional
        keyword arguments for the server.
        """
        return {}

    def get_http_port(self):
        """Returns the port used by the server.

        A new port is chosen for each test.
        """
        return self.__port

    def get_protocol(self):
        return 'http'

    def get_url(self, path):
        """Returns an absolute url for the given path on the test server."""
        return '%s://127.0.0.1:%s%s' % (self.get_protocol(),
                                        self.get_http_port(), path)

    def tearDown(self):
        self.http_server.stop()
        self.io_loop.run_sync(self.http_server.close_all_connections,
                              timeout=get_async_test_timeout())
        self.http_client.close()
        super(AsyncHTTPTestCase, self).tearDown()


class AsyncHTTPSTestCase(AsyncHTTPTestCase):
    """A test case that starts an HTTPS server.

    Interface is generally the same as `AsyncHTTPTestCase`.
    """
    def get_http_client(self):
        return AsyncHTTPClient(force_instance=True,
                               defaults=dict(validate_cert=False))

    def get_httpserver_options(self):
        return dict(ssl_options=self.get_ssl_options())

    def get_ssl_options(self):
        """May be overridden by subclasses to select SSL options.

        By default includes a self-signed testing certificate.
        """
        # Testing keys were generated with:
        # openssl req -new -keyout tornado/test/test.key \
        #                     -out tornado/test/test.crt -nodes -days 3650 -x509
        module_dir = os.path.dirname(__file__)
        return dict(
            certfile=os.path.join(module_dir, 'test', 'test.crt'),
            keyfile=os.path.join(module_dir, 'test', 'test.key'))

    def get_protocol(self):
        return 'https'


def gen_test(func=None, timeout=None):
    """Testing equivalent of ``@gen.coroutine``, to be applied to test methods.

    ``@gen.coroutine`` cannot be used on tests because the `.IOLoop` is not
    already running.  ``@gen_test`` should be applied to test methods
    on subclasses of `AsyncTestCase`.

    Example::

        class MyTest(AsyncHTTPTestCase):
            @gen_test
            def test_something(self):
                response = yield self.http_client.fetch(self.get_url('/'))

    By default, ``@gen_test`` times out after 5 seconds. The timeout may be
    overridden globally with the ``ASYNC_TEST_TIMEOUT`` environment variable,
    or for each test with the ``timeout`` keyword argument::

        class MyTest(AsyncHTTPTestCase):
            @gen_test(timeout=10)
            def test_something_slow(self):
                response = yield self.http_client.fetch(self.get_url('/'))

    Note that ``@gen_test`` is incompatible with `AsyncTestCase.stop`,
    `AsyncTestCase.wait`, and `AsyncHTTPTestCase.fetch`. Use ``yield
    self.http_client.fetch(self.get_url())`` as shown above instead.

    .. versionadded:: 3.1
       The ``timeout`` argument and ``ASYNC_TEST_TIMEOUT`` environment
       variable.

    .. versionchanged:: 4.0
       The wrapper now passes along ``*args, **kwargs`` so it can be used
       on functions with arguments.

    """
    if timeout is None:
        timeout = get_async_test_timeout()

    def wrap(f):
        # Stack up several decorators to allow us to access the generator
        # object itself.  In the innermost wrapper, we capture the generator
        # and save it in an attribute of self.  Next, we run the wrapped
        # function through @gen.coroutine.  Finally, the coroutine is
        # wrapped again to make it synchronous with run_sync.
        #
        # This is a good case study arguing for either some sort of
        # extensibility in the gen decorators or cancellation support.
        @functools.wraps(f)
        def pre_coroutine(self, *args, **kwargs):
            result = f(self, *args, **kwargs)
            if isinstance(result, GeneratorType) or iscoroutine(result):
                self._test_generator = result
            else:
                self._test_generator = None
            return result

        if iscoroutinefunction(f):
            coro = pre_coroutine
        else:
            coro = gen.coroutine(pre_coroutine)

        @functools.wraps(coro)
        def post_coroutine(self, *args, **kwargs):
            try:
                return self.io_loop.run_sync(
                    functools.partial(coro, self, *args, **kwargs),
                    timeout=timeout)
            except TimeoutError as e:
                # run_sync raises an error with an unhelpful traceback.
                # If the underlying generator is still running, we can throw the
                # exception back into it so the stack trace is replaced by the
                # point where the test is stopped. The only reason the generator
                # would not be running would be if it were cancelled, which means
                # a native coroutine, so we can rely on the cr_running attribute.
                if getattr(self._test_generator, 'cr_running', True):
                    self._test_generator.throw(e)
                    # In case the test contains an overly broad except
                    # clause, we may get back here.
                # Coroutine was stopped or didn't raise a useful stack trace,
                # so re-raise the original exception which is better than nothing.
                raise
        return post_coroutine

    if func is not None:
        # Used like:
        #     @gen_test
        #     def f(self):
        #         pass
        return wrap(func)
    else:
        # Used like @gen_test(timeout=10)
        return wrap


# Without this attribute, nosetests will try to run gen_test as a test
# anywhere it is imported.
gen_test.__test__ = False  # type: ignore


class ExpectLog(logging.Filter):
    """Context manager to capture and suppress expected log output.

    Useful to make tests of error conditions less noisy, while still
    leaving unexpected log entries visible.  *Not thread safe.*

    The attribute ``logged_stack`` is set to true if any exception
    stack trace was logged.

    Usage::

        with ExpectLog('tornado.application', "Uncaught exception"):
            error_response = self.fetch("/some_page")

    .. versionchanged:: 4.3
       Added the ``logged_stack`` attribute.
    """
    def __init__(self, logger, regex, required=True):
        """Constructs an ExpectLog context manager.

        :param logger: Logger object (or name of logger) to watch.  Pass
            an empty string to watch the root logger.
        :param regex: Regular expression to match.  Any log entries on
            the specified logger that match this regex will be suppressed.
        :param required: If true, an exception will be raised if the end of
            the ``with`` statement is reached without matching any log entries.
        """
        if isinstance(logger, basestring_type):
            logger = logging.getLogger(logger)
        self.logger = logger
        self.regex = re.compile(regex)
        self.required = required
        self.matched = False
        self.logged_stack = False

    def filter(self, record):
        if record.exc_info:
            self.logged_stack = True
        message = record.getMessage()
        if self.regex.match(message):
            self.matched = True
            return False
        return True

    def __enter__(self):
        self.logger.addFilter(self)
        return self

    def __exit__(self, typ, value, tb):
        self.logger.removeFilter(self)
        if not typ and self.required and not self.matched:
            raise Exception("did not get expected log message")


def main(**kwargs):
    """A simple test runner.

    This test runner is essentially equivalent to `unittest.main` from
    the standard library, but adds support for tornado-style option
    parsing and log formatting. It is *not* necessary to use this
    `main` function to run tests using `AsyncTestCase`; these tests
    are self-contained and can run with any test runner.

    The easiest way to run a test is via the command line::

        python -m tornado.testing tornado.test.stack_context_test

    See the standard library unittest module for ways in which tests can
    be specified.

    Projects with many tests may wish to define a test script like
    ``tornado/test/runtests.py``.  This script should define a method
    ``all()`` which returns a test suite and then call
    `tornado.testing.main()`.  Note that even when a test script is
    used, the ``all()`` test suite may be overridden by naming a
    single test on the command line::

        # Runs all tests
        python -m tornado.test.runtests
        # Runs one test
        python -m tornado.test.runtests tornado.test.stack_context_test

    Additional keyword arguments passed through to ``unittest.main()``.
    For example, use ``tornado.testing.main(verbosity=2)``
    to show many test details as they are run.
    See http://docs.python.org/library/unittest.html#unittest.main
    for full argument list.

    .. versionchanged:: 5.0

       This function produces no output of its own; only that produced
       by the `unittest` module (Previously it would add a PASS or FAIL
       log message).
    """
    from tornado.options import define, options, parse_command_line

    define('exception_on_interrupt', type=bool, default=True,
           help=("If true (default), ctrl-c raises a KeyboardInterrupt "
                 "exception.  This prints a stack trace but cannot interrupt "
                 "certain operations.  If false, the process is more reliably "
                 "killed, but does not print a stack trace."))

    # support the same options as unittest's command-line interface
    define('verbose', type=bool)
    define('quiet', type=bool)
    define('failfast', type=bool)
    define('catch', type=bool)
    define('buffer', type=bool)

    argv = [sys.argv[0]] + parse_command_line(sys.argv)

    if not options.exception_on_interrupt:
        signal.signal(signal.SIGINT, signal.SIG_DFL)

    if options.verbose is not None:
        kwargs['verbosity'] = 2
    if options.quiet is not None:
        kwargs['verbosity'] = 0
    if options.failfast is not None:
        kwargs['failfast'] = True
    if options.catch is not None:
        kwargs['catchbreak'] = True
    if options.buffer is not None:
        kwargs['buffer'] = True

    if __name__ == '__main__' and len(argv) == 1:
        print("No tests specified", file=sys.stderr)
        sys.exit(1)
    # In order to be able to run tests by their fully-qualified name
    # on the command line without importing all tests here,
    # module must be set to None.  Python 3.2's unittest.main ignores
    # defaultTest if no module is given (it tries to do its own
    # test discovery, which is incompatible with auto2to3), so don't
    # set module if we're not asking for a specific test.
    if len(argv) > 1:
        unittest.main(module=None, argv=argv, **kwargs)
    else:
        unittest.main(defaultTest="all", argv=argv, **kwargs)


if __name__ == '__main__':
    main()

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