{
    "file_diffs": [
        {
            "old_file_content": "# flake8: noqa\nfrom __future__ import absolute_import, division, print_function\nfrom tornado.test.util import unittest\n\n\nclass ImportTest(unittest.TestCase):\n    def test_import_everything(self):\n        # Some of our modules are not otherwise tested.  Import them\n        # all (unless they have external dependencies) here to at\n        # least ensure that there are no syntax errors.\n        import tornado.auth\n        import tornado.autoreload\n        import tornado.concurrent\n        import tornado.escape\n        import tornado.gen\n        import tornado.http1connection\n        import tornado.httpclient\n        import tornado.httpserver\n        import tornado.httputil\n        import tornado.ioloop\n        import tornado.iostream\n        import tornado.locale\n        import tornado.log\n        import tornado.netutil\n        import tornado.options\n        import tornado.process\n        import tornado.simple_httpclient\n        import tornado.stack_context\n        import tornado.tcpserver\n        import tornado.tcpclient\n        import tornado.template\n        import tornado.testing\n        import tornado.util\n        import tornado.web\n        import tornado.websocket\n        import tornado.wsgi\n\n    # for modules with dependencies, if those dependencies can be loaded,\n    # load them too.\n\n    def test_import_pycurl(self):\n        try:\n            import pycurl  # type: ignore\n        except ImportError:\n            pass\n        else:\n            import tornado.curl_httpclient\n\n    def test_import_aliases(self):\n        # Ensure we don't delete formerly-documented aliases accidentally.\n        import tornado.ioloop\n        import tornado.gen\n        import tornado.util\n        self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)\n        self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)\n",
            "new_file_content": "# flake8: noqa\nfrom __future__ import absolute_import, division, print_function\n\nimport subprocess\nimport sys\n\nfrom tornado.test.util import unittest\n\n_import_everything = b\"\"\"\n# The event loop is not fork-safe, and it's easy to initialize an asyncio.Future\n# at startup, which in turn creates the default event loop and prevents forking.\n# Explicitly disallow the default event loop so that an error will be raised\n# if something tries to touch it.\ntry:\n    import asyncio\nexcept ImportError:\n    pass\nelse:\n    asyncio.set_event_loop(None)\n\nimport tornado.auth\nimport tornado.autoreload\nimport tornado.concurrent\nimport tornado.escape\nimport tornado.gen\nimport tornado.http1connection\nimport tornado.httpclient\nimport tornado.httpserver\nimport tornado.httputil\nimport tornado.ioloop\nimport tornado.iostream\nimport tornado.locale\nimport tornado.log\nimport tornado.netutil\nimport tornado.options\nimport tornado.process\nimport tornado.simple_httpclient\nimport tornado.stack_context\nimport tornado.tcpserver\nimport tornado.tcpclient\nimport tornado.template\nimport tornado.testing\nimport tornado.util\nimport tornado.web\nimport tornado.websocket\nimport tornado.wsgi\n\ntry:\n    import pycurl\nexcept ImportError:\n    pass\nelse:\n    import tornado.curl_httpclient\n\"\"\"\n\n\nclass ImportTest(unittest.TestCase):\n    def test_import_everything(self):\n        # Test that all Tornado modules can be imported without side effects,\n        # specifically without initializing the default asyncio event loop.\n        # Since we can't tell which modules may have already beein imported\n        # in our process, do it in a subprocess for a clean slate.\n        proc = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)\n        proc.communicate(_import_everything)\n        self.assertEqual(proc.returncode, 0)\n\n    def test_import_aliases(self):\n        # Ensure we don't delete formerly-documented aliases accidentally.\n        import tornado.ioloop\n        import tornado.gen\n        import tornado.util\n        self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)\n        self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)\n",
            "header": {
                "file": {
                    "path": "tornado/test/import_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "0e981482",
                "new_commit_hash": "ecc569eb",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/import_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/import_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1,
                            "length": 50
                        },
                        "new_range": {
                            "start": 1,
                            "length": 68
                        },
                        "section": ""
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "# flake8: noqa",
                                "type": "context"
                            },
                            {
                                "content": "from __future__ import absolute_import, division, print_function",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "import subprocess",
                                "type": "added"
                            },
                            {
                                "content": "import sys",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "from tornado.test.util import unittest",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "_import_everything = b\"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "# The event loop is not fork-safe, and it's easy to initialize an asyncio.Future",
                                "type": "added"
                            },
                            {
                                "content": "# at startup, which in turn creates the default event loop and prevents forking.",
                                "type": "added"
                            },
                            {
                                "content": "# Explicitly disallow the default event loop so that an error will be raised",
                                "type": "added"
                            },
                            {
                                "content": "# if something tries to touch it.",
                                "type": "added"
                            },
                            {
                                "content": "try:",
                                "type": "added"
                            },
                            {
                                "content": "    import asyncio",
                                "type": "added"
                            },
                            {
                                "content": "except ImportError:",
                                "type": "added"
                            },
                            {
                                "content": "    pass",
                                "type": "added"
                            },
                            {
                                "content": "else:",
                                "type": "added"
                            },
                            {
                                "content": "    asyncio.set_event_loop(None)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.auth",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.autoreload",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.concurrent",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.escape",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.gen",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.http1connection",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.httpclient",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.httpserver",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.httputil",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.ioloop",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.iostream",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.locale",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.log",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.netutil",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.options",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.process",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.simple_httpclient",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.stack_context",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.tcpserver",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.tcpclient",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.template",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.testing",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.util",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.web",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.websocket",
                                "type": "added"
                            },
                            {
                                "content": "import tornado.wsgi",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "try:",
                                "type": "added"
                            },
                            {
                                "content": "    import pycurl",
                                "type": "added"
                            },
                            {
                                "content": "except ImportError:",
                                "type": "added"
                            },
                            {
                                "content": "    pass",
                                "type": "added"
                            },
                            {
                                "content": "else:",
                                "type": "added"
                            },
                            {
                                "content": "    import tornado.curl_httpclient",
                                "type": "added"
                            },
                            {
                                "content": "\"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class ImportTest(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    def test_import_everything(self):",
                                "type": "context"
                            },
                            {
                                "content": "        # Some of our modules are not otherwise tested.  Import them",
                                "type": "deleted"
                            },
                            {
                                "content": "        # all (unless they have external dependencies) here to at",
                                "type": "deleted"
                            },
                            {
                                "content": "        # least ensure that there are no syntax errors.",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.auth",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.autoreload",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.concurrent",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.escape",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.gen",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.http1connection",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.httpclient",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.httpserver",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.httputil",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.ioloop",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.iostream",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.locale",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.log",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.netutil",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.options",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.process",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.simple_httpclient",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.stack_context",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.tcpserver",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.tcpclient",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.template",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.testing",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.util",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.web",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.websocket",
                                "type": "deleted"
                            },
                            {
                                "content": "        import tornado.wsgi",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "    # for modules with dependencies, if those dependencies can be loaded,",
                                "type": "deleted"
                            },
                            {
                                "content": "    # load them too.",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "    def test_import_pycurl(self):",
                                "type": "deleted"
                            },
                            {
                                "content": "        try:",
                                "type": "deleted"
                            },
                            {
                                "content": "            import pycurl  # type: ignore",
                                "type": "deleted"
                            },
                            {
                                "content": "        except ImportError:",
                                "type": "deleted"
                            },
                            {
                                "content": "            pass",
                                "type": "deleted"
                            },
                            {
                                "content": "        else:",
                                "type": "deleted"
                            },
                            {
                                "content": "            import tornado.curl_httpclient",
                                "type": "deleted"
                            },
                            {
                                "content": "        # Test that all Tornado modules can be imported without side effects,",
                                "type": "added"
                            },
                            {
                                "content": "        # specifically without initializing the default asyncio event loop.",
                                "type": "added"
                            },
                            {
                                "content": "        # Since we can't tell which modules may have already beein imported",
                                "type": "added"
                            },
                            {
                                "content": "        # in our process, do it in a subprocess for a clean slate.",
                                "type": "added"
                            },
                            {
                                "content": "        proc = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)",
                                "type": "added"
                            },
                            {
                                "content": "        proc.communicate(_import_everything)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(proc.returncode, 0)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_import_aliases(self):",
                                "type": "context"
                            },
                            {
                                "content": "        # Ensure we don't delete formerly-documented aliases accidentally.",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/import_test.py",
                            "type": "method",
                            "name": "ImportTest.test_import_everything",
                            "content": "class ImportTest(unittest.TestCase):\n    def test_import_everything(self):\n        # Some of our modules are not otherwise tested.  Import them\n        # all (unless they have external dependencies) here to at\n        # least ensure that there are no syntax errors.\n        import tornado.auth\n        import tornado.autoreload\n        import tornado.concurrent\n        import tornado.escape\n        import tornado.gen\n        import tornado.http1connection\n        import tornado.httpclient\n        import tornado.httpserver\n        import tornado.httputil\n        import tornado.ioloop\n        import tornado.iostream\n        import tornado.locale\n        import tornado.log\n        import tornado.netutil\n        import tornado.options\n        import tornado.process\n        import tornado.simple_httpclient\n        import tornado.stack_context\n        import tornado.tcpserver\n        import tornado.tcpclient\n        import tornado.template\n        import tornado.testing\n        import tornado.util\n        import tornado.web\n        import tornado.websocket\n        import tornado.wsgi\n\n    # for modules with dependencies, if those dependencies can be loaded,\n    # load them too.\n\n    def test_import_pycurl(self):\n        try:\n            import pycurl  # type: ignore\n        except ImportError:\n            pass\n        else:\n            import tornado.curl_httpclient\n\n    def test_import_aliases(self):\n        # Ensure we don't delete formerly-documented aliases accidentally.\n        import tornado.ioloop\n        import tornado.gen\n        import tornado.util\n        self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)\n        self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 7,
                            "end_lineno": 36,
                            "parent": {
                                "file_name": "tornado/test/import_test.py",
                                "type": "class",
                                "name": "ImportTest",
                                "content": "class ImportTest(unittest.TestCase):\n    def test_import_everything(self):\n        # Some of our modules are not otherwise tested.  Import them\n        # all (unless they have external dependencies) here to at\n        # least ensure that there are no syntax errors.\n        import tornado.auth\n        import tornado.autoreload\n        import tornado.concurrent\n        import tornado.escape\n        import tornado.gen\n        import tornado.http1connection\n        import tornado.httpclient\n        import tornado.httpserver\n        import tornado.httputil\n        import tornado.ioloop\n        import tornado.iostream\n        import tornado.locale\n        import tornado.log\n        import tornado.netutil\n        import tornado.options\n        import tornado.process\n        import tornado.simple_httpclient\n        import tornado.stack_context\n        import tornado.tcpserver\n        import tornado.tcpclient\n        import tornado.template\n        import tornado.testing\n        import tornado.util\n        import tornado.web\n        import tornado.websocket\n        import tornado.wsgi\n\n    # for modules with dependencies, if those dependencies can be loaded,\n    # load them too.\n\n    def test_import_pycurl(self):\n        try:\n            import pycurl  # type: ignore\n        except ImportError:\n            pass\n        else:\n            import tornado.curl_httpclient\n\n    def test_import_aliases(self):\n        # Ensure we don't delete formerly-documented aliases accidentally.\n        import tornado.ioloop\n        import tornado.gen\n        import tornado.util\n        self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)\n        self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 6,
                                "end_lineno": 55,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/import_test.py",
                            "type": "class",
                            "name": "ImportTest",
                            "content": "class ImportTest(unittest.TestCase):\n    def test_import_everything(self):\n        # Some of our modules are not otherwise tested.  Import them\n        # all (unless they have external dependencies) here to at\n        # least ensure that there are no syntax errors.\n        import tornado.auth\n        import tornado.autoreload\n        import tornado.concurrent\n        import tornado.escape\n        import tornado.gen\n        import tornado.http1connection\n        import tornado.httpclient\n        import tornado.httpserver\n        import tornado.httputil\n        import tornado.ioloop\n        import tornado.iostream\n        import tornado.locale\n        import tornado.log\n        import tornado.netutil\n        import tornado.options\n        import tornado.process\n        import tornado.simple_httpclient\n        import tornado.stack_context\n        import tornado.tcpserver\n        import tornado.tcpclient\n        import tornado.template\n        import tornado.testing\n        import tornado.util\n        import tornado.web\n        import tornado.websocket\n        import tornado.wsgi\n\n    # for modules with dependencies, if those dependencies can be loaded,\n    # load them too.\n\n    def test_import_pycurl(self):\n        try:\n            import pycurl  # type: ignore\n        except ImportError:\n            pass\n        else:\n            import tornado.curl_httpclient\n\n    def test_import_aliases(self):\n        # Ensure we don't delete formerly-documented aliases accidentally.\n        import tornado.ioloop\n        import tornado.gen\n        import tornado.util\n        self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)\n        self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 6,
                            "end_lineno": 55,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/import_test.py",
                            "type": "import",
                            "name": "subprocess",
                            "content": "import subprocess",
                            "ast_type_str": "Import",
                            "start_lineno": 4,
                            "end_lineno": 4,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/import_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "_import_everything = b\"\"\"\n# The event loop is not fork-safe, and it's easy to initialize an asyncio.Future\n# at startup, which in turn creates the default event loop and prevents forking.\n# Explicitly disallow the default event loop so that an error will be raised\n# if something tries to touch it.\ntry:\n    import asyncio\nexcept ImportError:\n    pass\nelse:\n    asyncio.set_event_loop(None)\n\nimport tornado.auth\nimport tornado.autoreload\nimport tornado.concurrent\nimport tornado.escape\nimport tornado.gen\nimport tornado.http1connection\nimport tornado.httpclient\nimport tornado.httpserver\nimport tornado.httputil\nimport tornado.ioloop\nimport tornado.iostream\nimport tornado.locale\nimport tornado.log\nimport tornado.netutil\nimport tornado.options\nimport tornado.process\nimport tornado.simple_httpclient\nimport tornado.stack_context\nimport tornado.tcpserver\nimport tornado.tcpclient\nimport tornado.template\nimport tornado.testing\nimport tornado.util\nimport tornado.web\nimport tornado.websocket\nimport tornado.wsgi\n\ntry:\n    import pycurl\nexcept ImportError:\n    pass\nelse:\n    import tornado.curl_httpclient\n\"\"\"",
                            "ast_type_str": "Assign",
                            "start_lineno": 9,
                            "end_lineno": 54,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/import_test.py",
                            "type": "import",
                            "name": "sys",
                            "content": "import sys",
                            "ast_type_str": "Import",
                            "start_lineno": 5,
                            "end_lineno": 5,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "tornado/test/import_test.py",
                            "type": "method",
                            "name": "ImportTest.test_import_pycurl",
                            "content": "class ImportTest(unittest.TestCase):\n    def test_import_everything(self):\n        # Some of our modules are not otherwise tested.  Import them\n        # all (unless they have external dependencies) here to at\n        # least ensure that there are no syntax errors.\n        import tornado.auth\n        import tornado.autoreload\n        import tornado.concurrent\n        import tornado.escape\n        import tornado.gen\n        import tornado.http1connection\n        import tornado.httpclient\n        import tornado.httpserver\n        import tornado.httputil\n        import tornado.ioloop\n        import tornado.iostream\n        import tornado.locale\n        import tornado.log\n        import tornado.netutil\n        import tornado.options\n        import tornado.process\n        import tornado.simple_httpclient\n        import tornado.stack_context\n        import tornado.tcpserver\n        import tornado.tcpclient\n        import tornado.template\n        import tornado.testing\n        import tornado.util\n        import tornado.web\n        import tornado.websocket\n        import tornado.wsgi\n\n    # for modules with dependencies, if those dependencies can be loaded,\n    # load them too.\n\n    def test_import_pycurl(self):\n        try:\n            import pycurl  # type: ignore\n        except ImportError:\n            pass\n        else:\n            import tornado.curl_httpclient\n\n    def test_import_aliases(self):\n        # Ensure we don't delete formerly-documented aliases accidentally.\n        import tornado.ioloop\n        import tornado.gen\n        import tornado.util\n        self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)\n        self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 41,
                            "end_lineno": 47,
                            "parent": {
                                "file_name": "tornado/test/import_test.py",
                                "type": "class",
                                "name": "ImportTest",
                                "content": "class ImportTest(unittest.TestCase):\n    def test_import_everything(self):\n        # Some of our modules are not otherwise tested.  Import them\n        # all (unless they have external dependencies) here to at\n        # least ensure that there are no syntax errors.\n        import tornado.auth\n        import tornado.autoreload\n        import tornado.concurrent\n        import tornado.escape\n        import tornado.gen\n        import tornado.http1connection\n        import tornado.httpclient\n        import tornado.httpserver\n        import tornado.httputil\n        import tornado.ioloop\n        import tornado.iostream\n        import tornado.locale\n        import tornado.log\n        import tornado.netutil\n        import tornado.options\n        import tornado.process\n        import tornado.simple_httpclient\n        import tornado.stack_context\n        import tornado.tcpserver\n        import tornado.tcpclient\n        import tornado.template\n        import tornado.testing\n        import tornado.util\n        import tornado.web\n        import tornado.websocket\n        import tornado.wsgi\n\n    # for modules with dependencies, if those dependencies can be loaded,\n    # load them too.\n\n    def test_import_pycurl(self):\n        try:\n            import pycurl  # type: ignore\n        except ImportError:\n            pass\n        else:\n            import tornado.curl_httpclient\n\n    def test_import_aliases(self):\n        # Ensure we don't delete formerly-documented aliases accidentally.\n        import tornado.ioloop\n        import tornado.gen\n        import tornado.util\n        self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)\n        self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 6,
                                "end_lineno": 55,
                                "parent": null
                            }
                        }
                    ]
                }
            ]
        },
        {
            "old_file_content": "#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"WSGI support for the Tornado web framework.\n\nWSGI is the Python standard for web servers, and allows for interoperability\nbetween Tornado and other Python web frameworks and servers.  This module\nprovides WSGI support in two ways:\n\n* `WSGIAdapter` converts a `tornado.web.Application` to the WSGI application\n  interface.  This is useful for running a Tornado app on another\n  HTTP server, such as Google App Engine.  See the `WSGIAdapter` class\n  documentation for limitations that apply.\n* `WSGIContainer` lets you run other WSGI applications and frameworks on the\n  Tornado HTTP server.  For example, with this class you can mix Django\n  and Tornado handlers in a single server.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport sys\nfrom io import BytesIO\nimport tornado\nimport warnings\n\nfrom tornado.concurrent import Future\nfrom tornado import escape\nfrom tornado import httputil\nfrom tornado.log import access_log\nfrom tornado import web\nfrom tornado.escape import native_str\nfrom tornado.util import unicode_type, PY3\n\n\nif PY3:\n    import urllib.parse as urllib_parse  # py3\nelse:\n    import urllib as urllib_parse\n\n# PEP 3333 specifies that WSGI on python 3 generally deals with byte strings\n# that are smuggled inside objects of type unicode (via the latin1 encoding).\n# These functions are like those in the tornado.escape module, but defined\n# here to minimize the temptation to use them in non-wsgi contexts.\nif str is unicode_type:\n    def to_wsgi_str(s):\n        assert isinstance(s, bytes)\n        return s.decode('latin1')\n\n    def from_wsgi_str(s):\n        assert isinstance(s, str)\n        return s.encode('latin1')\nelse:\n    def to_wsgi_str(s):\n        assert isinstance(s, bytes)\n        return s\n\n    def from_wsgi_str(s):\n        assert isinstance(s, str)\n        return s\n\n\nclass WSGIApplication(web.Application):\n    \"\"\"A WSGI equivalent of `tornado.web.Application`.\n\n    .. deprecated:: 4.0\n\n       Use a regular `.Application` and wrap it in `WSGIAdapter` instead.\n       This class will be removed in Tornado 6.0.\n    \"\"\"\n    def __call__(self, environ, start_response):\n        return WSGIAdapter(self)(environ, start_response)\n\n\n# WSGI has no facilities for flow control, so just return an already-done\n# Future when the interface requires it.\n_dummy_future = Future()\n_dummy_future.set_result(None)\n\n\nclass _WSGIConnection(httputil.HTTPConnection):\n    def __init__(self, method, start_response, context):\n        self.method = method\n        self.start_response = start_response\n        self.context = context\n        self._write_buffer = []\n        self._finished = False\n        self._expected_content_remaining = None\n        self._error = None\n\n    def set_close_callback(self, callback):\n        # WSGI has no facility for detecting a closed connection mid-request,\n        # so we can simply ignore the callback.\n        pass\n\n    def write_headers(self, start_line, headers, chunk=None, callback=None):\n        if self.method == 'HEAD':\n            self._expected_content_remaining = 0\n        elif 'Content-Length' in headers:\n            self._expected_content_remaining = int(headers['Content-Length'])\n        else:\n            self._expected_content_remaining = None\n        self.start_response(\n            '%s %s' % (start_line.code, start_line.reason),\n            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])\n        if chunk is not None:\n            self.write(chunk, callback)\n        elif callback is not None:\n            callback()\n        return _dummy_future\n\n    def write(self, chunk, callback=None):\n        if self._expected_content_remaining is not None:\n            self._expected_content_remaining -= len(chunk)\n            if self._expected_content_remaining < 0:\n                self._error = httputil.HTTPOutputError(\n                    \"Tried to write more data than Content-Length\")\n                raise self._error\n        self._write_buffer.append(chunk)\n        if callback is not None:\n            callback()\n        return _dummy_future\n\n    def finish(self):\n        if (self._expected_content_remaining is not None and\n                self._expected_content_remaining != 0):\n            self._error = httputil.HTTPOutputError(\n                \"Tried to write %d bytes less than Content-Length\" %\n                self._expected_content_remaining)\n            raise self._error\n        self._finished = True\n\n\nclass _WSGIRequestContext(object):\n    def __init__(self, remote_ip, protocol):\n        self.remote_ip = remote_ip\n        self.protocol = protocol\n\n    def __str__(self):\n        return self.remote_ip\n\n\nclass WSGIAdapter(object):\n    \"\"\"Converts a `tornado.web.Application` instance into a WSGI application.\n\n    Example usage::\n\n        import tornado.web\n        import tornado.wsgi\n        import wsgiref.simple_server\n\n        class MainHandler(tornado.web.RequestHandler):\n            def get(self):\n                self.write(\"Hello, world\")\n\n        if __name__ == \"__main__\":\n            application = tornado.web.Application([\n                (r\"/\", MainHandler),\n            ])\n            wsgi_app = tornado.wsgi.WSGIAdapter(application)\n            server = wsgiref.simple_server.make_server('', 8888, wsgi_app)\n            server.serve_forever()\n\n    See the `appengine demo\n    <https://github.com/tornadoweb/tornado/tree/stable/demos/appengine>`_\n    for an example of using this module to run a Tornado app on Google\n    App Engine.\n\n    In WSGI mode asynchronous methods are not supported.  This means\n    that it is not possible to use `.AsyncHTTPClient`, or the\n    `tornado.auth` or `tornado.websocket` modules.\n\n    In multithreaded WSGI servers on Python 3, it may be necessary to\n    permit `asyncio` to create event loops on any thread. Run the\n    following at startup (typically import time for WSGI\n    applications)::\n\n        import asyncio\n        from tornado.platform.asyncio import AnyThreadEventLoopPolicy\n        asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())\n\n    .. versionadded:: 4.0\n\n    .. deprecated:: 5.1\n\n       This class is deprecated and will be removed in Tornado 6.0.\n       Use Tornado's `.HTTPServer` instead of a WSGI container.\n    \"\"\"\n    def __init__(self, application):\n        warnings.warn(\"WSGIAdapter is deprecated, use Tornado's HTTPServer instead\",\n                      DeprecationWarning)\n        if isinstance(application, WSGIApplication):\n            self.application = lambda request: web.Application.__call__(\n                application, request)\n        else:\n            self.application = application\n\n    def __call__(self, environ, start_response):\n        method = environ[\"REQUEST_METHOD\"]\n        uri = urllib_parse.quote(from_wsgi_str(environ.get(\"SCRIPT_NAME\", \"\")))\n        uri += urllib_parse.quote(from_wsgi_str(environ.get(\"PATH_INFO\", \"\")))\n        if environ.get(\"QUERY_STRING\"):\n            uri += \"?\" + environ[\"QUERY_STRING\"]\n        headers = httputil.HTTPHeaders()\n        if environ.get(\"CONTENT_TYPE\"):\n            headers[\"Content-Type\"] = environ[\"CONTENT_TYPE\"]\n        if environ.get(\"CONTENT_LENGTH\"):\n            headers[\"Content-Length\"] = environ[\"CONTENT_LENGTH\"]\n        for key in environ:\n            if key.startswith(\"HTTP_\"):\n                headers[key[5:].replace(\"_\", \"-\")] = environ[key]\n        if headers.get(\"Content-Length\"):\n            body = environ[\"wsgi.input\"].read(\n                int(headers[\"Content-Length\"]))\n        else:\n            body = b\"\"\n        protocol = environ[\"wsgi.url_scheme\"]\n        remote_ip = environ.get(\"REMOTE_ADDR\", \"\")\n        if environ.get(\"HTTP_HOST\"):\n            host = environ[\"HTTP_HOST\"]\n        else:\n            host = environ[\"SERVER_NAME\"]\n        connection = _WSGIConnection(method, start_response,\n                                     _WSGIRequestContext(remote_ip, protocol))\n        request = httputil.HTTPServerRequest(\n            method, uri, \"HTTP/1.1\", headers=headers, body=body,\n            host=host, connection=connection)\n        request._parse_body()\n        self.application(request)\n        if connection._error:\n            raise connection._error\n        if not connection._finished:\n            raise Exception(\"request did not finish synchronously\")\n        return connection._write_buffer\n\n\nclass WSGIContainer(object):\n    r\"\"\"Makes a WSGI-compatible function runnable on Tornado's HTTP server.\n\n    .. warning::\n\n       WSGI is a *synchronous* interface, while Tornado's concurrency model\n       is based on single-threaded asynchronous execution.  This means that\n       running a WSGI app with Tornado's `WSGIContainer` is *less scalable*\n       than running the same app in a multi-threaded WSGI server like\n       ``gunicorn`` or ``uwsgi``.  Use `WSGIContainer` only when there are\n       benefits to combining Tornado and WSGI in the same process that\n       outweigh the reduced scalability.\n\n    Wrap a WSGI function in a `WSGIContainer` and pass it to `.HTTPServer` to\n    run it. For example::\n\n        def simple_app(environ, start_response):\n            status = \"200 OK\"\n            response_headers = [(\"Content-type\", \"text/plain\")]\n            start_response(status, response_headers)\n            return [\"Hello world!\\n\"]\n\n        container = tornado.wsgi.WSGIContainer(simple_app)\n        http_server = tornado.httpserver.HTTPServer(container)\n        http_server.listen(8888)\n        tornado.ioloop.IOLoop.current().start()\n\n    This class is intended to let other frameworks (Django, web.py, etc)\n    run on the Tornado HTTP server and I/O loop.\n\n    The `tornado.web.FallbackHandler` class is often useful for mixing\n    Tornado and WSGI apps in the same server.  See\n    https://github.com/bdarnell/django-tornado-demo for a complete example.\n    \"\"\"\n    def __init__(self, wsgi_application):\n        self.wsgi_application = wsgi_application\n\n    def __call__(self, request):\n        data = {}\n        response = []\n\n        def start_response(status, response_headers, exc_info=None):\n            data[\"status\"] = status\n            data[\"headers\"] = response_headers\n            return response.append\n        app_response = self.wsgi_application(\n            WSGIContainer.environ(request), start_response)\n        try:\n            response.extend(app_response)\n            body = b\"\".join(response)\n        finally:\n            if hasattr(app_response, \"close\"):\n                app_response.close()\n        if not data:\n            raise Exception(\"WSGI app did not call start_response\")\n\n        status_code, reason = data[\"status\"].split(' ', 1)\n        status_code = int(status_code)\n        headers = data[\"headers\"]\n        header_set = set(k.lower() for (k, v) in headers)\n        body = escape.utf8(body)\n        if status_code != 304:\n            if \"content-length\" not in header_set:\n                headers.append((\"Content-Length\", str(len(body))))\n            if \"content-type\" not in header_set:\n                headers.append((\"Content-Type\", \"text/html; charset=UTF-8\"))\n        if \"server\" not in header_set:\n            headers.append((\"Server\", \"TornadoServer/%s\" % tornado.version))\n\n        start_line = httputil.ResponseStartLine(\"HTTP/1.1\", status_code, reason)\n        header_obj = httputil.HTTPHeaders()\n        for key, value in headers:\n            header_obj.add(key, value)\n        request.connection.write_headers(start_line, header_obj, chunk=body)\n        request.connection.finish()\n        self._log(status_code, request)\n\n    @staticmethod\n    def environ(request):\n        \"\"\"Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.\n        \"\"\"\n        hostport = request.host.split(\":\")\n        if len(hostport) == 2:\n            host = hostport[0]\n            port = int(hostport[1])\n        else:\n            host = request.host\n            port = 443 if request.protocol == \"https\" else 80\n        environ = {\n            \"REQUEST_METHOD\": request.method,\n            \"SCRIPT_NAME\": \"\",\n            \"PATH_INFO\": to_wsgi_str(escape.url_unescape(\n                request.path, encoding=None, plus=False)),\n            \"QUERY_STRING\": request.query,\n            \"REMOTE_ADDR\": request.remote_ip,\n            \"SERVER_NAME\": host,\n            \"SERVER_PORT\": str(port),\n            \"SERVER_PROTOCOL\": request.version,\n            \"wsgi.version\": (1, 0),\n            \"wsgi.url_scheme\": request.protocol,\n            \"wsgi.input\": BytesIO(escape.utf8(request.body)),\n            \"wsgi.errors\": sys.stderr,\n            \"wsgi.multithread\": False,\n            \"wsgi.multiprocess\": True,\n            \"wsgi.run_once\": False,\n        }\n        if \"Content-Type\" in request.headers:\n            environ[\"CONTENT_TYPE\"] = request.headers.pop(\"Content-Type\")\n        if \"Content-Length\" in request.headers:\n            environ[\"CONTENT_LENGTH\"] = request.headers.pop(\"Content-Length\")\n        for key, value in request.headers.items():\n            environ[\"HTTP_\" + key.replace(\"-\", \"_\").upper()] = value\n        return environ\n\n    def _log(self, status_code, request):\n        if status_code < 400:\n            log_method = access_log.info\n        elif status_code < 500:\n            log_method = access_log.warning\n        else:\n            log_method = access_log.error\n        request_time = 1000.0 * request.request_time()\n        summary = request.method + \" \" + request.uri + \" (\" + \\\n            request.remote_ip + \")\"\n        log_method(\"%d %s %.2fms\", status_code, summary, request_time)\n\n\nHTTPRequest = httputil.HTTPServerRequest\n",
            "new_file_content": "#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"WSGI support for the Tornado web framework.\n\nWSGI is the Python standard for web servers, and allows for interoperability\nbetween Tornado and other Python web frameworks and servers.  This module\nprovides WSGI support in two ways:\n\n* `WSGIAdapter` converts a `tornado.web.Application` to the WSGI application\n  interface.  This is useful for running a Tornado app on another\n  HTTP server, such as Google App Engine.  See the `WSGIAdapter` class\n  documentation for limitations that apply.\n* `WSGIContainer` lets you run other WSGI applications and frameworks on the\n  Tornado HTTP server.  For example, with this class you can mix Django\n  and Tornado handlers in a single server.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport sys\nfrom io import BytesIO\nimport tornado\nimport warnings\n\nfrom tornado.concurrent import Future\nfrom tornado import escape\nfrom tornado import httputil\nfrom tornado.log import access_log\nfrom tornado import web\nfrom tornado.escape import native_str\nfrom tornado.util import unicode_type, PY3\n\n\nif PY3:\n    import urllib.parse as urllib_parse  # py3\nelse:\n    import urllib as urllib_parse\n\n# PEP 3333 specifies that WSGI on python 3 generally deals with byte strings\n# that are smuggled inside objects of type unicode (via the latin1 encoding).\n# These functions are like those in the tornado.escape module, but defined\n# here to minimize the temptation to use them in non-wsgi contexts.\nif str is unicode_type:\n    def to_wsgi_str(s):\n        assert isinstance(s, bytes)\n        return s.decode('latin1')\n\n    def from_wsgi_str(s):\n        assert isinstance(s, str)\n        return s.encode('latin1')\nelse:\n    def to_wsgi_str(s):\n        assert isinstance(s, bytes)\n        return s\n\n    def from_wsgi_str(s):\n        assert isinstance(s, str)\n        return s\n\n\nclass WSGIApplication(web.Application):\n    \"\"\"A WSGI equivalent of `tornado.web.Application`.\n\n    .. deprecated:: 4.0\n\n       Use a regular `.Application` and wrap it in `WSGIAdapter` instead.\n       This class will be removed in Tornado 6.0.\n    \"\"\"\n    def __call__(self, environ, start_response):\n        return WSGIAdapter(self)(environ, start_response)\n\n\n# WSGI has no facilities for flow control, so just return an already-done\n# Future when the interface requires it.\ndef _dummy_future():\n    f = Future()\n    f.set_result(None)\n    return f\n\n\nclass _WSGIConnection(httputil.HTTPConnection):\n    def __init__(self, method, start_response, context):\n        self.method = method\n        self.start_response = start_response\n        self.context = context\n        self._write_buffer = []\n        self._finished = False\n        self._expected_content_remaining = None\n        self._error = None\n\n    def set_close_callback(self, callback):\n        # WSGI has no facility for detecting a closed connection mid-request,\n        # so we can simply ignore the callback.\n        pass\n\n    def write_headers(self, start_line, headers, chunk=None, callback=None):\n        if self.method == 'HEAD':\n            self._expected_content_remaining = 0\n        elif 'Content-Length' in headers:\n            self._expected_content_remaining = int(headers['Content-Length'])\n        else:\n            self._expected_content_remaining = None\n        self.start_response(\n            '%s %s' % (start_line.code, start_line.reason),\n            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])\n        if chunk is not None:\n            self.write(chunk, callback)\n        elif callback is not None:\n            callback()\n        return _dummy_future()\n\n    def write(self, chunk, callback=None):\n        if self._expected_content_remaining is not None:\n            self._expected_content_remaining -= len(chunk)\n            if self._expected_content_remaining < 0:\n                self._error = httputil.HTTPOutputError(\n                    \"Tried to write more data than Content-Length\")\n                raise self._error\n        self._write_buffer.append(chunk)\n        if callback is not None:\n            callback()\n        return _dummy_future()\n\n    def finish(self):\n        if (self._expected_content_remaining is not None and\n                self._expected_content_remaining != 0):\n            self._error = httputil.HTTPOutputError(\n                \"Tried to write %d bytes less than Content-Length\" %\n                self._expected_content_remaining)\n            raise self._error\n        self._finished = True\n\n\nclass _WSGIRequestContext(object):\n    def __init__(self, remote_ip, protocol):\n        self.remote_ip = remote_ip\n        self.protocol = protocol\n\n    def __str__(self):\n        return self.remote_ip\n\n\nclass WSGIAdapter(object):\n    \"\"\"Converts a `tornado.web.Application` instance into a WSGI application.\n\n    Example usage::\n\n        import tornado.web\n        import tornado.wsgi\n        import wsgiref.simple_server\n\n        class MainHandler(tornado.web.RequestHandler):\n            def get(self):\n                self.write(\"Hello, world\")\n\n        if __name__ == \"__main__\":\n            application = tornado.web.Application([\n                (r\"/\", MainHandler),\n            ])\n            wsgi_app = tornado.wsgi.WSGIAdapter(application)\n            server = wsgiref.simple_server.make_server('', 8888, wsgi_app)\n            server.serve_forever()\n\n    See the `appengine demo\n    <https://github.com/tornadoweb/tornado/tree/stable/demos/appengine>`_\n    for an example of using this module to run a Tornado app on Google\n    App Engine.\n\n    In WSGI mode asynchronous methods are not supported.  This means\n    that it is not possible to use `.AsyncHTTPClient`, or the\n    `tornado.auth` or `tornado.websocket` modules.\n\n    In multithreaded WSGI servers on Python 3, it may be necessary to\n    permit `asyncio` to create event loops on any thread. Run the\n    following at startup (typically import time for WSGI\n    applications)::\n\n        import asyncio\n        from tornado.platform.asyncio import AnyThreadEventLoopPolicy\n        asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())\n\n    .. versionadded:: 4.0\n\n    .. deprecated:: 5.1\n\n       This class is deprecated and will be removed in Tornado 6.0.\n       Use Tornado's `.HTTPServer` instead of a WSGI container.\n    \"\"\"\n    def __init__(self, application):\n        warnings.warn(\"WSGIAdapter is deprecated, use Tornado's HTTPServer instead\",\n                      DeprecationWarning)\n        if isinstance(application, WSGIApplication):\n            self.application = lambda request: web.Application.__call__(\n                application, request)\n        else:\n            self.application = application\n\n    def __call__(self, environ, start_response):\n        method = environ[\"REQUEST_METHOD\"]\n        uri = urllib_parse.quote(from_wsgi_str(environ.get(\"SCRIPT_NAME\", \"\")))\n        uri += urllib_parse.quote(from_wsgi_str(environ.get(\"PATH_INFO\", \"\")))\n        if environ.get(\"QUERY_STRING\"):\n            uri += \"?\" + environ[\"QUERY_STRING\"]\n        headers = httputil.HTTPHeaders()\n        if environ.get(\"CONTENT_TYPE\"):\n            headers[\"Content-Type\"] = environ[\"CONTENT_TYPE\"]\n        if environ.get(\"CONTENT_LENGTH\"):\n            headers[\"Content-Length\"] = environ[\"CONTENT_LENGTH\"]\n        for key in environ:\n            if key.startswith(\"HTTP_\"):\n                headers[key[5:].replace(\"_\", \"-\")] = environ[key]\n        if headers.get(\"Content-Length\"):\n            body = environ[\"wsgi.input\"].read(\n                int(headers[\"Content-Length\"]))\n        else:\n            body = b\"\"\n        protocol = environ[\"wsgi.url_scheme\"]\n        remote_ip = environ.get(\"REMOTE_ADDR\", \"\")\n        if environ.get(\"HTTP_HOST\"):\n            host = environ[\"HTTP_HOST\"]\n        else:\n            host = environ[\"SERVER_NAME\"]\n        connection = _WSGIConnection(method, start_response,\n                                     _WSGIRequestContext(remote_ip, protocol))\n        request = httputil.HTTPServerRequest(\n            method, uri, \"HTTP/1.1\", headers=headers, body=body,\n            host=host, connection=connection)\n        request._parse_body()\n        self.application(request)\n        if connection._error:\n            raise connection._error\n        if not connection._finished:\n            raise Exception(\"request did not finish synchronously\")\n        return connection._write_buffer\n\n\nclass WSGIContainer(object):\n    r\"\"\"Makes a WSGI-compatible function runnable on Tornado's HTTP server.\n\n    .. warning::\n\n       WSGI is a *synchronous* interface, while Tornado's concurrency model\n       is based on single-threaded asynchronous execution.  This means that\n       running a WSGI app with Tornado's `WSGIContainer` is *less scalable*\n       than running the same app in a multi-threaded WSGI server like\n       ``gunicorn`` or ``uwsgi``.  Use `WSGIContainer` only when there are\n       benefits to combining Tornado and WSGI in the same process that\n       outweigh the reduced scalability.\n\n    Wrap a WSGI function in a `WSGIContainer` and pass it to `.HTTPServer` to\n    run it. For example::\n\n        def simple_app(environ, start_response):\n            status = \"200 OK\"\n            response_headers = [(\"Content-type\", \"text/plain\")]\n            start_response(status, response_headers)\n            return [\"Hello world!\\n\"]\n\n        container = tornado.wsgi.WSGIContainer(simple_app)\n        http_server = tornado.httpserver.HTTPServer(container)\n        http_server.listen(8888)\n        tornado.ioloop.IOLoop.current().start()\n\n    This class is intended to let other frameworks (Django, web.py, etc)\n    run on the Tornado HTTP server and I/O loop.\n\n    The `tornado.web.FallbackHandler` class is often useful for mixing\n    Tornado and WSGI apps in the same server.  See\n    https://github.com/bdarnell/django-tornado-demo for a complete example.\n    \"\"\"\n    def __init__(self, wsgi_application):\n        self.wsgi_application = wsgi_application\n\n    def __call__(self, request):\n        data = {}\n        response = []\n\n        def start_response(status, response_headers, exc_info=None):\n            data[\"status\"] = status\n            data[\"headers\"] = response_headers\n            return response.append\n        app_response = self.wsgi_application(\n            WSGIContainer.environ(request), start_response)\n        try:\n            response.extend(app_response)\n            body = b\"\".join(response)\n        finally:\n            if hasattr(app_response, \"close\"):\n                app_response.close()\n        if not data:\n            raise Exception(\"WSGI app did not call start_response\")\n\n        status_code, reason = data[\"status\"].split(' ', 1)\n        status_code = int(status_code)\n        headers = data[\"headers\"]\n        header_set = set(k.lower() for (k, v) in headers)\n        body = escape.utf8(body)\n        if status_code != 304:\n            if \"content-length\" not in header_set:\n                headers.append((\"Content-Length\", str(len(body))))\n            if \"content-type\" not in header_set:\n                headers.append((\"Content-Type\", \"text/html; charset=UTF-8\"))\n        if \"server\" not in header_set:\n            headers.append((\"Server\", \"TornadoServer/%s\" % tornado.version))\n\n        start_line = httputil.ResponseStartLine(\"HTTP/1.1\", status_code, reason)\n        header_obj = httputil.HTTPHeaders()\n        for key, value in headers:\n            header_obj.add(key, value)\n        request.connection.write_headers(start_line, header_obj, chunk=body)\n        request.connection.finish()\n        self._log(status_code, request)\n\n    @staticmethod\n    def environ(request):\n        \"\"\"Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.\n        \"\"\"\n        hostport = request.host.split(\":\")\n        if len(hostport) == 2:\n            host = hostport[0]\n            port = int(hostport[1])\n        else:\n            host = request.host\n            port = 443 if request.protocol == \"https\" else 80\n        environ = {\n            \"REQUEST_METHOD\": request.method,\n            \"SCRIPT_NAME\": \"\",\n            \"PATH_INFO\": to_wsgi_str(escape.url_unescape(\n                request.path, encoding=None, plus=False)),\n            \"QUERY_STRING\": request.query,\n            \"REMOTE_ADDR\": request.remote_ip,\n            \"SERVER_NAME\": host,\n            \"SERVER_PORT\": str(port),\n            \"SERVER_PROTOCOL\": request.version,\n            \"wsgi.version\": (1, 0),\n            \"wsgi.url_scheme\": request.protocol,\n            \"wsgi.input\": BytesIO(escape.utf8(request.body)),\n            \"wsgi.errors\": sys.stderr,\n            \"wsgi.multithread\": False,\n            \"wsgi.multiprocess\": True,\n            \"wsgi.run_once\": False,\n        }\n        if \"Content-Type\" in request.headers:\n            environ[\"CONTENT_TYPE\"] = request.headers.pop(\"Content-Type\")\n        if \"Content-Length\" in request.headers:\n            environ[\"CONTENT_LENGTH\"] = request.headers.pop(\"Content-Length\")\n        for key, value in request.headers.items():\n            environ[\"HTTP_\" + key.replace(\"-\", \"_\").upper()] = value\n        return environ\n\n    def _log(self, status_code, request):\n        if status_code < 400:\n            log_method = access_log.info\n        elif status_code < 500:\n            log_method = access_log.warning\n        else:\n            log_method = access_log.error\n        request_time = 1000.0 * request.request_time()\n        summary = request.method + \" \" + request.uri + \" (\" + \\\n            request.remote_ip + \")\"\n        log_method(\"%d %s %.2fms\", status_code, summary, request_time)\n\n\nHTTPRequest = httputil.HTTPServerRequest\n",
            "header": {
                "file": {
                    "path": "tornado/wsgi.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "beda0b9a",
                "new_commit_hash": "e1230da0",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/wsgi.py"
            },
            "plus_file": {
                "path": "b/tornado/wsgi.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 85,
                            "length": 8
                        },
                        "new_range": {
                            "start": 85,
                            "length": 10
                        },
                        "section": "class WSGIApplication(web.Application):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "# WSGI has no facilities for flow control, so just return an already-done",
                                "type": "context"
                            },
                            {
                                "content": "# Future when the interface requires it.",
                                "type": "context"
                            },
                            {
                                "content": "_dummy_future = Future()",
                                "type": "deleted"
                            },
                            {
                                "content": "_dummy_future.set_result(None)",
                                "type": "deleted"
                            },
                            {
                                "content": "def _dummy_future():",
                                "type": "added"
                            },
                            {
                                "content": "    f = Future()",
                                "type": "added"
                            },
                            {
                                "content": "    f.set_result(None)",
                                "type": "added"
                            },
                            {
                                "content": "    return f",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class _WSGIConnection(httputil.HTTPConnection):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/wsgi.py",
                            "type": "function",
                            "name": "_dummy_future",
                            "content": "def _dummy_future():\n    f = Future()\n    f.set_result(None)\n    return f",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 88,
                            "end_lineno": 91,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "tornado/wsgi.py",
                            "type": "statement",
                            "name": "",
                            "content": "_dummy_future = Future()",
                            "ast_type_str": "Assign",
                            "start_lineno": 88,
                            "end_lineno": 88,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/wsgi.py",
                            "type": "statement",
                            "name": "",
                            "content": "_dummy_future.set_result(None)",
                            "ast_type_str": "Expr",
                            "start_lineno": 89,
                            "end_lineno": 89,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 118,
                            "length": 7
                        },
                        "new_range": {
                            "start": 120,
                            "length": 7
                        },
                        "section": "class _WSGIConnection(httputil.HTTPConnection):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            self.write(chunk, callback)",
                                "type": "context"
                            },
                            {
                                "content": "        elif callback is not None:",
                                "type": "context"
                            },
                            {
                                "content": "            callback()",
                                "type": "context"
                            },
                            {
                                "content": "        return _dummy_future",
                                "type": "deleted"
                            },
                            {
                                "content": "        return _dummy_future()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def write(self, chunk, callback=None):",
                                "type": "context"
                            },
                            {
                                "content": "        if self._expected_content_remaining is not None:",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/wsgi.py",
                            "type": "method",
                            "name": "_WSGIConnection.write_headers",
                            "content": "class _WSGIConnection(httputil.HTTPConnection):\n    def __init__(self, method, start_response, context):\n        self.method = method\n        self.start_response = start_response\n        self.context = context\n        self._write_buffer = []\n        self._finished = False\n        self._expected_content_remaining = None\n        self._error = None\n\n    def set_close_callback(self, callback):\n        # WSGI has no facility for detecting a closed connection mid-request,\n        # so we can simply ignore the callback.\n        pass\n\n    def write_headers(self, start_line, headers, chunk=None, callback=None):\n        if self.method == 'HEAD':\n            self._expected_content_remaining = 0\n        elif 'Content-Length' in headers:\n            self._expected_content_remaining = int(headers['Content-Length'])\n        else:\n            self._expected_content_remaining = None\n        self.start_response(\n            '%s %s' % (start_line.code, start_line.reason),\n            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])\n        if chunk is not None:\n            self.write(chunk, callback)\n        elif callback is not None:\n            callback()\n        return _dummy_future\n\n    def write(self, chunk, callback=None):\n        if self._expected_content_remaining is not None:\n            self._expected_content_remaining -= len(chunk)\n            if self._expected_content_remaining < 0:\n                self._error = httputil.HTTPOutputError(\n                    \"Tried to write more data than Content-Length\")\n                raise self._error\n        self._write_buffer.append(chunk)\n        if callback is not None:\n            callback()\n        return _dummy_future\n\n    def finish(self):\n        if (self._expected_content_remaining is not None and\n                self._expected_content_remaining != 0):\n            self._error = httputil.HTTPOutputError(\n                \"Tried to write %d bytes less than Content-Length\" %\n                self._expected_content_remaining)\n            raise self._error\n        self._finished = True",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 107,
                            "end_lineno": 121,
                            "parent": {
                                "file_name": "tornado/wsgi.py",
                                "type": "class",
                                "name": "_WSGIConnection",
                                "content": "class _WSGIConnection(httputil.HTTPConnection):\n    def __init__(self, method, start_response, context):\n        self.method = method\n        self.start_response = start_response\n        self.context = context\n        self._write_buffer = []\n        self._finished = False\n        self._expected_content_remaining = None\n        self._error = None\n\n    def set_close_callback(self, callback):\n        # WSGI has no facility for detecting a closed connection mid-request,\n        # so we can simply ignore the callback.\n        pass\n\n    def write_headers(self, start_line, headers, chunk=None, callback=None):\n        if self.method == 'HEAD':\n            self._expected_content_remaining = 0\n        elif 'Content-Length' in headers:\n            self._expected_content_remaining = int(headers['Content-Length'])\n        else:\n            self._expected_content_remaining = None\n        self.start_response(\n            '%s %s' % (start_line.code, start_line.reason),\n            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])\n        if chunk is not None:\n            self.write(chunk, callback)\n        elif callback is not None:\n            callback()\n        return _dummy_future\n\n    def write(self, chunk, callback=None):\n        if self._expected_content_remaining is not None:\n            self._expected_content_remaining -= len(chunk)\n            if self._expected_content_remaining < 0:\n                self._error = httputil.HTTPOutputError(\n                    \"Tried to write more data than Content-Length\")\n                raise self._error\n        self._write_buffer.append(chunk)\n        if callback is not None:\n            callback()\n        return _dummy_future\n\n    def finish(self):\n        if (self._expected_content_remaining is not None and\n                self._expected_content_remaining != 0):\n            self._error = httputil.HTTPOutputError(\n                \"Tried to write %d bytes less than Content-Length\" %\n                self._expected_content_remaining)\n            raise self._error\n        self._finished = True",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 92,
                                "end_lineno": 142,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/wsgi.py",
                            "type": "class",
                            "name": "_WSGIConnection",
                            "content": "class _WSGIConnection(httputil.HTTPConnection):\n    def __init__(self, method, start_response, context):\n        self.method = method\n        self.start_response = start_response\n        self.context = context\n        self._write_buffer = []\n        self._finished = False\n        self._expected_content_remaining = None\n        self._error = None\n\n    def set_close_callback(self, callback):\n        # WSGI has no facility for detecting a closed connection mid-request,\n        # so we can simply ignore the callback.\n        pass\n\n    def write_headers(self, start_line, headers, chunk=None, callback=None):\n        if self.method == 'HEAD':\n            self._expected_content_remaining = 0\n        elif 'Content-Length' in headers:\n            self._expected_content_remaining = int(headers['Content-Length'])\n        else:\n            self._expected_content_remaining = None\n        self.start_response(\n            '%s %s' % (start_line.code, start_line.reason),\n            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])\n        if chunk is not None:\n            self.write(chunk, callback)\n        elif callback is not None:\n            callback()\n        return _dummy_future\n\n    def write(self, chunk, callback=None):\n        if self._expected_content_remaining is not None:\n            self._expected_content_remaining -= len(chunk)\n            if self._expected_content_remaining < 0:\n                self._error = httputil.HTTPOutputError(\n                    \"Tried to write more data than Content-Length\")\n                raise self._error\n        self._write_buffer.append(chunk)\n        if callback is not None:\n            callback()\n        return _dummy_future\n\n    def finish(self):\n        if (self._expected_content_remaining is not None and\n                self._expected_content_remaining != 0):\n            self._error = httputil.HTTPOutputError(\n                \"Tried to write %d bytes less than Content-Length\" %\n                self._expected_content_remaining)\n            raise self._error\n        self._finished = True",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 92,
                            "end_lineno": 142,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 130,
                            "length": 7
                        },
                        "new_range": {
                            "start": 132,
                            "length": 7
                        },
                        "section": "class _WSGIConnection(httputil.HTTPConnection):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self._write_buffer.append(chunk)",
                                "type": "context"
                            },
                            {
                                "content": "        if callback is not None:",
                                "type": "context"
                            },
                            {
                                "content": "            callback()",
                                "type": "context"
                            },
                            {
                                "content": "        return _dummy_future",
                                "type": "deleted"
                            },
                            {
                                "content": "        return _dummy_future()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def finish(self):",
                                "type": "context"
                            },
                            {
                                "content": "        if (self._expected_content_remaining is not None and",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/wsgi.py",
                            "type": "method",
                            "name": "_WSGIConnection.write",
                            "content": "class _WSGIConnection(httputil.HTTPConnection):\n    def __init__(self, method, start_response, context):\n        self.method = method\n        self.start_response = start_response\n        self.context = context\n        self._write_buffer = []\n        self._finished = False\n        self._expected_content_remaining = None\n        self._error = None\n\n    def set_close_callback(self, callback):\n        # WSGI has no facility for detecting a closed connection mid-request,\n        # so we can simply ignore the callback.\n        pass\n\n    def write_headers(self, start_line, headers, chunk=None, callback=None):\n        if self.method == 'HEAD':\n            self._expected_content_remaining = 0\n        elif 'Content-Length' in headers:\n            self._expected_content_remaining = int(headers['Content-Length'])\n        else:\n            self._expected_content_remaining = None\n        self.start_response(\n            '%s %s' % (start_line.code, start_line.reason),\n            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])\n        if chunk is not None:\n            self.write(chunk, callback)\n        elif callback is not None:\n            callback()\n        return _dummy_future\n\n    def write(self, chunk, callback=None):\n        if self._expected_content_remaining is not None:\n            self._expected_content_remaining -= len(chunk)\n            if self._expected_content_remaining < 0:\n                self._error = httputil.HTTPOutputError(\n                    \"Tried to write more data than Content-Length\")\n                raise self._error\n        self._write_buffer.append(chunk)\n        if callback is not None:\n            callback()\n        return _dummy_future\n\n    def finish(self):\n        if (self._expected_content_remaining is not None and\n                self._expected_content_remaining != 0):\n            self._error = httputil.HTTPOutputError(\n                \"Tried to write %d bytes less than Content-Length\" %\n                self._expected_content_remaining)\n            raise self._error\n        self._finished = True",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 123,
                            "end_lineno": 133,
                            "parent": {
                                "file_name": "tornado/wsgi.py",
                                "type": "class",
                                "name": "_WSGIConnection",
                                "content": "class _WSGIConnection(httputil.HTTPConnection):\n    def __init__(self, method, start_response, context):\n        self.method = method\n        self.start_response = start_response\n        self.context = context\n        self._write_buffer = []\n        self._finished = False\n        self._expected_content_remaining = None\n        self._error = None\n\n    def set_close_callback(self, callback):\n        # WSGI has no facility for detecting a closed connection mid-request,\n        # so we can simply ignore the callback.\n        pass\n\n    def write_headers(self, start_line, headers, chunk=None, callback=None):\n        if self.method == 'HEAD':\n            self._expected_content_remaining = 0\n        elif 'Content-Length' in headers:\n            self._expected_content_remaining = int(headers['Content-Length'])\n        else:\n            self._expected_content_remaining = None\n        self.start_response(\n            '%s %s' % (start_line.code, start_line.reason),\n            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])\n        if chunk is not None:\n            self.write(chunk, callback)\n        elif callback is not None:\n            callback()\n        return _dummy_future\n\n    def write(self, chunk, callback=None):\n        if self._expected_content_remaining is not None:\n            self._expected_content_remaining -= len(chunk)\n            if self._expected_content_remaining < 0:\n                self._error = httputil.HTTPOutputError(\n                    \"Tried to write more data than Content-Length\")\n                raise self._error\n        self._write_buffer.append(chunk)\n        if callback is not None:\n            callback()\n        return _dummy_future\n\n    def finish(self):\n        if (self._expected_content_remaining is not None and\n                self._expected_content_remaining != 0):\n            self._error = httputil.HTTPOutputError(\n                \"Tried to write %d bytes less than Content-Length\" %\n                self._expected_content_remaining)\n            raise self._error\n        self._finished = True",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 92,
                                "end_lineno": 142,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/wsgi.py",
                            "type": "class",
                            "name": "_WSGIConnection",
                            "content": "class _WSGIConnection(httputil.HTTPConnection):\n    def __init__(self, method, start_response, context):\n        self.method = method\n        self.start_response = start_response\n        self.context = context\n        self._write_buffer = []\n        self._finished = False\n        self._expected_content_remaining = None\n        self._error = None\n\n    def set_close_callback(self, callback):\n        # WSGI has no facility for detecting a closed connection mid-request,\n        # so we can simply ignore the callback.\n        pass\n\n    def write_headers(self, start_line, headers, chunk=None, callback=None):\n        if self.method == 'HEAD':\n            self._expected_content_remaining = 0\n        elif 'Content-Length' in headers:\n            self._expected_content_remaining = int(headers['Content-Length'])\n        else:\n            self._expected_content_remaining = None\n        self.start_response(\n            '%s %s' % (start_line.code, start_line.reason),\n            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])\n        if chunk is not None:\n            self.write(chunk, callback)\n        elif callback is not None:\n            callback()\n        return _dummy_future\n\n    def write(self, chunk, callback=None):\n        if self._expected_content_remaining is not None:\n            self._expected_content_remaining -= len(chunk)\n            if self._expected_content_remaining < 0:\n                self._error = httputil.HTTPOutputError(\n                    \"Tried to write more data than Content-Length\")\n                raise self._error\n        self._write_buffer.append(chunk)\n        if callback is not None:\n            callback()\n        return _dummy_future\n\n    def finish(self):\n        if (self._expected_content_remaining is not None and\n                self._expected_content_remaining != 0):\n            self._error = httputil.HTTPOutputError(\n                \"Tried to write %d bytes less than Content-Length\" %\n                self._expected_content_remaining)\n            raise self._error\n        self._finished = True",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 92,
                            "end_lineno": 142,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "ccc89025f25079f616c1d0475a35b788e81276ae^",
    "new_commit_hash": "ccc89025f25079f616c1d0475a35b788e81276ae",
    "commit_message": "wsgi: Avoid touching the asyncio event loop at import time\n\nRewrite import_test. Its original purpose of augmenting our once-poor\ntest coverage, but it can now be useful for ensuring the absence of\nimport-time side effects.\n\nFixes #2426",
    "commit_date": "2018-07-06T15:02:55-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "ccc89025f25079f616c1d0475a35b788e81276ae",
    "test_file_codes": [
        "# flake8: noqa\nfrom __future__ import absolute_import, division, print_function\n\nimport subprocess\nimport sys\n\nfrom tornado.test.util import unittest\n\n_import_everything = b\"\"\"\n# The event loop is not fork-safe, and it's easy to initialize an asyncio.Future\n# at startup, which in turn creates the default event loop and prevents forking.\n# Explicitly disallow the default event loop so that an error will be raised\n# if something tries to touch it.\ntry:\n    import asyncio\nexcept ImportError:\n    pass\nelse:\n    asyncio.set_event_loop(None)\n\nimport tornado.auth\nimport tornado.autoreload\nimport tornado.concurrent\nimport tornado.escape\nimport tornado.gen\nimport tornado.http1connection\nimport tornado.httpclient\nimport tornado.httpserver\nimport tornado.httputil\nimport tornado.ioloop\nimport tornado.iostream\nimport tornado.locale\nimport tornado.log\nimport tornado.netutil\nimport tornado.options\nimport tornado.process\nimport tornado.simple_httpclient\nimport tornado.stack_context\nimport tornado.tcpserver\nimport tornado.tcpclient\nimport tornado.template\nimport tornado.testing\nimport tornado.util\nimport tornado.web\nimport tornado.websocket\nimport tornado.wsgi\n\ntry:\n    import pycurl\nexcept ImportError:\n    pass\nelse:\n    import tornado.curl_httpclient\n\"\"\"\n\n\nclass ImportTest(unittest.TestCase):\n    def test_import_everything(self):\n        # Test that all Tornado modules can be imported without side effects,\n        # specifically without initializing the default asyncio event loop.\n        # Since we can't tell which modules may have already beein imported\n        # in our process, do it in a subprocess for a clean slate.\n        proc = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)\n        proc.communicate(_import_everything)\n        self.assertEqual(proc.returncode, 0)\n\n    def test_import_aliases(self):\n        # Ensure we don't delete formerly-documented aliases accidentally.\n        import tornado.ioloop\n        import tornado.gen\n        import tornado.util\n        self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)\n        self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)\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 845ms\nPrepared 1 package in 988ms\nInstalled 1 package in 1ms\n + tornado==5.1b1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_ccc89025f25079f616c1d0475a35b788e81276ae)\nResolved 29 packages in 16ms\nInstalled 29 packages in 164ms\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_ccc89025f25079f616c1d0475a35b788e81276ae\n..\ncollected 2 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ImportTest::test_import_aliases\nPASSED r2e_tests.test_1::ImportTest::test_import_everything\n=================== 2 passed in 0.24s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_ccc89025f25079f616c1d0475a35b788e81276ae\n..\ncollected 2 items\n\n=================================== FAILURES ===================================\n__________ ImportTest.test_import_everything __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_ccc89025f25079f616c1d0475a35b788e81276ae/r2e_tests/test_1.py\", line 65, in test_import_everything\n    self.assertEqual(proc.returncode, 0)\nAssertionError: 1 != 0\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ImportTest::test_import_aliases\nFAILED r2e_tests.test_1::ImportTest::test_import_everything\n=================== 1 failed, 1 passed in 0.13s ===================\n",
    "old_commit_res_stderr": "Traceback (most recent call last):\n  File \"<stdin>\", line 38, in <module>\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_ccc89025f25079f616c1d0475a35b788e81276ae/tornado/wsgi.py\", line 88, in <module>\n    _dummy_future = Future()\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/events.py\", line 642, in get_event_loop\n    raise RuntimeError('There is no current event loop in thread %r.'\nRuntimeError: There is no current event loop in thread 'MainThread'.\n"
}
tornado/test/import_test.py tornado/wsgi.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Importing `tornado.wsgi` Initializes asyncio Event Loop at Import Time Causing Side Effects

**Description:**
When importing the `tornado.wsgi` module, it interacts with the asyncio event loop during the import process. This unintended side effect prevents subprocesses from running correctly, leading to failures in environments where the asyncio loop should remain untouched.

**Example Code:**
```python
import subprocess
import sys

import_code = """
import tornado.wsgi
"""

process = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)
process.communicate(import_code.encode())
print(process.returncode)
```

**Expected Behavior:**
Importing `tornado.wsgi` should not interact with or initialize the asyncio event loop at import time. This ensures that subprocesses can execute without any side effects related to the event loop.

**Actual Behavior:**
Running the above code results in the subprocess exiting with a non-zero status code, indicating a failure caused by the import-time interaction with the asyncio event loop.
[/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/wsgi.py
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""WSGI support for the Tornado web framework.

WSGI is the Python standard for web servers, and allows for interoperability
between Tornado and other Python web frameworks and servers.  This module
provides WSGI support in two ways:

* `WSGIAdapter` converts a `tornado.web.Application` to the WSGI application
  interface.  This is useful for running a Tornado app on another
  HTTP server, such as Google App Engine.  See the `WSGIAdapter` class
  documentation for limitations that apply.
* `WSGIContainer` lets you run other WSGI applications and frameworks on the
  Tornado HTTP server.  For example, with this class you can mix Django
  and Tornado handlers in a single server.
"""

from __future__ import absolute_import, division, print_function

import sys
from io import BytesIO
import tornado
import warnings

from tornado.concurrent import Future
from tornado import escape
from tornado import httputil
from tornado.log import access_log
from tornado import web
from tornado.escape import native_str
from tornado.util import unicode_type, PY3


if PY3:
    import urllib.parse as urllib_parse  # py3
else:
    import urllib as urllib_parse

# PEP 3333 specifies that WSGI on python 3 generally deals with byte strings
# that are smuggled inside objects of type unicode (via the latin1 encoding).
# These functions are like those in the tornado.escape module, but defined
# here to minimize the temptation to use them in non-wsgi contexts.
if str is unicode_type:
    def to_wsgi_str(s):
        assert isinstance(s, bytes)
        return s.decode('latin1')

    def from_wsgi_str(s):
        assert isinstance(s, str)
        return s.encode('latin1')
else:
    def to_wsgi_str(s):
        assert isinstance(s, bytes)
        return s

    def from_wsgi_str(s):
        assert isinstance(s, str)
        return s


class WSGIApplication(web.Application):
    """A WSGI equivalent of `tornado.web.Application`.

    .. deprecated:: 4.0

       Use a regular `.Application` and wrap it in `WSGIAdapter` instead.
       This class will be removed in Tornado 6.0.
    """
    def __call__(self, environ, start_response):
        return WSGIAdapter(self)(environ, start_response)


# WSGI has no facilities for flow control, so just return an already-done
# Future when the interface requires it.
_dummy_future = Future()
_dummy_future.set_result(None)


class _WSGIConnection(httputil.HTTPConnection):
    def __init__(self, method, start_response, context):
        self.method = method
        self.start_response = start_response
        self.context = context
        self._write_buffer = []
        self._finished = False
        self._expected_content_remaining = None
        self._error = None

    def set_close_callback(self, callback):
        # WSGI has no facility for detecting a closed connection mid-request,
        # so we can simply ignore the callback.
        pass

    def write_headers(self, start_line, headers, chunk=None, callback=None):
        if self.method == 'HEAD':
            self._expected_content_remaining = 0
        elif 'Content-Length' in headers:
            self._expected_content_remaining = int(headers['Content-Length'])
        else:
            self._expected_content_remaining = None
        self.start_response(
            '%s %s' % (start_line.code, start_line.reason),
            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])
        if chunk is not None:
            self.write(chunk, callback)
        elif callback is not None:
            callback()
        return _dummy_future

    def write(self, chunk, callback=None):
        if self._expected_content_remaining is not None:
            self._expected_content_remaining -= len(chunk)
            if self._expected_content_remaining < 0:
                self._error = httputil.HTTPOutputError(
                    "Tried to write more data than Content-Length")
                raise self._error
        self._write_buffer.append(chunk)
        if callback is not None:
            callback()
        return _dummy_future

    def finish(self):
        if (self._expected_content_remaining is not None and
                self._expected_content_remaining != 0):
            self._error = httputil.HTTPOutputError(
                "Tried to write %d bytes less than Content-Length" %
                self._expected_content_remaining)
            raise self._error
        self._finished = True


class _WSGIRequestContext(object):
    def __init__(self, remote_ip, protocol):
        self.remote_ip = remote_ip
        self.protocol = protocol

    def __str__(self):
        return self.remote_ip


class WSGIAdapter(object):
    """Converts a `tornado.web.Application` instance into a WSGI application.

    Example usage::

        import tornado.web
        import tornado.wsgi
        import wsgiref.simple_server

        class MainHandler(tornado.web.RequestHandler):
            def get(self):
                self.write("Hello, world")

        if __name__ == "__main__":
            application = tornado.web.Application([
                (r"/", MainHandler),
            ])
            wsgi_app = tornado.wsgi.WSGIAdapter(application)
            server = wsgiref.simple_server.make_server('', 8888, wsgi_app)
            server.serve_forever()

    See the `appengine demo
    <https://github.com/tornadoweb/tornado/tree/stable/demos/appengine>`_
    for an example of using this module to run a Tornado app on Google
    App Engine.

    In WSGI mode asynchronous methods are not supported.  This means
    that it is not possible to use `.AsyncHTTPClient`, or the
    `tornado.auth` or `tornado.websocket` modules.

    In multithreaded WSGI servers on Python 3, it may be necessary to
    permit `asyncio` to create event loops on any thread. Run the
    following at startup (typically import time for WSGI
    applications)::

        import asyncio
        from tornado.platform.asyncio import AnyThreadEventLoopPolicy
        asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())

    .. versionadded:: 4.0

    .. deprecated:: 5.1

       This class is deprecated and will be removed in Tornado 6.0.
       Use Tornado's `.HTTPServer` instead of a WSGI container.
    """
    def __init__(self, application):
        warnings.warn("WSGIAdapter is deprecated, use Tornado's HTTPServer instead",
                      DeprecationWarning)
        if isinstance(application, WSGIApplication):
            self.application = lambda request: web.Application.__call__(
                application, request)
        else:
            self.application = application

    def __call__(self, environ, start_response):
        method = environ["REQUEST_METHOD"]
        uri = urllib_parse.quote(from_wsgi_str(environ.get("SCRIPT_NAME", "")))
        uri += urllib_parse.quote(from_wsgi_str(environ.get("PATH_INFO", "")))
        if environ.get("QUERY_STRING"):
            uri += "?" + environ["QUERY_STRING"]
        headers = httputil.HTTPHeaders()
        if environ.get("CONTENT_TYPE"):
            headers["Content-Type"] = environ["CONTENT_TYPE"]
        if environ.get("CONTENT_LENGTH"):
            headers["Content-Length"] = environ["CONTENT_LENGTH"]
        for key in environ:
            if key.startswith("HTTP_"):
                headers[key[5:].replace("_", "-")] = environ[key]
        if headers.get("Content-Length"):
            body = environ["wsgi.input"].read(
                int(headers["Content-Length"]))
        else:
            body = b""
        protocol = environ["wsgi.url_scheme"]
        remote_ip = environ.get("REMOTE_ADDR", "")
        if environ.get("HTTP_HOST"):
            host = environ["HTTP_HOST"]
        else:
            host = environ["SERVER_NAME"]
        connection = _WSGIConnection(method, start_response,
                                     _WSGIRequestContext(remote_ip, protocol))
        request = httputil.HTTPServerRequest(
            method, uri, "HTTP/1.1", headers=headers, body=body,
            host=host, connection=connection)
        request._parse_body()
        self.application(request)
        if connection._error:
            raise connection._error
        if not connection._finished:
            raise Exception("request did not finish synchronously")
        return connection._write_buffer


class WSGIContainer(object):
    r"""Makes a WSGI-compatible function runnable on Tornado's HTTP server.

    .. warning::

       WSGI is a *synchronous* interface, while Tornado's concurrency model
       is based on single-threaded asynchronous execution.  This means that
       running a WSGI app with Tornado's `WSGIContainer` is *less scalable*
       than running the same app in a multi-threaded WSGI server like
       ``gunicorn`` or ``uwsgi``.  Use `WSGIContainer` only when there are
       benefits to combining Tornado and WSGI in the same process that
       outweigh the reduced scalability.

    Wrap a WSGI function in a `WSGIContainer` and pass it to `.HTTPServer` to
    run it. For example::

        def simple_app(environ, start_response):
            status = "200 OK"
            response_headers = [("Content-type", "text/plain")]
            start_response(status, response_headers)
            return ["Hello world!\n"]

        container = tornado.wsgi.WSGIContainer(simple_app)
        http_server = tornado.httpserver.HTTPServer(container)
        http_server.listen(8888)
        tornado.ioloop.IOLoop.current().start()

    This class is intended to let other frameworks (Django, web.py, etc)
    run on the Tornado HTTP server and I/O loop.

    The `tornado.web.FallbackHandler` class is often useful for mixing
    Tornado and WSGI apps in the same server.  See
    https://github.com/bdarnell/django-tornado-demo for a complete example.
    """
    def __init__(self, wsgi_application):
        self.wsgi_application = wsgi_application

    def __call__(self, request):
        data = {}
        response = []

        def start_response(status, response_headers, exc_info=None):
            data["status"] = status
            data["headers"] = response_headers
            return response.append
        app_response = self.wsgi_application(
            WSGIContainer.environ(request), start_response)
        try:
            response.extend(app_response)
            body = b"".join(response)
        finally:
            if hasattr(app_response, "close"):
                app_response.close()
        if not data:
            raise Exception("WSGI app did not call start_response")

        status_code, reason = data["status"].split(' ', 1)
        status_code = int(status_code)
        headers = data["headers"]
        header_set = set(k.lower() for (k, v) in headers)
        body = escape.utf8(body)
        if status_code != 304:
            if "content-length" not in header_set:
                headers.append(("Content-Length", str(len(body))))
            if "content-type" not in header_set:
                headers.append(("Content-Type", "text/html; charset=UTF-8"))
        if "server" not in header_set:
            headers.append(("Server", "TornadoServer/%s" % tornado.version))

        start_line = httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
        header_obj = httputil.HTTPHeaders()
        for key, value in headers:
            header_obj.add(key, value)
        request.connection.write_headers(start_line, header_obj, chunk=body)
        request.connection.finish()
        self._log(status_code, request)

    @staticmethod
    def environ(request):
        """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
        """
        hostport = request.host.split(":")
        if len(hostport) == 2:
            host = hostport[0]
            port = int(hostport[1])
        else:
            host = request.host
            port = 443 if request.protocol == "https" else 80
        environ = {
            "REQUEST_METHOD": request.method,
            "SCRIPT_NAME": "",
            "PATH_INFO": to_wsgi_str(escape.url_unescape(
                request.path, encoding=None, plus=False)),
            "QUERY_STRING": request.query,
            "REMOTE_ADDR": request.remote_ip,
            "SERVER_NAME": host,
            "SERVER_PORT": str(port),
            "SERVER_PROTOCOL": request.version,
            "wsgi.version": (1, 0),
            "wsgi.url_scheme": request.protocol,
            "wsgi.input": BytesIO(escape.utf8(request.body)),
            "wsgi.errors": sys.stderr,
            "wsgi.multithread": False,
            "wsgi.multiprocess": True,
            "wsgi.run_once": False,
        }
        if "Content-Type" in request.headers:
            environ["CONTENT_TYPE"] = request.headers.pop("Content-Type")
        if "Content-Length" in request.headers:
            environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length")
        for key, value in request.headers.items():
            environ["HTTP_" + key.replace("-", "_").upper()] = value
        return environ

    def _log(self, status_code, request):
        if status_code < 400:
            log_method = access_log.info
        elif status_code < 500:
            log_method = access_log.warning
        else:
            log_method = access_log.error
        request_time = 1000.0 * request.request_time()
        summary = request.method + " " + request.uri + " (" + \
            request.remote_ip + ")"
        log_method("%d %s %.2fms", status_code, summary, request_time)


HTTPRequest = httputil.HTTPServerRequest

```
--- 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:** Importing `tornado.wsgi` Initializes asyncio Event Loop at Import Time Causing Side Effects

**Description:**
When importing the `tornado.wsgi` module, it interacts with the asyncio event loop during the import process. This unintended side effect prevents subprocesses from running correctly, leading to failures in environments where the asyncio loop should remain untouched.

**Example Code:**
```python
import subprocess
import sys

import_code = """
import tornado.wsgi
"""

process = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)
process.communicate(import_code.encode())
print(process.returncode)
```

**Expected Behavior:**
Importing `tornado.wsgi` should not interact with or initialize the asyncio event loop at import time. This ensures that subprocesses can execute without any side effects related to the event loop.

**Actual Behavior:**
Running the above code results in the subprocess exiting with a non-zero status code, indicating a failure caused by the import-time interaction with the asyncio event loop.
[/ISSUE]
{
    "ImportTest.test_import_aliases": "PASSED",
    "ImportTest.test_import_everything": "PASSED"
}
diff --git a/tornado/wsgi.py b/tornado/wsgi.py
index beda0b9a..e1230da0 100644
--- a/tornado/wsgi.py
+++ b/tornado/wsgi.py
@@ -85,8 +85,10 @@ class WSGIApplication(web.Application):
 
 # WSGI has no facilities for flow control, so just return an already-done
 # Future when the interface requires it.
-_dummy_future = Future()
-_dummy_future.set_result(None)
+def _dummy_future():
+    f = Future()
+    f.set_result(None)
+    return f
 
 
 class _WSGIConnection(httputil.HTTPConnection):
@@ -118,7 +120,7 @@ class _WSGIConnection(httputil.HTTPConnection):
             self.write(chunk, callback)
         elif callback is not None:
             callback()
-        return _dummy_future
+        return _dummy_future()
 
     def write(self, chunk, callback=None):
         if self._expected_content_remaining is not None:
@@ -130,7 +132,7 @@ class _WSGIConnection(httputil.HTTPConnection):
         self._write_buffer.append(chunk)
         if callback is not None:
             callback()
-        return _dummy_future
+        return _dummy_future()
 
     def finish(self):
         if (self._expected_content_remaining is not None and
 

{"tornado/wsgi.py": "#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"WSGI support for the Tornado web framework.\n\nWSGI is the Python standard for web servers, and allows for interoperability\nbetween Tornado and other Python web frameworks and servers.  This module\nprovides WSGI support in two ways:\n\n* `WSGIAdapter` converts a `tornado.web.Application` to the WSGI application\n  interface.  This is useful for running a Tornado app on another\n  HTTP server, such as Google App Engine.  See the `WSGIAdapter` class\n  documentation for limitations that apply.\n* `WSGIContainer` lets you run other WSGI applications and frameworks on the\n  Tornado HTTP server.  For example, with this class you can mix Django\n  and Tornado handlers in a single server.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport sys\nfrom io import BytesIO\nimport tornado\nimport warnings\n\nfrom tornado.concurrent import Future\nfrom tornado import escape\nfrom tornado import httputil\nfrom tornado.log import access_log\nfrom tornado import web\nfrom tornado.escape import native_str\nfrom tornado.util import unicode_type, PY3\n\n\nif PY3:\n    import urllib.parse as urllib_parse  # py3\nelse:\n    import urllib as urllib_parse\n\n# PEP 3333 specifies that WSGI on python 3 generally deals with byte strings\n# that are smuggled inside objects of type unicode (via the latin1 encoding).\n# These functions are like those in the tornado.escape module, but defined\n# here to minimize the temptation to use them in non-wsgi contexts.\nif str is unicode_type:\n    def to_wsgi_str(s):\n        assert isinstance(s, bytes)\n        return s.decode('latin1')\n\n    def from_wsgi_str(s):\n        assert isinstance(s, str)\n        return s.encode('latin1')\nelse:\n    def to_wsgi_str(s):\n        assert isinstance(s, bytes)\n        return s\n\n    def from_wsgi_str(s):\n        assert isinstance(s, str)\n        return s\n\n\nclass WSGIApplication(web.Application):\n    \"\"\"A WSGI equivalent of `tornado.web.Application`.\n\n    .. deprecated:: 4.0\n\n       Use a regular `.Application` and wrap it in `WSGIAdapter` instead.\n       This class will be removed in Tornado 6.0.\n    \"\"\"\n    def __call__(self, environ, start_response):\n        return WSGIAdapter(self)(environ, start_response)\n\n\n# WSGI has no facilities for flow control, so just return an already-done\n# Future when the interface requires it.\n_dummy_future = Future()\n_dummy_future.set_result(None)\n\n\nclass _WSGIConnection(httputil.HTTPConnection):\n    def __init__(self, method, start_response, context):\n        self.method = method\n        self.start_response = start_response\n        self.context = context\n        self._write_buffer = []\n        self._finished = False\n        self._expected_content_remaining = None\n        self._error = None\n\n    def set_close_callback(self, callback):\n        # WSGI has no facility for detecting a closed connection mid-request,\n        # so we can simply ignore the callback.\n        pass\n\n    def write_headers(self, start_line, headers, chunk=None, callback=None):\n        if self.method == 'HEAD':\n            self._expected_content_remaining = 0\n        elif 'Content-Length' in headers:\n            self._expected_content_remaining = int(headers['Content-Length'])\n        else:\n            self._expected_content_remaining = None\n        self.start_response(\n            '%s %s' % (start_line.code, start_line.reason),\n            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])\n        if chunk is not None:\n            self.write(chunk, callback)\n        elif callback is not None:\n            callback()\n        return _dummy_future\n\n    def write(self, chunk, callback=None):\n        if self._expected_content_remaining is not None:\n            self._expected_content_remaining -= len(chunk)\n            if self._expected_content_remaining < 0:\n                self._error = httputil.HTTPOutputError(\n                    \"Tried to write more data than Content-Length\")\n                raise self._error\n        self._write_buffer.append(chunk)\n        if callback is not None:\n            callback()\n        return _dummy_future\n\n    def finish(self):\n        if (self._expected_content_remaining is not None and\n                self._expected_content_remaining != 0):\n            self._error = httputil.HTTPOutputError(\n                \"Tried to write %d bytes less than Content-Length\" %\n                self._expected_content_remaining)\n            raise self._error\n        self._finished = True\n\n\nclass _WSGIRequestContext(object):\n    def __init__(self, remote_ip, protocol):\n        self.remote_ip = remote_ip\n        self.protocol = protocol\n\n    def __str__(self):\n        return self.remote_ip\n\n\nclass WSGIAdapter(object):\n    \"\"\"Converts a `tornado.web.Application` instance into a WSGI application.\n\n    Example usage::\n\n        import tornado.web\n        import tornado.wsgi\n        import wsgiref.simple_server\n\n        class MainHandler(tornado.web.RequestHandler):\n            def get(self):\n                self.write(\"Hello, world\")\n\n        if __name__ == \"__main__\":\n            application = tornado.web.Application([\n                (r\"/\", MainHandler),\n            ])\n            wsgi_app = tornado.wsgi.WSGIAdapter(application)\n            server = wsgiref.simple_server.make_server('', 8888, wsgi_app)\n            server.serve_forever()\n\n    See the `appengine demo\n    <https://github.com/tornadoweb/tornado/tree/stable/demos/appengine>`_\n    for an example of using this module to run a Tornado app on Google\n    App Engine.\n\n    In WSGI mode asynchronous methods are not supported.  This means\n    that it is not possible to use `.AsyncHTTPClient`, or the\n    `tornado.auth` or `tornado.websocket` modules.\n\n    In multithreaded WSGI servers on Python 3, it may be necessary to\n    permit `asyncio` to create event loops on any thread. Run the\n    following at startup (typically import time for WSGI\n    applications)::\n\n        import asyncio\n        from tornado.platform.asyncio import AnyThreadEventLoopPolicy\n        asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())\n\n    .. versionadded:: 4.0\n\n    .. deprecated:: 5.1\n\n       This class is deprecated and will be removed in Tornado 6.0.\n       Use Tornado's `.HTTPServer` instead of a WSGI container.\n    \"\"\"\n    def __init__(self, application):\n        warnings.warn(\"WSGIAdapter is deprecated, use Tornado's HTTPServer instead\",\n                      DeprecationWarning)\n        if isinstance(application, WSGIApplication):\n            self.application = lambda request: web.Application.__call__(\n                application, request)\n        else:\n            self.application = application\n\n    def __call__(self, environ, start_response):\n        method = environ[\"REQUEST_METHOD\"]\n        uri = urllib_parse.quote(from_wsgi_str(environ.get(\"SCRIPT_NAME\", \"\")))\n        uri += urllib_parse.quote(from_wsgi_str(environ.get(\"PATH_INFO\", \"\")))\n        if environ.get(\"QUERY_STRING\"):\n            uri += \"?\" + environ[\"QUERY_STRING\"]\n        headers = httputil.HTTPHeaders()\n        if environ.get(\"CONTENT_TYPE\"):\n            headers[\"Content-Type\"] = environ[\"CONTENT_TYPE\"]\n        if environ.get(\"CONTENT_LENGTH\"):\n            headers[\"Content-Length\"] = environ[\"CONTENT_LENGTH\"]\n        for key in environ:\n            if key.startswith(\"HTTP_\"):\n                headers[key[5:].replace(\"_\", \"-\")] = environ[key]\n        if headers.get(\"Content-Length\"):\n            body = environ[\"wsgi.input\"].read(\n                int(headers[\"Content-Length\"]))\n        else:\n            body = b\"\"\n        protocol = environ[\"wsgi.url_scheme\"]\n        remote_ip = environ.get(\"REMOTE_ADDR\", \"\")\n        if environ.get(\"HTTP_HOST\"):\n            host = environ[\"HTTP_HOST\"]\n        else:\n            host = environ[\"SERVER_NAME\"]\n        connection = _WSGIConnection(method, start_response,\n                                     _WSGIRequestContext(remote_ip, protocol))\n        request = httputil.HTTPServerRequest(\n            method, uri, \"HTTP/1.1\", headers=headers, body=body,\n            host=host, connection=connection)\n        request._parse_body()\n        self.application(request)\n        if connection._error:\n            raise connection._error\n        if not connection._finished:\n            raise Exception(\"request did not finish synchronously\")\n        return connection._write_buffer\n\n\nclass WSGIContainer(object):\n    r\"\"\"Makes a WSGI-compatible function runnable on Tornado's HTTP server.\n\n    .. warning::\n\n       WSGI is a *synchronous* interface, while Tornado's concurrency model\n       is based on single-threaded asynchronous execution.  This means that\n       running a WSGI app with Tornado's `WSGIContainer` is *less scalable*\n       than running the same app in a multi-threaded WSGI server like\n       ``gunicorn`` or ``uwsgi``.  Use `WSGIContainer` only when there are\n       benefits to combining Tornado and WSGI in the same process that\n       outweigh the reduced scalability.\n\n    Wrap a WSGI function in a `WSGIContainer` and pass it to `.HTTPServer` to\n    run it. For example::\n\n        def simple_app(environ, start_response):\n            status = \"200 OK\"\n            response_headers = [(\"Content-type\", \"text/plain\")]\n            start_response(status, response_headers)\n            return [\"Hello world!\\n\"]\n\n        container = tornado.wsgi.WSGIContainer(simple_app)\n        http_server = tornado.httpserver.HTTPServer(container)\n        http_server.listen(8888)\n        tornado.ioloop.IOLoop.current().start()\n\n    This class is intended to let other frameworks (Django, web.py, etc)\n    run on the Tornado HTTP server and I/O loop.\n\n    The `tornado.web.FallbackHandler` class is often useful for mixing\n    Tornado and WSGI apps in the same server.  See\n    https://github.com/bdarnell/django-tornado-demo for a complete example.\n    \"\"\"\n    def __init__(self, wsgi_application):\n        self.wsgi_application = wsgi_application\n\n    def __call__(self, request):\n        data = {}\n        response = []\n\n        def start_response(status, response_headers, exc_info=None):\n            data[\"status\"] = status\n            data[\"headers\"] = response_headers\n            return response.append\n        app_response = self.wsgi_application(\n            WSGIContainer.environ(request), start_response)\n        try:\n            response.extend(app_response)\n            body = b\"\".join(response)\n        finally:\n            if hasattr(app_response, \"close\"):\n                app_response.close()\n        if not data:\n            raise Exception(\"WSGI app did not call start_response\")\n\n        status_code, reason = data[\"status\"].split(' ', 1)\n        status_code = int(status_code)\n        headers = data[\"headers\"]\n        header_set = set(k.lower() for (k, v) in headers)\n        body = escape.utf8(body)\n        if status_code != 304:\n            if \"content-length\" not in header_set:\n                headers.append((\"Content-Length\", str(len(body))))\n            if \"content-type\" not in header_set:\n                headers.append((\"Content-Type\", \"text/html; charset=UTF-8\"))\n        if \"server\" not in header_set:\n            headers.append((\"Server\", \"TornadoServer/%s\" % tornado.version))\n\n        start_line = httputil.ResponseStartLine(\"HTTP/1.1\", status_code, reason)\n        header_obj = httputil.HTTPHeaders()\n        for key, value in headers:\n            header_obj.add(key, value)\n        request.connection.write_headers(start_line, header_obj, chunk=body)\n        request.connection.finish()\n        self._log(status_code, request)\n\n    @staticmethod\n    def environ(request):\n        \"\"\"Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.\n        \"\"\"\n        hostport = request.host.split(\":\")\n        if len(hostport) == 2:\n            host = hostport[0]\n            port = int(hostport[1])\n        else:\n            host = request.host\n            port = 443 if request.protocol == \"https\" else 80\n        environ = {\n            \"REQUEST_METHOD\": request.method,\n            \"SCRIPT_NAME\": \"\",\n            \"PATH_INFO\": to_wsgi_str(escape.url_unescape(\n                request.path, encoding=None, plus=False)),\n            \"QUERY_STRING\": request.query,\n            \"REMOTE_ADDR\": request.remote_ip,\n            \"SERVER_NAME\": host,\n            \"SERVER_PORT\": str(port),\n            \"SERVER_PROTOCOL\": request.version,\n            \"wsgi.version\": (1, 0),\n            \"wsgi.url_scheme\": request.protocol,\n            \"wsgi.input\": BytesIO(escape.utf8(request.body)),\n            \"wsgi.errors\": sys.stderr,\n            \"wsgi.multithread\": False,\n            \"wsgi.multiprocess\": True,\n            \"wsgi.run_once\": False,\n        }\n        if \"Content-Type\" in request.headers:\n            environ[\"CONTENT_TYPE\"] = request.headers.pop(\"Content-Type\")\n        if \"Content-Length\" in request.headers:\n            environ[\"CONTENT_LENGTH\"] = request.headers.pop(\"Content-Length\")\n        for key, value in request.headers.items():\n            environ[\"HTTP_\" + key.replace(\"-\", \"_\").upper()] = value\n        return environ\n\n    def _log(self, status_code, request):\n        if status_code < 400:\n            log_method = access_log.info\n        elif status_code < 500:\n            log_method = access_log.warning\n        else:\n            log_method = access_log.error\n        request_time = 1000.0 * request.request_time()\n        summary = request.method + \" \" + request.uri + \" (\" + \\\n            request.remote_ip + \")\"\n        log_method(\"%d %s %.2fms\", status_code, summary, request_time)\n\n\nHTTPRequest = httputil.HTTPServerRequest\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:** Importing `tornado.wsgi` Initializes asyncio Event Loop at Import Time Causing Side Effects

**Description:**
When importing the `tornado.wsgi` module, it interacts with the asyncio event loop during the import process. This unintended side effect prevents subprocesses from running correctly, leading to failures in environments where the asyncio loop should remain untouched.

**Example Code:**
```python
import subprocess
import sys

import_code = """
import tornado.wsgi
"""

process = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)
process.communicate(import_code.encode())
print(process.returncode)
```

**Expected Behavior:**
Importing `tornado.wsgi` should not interact with or initialize the asyncio event loop at import time. This ensures that subprocesses can execute without any side effects related to the event loop.

**Actual Behavior:**
Running the above code results in the subprocess exiting with a non-zero status code, indicating a failure caused by the import-time interaction with the asyncio event loop.
[/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/wsgi.py
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""WSGI support for the Tornado web framework.

WSGI is the Python standard for web servers, and allows for interoperability
between Tornado and other Python web frameworks and servers.  This module
provides WSGI support in two ways:

* `WSGIAdapter` converts a `tornado.web.Application` to the WSGI application
  interface.  This is useful for running a Tornado app on another
  HTTP server, such as Google App Engine.  See the `WSGIAdapter` class
  documentation for limitations that apply.
* `WSGIContainer` lets you run other WSGI applications and frameworks on the
  Tornado HTTP server.  For example, with this class you can mix Django
  and Tornado handlers in a single server.
"""

from __future__ import absolute_import, division, print_function

import sys
from io import BytesIO
import tornado
import warnings

from tornado.concurrent import Future
from tornado import escape
from tornado import httputil
from tornado.log import access_log
from tornado import web
from tornado.escape import native_str
from tornado.util import unicode_type, PY3


if PY3:
    import urllib.parse as urllib_parse  # py3
else:
    import urllib as urllib_parse

# PEP 3333 specifies that WSGI on python 3 generally deals with byte strings
# that are smuggled inside objects of type unicode (via the latin1 encoding).
# These functions are like those in the tornado.escape module, but defined
# here to minimize the temptation to use them in non-wsgi contexts.
if str is unicode_type:
    def to_wsgi_str(s):
        assert isinstance(s, bytes)
        return s.decode('latin1')

    def from_wsgi_str(s):
        assert isinstance(s, str)
        return s.encode('latin1')
else:
    def to_wsgi_str(s):
        assert isinstance(s, bytes)
        return s

    def from_wsgi_str(s):
        assert isinstance(s, str)
        return s


class WSGIApplication(web.Application):
    """A WSGI equivalent of `tornado.web.Application`.

    .. deprecated:: 4.0

       Use a regular `.Application` and wrap it in `WSGIAdapter` instead.
       This class will be removed in Tornado 6.0.
    """
    def __call__(self, environ, start_response):
        return WSGIAdapter(self)(environ, start_response)


# WSGI has no facilities for flow control, so just return an already-done
# Future when the interface requires it.
_dummy_future = Future()
_dummy_future.set_result(None)


class _WSGIConnection(httputil.HTTPConnection):
    def __init__(self, method, start_response, context):
        self.method = method
        self.start_response = start_response
        self.context = context
        self._write_buffer = []
        self._finished = False
        self._expected_content_remaining = None
        self._error = None

    def set_close_callback(self, callback):
        # WSGI has no facility for detecting a closed connection mid-request,
        # so we can simply ignore the callback.
        pass

    def write_headers(self, start_line, headers, chunk=None, callback=None):
        if self.method == 'HEAD':
            self._expected_content_remaining = 0
        elif 'Content-Length' in headers:
            self._expected_content_remaining = int(headers['Content-Length'])
        else:
            self._expected_content_remaining = None
        self.start_response(
            '%s %s' % (start_line.code, start_line.reason),
            [(native_str(k), native_str(v)) for (k, v) in headers.get_all()])
        if chunk is not None:
            self.write(chunk, callback)
        elif callback is not None:
            callback()
        return _dummy_future

    def write(self, chunk, callback=None):
        if self._expected_content_remaining is not None:
            self._expected_content_remaining -= len(chunk)
            if self._expected_content_remaining < 0:
                self._error = httputil.HTTPOutputError(
                    "Tried to write more data than Content-Length")
                raise self._error
        self._write_buffer.append(chunk)
        if callback is not None:
            callback()
        return _dummy_future

    def finish(self):
        if (self._expected_content_remaining is not None and
                self._expected_content_remaining != 0):
            self._error = httputil.HTTPOutputError(
                "Tried to write %d bytes less than Content-Length" %
                self._expected_content_remaining)
            raise self._error
        self._finished = True


class _WSGIRequestContext(object):
    def __init__(self, remote_ip, protocol):
        self.remote_ip = remote_ip
        self.protocol = protocol

    def __str__(self):
        return self.remote_ip


class WSGIAdapter(object):
    """Converts a `tornado.web.Application` instance into a WSGI application.

    Example usage::

        import tornado.web
        import tornado.wsgi
        import wsgiref.simple_server

        class MainHandler(tornado.web.RequestHandler):
            def get(self):
                self.write("Hello, world")

        if __name__ == "__main__":
            application = tornado.web.Application([
                (r"/", MainHandler),
            ])
            wsgi_app = tornado.wsgi.WSGIAdapter(application)
            server = wsgiref.simple_server.make_server('', 8888, wsgi_app)
            server.serve_forever()

    See the `appengine demo
    <https://github.com/tornadoweb/tornado/tree/stable/demos/appengine>`_
    for an example of using this module to run a Tornado app on Google
    App Engine.

    In WSGI mode asynchronous methods are not supported.  This means
    that it is not possible to use `.AsyncHTTPClient`, or the
    `tornado.auth` or `tornado.websocket` modules.

    In multithreaded WSGI servers on Python 3, it may be necessary to
    permit `asyncio` to create event loops on any thread. Run the
    following at startup (typically import time for WSGI
    applications)::

        import asyncio
        from tornado.platform.asyncio import AnyThreadEventLoopPolicy
        asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())

    .. versionadded:: 4.0

    .. deprecated:: 5.1

       This class is deprecated and will be removed in Tornado 6.0.
       Use Tornado's `.HTTPServer` instead of a WSGI container.
    """
    def __init__(self, application):
        warnings.warn("WSGIAdapter is deprecated, use Tornado's HTTPServer instead",
                      DeprecationWarning)
        if isinstance(application, WSGIApplication):
            self.application = lambda request: web.Application.__call__(
                application, request)
        else:
            self.application = application

    def __call__(self, environ, start_response):
        method = environ["REQUEST_METHOD"]
        uri = urllib_parse.quote(from_wsgi_str(environ.get("SCRIPT_NAME", "")))
        uri += urllib_parse.quote(from_wsgi_str(environ.get("PATH_INFO", "")))
        if environ.get("QUERY_STRING"):
            uri += "?" + environ["QUERY_STRING"]
        headers = httputil.HTTPHeaders()
        if environ.get("CONTENT_TYPE"):
            headers["Content-Type"] = environ["CONTENT_TYPE"]
        if environ.get("CONTENT_LENGTH"):
            headers["Content-Length"] = environ["CONTENT_LENGTH"]
        for key in environ:
            if key.startswith("HTTP_"):
                headers[key[5:].replace("_", "-")] = environ[key]
        if headers.get("Content-Length"):
            body = environ["wsgi.input"].read(
                int(headers["Content-Length"]))
        else:
            body = b""
        protocol = environ["wsgi.url_scheme"]
        remote_ip = environ.get("REMOTE_ADDR", "")
        if environ.get("HTTP_HOST"):
            host = environ["HTTP_HOST"]
        else:
            host = environ["SERVER_NAME"]
        connection = _WSGIConnection(method, start_response,
                                     _WSGIRequestContext(remote_ip, protocol))
        request = httputil.HTTPServerRequest(
            method, uri, "HTTP/1.1", headers=headers, body=body,
            host=host, connection=connection)
        request._parse_body()
        self.application(request)
        if connection._error:
            raise connection._error
        if not connection._finished:
            raise Exception("request did not finish synchronously")
        return connection._write_buffer


class WSGIContainer(object):
    r"""Makes a WSGI-compatible function runnable on Tornado's HTTP server.

    .. warning::

       WSGI is a *synchronous* interface, while Tornado's concurrency model
       is based on single-threaded asynchronous execution.  This means that
       running a WSGI app with Tornado's `WSGIContainer` is *less scalable*
       than running the same app in a multi-threaded WSGI server like
       ``gunicorn`` or ``uwsgi``.  Use `WSGIContainer` only when there are
       benefits to combining Tornado and WSGI in the same process that
       outweigh the reduced scalability.

    Wrap a WSGI function in a `WSGIContainer` and pass it to `.HTTPServer` to
    run it. For example::

        def simple_app(environ, start_response):
            status = "200 OK"
            response_headers = [("Content-type", "text/plain")]
            start_response(status, response_headers)
            return ["Hello world!\n"]

        container = tornado.wsgi.WSGIContainer(simple_app)
        http_server = tornado.httpserver.HTTPServer(container)
        http_server.listen(8888)
        tornado.ioloop.IOLoop.current().start()

    This class is intended to let other frameworks (Django, web.py, etc)
    run on the Tornado HTTP server and I/O loop.

    The `tornado.web.FallbackHandler` class is often useful for mixing
    Tornado and WSGI apps in the same server.  See
    https://github.com/bdarnell/django-tornado-demo for a complete example.
    """
    def __init__(self, wsgi_application):
        self.wsgi_application = wsgi_application

    def __call__(self, request):
        data = {}
        response = []

        def start_response(status, response_headers, exc_info=None):
            data["status"] = status
            data["headers"] = response_headers
            return response.append
        app_response = self.wsgi_application(
            WSGIContainer.environ(request), start_response)
        try:
            response.extend(app_response)
            body = b"".join(response)
        finally:
            if hasattr(app_response, "close"):
                app_response.close()
        if not data:
            raise Exception("WSGI app did not call start_response")

        status_code, reason = data["status"].split(' ', 1)
        status_code = int(status_code)
        headers = data["headers"]
        header_set = set(k.lower() for (k, v) in headers)
        body = escape.utf8(body)
        if status_code != 304:
            if "content-length" not in header_set:
                headers.append(("Content-Length", str(len(body))))
            if "content-type" not in header_set:
                headers.append(("Content-Type", "text/html; charset=UTF-8"))
        if "server" not in header_set:
            headers.append(("Server", "TornadoServer/%s" % tornado.version))

        start_line = httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
        header_obj = httputil.HTTPHeaders()
        for key, value in headers:
            header_obj.add(key, value)
        request.connection.write_headers(start_line, header_obj, chunk=body)
        request.connection.finish()
        self._log(status_code, request)

    @staticmethod
    def environ(request):
        """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
        """
        hostport = request.host.split(":")
        if len(hostport) == 2:
            host = hostport[0]
            port = int(hostport[1])
        else:
            host = request.host
            port = 443 if request.protocol == "https" else 80
        environ = {
            "REQUEST_METHOD": request.method,
            "SCRIPT_NAME": "",
            "PATH_INFO": to_wsgi_str(escape.url_unescape(
                request.path, encoding=None, plus=False)),
            "QUERY_STRING": request.query,
            "REMOTE_ADDR": request.remote_ip,
            "SERVER_NAME": host,
            "SERVER_PORT": str(port),
            "SERVER_PROTOCOL": request.version,
            "wsgi.version": (1, 0),
            "wsgi.url_scheme": request.protocol,
            "wsgi.input": BytesIO(escape.utf8(request.body)),
            "wsgi.errors": sys.stderr,
            "wsgi.multithread": False,
            "wsgi.multiprocess": True,
            "wsgi.run_once": False,
        }
        if "Content-Type" in request.headers:
            environ["CONTENT_TYPE"] = request.headers.pop("Content-Type")
        if "Content-Length" in request.headers:
            environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length")
        for key, value in request.headers.items():
            environ["HTTP_" + key.replace("-", "_").upper()] = value
        return environ

    def _log(self, status_code, request):
        if status_code < 400:
            log_method = access_log.info
        elif status_code < 500:
            log_method = access_log.warning
        else:
            log_method = access_log.error
        request_time = 1000.0 * request.request_time()
        summary = request.method + " " + request.uri + " (" + \
            request.remote_ip + ")"
        log_method("%d %s %.2fms", status_code, summary, request_time)


HTTPRequest = httputil.HTTPServerRequest

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