{
    "file_diffs": [
        {
            "old_file_content": "#!/usr/bin/env python\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nfrom tornado.escape import utf8, _unicode, native_str\nfrom tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy\nfrom tornado.httputil import HTTPHeaders\nfrom tornado.iostream import IOStream, SSLIOStream\nfrom tornado.netutil import Resolver, OverrideResolver\nfrom tornado.log import gen_log\nfrom tornado import stack_context\nfrom tornado.util import GzipDecompressor\n\nimport base64\nimport collections\nimport copy\nimport functools\nimport os.path\nimport re\nimport socket\nimport ssl\nimport sys\n\ntry:\n    from io import BytesIO  # python 3\nexcept ImportError:\n    from cStringIO import StringIO as BytesIO  # python 2\n\ntry:\n    import urlparse  # py2\nexcept ImportError:\n    import urllib.parse as urlparse  # py3\n\n_DEFAULT_CA_CERTS = os.path.dirname(__file__) + '/ca-certificates.crt'\n\n\nclass SimpleAsyncHTTPClient(AsyncHTTPClient):\n    \"\"\"Non-blocking HTTP client with no external dependencies.\n\n    This class implements an HTTP 1.1 client on top of Tornado's IOStreams.\n    It does not currently implement all applicable parts of the HTTP\n    specification, but it does enough to work with major web service APIs.\n\n    Some features found in the curl-based AsyncHTTPClient are not yet\n    supported.  In particular, proxies are not supported, connections\n    are not reused, and callers cannot select the network interface to be\n    used.\n    \"\"\"\n    def initialize(self, io_loop, max_clients=10,\n                   hostname_mapping=None, max_buffer_size=104857600,\n                   resolver=None, defaults=None):\n        \"\"\"Creates a AsyncHTTPClient.\n\n        Only a single AsyncHTTPClient instance exists per IOLoop\n        in order to provide limitations on the number of pending connections.\n        force_instance=True may be used to suppress this behavior.\n\n        max_clients is the number of concurrent requests that can be\n        in progress.  Note that this arguments are only used when the\n        client is first created, and will be ignored when an existing\n        client is reused.\n\n        hostname_mapping is a dictionary mapping hostnames to IP addresses.\n        It can be used to make local DNS changes when modifying system-wide\n        settings like /etc/hosts is not possible or desirable (e.g. in\n        unittests).\n\n        max_buffer_size is the number of bytes that can be read by IOStream. It\n        defaults to 100mb.\n        \"\"\"\n        super(SimpleAsyncHTTPClient, self).initialize(io_loop,\n                                                      defaults=defaults)\n        self.max_clients = max_clients\n        self.queue = collections.deque()\n        self.active = {}\n        self.waiting = {}\n        self.max_buffer_size = max_buffer_size\n        if resolver:\n            self.resolver = resolver\n            self.own_resolver = False\n        else:\n            self.resolver = Resolver(io_loop=io_loop)\n            self.own_resolver = True\n        if hostname_mapping is not None:\n            self.resolver = OverrideResolver(resolver=self.resolver,\n                                             mapping=hostname_mapping)\n\n    def close(self):\n        super(SimpleAsyncHTTPClient, self).close()\n        if self.own_resolver:\n            self.resolver.close()\n\n    def fetch_impl(self, request, callback):\n        key = object()\n        self.queue.append((key, request, callback))\n        if not len(self.active) < self.max_clients:\n            timeout_handle = self.io_loop.add_timeout(\n                self.io_loop.time() + min(request.connect_timeout,\n                                          request.request_timeout),\n                functools.partial(self._on_timeout, key))\n        else:\n            timeout_handle = None\n        self.waiting[key] = (request, callback, timeout_handle)\n        self._process_queue()\n        if self.queue:\n            gen_log.debug(\"max_clients limit reached, request queued. \"\n                          \"%d active, %d queued requests.\" % (\n                              len(self.active), len(self.queue)))\n\n    def _process_queue(self):\n        with stack_context.NullContext():\n            while self.queue and len(self.active) < self.max_clients:\n                key, request, callback = self.queue.popleft()\n                if key not in self.waiting:\n                    continue\n                self._remove_timeout(key)\n                self.active[key] = (request, callback)\n                release_callback = functools.partial(self._release_fetch, key)\n                self._handle_request(request, release_callback, callback)\n\n    def _handle_request(self, request, release_callback, final_callback):\n        _HTTPConnection(self.io_loop, self, request, release_callback,\n                        final_callback, self.max_buffer_size, self.resolver)\n\n    def _release_fetch(self, key):\n        del self.active[key]\n        self._process_queue()\n\n    def _remove_timeout(self, key):\n        if key in self.waiting:\n            request, callback, timeout_handle = self.waiting[key]\n            if timeout_handle is not None:\n                self.io_loop.remove_timeout(timeout_handle)\n            del self.waiting[key]\n\n    def _on_timeout(self, key):\n        request, callback, timeout_handle = self.waiting[key]\n        self.queue.remove((key, request, callback))\n        timeout_response = HTTPResponse(\n            request, 599, error=HTTPError(599, \"Timeout\"),\n            request_time=self.io_loop.time() - request.start_time)\n        self.io_loop.add_callback(callback, timeout_response)\n        del self.waiting[key]\n\n\nclass _HTTPConnection(object):\n    _SUPPORTED_METHODS = set([\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"])\n\n    def __init__(self, io_loop, client, request, release_callback,\n                 final_callback, max_buffer_size, resolver):\n        self.start_time = io_loop.time()\n        self.io_loop = io_loop\n        self.client = client\n        self.request = request\n        self.release_callback = release_callback\n        self.final_callback = final_callback\n        self.max_buffer_size = max_buffer_size\n        self.resolver = resolver\n        self.code = None\n        self.headers = None\n        self.chunks = None\n        self._decompressor = None\n        # Timeout handle returned by IOLoop.add_timeout\n        self._timeout = None\n        with stack_context.ExceptionStackContext(self._handle_exception):\n            self.parsed = urlparse.urlsplit(_unicode(self.request.url))\n            if self.parsed.scheme not in (\"http\", \"https\"):\n                raise ValueError(\"Unsupported url scheme: %s\" %\n                                 self.request.url)\n            # urlsplit results have hostname and port results, but they\n            # didn't support ipv6 literals until python 2.7.\n            netloc = self.parsed.netloc\n            if \"@\" in netloc:\n                userpass, _, netloc = netloc.rpartition(\"@\")\n            match = re.match(r'^(.+):(\\d+)$', netloc)\n            if match:\n                host = match.group(1)\n                port = int(match.group(2))\n            else:\n                host = netloc\n                port = 443 if self.parsed.scheme == \"https\" else 80\n            if re.match(r'^\\[.*\\]$', host):\n                # raw ipv6 addresses in urls are enclosed in brackets\n                host = host[1:-1]\n            self.parsed_hostname = host  # save final host for _on_connect\n\n            if request.allow_ipv6:\n                af = socket.AF_UNSPEC\n            else:\n                # We only try the first IP we get from getaddrinfo,\n                # so restrict to ipv4 by default.\n                af = socket.AF_INET\n\n            timeout = min(self.request.connect_timeout, self.request.request_timeout)\n            if timeout:\n                self._timeout = self.io_loop.add_timeout(\n                    self.start_time + timeout,\n                    stack_context.wrap(self._on_timeout))\n            self.resolver.resolve(host, port, af, callback=self._on_resolve)\n\n    def _on_resolve(self, addrinfo):\n        if self.final_callback is None:\n            # final_callback is cleared if we've hit our timeout\n            return\n        self.stream = self._create_stream(addrinfo)\n        self.stream.set_close_callback(self._on_close)\n        # ipv6 addresses are broken (in self.parsed.hostname) until\n        # 2.7, here is correctly parsed value calculated in __init__\n        sockaddr = addrinfo[0][1]\n        self.stream.connect(sockaddr, self._on_connect,\n                            server_hostname=self.parsed_hostname)\n\n    def _create_stream(self, addrinfo):\n        af = addrinfo[0][0]\n        if self.parsed.scheme == \"https\":\n            ssl_options = {}\n            if self.request.validate_cert:\n                ssl_options[\"cert_reqs\"] = ssl.CERT_REQUIRED\n            if self.request.ca_certs is not None:\n                ssl_options[\"ca_certs\"] = self.request.ca_certs\n            else:\n                ssl_options[\"ca_certs\"] = _DEFAULT_CA_CERTS\n            if self.request.client_key is not None:\n                ssl_options[\"keyfile\"] = self.request.client_key\n            if self.request.client_cert is not None:\n                ssl_options[\"certfile\"] = self.request.client_cert\n\n            # SSL interoperability is tricky.  We want to disable\n            # SSLv2 for security reasons; it wasn't disabled by default\n            # until openssl 1.0.  The best way to do this is to use\n            # the SSL_OP_NO_SSLv2, but that wasn't exposed to python\n            # until 3.2.  Python 2.7 adds the ciphers argument, which\n            # can also be used to disable SSLv2.  As a last resort\n            # on python 2.6, we set ssl_version to TLSv1.  This is\n            # more narrow than we'd like since it also breaks\n            # compatibility with servers configured for SSLv3 only,\n            # but nearly all servers support both SSLv3 and TLSv1:\n            # http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html\n            if sys.version_info >= (2, 7):\n                # In addition to disabling SSLv2, we also exclude certain\n                # classes of insecure ciphers.\n                ssl_options[\"ciphers\"] = \"DEFAULT:!SSLv2:!EXPORT:!DES\"\n            else:\n                # This is really only necessary for pre-1.0 versions\n                # of openssl, but python 2.6 doesn't expose version\n                # information.\n                ssl_options[\"ssl_version\"] = ssl.PROTOCOL_TLSv1\n\n            return SSLIOStream(socket.socket(af),\n                               io_loop=self.io_loop,\n                               ssl_options=ssl_options,\n                               max_buffer_size=self.max_buffer_size)\n        else:\n            return IOStream(socket.socket(af),\n                            io_loop=self.io_loop,\n                            max_buffer_size=self.max_buffer_size)\n\n    def _on_timeout(self):\n        self._timeout = None\n        if self.final_callback is not None:\n            raise HTTPError(599, \"Timeout\")\n\n    def _remove_timeout(self):\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def _on_connect(self):\n        self._remove_timeout()\n        if self.final_callback is None:\n            return\n        if self.request.request_timeout:\n            self._timeout = self.io_loop.add_timeout(\n                self.start_time + self.request.request_timeout,\n                stack_context.wrap(self._on_timeout))\n        if (self.request.method not in self._SUPPORTED_METHODS and\n                not self.request.allow_nonstandard_methods):\n            raise KeyError(\"unknown method %s\" % self.request.method)\n        for key in ('network_interface',\n                    'proxy_host', 'proxy_port',\n                    'proxy_username', 'proxy_password'):\n            if getattr(self.request, key, None):\n                raise NotImplementedError('%s not supported' % key)\n        if \"Connection\" not in self.request.headers:\n            self.request.headers[\"Connection\"] = \"close\"\n        if \"Host\" not in self.request.headers:\n            if '@' in self.parsed.netloc:\n                self.request.headers[\"Host\"] = self.parsed.netloc.rpartition('@')[-1]\n            else:\n                self.request.headers[\"Host\"] = self.parsed.netloc\n        username, password = None, None\n        if self.parsed.username is not None:\n            username, password = self.parsed.username, self.parsed.password\n        elif self.request.auth_username is not None:\n            username = self.request.auth_username\n            password = self.request.auth_password or ''\n        if username is not None:\n            if self.request.auth_mode not in (None, \"basic\"):\n                raise ValueError(\"unsupported auth_mode %s\",\n                                 self.request.auth_mode)\n            auth = utf8(username) + b\":\" + utf8(password)\n            self.request.headers[\"Authorization\"] = (b\"Basic \" +\n                                                     base64.b64encode(auth))\n        if self.request.user_agent:\n            self.request.headers[\"User-Agent\"] = self.request.user_agent\n        if not self.request.allow_nonstandard_methods:\n            if self.request.method in (\"POST\", \"PATCH\", \"PUT\"):\n                if self.request.body is None:\n                    raise AssertionError(\n                        'Body must not be empty for \"%s\" request'\n                        % self.request.method)\n            else:\n                if self.request.body is not None:\n                    raise AssertionError(\n                        'Body must be empty for \"%s\" request'\n                        % self.request.method)\n        if self.request.body is not None:\n            self.request.headers[\"Content-Length\"] = str(len(\n                self.request.body))\n        if (self.request.method == \"POST\" and\n                \"Content-Type\" not in self.request.headers):\n            self.request.headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n        if self.request.use_gzip:\n            self.request.headers[\"Accept-Encoding\"] = \"gzip\"\n        req_path = ((self.parsed.path or '/') +\n                   (('?' + self.parsed.query) if self.parsed.query else ''))\n        request_lines = [utf8(\"%s %s HTTP/1.1\" % (self.request.method,\n                                                  req_path))]\n        for k, v in self.request.headers.get_all():\n            line = utf8(k) + b\": \" + utf8(v)\n            if b'\\n' in line:\n                raise ValueError('Newline in header: ' + repr(line))\n            request_lines.append(line)\n        request_str = b\"\\r\\n\".join(request_lines) + b\"\\r\\n\\r\\n\"\n        if self.request.body is not None:\n            request_str += self.request.body\n        self.stream.set_nodelay(True)\n        self.stream.write(request_str)\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _release(self):\n        if self.release_callback is not None:\n            release_callback = self.release_callback\n            self.release_callback = None\n            release_callback()\n\n    def _run_callback(self, response):\n        self._release()\n        if self.final_callback is not None:\n            final_callback = self.final_callback\n            self.final_callback = None\n            self.io_loop.add_callback(final_callback, response)\n\n    def _handle_exception(self, typ, value, tb):\n        if self.final_callback:\n            self._remove_timeout()\n            self._run_callback(HTTPResponse(self.request, 599, error=value,\n                                            request_time=self.io_loop.time() - self.start_time,\n                                            ))\n\n            if hasattr(self, \"stream\"):\n                self.stream.close()\n            return True\n        else:\n            # If our callback has already been called, we are probably\n            # catching an exception that is not caused by us but rather\n            # some child of our callback. Rather than drop it on the floor,\n            # pass it along.\n            return False\n\n    def _on_close(self):\n        if self.final_callback is not None:\n            message = \"Connection closed\"\n            if self.stream.error:\n                message = str(self.stream.error)\n            raise HTTPError(599, message)\n\n    def _handle_1xx(self, code):\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _on_headers(self, data):\n        data = native_str(data.decode(\"latin1\"))\n        first_line, _, header_data = data.partition(\"\\n\")\n        match = re.match(\"HTTP/1.[01] ([0-9]+) ([^\\r]*)\", first_line)\n        assert match\n        code = int(match.group(1))\n        self.headers = HTTPHeaders.parse(header_data)\n        if 100 <= code < 200:\n            self._handle_1xx(code)\n            return\n        else:\n            self.code = code\n            self.reason = match.group(2)\n\n        if \"Content-Length\" in self.headers:\n            if \",\" in self.headers[\"Content-Length\"]:\n                # Proxies sometimes cause Content-Length headers to get\n                # duplicated.  If all the values are identical then we can\n                # use them but if they differ it's an error.\n                pieces = re.split(r',\\s*', self.headers[\"Content-Length\"])\n                if any(i != pieces[0] for i in pieces):\n                    raise ValueError(\"Multiple unequal Content-Lengths: %r\" %\n                                     self.headers[\"Content-Length\"])\n                self.headers[\"Content-Length\"] = pieces[0]\n            content_length = int(self.headers[\"Content-Length\"])\n        else:\n            content_length = None\n\n        if self.request.header_callback is not None:\n            # re-attach the newline we split on earlier\n            self.request.header_callback(first_line + _)\n            for k, v in self.headers.get_all():\n                self.request.header_callback(\"%s: %s\\r\\n\" % (k, v))\n            self.request.header_callback('\\r\\n')\n\n        if self.request.method == \"HEAD\" or self.code == 304:\n            # HEAD requests and 304 responses never have content, even\n            # though they may have content-length headers\n            self._on_body(b\"\")\n            return\n        if 100 <= self.code < 200 or self.code == 204:\n            # These response codes never have bodies\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3\n            if (\"Transfer-Encoding\" in self.headers or\n                    content_length not in (None, 0)):\n                raise ValueError(\"Response with code %d should not have body\" %\n                                 self.code)\n            self._on_body(b\"\")\n            return\n\n        if (self.request.use_gzip and\n                self.headers.get(\"Content-Encoding\") == \"gzip\"):\n            self._decompressor = GzipDecompressor()\n        if self.headers.get(\"Transfer-Encoding\") == \"chunked\":\n            self.chunks = []\n            self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)\n        elif content_length is not None:\n            self.stream.read_bytes(content_length, self._on_body)\n        else:\n            self.stream.read_until_close(self._on_body)\n\n    def _on_body(self, data):\n        self._remove_timeout()\n        original_request = getattr(self.request, \"original_request\",\n                                   self.request)\n        if (self.request.follow_redirects and\n            self.request.max_redirects > 0 and\n                self.code in (301, 302, 303, 307)):\n            assert isinstance(self.request, _RequestProxy)\n            new_request = copy.copy(self.request.request)\n            new_request.url = urlparse.urljoin(self.request.url,\n                                               self.headers[\"Location\"])\n            new_request.max_redirects = self.request.max_redirects - 1\n            del new_request.headers[\"Host\"]\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4\n            # Client SHOULD make a GET request after a 303.\n            # According to the spec, 302 should be followed by the same\n            # method as the original request, but in practice browsers\n            # treat 302 the same as 303, and many servers use 302 for\n            # compatibility with pre-HTTP/1.1 user agents which don't\n            # understand the 303 status.\n            if self.code in (302, 303):\n                new_request.method = \"GET\"\n                new_request.body = None\n                for h in [\"Content-Length\", \"Content-Type\",\n                          \"Content-Encoding\", \"Transfer-Encoding\"]:\n                    try:\n                        del self.request.headers[h]\n                    except KeyError:\n                        pass\n            new_request.original_request = original_request\n            final_callback = self.final_callback\n            self.final_callback = None\n            self._release()\n            self.client.fetch(new_request, final_callback)\n            self._on_end_request()\n            return\n        if self._decompressor:\n            data = (self._decompressor.decompress(data) +\n                    self._decompressor.flush())\n        if self.request.streaming_callback:\n            if self.chunks is None:\n                # if chunks is not None, we already called streaming_callback\n                # in _on_chunk_data\n                self.request.streaming_callback(data)\n            buffer = BytesIO()\n        else:\n            buffer = BytesIO(data)  # TODO: don't require one big string?\n        response = HTTPResponse(original_request,\n                                self.code, reason=self.reason,\n                                headers=self.headers,\n                                request_time=self.io_loop.time() - self.start_time,\n                                buffer=buffer,\n                                effective_url=self.request.url)\n        self._run_callback(response)\n        self._on_end_request()\n\n    def _on_end_request(self):\n        self.stream.close()\n\n    def _on_chunk_length(self, data):\n        # TODO: \"chunk extensions\" http://tools.ietf.org/html/rfc2616#section-3.6.1\n        length = int(data.strip(), 16)\n        if length == 0:\n            if self._decompressor is not None:\n                tail = self._decompressor.flush()\n                if tail:\n                    # I believe the tail will always be empty (i.e.\n                    # decompress will return all it can).  The purpose\n                    # of the flush call is to detect errors such\n                    # as truncated input.  But in case it ever returns\n                    # anything, treat it as an extra chunk\n                    if self.request.streaming_callback is not None:\n                        self.request.streaming_callback(tail)\n                    else:\n                        self.chunks.append(tail)\n                # all the data has been decompressed, so we don't need to\n                # decompress again in _on_body\n                self._decompressor = None\n            self._on_body(b''.join(self.chunks))\n        else:\n            self.stream.read_bytes(length + 2,  # chunk ends with \\r\\n\n                                   self._on_chunk_data)\n\n    def _on_chunk_data(self, data):\n        assert data[-2:] == b\"\\r\\n\"\n        chunk = data[:-2]\n        if self._decompressor:\n            chunk = self._decompressor.decompress(chunk)\n        if self.request.streaming_callback is not None:\n            self.request.streaming_callback(chunk)\n        else:\n            self.chunks.append(chunk)\n        self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)\n\n\nif __name__ == \"__main__\":\n    AsyncHTTPClient.configure(SimpleAsyncHTTPClient)\n    main()\n",
            "new_file_content": "#!/usr/bin/env python\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nfrom tornado.escape import utf8, _unicode, native_str\nfrom tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy\nfrom tornado.httputil import HTTPHeaders\nfrom tornado.iostream import IOStream, SSLIOStream\nfrom tornado.netutil import Resolver, OverrideResolver\nfrom tornado.log import gen_log\nfrom tornado import stack_context\nfrom tornado.util import GzipDecompressor\n\nimport base64\nimport collections\nimport copy\nimport functools\nimport os.path\nimport re\nimport socket\nimport ssl\nimport sys\n\ntry:\n    from io import BytesIO  # python 3\nexcept ImportError:\n    from cStringIO import StringIO as BytesIO  # python 2\n\ntry:\n    import urlparse  # py2\nexcept ImportError:\n    import urllib.parse as urlparse  # py3\n\n_DEFAULT_CA_CERTS = os.path.dirname(__file__) + '/ca-certificates.crt'\n\n\nclass SimpleAsyncHTTPClient(AsyncHTTPClient):\n    \"\"\"Non-blocking HTTP client with no external dependencies.\n\n    This class implements an HTTP 1.1 client on top of Tornado's IOStreams.\n    It does not currently implement all applicable parts of the HTTP\n    specification, but it does enough to work with major web service APIs.\n\n    Some features found in the curl-based AsyncHTTPClient are not yet\n    supported.  In particular, proxies are not supported, connections\n    are not reused, and callers cannot select the network interface to be\n    used.\n    \"\"\"\n    def initialize(self, io_loop, max_clients=10,\n                   hostname_mapping=None, max_buffer_size=104857600,\n                   resolver=None, defaults=None):\n        \"\"\"Creates a AsyncHTTPClient.\n\n        Only a single AsyncHTTPClient instance exists per IOLoop\n        in order to provide limitations on the number of pending connections.\n        force_instance=True may be used to suppress this behavior.\n\n        max_clients is the number of concurrent requests that can be\n        in progress.  Note that this arguments are only used when the\n        client is first created, and will be ignored when an existing\n        client is reused.\n\n        hostname_mapping is a dictionary mapping hostnames to IP addresses.\n        It can be used to make local DNS changes when modifying system-wide\n        settings like /etc/hosts is not possible or desirable (e.g. in\n        unittests).\n\n        max_buffer_size is the number of bytes that can be read by IOStream. It\n        defaults to 100mb.\n        \"\"\"\n        super(SimpleAsyncHTTPClient, self).initialize(io_loop,\n                                                      defaults=defaults)\n        self.max_clients = max_clients\n        self.queue = collections.deque()\n        self.active = {}\n        self.waiting = {}\n        self.max_buffer_size = max_buffer_size\n        if resolver:\n            self.resolver = resolver\n            self.own_resolver = False\n        else:\n            self.resolver = Resolver(io_loop=io_loop)\n            self.own_resolver = True\n        if hostname_mapping is not None:\n            self.resolver = OverrideResolver(resolver=self.resolver,\n                                             mapping=hostname_mapping)\n\n    def close(self):\n        super(SimpleAsyncHTTPClient, self).close()\n        if self.own_resolver:\n            self.resolver.close()\n\n    def fetch_impl(self, request, callback):\n        key = object()\n        self.queue.append((key, request, callback))\n        if not len(self.active) < self.max_clients:\n            timeout_handle = self.io_loop.add_timeout(\n                self.io_loop.time() + min(request.connect_timeout,\n                                          request.request_timeout),\n                functools.partial(self._on_timeout, key))\n        else:\n            timeout_handle = None\n        self.waiting[key] = (request, callback, timeout_handle)\n        self._process_queue()\n        if self.queue:\n            gen_log.debug(\"max_clients limit reached, request queued. \"\n                          \"%d active, %d queued requests.\" % (\n                              len(self.active), len(self.queue)))\n\n    def _process_queue(self):\n        with stack_context.NullContext():\n            while self.queue and len(self.active) < self.max_clients:\n                key, request, callback = self.queue.popleft()\n                if key not in self.waiting:\n                    continue\n                self._remove_timeout(key)\n                self.active[key] = (request, callback)\n                release_callback = functools.partial(self._release_fetch, key)\n                self._handle_request(request, release_callback, callback)\n\n    def _handle_request(self, request, release_callback, final_callback):\n        _HTTPConnection(self.io_loop, self, request, release_callback,\n                        final_callback, self.max_buffer_size, self.resolver)\n\n    def _release_fetch(self, key):\n        del self.active[key]\n        self._process_queue()\n\n    def _remove_timeout(self, key):\n        if key in self.waiting:\n            request, callback, timeout_handle = self.waiting[key]\n            if timeout_handle is not None:\n                self.io_loop.remove_timeout(timeout_handle)\n            del self.waiting[key]\n\n    def _on_timeout(self, key):\n        request, callback, timeout_handle = self.waiting[key]\n        self.queue.remove((key, request, callback))\n        timeout_response = HTTPResponse(\n            request, 599, error=HTTPError(599, \"Timeout\"),\n            request_time=self.io_loop.time() - request.start_time)\n        self.io_loop.add_callback(callback, timeout_response)\n        del self.waiting[key]\n\n\nclass _HTTPConnection(object):\n    _SUPPORTED_METHODS = set([\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"])\n\n    def __init__(self, io_loop, client, request, release_callback,\n                 final_callback, max_buffer_size, resolver):\n        self.start_time = io_loop.time()\n        self.io_loop = io_loop\n        self.client = client\n        self.request = request\n        self.release_callback = release_callback\n        self.final_callback = final_callback\n        self.max_buffer_size = max_buffer_size\n        self.resolver = resolver\n        self.code = None\n        self.headers = None\n        self.chunks = None\n        self._decompressor = None\n        # Timeout handle returned by IOLoop.add_timeout\n        self._timeout = None\n        with stack_context.ExceptionStackContext(self._handle_exception):\n            self.parsed = urlparse.urlsplit(_unicode(self.request.url))\n            if self.parsed.scheme not in (\"http\", \"https\"):\n                raise ValueError(\"Unsupported url scheme: %s\" %\n                                 self.request.url)\n            # urlsplit results have hostname and port results, but they\n            # didn't support ipv6 literals until python 2.7.\n            netloc = self.parsed.netloc\n            if \"@\" in netloc:\n                userpass, _, netloc = netloc.rpartition(\"@\")\n            match = re.match(r'^(.+):(\\d+)$', netloc)\n            if match:\n                host = match.group(1)\n                port = int(match.group(2))\n            else:\n                host = netloc\n                port = 443 if self.parsed.scheme == \"https\" else 80\n            if re.match(r'^\\[.*\\]$', host):\n                # raw ipv6 addresses in urls are enclosed in brackets\n                host = host[1:-1]\n            self.parsed_hostname = host  # save final host for _on_connect\n\n            if request.allow_ipv6:\n                af = socket.AF_UNSPEC\n            else:\n                # We only try the first IP we get from getaddrinfo,\n                # so restrict to ipv4 by default.\n                af = socket.AF_INET\n\n            timeout = min(self.request.connect_timeout, self.request.request_timeout)\n            if timeout:\n                self._timeout = self.io_loop.add_timeout(\n                    self.start_time + timeout,\n                    stack_context.wrap(self._on_timeout))\n            self.resolver.resolve(host, port, af, callback=self._on_resolve)\n\n    def _on_resolve(self, addrinfo):\n        if self.final_callback is None:\n            # final_callback is cleared if we've hit our timeout\n            return\n        self.stream = self._create_stream(addrinfo)\n        self.stream.set_close_callback(self._on_close)\n        # ipv6 addresses are broken (in self.parsed.hostname) until\n        # 2.7, here is correctly parsed value calculated in __init__\n        sockaddr = addrinfo[0][1]\n        self.stream.connect(sockaddr, self._on_connect,\n                            server_hostname=self.parsed_hostname)\n\n    def _create_stream(self, addrinfo):\n        af = addrinfo[0][0]\n        if self.parsed.scheme == \"https\":\n            ssl_options = {}\n            if self.request.validate_cert:\n                ssl_options[\"cert_reqs\"] = ssl.CERT_REQUIRED\n            if self.request.ca_certs is not None:\n                ssl_options[\"ca_certs\"] = self.request.ca_certs\n            else:\n                ssl_options[\"ca_certs\"] = _DEFAULT_CA_CERTS\n            if self.request.client_key is not None:\n                ssl_options[\"keyfile\"] = self.request.client_key\n            if self.request.client_cert is not None:\n                ssl_options[\"certfile\"] = self.request.client_cert\n\n            # SSL interoperability is tricky.  We want to disable\n            # SSLv2 for security reasons; it wasn't disabled by default\n            # until openssl 1.0.  The best way to do this is to use\n            # the SSL_OP_NO_SSLv2, but that wasn't exposed to python\n            # until 3.2.  Python 2.7 adds the ciphers argument, which\n            # can also be used to disable SSLv2.  As a last resort\n            # on python 2.6, we set ssl_version to TLSv1.  This is\n            # more narrow than we'd like since it also breaks\n            # compatibility with servers configured for SSLv3 only,\n            # but nearly all servers support both SSLv3 and TLSv1:\n            # http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html\n            if sys.version_info >= (2, 7):\n                # In addition to disabling SSLv2, we also exclude certain\n                # classes of insecure ciphers.\n                ssl_options[\"ciphers\"] = \"DEFAULT:!SSLv2:!EXPORT:!DES\"\n            else:\n                # This is really only necessary for pre-1.0 versions\n                # of openssl, but python 2.6 doesn't expose version\n                # information.\n                ssl_options[\"ssl_version\"] = ssl.PROTOCOL_TLSv1\n\n            return SSLIOStream(socket.socket(af),\n                               io_loop=self.io_loop,\n                               ssl_options=ssl_options,\n                               max_buffer_size=self.max_buffer_size)\n        else:\n            return IOStream(socket.socket(af),\n                            io_loop=self.io_loop,\n                            max_buffer_size=self.max_buffer_size)\n\n    def _on_timeout(self):\n        self._timeout = None\n        if self.final_callback is not None:\n            raise HTTPError(599, \"Timeout\")\n\n    def _remove_timeout(self):\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def _on_connect(self):\n        self._remove_timeout()\n        if self.final_callback is None:\n            return\n        if self.request.request_timeout:\n            self._timeout = self.io_loop.add_timeout(\n                self.start_time + self.request.request_timeout,\n                stack_context.wrap(self._on_timeout))\n        if (self.request.method not in self._SUPPORTED_METHODS and\n                not self.request.allow_nonstandard_methods):\n            raise KeyError(\"unknown method %s\" % self.request.method)\n        for key in ('network_interface',\n                    'proxy_host', 'proxy_port',\n                    'proxy_username', 'proxy_password'):\n            if getattr(self.request, key, None):\n                raise NotImplementedError('%s not supported' % key)\n        if \"Connection\" not in self.request.headers:\n            self.request.headers[\"Connection\"] = \"close\"\n        if \"Host\" not in self.request.headers:\n            if '@' in self.parsed.netloc:\n                self.request.headers[\"Host\"] = self.parsed.netloc.rpartition('@')[-1]\n            else:\n                self.request.headers[\"Host\"] = self.parsed.netloc\n        username, password = None, None\n        if self.parsed.username is not None:\n            username, password = self.parsed.username, self.parsed.password\n        elif self.request.auth_username is not None:\n            username = self.request.auth_username\n            password = self.request.auth_password or ''\n        if username is not None:\n            if self.request.auth_mode not in (None, \"basic\"):\n                raise ValueError(\"unsupported auth_mode %s\",\n                                 self.request.auth_mode)\n            auth = utf8(username) + b\":\" + utf8(password)\n            self.request.headers[\"Authorization\"] = (b\"Basic \" +\n                                                     base64.b64encode(auth))\n        if self.request.user_agent:\n            self.request.headers[\"User-Agent\"] = self.request.user_agent\n        if not self.request.allow_nonstandard_methods:\n            if self.request.method in (\"POST\", \"PATCH\", \"PUT\"):\n                if self.request.body is None:\n                    raise AssertionError(\n                        'Body must not be empty for \"%s\" request'\n                        % self.request.method)\n            else:\n                if self.request.body is not None:\n                    raise AssertionError(\n                        'Body must be empty for \"%s\" request'\n                        % self.request.method)\n        if self.request.body is not None:\n            self.request.headers[\"Content-Length\"] = str(len(\n                self.request.body))\n        if (self.request.method == \"POST\" and\n                \"Content-Type\" not in self.request.headers):\n            self.request.headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n        if self.request.use_gzip:\n            self.request.headers[\"Accept-Encoding\"] = \"gzip\"\n        req_path = ((self.parsed.path or '/') +\n                   (('?' + self.parsed.query) if self.parsed.query else ''))\n        request_lines = [utf8(\"%s %s HTTP/1.1\" % (self.request.method,\n                                                  req_path))]\n        for k, v in self.request.headers.get_all():\n            line = utf8(k) + b\": \" + utf8(v)\n            if b'\\n' in line:\n                raise ValueError('Newline in header: ' + repr(line))\n            request_lines.append(line)\n        request_str = b\"\\r\\n\".join(request_lines) + b\"\\r\\n\\r\\n\"\n        if self.request.body is not None:\n            request_str += self.request.body\n        self.stream.set_nodelay(True)\n        self.stream.write(request_str)\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _release(self):\n        if self.release_callback is not None:\n            release_callback = self.release_callback\n            self.release_callback = None\n            release_callback()\n\n    def _run_callback(self, response):\n        self._release()\n        if self.final_callback is not None:\n            final_callback = self.final_callback\n            self.final_callback = None\n            self.io_loop.add_callback(final_callback, response)\n\n    def _handle_exception(self, typ, value, tb):\n        if self.final_callback:\n            self._remove_timeout()\n            self._run_callback(HTTPResponse(self.request, 599, error=value,\n                                            request_time=self.io_loop.time() - self.start_time,\n                                            ))\n\n            if hasattr(self, \"stream\"):\n                self.stream.close()\n            return True\n        else:\n            # If our callback has already been called, we are probably\n            # catching an exception that is not caused by us but rather\n            # some child of our callback. Rather than drop it on the floor,\n            # pass it along.\n            return False\n\n    def _on_close(self):\n        if self.final_callback is not None:\n            message = \"Connection closed\"\n            if self.stream.error:\n                raise self.stream.error\n            raise HTTPError(599, message)\n\n    def _handle_1xx(self, code):\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _on_headers(self, data):\n        data = native_str(data.decode(\"latin1\"))\n        first_line, _, header_data = data.partition(\"\\n\")\n        match = re.match(\"HTTP/1.[01] ([0-9]+) ([^\\r]*)\", first_line)\n        assert match\n        code = int(match.group(1))\n        self.headers = HTTPHeaders.parse(header_data)\n        if 100 <= code < 200:\n            self._handle_1xx(code)\n            return\n        else:\n            self.code = code\n            self.reason = match.group(2)\n\n        if \"Content-Length\" in self.headers:\n            if \",\" in self.headers[\"Content-Length\"]:\n                # Proxies sometimes cause Content-Length headers to get\n                # duplicated.  If all the values are identical then we can\n                # use them but if they differ it's an error.\n                pieces = re.split(r',\\s*', self.headers[\"Content-Length\"])\n                if any(i != pieces[0] for i in pieces):\n                    raise ValueError(\"Multiple unequal Content-Lengths: %r\" %\n                                     self.headers[\"Content-Length\"])\n                self.headers[\"Content-Length\"] = pieces[0]\n            content_length = int(self.headers[\"Content-Length\"])\n        else:\n            content_length = None\n\n        if self.request.header_callback is not None:\n            # re-attach the newline we split on earlier\n            self.request.header_callback(first_line + _)\n            for k, v in self.headers.get_all():\n                self.request.header_callback(\"%s: %s\\r\\n\" % (k, v))\n            self.request.header_callback('\\r\\n')\n\n        if self.request.method == \"HEAD\" or self.code == 304:\n            # HEAD requests and 304 responses never have content, even\n            # though they may have content-length headers\n            self._on_body(b\"\")\n            return\n        if 100 <= self.code < 200 or self.code == 204:\n            # These response codes never have bodies\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3\n            if (\"Transfer-Encoding\" in self.headers or\n                    content_length not in (None, 0)):\n                raise ValueError(\"Response with code %d should not have body\" %\n                                 self.code)\n            self._on_body(b\"\")\n            return\n\n        if (self.request.use_gzip and\n                self.headers.get(\"Content-Encoding\") == \"gzip\"):\n            self._decompressor = GzipDecompressor()\n        if self.headers.get(\"Transfer-Encoding\") == \"chunked\":\n            self.chunks = []\n            self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)\n        elif content_length is not None:\n            self.stream.read_bytes(content_length, self._on_body)\n        else:\n            self.stream.read_until_close(self._on_body)\n\n    def _on_body(self, data):\n        self._remove_timeout()\n        original_request = getattr(self.request, \"original_request\",\n                                   self.request)\n        if (self.request.follow_redirects and\n            self.request.max_redirects > 0 and\n                self.code in (301, 302, 303, 307)):\n            assert isinstance(self.request, _RequestProxy)\n            new_request = copy.copy(self.request.request)\n            new_request.url = urlparse.urljoin(self.request.url,\n                                               self.headers[\"Location\"])\n            new_request.max_redirects = self.request.max_redirects - 1\n            del new_request.headers[\"Host\"]\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4\n            # Client SHOULD make a GET request after a 303.\n            # According to the spec, 302 should be followed by the same\n            # method as the original request, but in practice browsers\n            # treat 302 the same as 303, and many servers use 302 for\n            # compatibility with pre-HTTP/1.1 user agents which don't\n            # understand the 303 status.\n            if self.code in (302, 303):\n                new_request.method = \"GET\"\n                new_request.body = None\n                for h in [\"Content-Length\", \"Content-Type\",\n                          \"Content-Encoding\", \"Transfer-Encoding\"]:\n                    try:\n                        del self.request.headers[h]\n                    except KeyError:\n                        pass\n            new_request.original_request = original_request\n            final_callback = self.final_callback\n            self.final_callback = None\n            self._release()\n            self.client.fetch(new_request, final_callback)\n            self._on_end_request()\n            return\n        if self._decompressor:\n            data = (self._decompressor.decompress(data) +\n                    self._decompressor.flush())\n        if self.request.streaming_callback:\n            if self.chunks is None:\n                # if chunks is not None, we already called streaming_callback\n                # in _on_chunk_data\n                self.request.streaming_callback(data)\n            buffer = BytesIO()\n        else:\n            buffer = BytesIO(data)  # TODO: don't require one big string?\n        response = HTTPResponse(original_request,\n                                self.code, reason=self.reason,\n                                headers=self.headers,\n                                request_time=self.io_loop.time() - self.start_time,\n                                buffer=buffer,\n                                effective_url=self.request.url)\n        self._run_callback(response)\n        self._on_end_request()\n\n    def _on_end_request(self):\n        self.stream.close()\n\n    def _on_chunk_length(self, data):\n        # TODO: \"chunk extensions\" http://tools.ietf.org/html/rfc2616#section-3.6.1\n        length = int(data.strip(), 16)\n        if length == 0:\n            if self._decompressor is not None:\n                tail = self._decompressor.flush()\n                if tail:\n                    # I believe the tail will always be empty (i.e.\n                    # decompress will return all it can).  The purpose\n                    # of the flush call is to detect errors such\n                    # as truncated input.  But in case it ever returns\n                    # anything, treat it as an extra chunk\n                    if self.request.streaming_callback is not None:\n                        self.request.streaming_callback(tail)\n                    else:\n                        self.chunks.append(tail)\n                # all the data has been decompressed, so we don't need to\n                # decompress again in _on_body\n                self._decompressor = None\n            self._on_body(b''.join(self.chunks))\n        else:\n            self.stream.read_bytes(length + 2,  # chunk ends with \\r\\n\n                                   self._on_chunk_data)\n\n    def _on_chunk_data(self, data):\n        assert data[-2:] == b\"\\r\\n\"\n        chunk = data[:-2]\n        if self._decompressor:\n            chunk = self._decompressor.decompress(chunk)\n        if self.request.streaming_callback is not None:\n            self.request.streaming_callback(chunk)\n        else:\n            self.chunks.append(chunk)\n        self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)\n\n\nif __name__ == \"__main__\":\n    AsyncHTTPClient.configure(SimpleAsyncHTTPClient)\n    main()\n",
            "header": {
                "file": {
                    "path": "tornado/simple_httpclient.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "c7e6f1a9",
                "new_commit_hash": "d5b98061",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/simple_httpclient.py"
            },
            "plus_file": {
                "path": "b/tornado/simple_httpclient.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 371,
                            "length": 7
                        },
                        "new_range": {
                            "start": 371,
                            "length": 7
                        },
                        "section": "class _HTTPConnection(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        if self.final_callback is not None:",
                                "type": "context"
                            },
                            {
                                "content": "            message = \"Connection closed\"",
                                "type": "context"
                            },
                            {
                                "content": "            if self.stream.error:",
                                "type": "context"
                            },
                            {
                                "content": "                message = str(self.stream.error)",
                                "type": "deleted"
                            },
                            {
                                "content": "                raise self.stream.error",
                                "type": "added"
                            },
                            {
                                "content": "            raise HTTPError(599, message)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def _handle_1xx(self, code):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/simple_httpclient.py",
                            "type": "method",
                            "name": "_HTTPConnection._on_close",
                            "content": "class _HTTPConnection(object):\n    _SUPPORTED_METHODS = set([\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"])\n\n    def __init__(self, io_loop, client, request, release_callback,\n                 final_callback, max_buffer_size, resolver):\n        self.start_time = io_loop.time()\n        self.io_loop = io_loop\n        self.client = client\n        self.request = request\n        self.release_callback = release_callback\n        self.final_callback = final_callback\n        self.max_buffer_size = max_buffer_size\n        self.resolver = resolver\n        self.code = None\n        self.headers = None\n        self.chunks = None\n        self._decompressor = None\n        # Timeout handle returned by IOLoop.add_timeout\n        self._timeout = None\n        with stack_context.ExceptionStackContext(self._handle_exception):\n            self.parsed = urlparse.urlsplit(_unicode(self.request.url))\n            if self.parsed.scheme not in (\"http\", \"https\"):\n                raise ValueError(\"Unsupported url scheme: %s\" %\n                                 self.request.url)\n            # urlsplit results have hostname and port results, but they\n            # didn't support ipv6 literals until python 2.7.\n            netloc = self.parsed.netloc\n            if \"@\" in netloc:\n                userpass, _, netloc = netloc.rpartition(\"@\")\n            match = re.match(r'^(.+):(\\d+)$', netloc)\n            if match:\n                host = match.group(1)\n                port = int(match.group(2))\n            else:\n                host = netloc\n                port = 443 if self.parsed.scheme == \"https\" else 80\n            if re.match(r'^\\[.*\\]$', host):\n                # raw ipv6 addresses in urls are enclosed in brackets\n                host = host[1:-1]\n            self.parsed_hostname = host  # save final host for _on_connect\n\n            if request.allow_ipv6:\n                af = socket.AF_UNSPEC\n            else:\n                # We only try the first IP we get from getaddrinfo,\n                # so restrict to ipv4 by default.\n                af = socket.AF_INET\n\n            timeout = min(self.request.connect_timeout, self.request.request_timeout)\n            if timeout:\n                self._timeout = self.io_loop.add_timeout(\n                    self.start_time + timeout,\n                    stack_context.wrap(self._on_timeout))\n            self.resolver.resolve(host, port, af, callback=self._on_resolve)\n\n    def _on_resolve(self, addrinfo):\n        if self.final_callback is None:\n            # final_callback is cleared if we've hit our timeout\n            return\n        self.stream = self._create_stream(addrinfo)\n        self.stream.set_close_callback(self._on_close)\n        # ipv6 addresses are broken (in self.parsed.hostname) until\n        # 2.7, here is correctly parsed value calculated in __init__\n        sockaddr = addrinfo[0][1]\n        self.stream.connect(sockaddr, self._on_connect,\n                            server_hostname=self.parsed_hostname)\n\n    def _create_stream(self, addrinfo):\n        af = addrinfo[0][0]\n        if self.parsed.scheme == \"https\":\n            ssl_options = {}\n            if self.request.validate_cert:\n                ssl_options[\"cert_reqs\"] = ssl.CERT_REQUIRED\n            if self.request.ca_certs is not None:\n                ssl_options[\"ca_certs\"] = self.request.ca_certs\n            else:\n                ssl_options[\"ca_certs\"] = _DEFAULT_CA_CERTS\n            if self.request.client_key is not None:\n                ssl_options[\"keyfile\"] = self.request.client_key\n            if self.request.client_cert is not None:\n                ssl_options[\"certfile\"] = self.request.client_cert\n\n            # SSL interoperability is tricky.  We want to disable\n            # SSLv2 for security reasons; it wasn't disabled by default\n            # until openssl 1.0.  The best way to do this is to use\n            # the SSL_OP_NO_SSLv2, but that wasn't exposed to python\n            # until 3.2.  Python 2.7 adds the ciphers argument, which\n            # can also be used to disable SSLv2.  As a last resort\n            # on python 2.6, we set ssl_version to TLSv1.  This is\n            # more narrow than we'd like since it also breaks\n            # compatibility with servers configured for SSLv3 only,\n            # but nearly all servers support both SSLv3 and TLSv1:\n            # http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html\n            if sys.version_info >= (2, 7):\n                # In addition to disabling SSLv2, we also exclude certain\n                # classes of insecure ciphers.\n                ssl_options[\"ciphers\"] = \"DEFAULT:!SSLv2:!EXPORT:!DES\"\n            else:\n                # This is really only necessary for pre-1.0 versions\n                # of openssl, but python 2.6 doesn't expose version\n                # information.\n                ssl_options[\"ssl_version\"] = ssl.PROTOCOL_TLSv1\n\n            return SSLIOStream(socket.socket(af),\n                               io_loop=self.io_loop,\n                               ssl_options=ssl_options,\n                               max_buffer_size=self.max_buffer_size)\n        else:\n            return IOStream(socket.socket(af),\n                            io_loop=self.io_loop,\n                            max_buffer_size=self.max_buffer_size)\n\n    def _on_timeout(self):\n        self._timeout = None\n        if self.final_callback is not None:\n            raise HTTPError(599, \"Timeout\")\n\n    def _remove_timeout(self):\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def _on_connect(self):\n        self._remove_timeout()\n        if self.final_callback is None:\n            return\n        if self.request.request_timeout:\n            self._timeout = self.io_loop.add_timeout(\n                self.start_time + self.request.request_timeout,\n                stack_context.wrap(self._on_timeout))\n        if (self.request.method not in self._SUPPORTED_METHODS and\n                not self.request.allow_nonstandard_methods):\n            raise KeyError(\"unknown method %s\" % self.request.method)\n        for key in ('network_interface',\n                    'proxy_host', 'proxy_port',\n                    'proxy_username', 'proxy_password'):\n            if getattr(self.request, key, None):\n                raise NotImplementedError('%s not supported' % key)\n        if \"Connection\" not in self.request.headers:\n            self.request.headers[\"Connection\"] = \"close\"\n        if \"Host\" not in self.request.headers:\n            if '@' in self.parsed.netloc:\n                self.request.headers[\"Host\"] = self.parsed.netloc.rpartition('@')[-1]\n            else:\n                self.request.headers[\"Host\"] = self.parsed.netloc\n        username, password = None, None\n        if self.parsed.username is not None:\n            username, password = self.parsed.username, self.parsed.password\n        elif self.request.auth_username is not None:\n            username = self.request.auth_username\n            password = self.request.auth_password or ''\n        if username is not None:\n            if self.request.auth_mode not in (None, \"basic\"):\n                raise ValueError(\"unsupported auth_mode %s\",\n                                 self.request.auth_mode)\n            auth = utf8(username) + b\":\" + utf8(password)\n            self.request.headers[\"Authorization\"] = (b\"Basic \" +\n                                                     base64.b64encode(auth))\n        if self.request.user_agent:\n            self.request.headers[\"User-Agent\"] = self.request.user_agent\n        if not self.request.allow_nonstandard_methods:\n            if self.request.method in (\"POST\", \"PATCH\", \"PUT\"):\n                if self.request.body is None:\n                    raise AssertionError(\n                        'Body must not be empty for \"%s\" request'\n                        % self.request.method)\n            else:\n                if self.request.body is not None:\n                    raise AssertionError(\n                        'Body must be empty for \"%s\" request'\n                        % self.request.method)\n        if self.request.body is not None:\n            self.request.headers[\"Content-Length\"] = str(len(\n                self.request.body))\n        if (self.request.method == \"POST\" and\n                \"Content-Type\" not in self.request.headers):\n            self.request.headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n        if self.request.use_gzip:\n            self.request.headers[\"Accept-Encoding\"] = \"gzip\"\n        req_path = ((self.parsed.path or '/') +\n                   (('?' + self.parsed.query) if self.parsed.query else ''))\n        request_lines = [utf8(\"%s %s HTTP/1.1\" % (self.request.method,\n                                                  req_path))]\n        for k, v in self.request.headers.get_all():\n            line = utf8(k) + b\": \" + utf8(v)\n            if b'\\n' in line:\n                raise ValueError('Newline in header: ' + repr(line))\n            request_lines.append(line)\n        request_str = b\"\\r\\n\".join(request_lines) + b\"\\r\\n\\r\\n\"\n        if self.request.body is not None:\n            request_str += self.request.body\n        self.stream.set_nodelay(True)\n        self.stream.write(request_str)\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _release(self):\n        if self.release_callback is not None:\n            release_callback = self.release_callback\n            self.release_callback = None\n            release_callback()\n\n    def _run_callback(self, response):\n        self._release()\n        if self.final_callback is not None:\n            final_callback = self.final_callback\n            self.final_callback = None\n            self.io_loop.add_callback(final_callback, response)\n\n    def _handle_exception(self, typ, value, tb):\n        if self.final_callback:\n            self._remove_timeout()\n            self._run_callback(HTTPResponse(self.request, 599, error=value,\n                                            request_time=self.io_loop.time() - self.start_time,\n                                            ))\n\n            if hasattr(self, \"stream\"):\n                self.stream.close()\n            return True\n        else:\n            # If our callback has already been called, we are probably\n            # catching an exception that is not caused by us but rather\n            # some child of our callback. Rather than drop it on the floor,\n            # pass it along.\n            return False\n\n    def _on_close(self):\n        if self.final_callback is not None:\n            message = \"Connection closed\"\n            if self.stream.error:\n                message = str(self.stream.error)\n            raise HTTPError(599, message)\n\n    def _handle_1xx(self, code):\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _on_headers(self, data):\n        data = native_str(data.decode(\"latin1\"))\n        first_line, _, header_data = data.partition(\"\\n\")\n        match = re.match(\"HTTP/1.[01] ([0-9]+) ([^\\r]*)\", first_line)\n        assert match\n        code = int(match.group(1))\n        self.headers = HTTPHeaders.parse(header_data)\n        if 100 <= code < 200:\n            self._handle_1xx(code)\n            return\n        else:\n            self.code = code\n            self.reason = match.group(2)\n\n        if \"Content-Length\" in self.headers:\n            if \",\" in self.headers[\"Content-Length\"]:\n                # Proxies sometimes cause Content-Length headers to get\n                # duplicated.  If all the values are identical then we can\n                # use them but if they differ it's an error.\n                pieces = re.split(r',\\s*', self.headers[\"Content-Length\"])\n                if any(i != pieces[0] for i in pieces):\n                    raise ValueError(\"Multiple unequal Content-Lengths: %r\" %\n                                     self.headers[\"Content-Length\"])\n                self.headers[\"Content-Length\"] = pieces[0]\n            content_length = int(self.headers[\"Content-Length\"])\n        else:\n            content_length = None\n\n        if self.request.header_callback is not None:\n            # re-attach the newline we split on earlier\n            self.request.header_callback(first_line + _)\n            for k, v in self.headers.get_all():\n                self.request.header_callback(\"%s: %s\\r\\n\" % (k, v))\n            self.request.header_callback('\\r\\n')\n\n        if self.request.method == \"HEAD\" or self.code == 304:\n            # HEAD requests and 304 responses never have content, even\n            # though they may have content-length headers\n            self._on_body(b\"\")\n            return\n        if 100 <= self.code < 200 or self.code == 204:\n            # These response codes never have bodies\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3\n            if (\"Transfer-Encoding\" in self.headers or\n                    content_length not in (None, 0)):\n                raise ValueError(\"Response with code %d should not have body\" %\n                                 self.code)\n            self._on_body(b\"\")\n            return\n\n        if (self.request.use_gzip and\n                self.headers.get(\"Content-Encoding\") == \"gzip\"):\n            self._decompressor = GzipDecompressor()\n        if self.headers.get(\"Transfer-Encoding\") == \"chunked\":\n            self.chunks = []\n            self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)\n        elif content_length is not None:\n            self.stream.read_bytes(content_length, self._on_body)\n        else:\n            self.stream.read_until_close(self._on_body)\n\n    def _on_body(self, data):\n        self._remove_timeout()\n        original_request = getattr(self.request, \"original_request\",\n                                   self.request)\n        if (self.request.follow_redirects and\n            self.request.max_redirects > 0 and\n                self.code in (301, 302, 303, 307)):\n            assert isinstance(self.request, _RequestProxy)\n            new_request = copy.copy(self.request.request)\n            new_request.url = urlparse.urljoin(self.request.url,\n                                               self.headers[\"Location\"])\n            new_request.max_redirects = self.request.max_redirects - 1\n            del new_request.headers[\"Host\"]\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4\n            # Client SHOULD make a GET request after a 303.\n            # According to the spec, 302 should be followed by the same\n            # method as the original request, but in practice browsers\n            # treat 302 the same as 303, and many servers use 302 for\n            # compatibility with pre-HTTP/1.1 user agents which don't\n            # understand the 303 status.\n            if self.code in (302, 303):\n                new_request.method = \"GET\"\n                new_request.body = None\n                for h in [\"Content-Length\", \"Content-Type\",\n                          \"Content-Encoding\", \"Transfer-Encoding\"]:\n                    try:\n                        del self.request.headers[h]\n                    except KeyError:\n                        pass\n            new_request.original_request = original_request\n            final_callback = self.final_callback\n            self.final_callback = None\n            self._release()\n            self.client.fetch(new_request, final_callback)\n            self._on_end_request()\n            return\n        if self._decompressor:\n            data = (self._decompressor.decompress(data) +\n                    self._decompressor.flush())\n        if self.request.streaming_callback:\n            if self.chunks is None:\n                # if chunks is not None, we already called streaming_callback\n                # in _on_chunk_data\n                self.request.streaming_callback(data)\n            buffer = BytesIO()\n        else:\n            buffer = BytesIO(data)  # TODO: don't require one big string?\n        response = HTTPResponse(original_request,\n                                self.code, reason=self.reason,\n                                headers=self.headers,\n                                request_time=self.io_loop.time() - self.start_time,\n                                buffer=buffer,\n                                effective_url=self.request.url)\n        self._run_callback(response)\n        self._on_end_request()\n\n    def _on_end_request(self):\n        self.stream.close()\n\n    def _on_chunk_length(self, data):\n        # TODO: \"chunk extensions\" http://tools.ietf.org/html/rfc2616#section-3.6.1\n        length = int(data.strip(), 16)\n        if length == 0:\n            if self._decompressor is not None:\n                tail = self._decompressor.flush()\n                if tail:\n                    # I believe the tail will always be empty (i.e.\n                    # decompress will return all it can).  The purpose\n                    # of the flush call is to detect errors such\n                    # as truncated input.  But in case it ever returns\n                    # anything, treat it as an extra chunk\n                    if self.request.streaming_callback is not None:\n                        self.request.streaming_callback(tail)\n                    else:\n                        self.chunks.append(tail)\n                # all the data has been decompressed, so we don't need to\n                # decompress again in _on_body\n                self._decompressor = None\n            self._on_body(b''.join(self.chunks))\n        else:\n            self.stream.read_bytes(length + 2,  # chunk ends with \\r\\n\n                                   self._on_chunk_data)\n\n    def _on_chunk_data(self, data):\n        assert data[-2:] == b\"\\r\\n\"\n        chunk = data[:-2]\n        if self._decompressor:\n            chunk = self._decompressor.decompress(chunk)\n        if self.request.streaming_callback is not None:\n            self.request.streaming_callback(chunk)\n        else:\n            self.chunks.append(chunk)\n        self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 370,
                            "end_lineno": 375,
                            "parent": {
                                "file_name": "tornado/simple_httpclient.py",
                                "type": "class",
                                "name": "_HTTPConnection",
                                "content": "class _HTTPConnection(object):\n    _SUPPORTED_METHODS = set([\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"])\n\n    def __init__(self, io_loop, client, request, release_callback,\n                 final_callback, max_buffer_size, resolver):\n        self.start_time = io_loop.time()\n        self.io_loop = io_loop\n        self.client = client\n        self.request = request\n        self.release_callback = release_callback\n        self.final_callback = final_callback\n        self.max_buffer_size = max_buffer_size\n        self.resolver = resolver\n        self.code = None\n        self.headers = None\n        self.chunks = None\n        self._decompressor = None\n        # Timeout handle returned by IOLoop.add_timeout\n        self._timeout = None\n        with stack_context.ExceptionStackContext(self._handle_exception):\n            self.parsed = urlparse.urlsplit(_unicode(self.request.url))\n            if self.parsed.scheme not in (\"http\", \"https\"):\n                raise ValueError(\"Unsupported url scheme: %s\" %\n                                 self.request.url)\n            # urlsplit results have hostname and port results, but they\n            # didn't support ipv6 literals until python 2.7.\n            netloc = self.parsed.netloc\n            if \"@\" in netloc:\n                userpass, _, netloc = netloc.rpartition(\"@\")\n            match = re.match(r'^(.+):(\\d+)$', netloc)\n            if match:\n                host = match.group(1)\n                port = int(match.group(2))\n            else:\n                host = netloc\n                port = 443 if self.parsed.scheme == \"https\" else 80\n            if re.match(r'^\\[.*\\]$', host):\n                # raw ipv6 addresses in urls are enclosed in brackets\n                host = host[1:-1]\n            self.parsed_hostname = host  # save final host for _on_connect\n\n            if request.allow_ipv6:\n                af = socket.AF_UNSPEC\n            else:\n                # We only try the first IP we get from getaddrinfo,\n                # so restrict to ipv4 by default.\n                af = socket.AF_INET\n\n            timeout = min(self.request.connect_timeout, self.request.request_timeout)\n            if timeout:\n                self._timeout = self.io_loop.add_timeout(\n                    self.start_time + timeout,\n                    stack_context.wrap(self._on_timeout))\n            self.resolver.resolve(host, port, af, callback=self._on_resolve)\n\n    def _on_resolve(self, addrinfo):\n        if self.final_callback is None:\n            # final_callback is cleared if we've hit our timeout\n            return\n        self.stream = self._create_stream(addrinfo)\n        self.stream.set_close_callback(self._on_close)\n        # ipv6 addresses are broken (in self.parsed.hostname) until\n        # 2.7, here is correctly parsed value calculated in __init__\n        sockaddr = addrinfo[0][1]\n        self.stream.connect(sockaddr, self._on_connect,\n                            server_hostname=self.parsed_hostname)\n\n    def _create_stream(self, addrinfo):\n        af = addrinfo[0][0]\n        if self.parsed.scheme == \"https\":\n            ssl_options = {}\n            if self.request.validate_cert:\n                ssl_options[\"cert_reqs\"] = ssl.CERT_REQUIRED\n            if self.request.ca_certs is not None:\n                ssl_options[\"ca_certs\"] = self.request.ca_certs\n            else:\n                ssl_options[\"ca_certs\"] = _DEFAULT_CA_CERTS\n            if self.request.client_key is not None:\n                ssl_options[\"keyfile\"] = self.request.client_key\n            if self.request.client_cert is not None:\n                ssl_options[\"certfile\"] = self.request.client_cert\n\n            # SSL interoperability is tricky.  We want to disable\n            # SSLv2 for security reasons; it wasn't disabled by default\n            # until openssl 1.0.  The best way to do this is to use\n            # the SSL_OP_NO_SSLv2, but that wasn't exposed to python\n            # until 3.2.  Python 2.7 adds the ciphers argument, which\n            # can also be used to disable SSLv2.  As a last resort\n            # on python 2.6, we set ssl_version to TLSv1.  This is\n            # more narrow than we'd like since it also breaks\n            # compatibility with servers configured for SSLv3 only,\n            # but nearly all servers support both SSLv3 and TLSv1:\n            # http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html\n            if sys.version_info >= (2, 7):\n                # In addition to disabling SSLv2, we also exclude certain\n                # classes of insecure ciphers.\n                ssl_options[\"ciphers\"] = \"DEFAULT:!SSLv2:!EXPORT:!DES\"\n            else:\n                # This is really only necessary for pre-1.0 versions\n                # of openssl, but python 2.6 doesn't expose version\n                # information.\n                ssl_options[\"ssl_version\"] = ssl.PROTOCOL_TLSv1\n\n            return SSLIOStream(socket.socket(af),\n                               io_loop=self.io_loop,\n                               ssl_options=ssl_options,\n                               max_buffer_size=self.max_buffer_size)\n        else:\n            return IOStream(socket.socket(af),\n                            io_loop=self.io_loop,\n                            max_buffer_size=self.max_buffer_size)\n\n    def _on_timeout(self):\n        self._timeout = None\n        if self.final_callback is not None:\n            raise HTTPError(599, \"Timeout\")\n\n    def _remove_timeout(self):\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def _on_connect(self):\n        self._remove_timeout()\n        if self.final_callback is None:\n            return\n        if self.request.request_timeout:\n            self._timeout = self.io_loop.add_timeout(\n                self.start_time + self.request.request_timeout,\n                stack_context.wrap(self._on_timeout))\n        if (self.request.method not in self._SUPPORTED_METHODS and\n                not self.request.allow_nonstandard_methods):\n            raise KeyError(\"unknown method %s\" % self.request.method)\n        for key in ('network_interface',\n                    'proxy_host', 'proxy_port',\n                    'proxy_username', 'proxy_password'):\n            if getattr(self.request, key, None):\n                raise NotImplementedError('%s not supported' % key)\n        if \"Connection\" not in self.request.headers:\n            self.request.headers[\"Connection\"] = \"close\"\n        if \"Host\" not in self.request.headers:\n            if '@' in self.parsed.netloc:\n                self.request.headers[\"Host\"] = self.parsed.netloc.rpartition('@')[-1]\n            else:\n                self.request.headers[\"Host\"] = self.parsed.netloc\n        username, password = None, None\n        if self.parsed.username is not None:\n            username, password = self.parsed.username, self.parsed.password\n        elif self.request.auth_username is not None:\n            username = self.request.auth_username\n            password = self.request.auth_password or ''\n        if username is not None:\n            if self.request.auth_mode not in (None, \"basic\"):\n                raise ValueError(\"unsupported auth_mode %s\",\n                                 self.request.auth_mode)\n            auth = utf8(username) + b\":\" + utf8(password)\n            self.request.headers[\"Authorization\"] = (b\"Basic \" +\n                                                     base64.b64encode(auth))\n        if self.request.user_agent:\n            self.request.headers[\"User-Agent\"] = self.request.user_agent\n        if not self.request.allow_nonstandard_methods:\n            if self.request.method in (\"POST\", \"PATCH\", \"PUT\"):\n                if self.request.body is None:\n                    raise AssertionError(\n                        'Body must not be empty for \"%s\" request'\n                        % self.request.method)\n            else:\n                if self.request.body is not None:\n                    raise AssertionError(\n                        'Body must be empty for \"%s\" request'\n                        % self.request.method)\n        if self.request.body is not None:\n            self.request.headers[\"Content-Length\"] = str(len(\n                self.request.body))\n        if (self.request.method == \"POST\" and\n                \"Content-Type\" not in self.request.headers):\n            self.request.headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n        if self.request.use_gzip:\n            self.request.headers[\"Accept-Encoding\"] = \"gzip\"\n        req_path = ((self.parsed.path or '/') +\n                   (('?' + self.parsed.query) if self.parsed.query else ''))\n        request_lines = [utf8(\"%s %s HTTP/1.1\" % (self.request.method,\n                                                  req_path))]\n        for k, v in self.request.headers.get_all():\n            line = utf8(k) + b\": \" + utf8(v)\n            if b'\\n' in line:\n                raise ValueError('Newline in header: ' + repr(line))\n            request_lines.append(line)\n        request_str = b\"\\r\\n\".join(request_lines) + b\"\\r\\n\\r\\n\"\n        if self.request.body is not None:\n            request_str += self.request.body\n        self.stream.set_nodelay(True)\n        self.stream.write(request_str)\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _release(self):\n        if self.release_callback is not None:\n            release_callback = self.release_callback\n            self.release_callback = None\n            release_callback()\n\n    def _run_callback(self, response):\n        self._release()\n        if self.final_callback is not None:\n            final_callback = self.final_callback\n            self.final_callback = None\n            self.io_loop.add_callback(final_callback, response)\n\n    def _handle_exception(self, typ, value, tb):\n        if self.final_callback:\n            self._remove_timeout()\n            self._run_callback(HTTPResponse(self.request, 599, error=value,\n                                            request_time=self.io_loop.time() - self.start_time,\n                                            ))\n\n            if hasattr(self, \"stream\"):\n                self.stream.close()\n            return True\n        else:\n            # If our callback has already been called, we are probably\n            # catching an exception that is not caused by us but rather\n            # some child of our callback. Rather than drop it on the floor,\n            # pass it along.\n            return False\n\n    def _on_close(self):\n        if self.final_callback is not None:\n            message = \"Connection closed\"\n            if self.stream.error:\n                message = str(self.stream.error)\n            raise HTTPError(599, message)\n\n    def _handle_1xx(self, code):\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _on_headers(self, data):\n        data = native_str(data.decode(\"latin1\"))\n        first_line, _, header_data = data.partition(\"\\n\")\n        match = re.match(\"HTTP/1.[01] ([0-9]+) ([^\\r]*)\", first_line)\n        assert match\n        code = int(match.group(1))\n        self.headers = HTTPHeaders.parse(header_data)\n        if 100 <= code < 200:\n            self._handle_1xx(code)\n            return\n        else:\n            self.code = code\n            self.reason = match.group(2)\n\n        if \"Content-Length\" in self.headers:\n            if \",\" in self.headers[\"Content-Length\"]:\n                # Proxies sometimes cause Content-Length headers to get\n                # duplicated.  If all the values are identical then we can\n                # use them but if they differ it's an error.\n                pieces = re.split(r',\\s*', self.headers[\"Content-Length\"])\n                if any(i != pieces[0] for i in pieces):\n                    raise ValueError(\"Multiple unequal Content-Lengths: %r\" %\n                                     self.headers[\"Content-Length\"])\n                self.headers[\"Content-Length\"] = pieces[0]\n            content_length = int(self.headers[\"Content-Length\"])\n        else:\n            content_length = None\n\n        if self.request.header_callback is not None:\n            # re-attach the newline we split on earlier\n            self.request.header_callback(first_line + _)\n            for k, v in self.headers.get_all():\n                self.request.header_callback(\"%s: %s\\r\\n\" % (k, v))\n            self.request.header_callback('\\r\\n')\n\n        if self.request.method == \"HEAD\" or self.code == 304:\n            # HEAD requests and 304 responses never have content, even\n            # though they may have content-length headers\n            self._on_body(b\"\")\n            return\n        if 100 <= self.code < 200 or self.code == 204:\n            # These response codes never have bodies\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3\n            if (\"Transfer-Encoding\" in self.headers or\n                    content_length not in (None, 0)):\n                raise ValueError(\"Response with code %d should not have body\" %\n                                 self.code)\n            self._on_body(b\"\")\n            return\n\n        if (self.request.use_gzip and\n                self.headers.get(\"Content-Encoding\") == \"gzip\"):\n            self._decompressor = GzipDecompressor()\n        if self.headers.get(\"Transfer-Encoding\") == \"chunked\":\n            self.chunks = []\n            self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)\n        elif content_length is not None:\n            self.stream.read_bytes(content_length, self._on_body)\n        else:\n            self.stream.read_until_close(self._on_body)\n\n    def _on_body(self, data):\n        self._remove_timeout()\n        original_request = getattr(self.request, \"original_request\",\n                                   self.request)\n        if (self.request.follow_redirects and\n            self.request.max_redirects > 0 and\n                self.code in (301, 302, 303, 307)):\n            assert isinstance(self.request, _RequestProxy)\n            new_request = copy.copy(self.request.request)\n            new_request.url = urlparse.urljoin(self.request.url,\n                                               self.headers[\"Location\"])\n            new_request.max_redirects = self.request.max_redirects - 1\n            del new_request.headers[\"Host\"]\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4\n            # Client SHOULD make a GET request after a 303.\n            # According to the spec, 302 should be followed by the same\n            # method as the original request, but in practice browsers\n            # treat 302 the same as 303, and many servers use 302 for\n            # compatibility with pre-HTTP/1.1 user agents which don't\n            # understand the 303 status.\n            if self.code in (302, 303):\n                new_request.method = \"GET\"\n                new_request.body = None\n                for h in [\"Content-Length\", \"Content-Type\",\n                          \"Content-Encoding\", \"Transfer-Encoding\"]:\n                    try:\n                        del self.request.headers[h]\n                    except KeyError:\n                        pass\n            new_request.original_request = original_request\n            final_callback = self.final_callback\n            self.final_callback = None\n            self._release()\n            self.client.fetch(new_request, final_callback)\n            self._on_end_request()\n            return\n        if self._decompressor:\n            data = (self._decompressor.decompress(data) +\n                    self._decompressor.flush())\n        if self.request.streaming_callback:\n            if self.chunks is None:\n                # if chunks is not None, we already called streaming_callback\n                # in _on_chunk_data\n                self.request.streaming_callback(data)\n            buffer = BytesIO()\n        else:\n            buffer = BytesIO(data)  # TODO: don't require one big string?\n        response = HTTPResponse(original_request,\n                                self.code, reason=self.reason,\n                                headers=self.headers,\n                                request_time=self.io_loop.time() - self.start_time,\n                                buffer=buffer,\n                                effective_url=self.request.url)\n        self._run_callback(response)\n        self._on_end_request()\n\n    def _on_end_request(self):\n        self.stream.close()\n\n    def _on_chunk_length(self, data):\n        # TODO: \"chunk extensions\" http://tools.ietf.org/html/rfc2616#section-3.6.1\n        length = int(data.strip(), 16)\n        if length == 0:\n            if self._decompressor is not None:\n                tail = self._decompressor.flush()\n                if tail:\n                    # I believe the tail will always be empty (i.e.\n                    # decompress will return all it can).  The purpose\n                    # of the flush call is to detect errors such\n                    # as truncated input.  But in case it ever returns\n                    # anything, treat it as an extra chunk\n                    if self.request.streaming_callback is not None:\n                        self.request.streaming_callback(tail)\n                    else:\n                        self.chunks.append(tail)\n                # all the data has been decompressed, so we don't need to\n                # decompress again in _on_body\n                self._decompressor = None\n            self._on_body(b''.join(self.chunks))\n        else:\n            self.stream.read_bytes(length + 2,  # chunk ends with \\r\\n\n                                   self._on_chunk_data)\n\n    def _on_chunk_data(self, data):\n        assert data[-2:] == b\"\\r\\n\"\n        chunk = data[:-2]\n        if self._decompressor:\n            chunk = self._decompressor.decompress(chunk)\n        if self.request.streaming_callback is not None:\n            self.request.streaming_callback(chunk)\n        else:\n            self.chunks.append(chunk)\n        self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 145,
                                "end_lineno": 533,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/simple_httpclient.py",
                            "type": "class",
                            "name": "_HTTPConnection",
                            "content": "class _HTTPConnection(object):\n    _SUPPORTED_METHODS = set([\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"])\n\n    def __init__(self, io_loop, client, request, release_callback,\n                 final_callback, max_buffer_size, resolver):\n        self.start_time = io_loop.time()\n        self.io_loop = io_loop\n        self.client = client\n        self.request = request\n        self.release_callback = release_callback\n        self.final_callback = final_callback\n        self.max_buffer_size = max_buffer_size\n        self.resolver = resolver\n        self.code = None\n        self.headers = None\n        self.chunks = None\n        self._decompressor = None\n        # Timeout handle returned by IOLoop.add_timeout\n        self._timeout = None\n        with stack_context.ExceptionStackContext(self._handle_exception):\n            self.parsed = urlparse.urlsplit(_unicode(self.request.url))\n            if self.parsed.scheme not in (\"http\", \"https\"):\n                raise ValueError(\"Unsupported url scheme: %s\" %\n                                 self.request.url)\n            # urlsplit results have hostname and port results, but they\n            # didn't support ipv6 literals until python 2.7.\n            netloc = self.parsed.netloc\n            if \"@\" in netloc:\n                userpass, _, netloc = netloc.rpartition(\"@\")\n            match = re.match(r'^(.+):(\\d+)$', netloc)\n            if match:\n                host = match.group(1)\n                port = int(match.group(2))\n            else:\n                host = netloc\n                port = 443 if self.parsed.scheme == \"https\" else 80\n            if re.match(r'^\\[.*\\]$', host):\n                # raw ipv6 addresses in urls are enclosed in brackets\n                host = host[1:-1]\n            self.parsed_hostname = host  # save final host for _on_connect\n\n            if request.allow_ipv6:\n                af = socket.AF_UNSPEC\n            else:\n                # We only try the first IP we get from getaddrinfo,\n                # so restrict to ipv4 by default.\n                af = socket.AF_INET\n\n            timeout = min(self.request.connect_timeout, self.request.request_timeout)\n            if timeout:\n                self._timeout = self.io_loop.add_timeout(\n                    self.start_time + timeout,\n                    stack_context.wrap(self._on_timeout))\n            self.resolver.resolve(host, port, af, callback=self._on_resolve)\n\n    def _on_resolve(self, addrinfo):\n        if self.final_callback is None:\n            # final_callback is cleared if we've hit our timeout\n            return\n        self.stream = self._create_stream(addrinfo)\n        self.stream.set_close_callback(self._on_close)\n        # ipv6 addresses are broken (in self.parsed.hostname) until\n        # 2.7, here is correctly parsed value calculated in __init__\n        sockaddr = addrinfo[0][1]\n        self.stream.connect(sockaddr, self._on_connect,\n                            server_hostname=self.parsed_hostname)\n\n    def _create_stream(self, addrinfo):\n        af = addrinfo[0][0]\n        if self.parsed.scheme == \"https\":\n            ssl_options = {}\n            if self.request.validate_cert:\n                ssl_options[\"cert_reqs\"] = ssl.CERT_REQUIRED\n            if self.request.ca_certs is not None:\n                ssl_options[\"ca_certs\"] = self.request.ca_certs\n            else:\n                ssl_options[\"ca_certs\"] = _DEFAULT_CA_CERTS\n            if self.request.client_key is not None:\n                ssl_options[\"keyfile\"] = self.request.client_key\n            if self.request.client_cert is not None:\n                ssl_options[\"certfile\"] = self.request.client_cert\n\n            # SSL interoperability is tricky.  We want to disable\n            # SSLv2 for security reasons; it wasn't disabled by default\n            # until openssl 1.0.  The best way to do this is to use\n            # the SSL_OP_NO_SSLv2, but that wasn't exposed to python\n            # until 3.2.  Python 2.7 adds the ciphers argument, which\n            # can also be used to disable SSLv2.  As a last resort\n            # on python 2.6, we set ssl_version to TLSv1.  This is\n            # more narrow than we'd like since it also breaks\n            # compatibility with servers configured for SSLv3 only,\n            # but nearly all servers support both SSLv3 and TLSv1:\n            # http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html\n            if sys.version_info >= (2, 7):\n                # In addition to disabling SSLv2, we also exclude certain\n                # classes of insecure ciphers.\n                ssl_options[\"ciphers\"] = \"DEFAULT:!SSLv2:!EXPORT:!DES\"\n            else:\n                # This is really only necessary for pre-1.0 versions\n                # of openssl, but python 2.6 doesn't expose version\n                # information.\n                ssl_options[\"ssl_version\"] = ssl.PROTOCOL_TLSv1\n\n            return SSLIOStream(socket.socket(af),\n                               io_loop=self.io_loop,\n                               ssl_options=ssl_options,\n                               max_buffer_size=self.max_buffer_size)\n        else:\n            return IOStream(socket.socket(af),\n                            io_loop=self.io_loop,\n                            max_buffer_size=self.max_buffer_size)\n\n    def _on_timeout(self):\n        self._timeout = None\n        if self.final_callback is not None:\n            raise HTTPError(599, \"Timeout\")\n\n    def _remove_timeout(self):\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def _on_connect(self):\n        self._remove_timeout()\n        if self.final_callback is None:\n            return\n        if self.request.request_timeout:\n            self._timeout = self.io_loop.add_timeout(\n                self.start_time + self.request.request_timeout,\n                stack_context.wrap(self._on_timeout))\n        if (self.request.method not in self._SUPPORTED_METHODS and\n                not self.request.allow_nonstandard_methods):\n            raise KeyError(\"unknown method %s\" % self.request.method)\n        for key in ('network_interface',\n                    'proxy_host', 'proxy_port',\n                    'proxy_username', 'proxy_password'):\n            if getattr(self.request, key, None):\n                raise NotImplementedError('%s not supported' % key)\n        if \"Connection\" not in self.request.headers:\n            self.request.headers[\"Connection\"] = \"close\"\n        if \"Host\" not in self.request.headers:\n            if '@' in self.parsed.netloc:\n                self.request.headers[\"Host\"] = self.parsed.netloc.rpartition('@')[-1]\n            else:\n                self.request.headers[\"Host\"] = self.parsed.netloc\n        username, password = None, None\n        if self.parsed.username is not None:\n            username, password = self.parsed.username, self.parsed.password\n        elif self.request.auth_username is not None:\n            username = self.request.auth_username\n            password = self.request.auth_password or ''\n        if username is not None:\n            if self.request.auth_mode not in (None, \"basic\"):\n                raise ValueError(\"unsupported auth_mode %s\",\n                                 self.request.auth_mode)\n            auth = utf8(username) + b\":\" + utf8(password)\n            self.request.headers[\"Authorization\"] = (b\"Basic \" +\n                                                     base64.b64encode(auth))\n        if self.request.user_agent:\n            self.request.headers[\"User-Agent\"] = self.request.user_agent\n        if not self.request.allow_nonstandard_methods:\n            if self.request.method in (\"POST\", \"PATCH\", \"PUT\"):\n                if self.request.body is None:\n                    raise AssertionError(\n                        'Body must not be empty for \"%s\" request'\n                        % self.request.method)\n            else:\n                if self.request.body is not None:\n                    raise AssertionError(\n                        'Body must be empty for \"%s\" request'\n                        % self.request.method)\n        if self.request.body is not None:\n            self.request.headers[\"Content-Length\"] = str(len(\n                self.request.body))\n        if (self.request.method == \"POST\" and\n                \"Content-Type\" not in self.request.headers):\n            self.request.headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n        if self.request.use_gzip:\n            self.request.headers[\"Accept-Encoding\"] = \"gzip\"\n        req_path = ((self.parsed.path or '/') +\n                   (('?' + self.parsed.query) if self.parsed.query else ''))\n        request_lines = [utf8(\"%s %s HTTP/1.1\" % (self.request.method,\n                                                  req_path))]\n        for k, v in self.request.headers.get_all():\n            line = utf8(k) + b\": \" + utf8(v)\n            if b'\\n' in line:\n                raise ValueError('Newline in header: ' + repr(line))\n            request_lines.append(line)\n        request_str = b\"\\r\\n\".join(request_lines) + b\"\\r\\n\\r\\n\"\n        if self.request.body is not None:\n            request_str += self.request.body\n        self.stream.set_nodelay(True)\n        self.stream.write(request_str)\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _release(self):\n        if self.release_callback is not None:\n            release_callback = self.release_callback\n            self.release_callback = None\n            release_callback()\n\n    def _run_callback(self, response):\n        self._release()\n        if self.final_callback is not None:\n            final_callback = self.final_callback\n            self.final_callback = None\n            self.io_loop.add_callback(final_callback, response)\n\n    def _handle_exception(self, typ, value, tb):\n        if self.final_callback:\n            self._remove_timeout()\n            self._run_callback(HTTPResponse(self.request, 599, error=value,\n                                            request_time=self.io_loop.time() - self.start_time,\n                                            ))\n\n            if hasattr(self, \"stream\"):\n                self.stream.close()\n            return True\n        else:\n            # If our callback has already been called, we are probably\n            # catching an exception that is not caused by us but rather\n            # some child of our callback. Rather than drop it on the floor,\n            # pass it along.\n            return False\n\n    def _on_close(self):\n        if self.final_callback is not None:\n            message = \"Connection closed\"\n            if self.stream.error:\n                message = str(self.stream.error)\n            raise HTTPError(599, message)\n\n    def _handle_1xx(self, code):\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _on_headers(self, data):\n        data = native_str(data.decode(\"latin1\"))\n        first_line, _, header_data = data.partition(\"\\n\")\n        match = re.match(\"HTTP/1.[01] ([0-9]+) ([^\\r]*)\", first_line)\n        assert match\n        code = int(match.group(1))\n        self.headers = HTTPHeaders.parse(header_data)\n        if 100 <= code < 200:\n            self._handle_1xx(code)\n            return\n        else:\n            self.code = code\n            self.reason = match.group(2)\n\n        if \"Content-Length\" in self.headers:\n            if \",\" in self.headers[\"Content-Length\"]:\n                # Proxies sometimes cause Content-Length headers to get\n                # duplicated.  If all the values are identical then we can\n                # use them but if they differ it's an error.\n                pieces = re.split(r',\\s*', self.headers[\"Content-Length\"])\n                if any(i != pieces[0] for i in pieces):\n                    raise ValueError(\"Multiple unequal Content-Lengths: %r\" %\n                                     self.headers[\"Content-Length\"])\n                self.headers[\"Content-Length\"] = pieces[0]\n            content_length = int(self.headers[\"Content-Length\"])\n        else:\n            content_length = None\n\n        if self.request.header_callback is not None:\n            # re-attach the newline we split on earlier\n            self.request.header_callback(first_line + _)\n            for k, v in self.headers.get_all():\n                self.request.header_callback(\"%s: %s\\r\\n\" % (k, v))\n            self.request.header_callback('\\r\\n')\n\n        if self.request.method == \"HEAD\" or self.code == 304:\n            # HEAD requests and 304 responses never have content, even\n            # though they may have content-length headers\n            self._on_body(b\"\")\n            return\n        if 100 <= self.code < 200 or self.code == 204:\n            # These response codes never have bodies\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3\n            if (\"Transfer-Encoding\" in self.headers or\n                    content_length not in (None, 0)):\n                raise ValueError(\"Response with code %d should not have body\" %\n                                 self.code)\n            self._on_body(b\"\")\n            return\n\n        if (self.request.use_gzip and\n                self.headers.get(\"Content-Encoding\") == \"gzip\"):\n            self._decompressor = GzipDecompressor()\n        if self.headers.get(\"Transfer-Encoding\") == \"chunked\":\n            self.chunks = []\n            self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)\n        elif content_length is not None:\n            self.stream.read_bytes(content_length, self._on_body)\n        else:\n            self.stream.read_until_close(self._on_body)\n\n    def _on_body(self, data):\n        self._remove_timeout()\n        original_request = getattr(self.request, \"original_request\",\n                                   self.request)\n        if (self.request.follow_redirects and\n            self.request.max_redirects > 0 and\n                self.code in (301, 302, 303, 307)):\n            assert isinstance(self.request, _RequestProxy)\n            new_request = copy.copy(self.request.request)\n            new_request.url = urlparse.urljoin(self.request.url,\n                                               self.headers[\"Location\"])\n            new_request.max_redirects = self.request.max_redirects - 1\n            del new_request.headers[\"Host\"]\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4\n            # Client SHOULD make a GET request after a 303.\n            # According to the spec, 302 should be followed by the same\n            # method as the original request, but in practice browsers\n            # treat 302 the same as 303, and many servers use 302 for\n            # compatibility with pre-HTTP/1.1 user agents which don't\n            # understand the 303 status.\n            if self.code in (302, 303):\n                new_request.method = \"GET\"\n                new_request.body = None\n                for h in [\"Content-Length\", \"Content-Type\",\n                          \"Content-Encoding\", \"Transfer-Encoding\"]:\n                    try:\n                        del self.request.headers[h]\n                    except KeyError:\n                        pass\n            new_request.original_request = original_request\n            final_callback = self.final_callback\n            self.final_callback = None\n            self._release()\n            self.client.fetch(new_request, final_callback)\n            self._on_end_request()\n            return\n        if self._decompressor:\n            data = (self._decompressor.decompress(data) +\n                    self._decompressor.flush())\n        if self.request.streaming_callback:\n            if self.chunks is None:\n                # if chunks is not None, we already called streaming_callback\n                # in _on_chunk_data\n                self.request.streaming_callback(data)\n            buffer = BytesIO()\n        else:\n            buffer = BytesIO(data)  # TODO: don't require one big string?\n        response = HTTPResponse(original_request,\n                                self.code, reason=self.reason,\n                                headers=self.headers,\n                                request_time=self.io_loop.time() - self.start_time,\n                                buffer=buffer,\n                                effective_url=self.request.url)\n        self._run_callback(response)\n        self._on_end_request()\n\n    def _on_end_request(self):\n        self.stream.close()\n\n    def _on_chunk_length(self, data):\n        # TODO: \"chunk extensions\" http://tools.ietf.org/html/rfc2616#section-3.6.1\n        length = int(data.strip(), 16)\n        if length == 0:\n            if self._decompressor is not None:\n                tail = self._decompressor.flush()\n                if tail:\n                    # I believe the tail will always be empty (i.e.\n                    # decompress will return all it can).  The purpose\n                    # of the flush call is to detect errors such\n                    # as truncated input.  But in case it ever returns\n                    # anything, treat it as an extra chunk\n                    if self.request.streaming_callback is not None:\n                        self.request.streaming_callback(tail)\n                    else:\n                        self.chunks.append(tail)\n                # all the data has been decompressed, so we don't need to\n                # decompress again in _on_body\n                self._decompressor = None\n            self._on_body(b''.join(self.chunks))\n        else:\n            self.stream.read_bytes(length + 2,  # chunk ends with \\r\\n\n                                   self._on_chunk_data)\n\n    def _on_chunk_data(self, data):\n        assert data[-2:] == b\"\\r\\n\"\n        chunk = data[:-2]\n        if self._decompressor:\n            chunk = self._decompressor.decompress(chunk)\n        if self.request.streaming_callback is not None:\n            self.request.streaming_callback(chunk)\n        else:\n            self.chunks.append(chunk)\n        self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 145,
                            "end_lineno": 533,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport traceback\n\nfrom tornado.concurrent import Future\nfrom tornado.httpclient import HTTPError, HTTPRequest\nfrom tornado.log import gen_log\nfrom tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler\n\ntry:\n    import tornado.websocket\nexcept ImportError:\n    # The unittest module presents misleading errors on ImportError\n    # (it acts as if websocket_test could not be found, hiding the underlying\n    # error).  If we get an ImportError here (which could happen due to\n    # TORNADO_EXTENSION=1), print some extra information before failing.\n    traceback.print_exc()\n    raise\n\nfrom tornado.websocket import WebSocketHandler, websocket_connect, WebSocketError, _websocket_mask_python\n\ntry:\n    from tornado import speedups\nexcept ImportError:\n    speedups = None\n\n\nclass TestWebSocketHandler(WebSocketHandler):\n    \"\"\"Base class for testing handlers that exposes the on_close event.\n\n    This allows for deterministic cleanup of the associated socket.\n    \"\"\"\n    def initialize(self, close_future):\n        self.close_future = close_future\n\n    def on_close(self):\n        self.close_future.set_result((self.close_code, self.close_reason))\n\n\nclass EchoHandler(TestWebSocketHandler):\n    def on_message(self, message):\n        self.write_message(message, isinstance(message, bytes))\n\n\nclass HeaderHandler(TestWebSocketHandler):\n    def open(self):\n        self.write_message(self.request.headers.get('X-Test', ''))\n\n\nclass NonWebSocketHandler(RequestHandler):\n    def get(self):\n        self.write('ok')\n\n\nclass CloseReasonHandler(TestWebSocketHandler):\n    def open(self):\n        self.close(1001, \"goodbye\")\n\n\nclass WebSocketTest(AsyncHTTPTestCase):\n    def get_app(self):\n        self.close_future = Future()\n        return Application([\n            ('/echo', EchoHandler, dict(close_future=self.close_future)),\n            ('/non_ws', NonWebSocketHandler),\n            ('/header', HeaderHandler, dict(close_future=self.close_future)),\n            ('/close_reason', CloseReasonHandler,\n             dict(close_future=self.close_future)),\n        ])\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop)\n        ws.write_message('hello')\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop, callback=self.stop)\n        ws = self.wait().result()\n        ws.write_message('hello')\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, 'hello')\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(\n                'ws://localhost:%d/notfound' % self.get_http_port(),\n                io_loop=self.io_loop)\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield websocket_connect(\n                'ws://localhost:%d/non_ws' % self.get_http_port(),\n                io_loop=self.io_loop)\n\n    @skipOnTravis\n    @gen_test\n    def test_websocket_network_timeout(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=0.01)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=3600)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.write_message('hello')\n        ws.write_message('world')\n        ws.stream.close()\n        yield self.close_future\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest('ws://localhost:%d/header' % self.get_http_port(),\n                        headers={'X-Test': 'hello'}))\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/close_reason' % self.get_http_port())\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.close(1001, 'goodbye')\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, 'goodbye')\n\n\nclass MaskFunctionMixin(object):\n    # Subclasses should define self.mask(mask, data)\n    def test_mask(self):\n        self.assertEqual(self.mask(b'abcd', b''), b'')\n        self.assertEqual(self.mask(b'abcd', b'b'), b'\\x03')\n        self.assertEqual(self.mask(b'abcd', b'54321'), b'TVPVP')\n        self.assertEqual(self.mask(b'ZXCV', b'98765432'), b'c`t`olpd')\n        # Include test cases with \\x00 bytes (to ensure that the C\n        # extension isn't depending on null-terminated strings) and\n        # bytes with the high bit set (to smoke out signedness issues).\n        self.assertEqual(self.mask(b'\\x00\\x01\\x02\\x03',\n                                   b'\\xff\\xfb\\xfd\\xfc\\xfe\\xfa'),\n                         b'\\xff\\xfa\\xff\\xff\\xfe\\xfb')\n        self.assertEqual(self.mask(b'\\xff\\xfb\\xfd\\xfc',\n                                   b'\\x00\\x01\\x02\\x03\\x04\\x05'),\n                         b'\\xff\\xfa\\xff\\xff\\xfb\\xfe')\n\n\nclass PythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return _websocket_mask_python(mask, data)\n\n\n@unittest.skipIf(speedups is None, \"tornado.speedups module not present\")\nclass CythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return speedups.websocket_mask(mask, data)\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport traceback\n\nfrom tornado.concurrent import Future\nfrom tornado.httpclient import HTTPError, HTTPRequest\nfrom tornado.log import gen_log\nfrom tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler\n\ntry:\n    import tornado.websocket\nexcept ImportError:\n    # The unittest module presents misleading errors on ImportError\n    # (it acts as if websocket_test could not be found, hiding the underlying\n    # error).  If we get an ImportError here (which could happen due to\n    # TORNADO_EXTENSION=1), print some extra information before failing.\n    traceback.print_exc()\n    raise\n\nfrom tornado.websocket import WebSocketHandler, websocket_connect, WebSocketError, _websocket_mask_python\n\ntry:\n    from tornado import speedups\nexcept ImportError:\n    speedups = None\n\n\nclass TestWebSocketHandler(WebSocketHandler):\n    \"\"\"Base class for testing handlers that exposes the on_close event.\n\n    This allows for deterministic cleanup of the associated socket.\n    \"\"\"\n    def initialize(self, close_future):\n        self.close_future = close_future\n\n    def on_close(self):\n        self.close_future.set_result((self.close_code, self.close_reason))\n\n\nclass EchoHandler(TestWebSocketHandler):\n    def on_message(self, message):\n        self.write_message(message, isinstance(message, bytes))\n\n\nclass HeaderHandler(TestWebSocketHandler):\n    def open(self):\n        self.write_message(self.request.headers.get('X-Test', ''))\n\n\nclass NonWebSocketHandler(RequestHandler):\n    def get(self):\n        self.write('ok')\n\n\nclass CloseReasonHandler(TestWebSocketHandler):\n    def open(self):\n        self.close(1001, \"goodbye\")\n\n\nclass WebSocketTest(AsyncHTTPTestCase):\n    def get_app(self):\n        self.close_future = Future()\n        return Application([\n            ('/echo', EchoHandler, dict(close_future=self.close_future)),\n            ('/non_ws', NonWebSocketHandler),\n            ('/header', HeaderHandler, dict(close_future=self.close_future)),\n            ('/close_reason', CloseReasonHandler,\n             dict(close_future=self.close_future)),\n        ])\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop)\n        ws.write_message('hello')\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop, callback=self.stop)\n        ws = self.wait().result()\n        ws.write_message('hello')\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, 'hello')\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(\n                'ws://localhost:%d/notfound' % self.get_http_port(),\n                io_loop=self.io_loop)\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield websocket_connect(\n                'ws://localhost:%d/non_ws' % self.get_http_port(),\n                io_loop=self.io_loop)\n\n    @skipOnTravis\n    @gen_test\n    def test_websocket_network_timeout(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=0.01)\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=3600)\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.write_message('hello')\n        ws.write_message('world')\n        ws.stream.close()\n        yield self.close_future\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest('ws://localhost:%d/header' % self.get_http_port(),\n                        headers={'X-Test': 'hello'}))\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/close_reason' % self.get_http_port())\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.close(1001, 'goodbye')\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, 'goodbye')\n\n\nclass MaskFunctionMixin(object):\n    # Subclasses should define self.mask(mask, data)\n    def test_mask(self):\n        self.assertEqual(self.mask(b'abcd', b''), b'')\n        self.assertEqual(self.mask(b'abcd', b'b'), b'\\x03')\n        self.assertEqual(self.mask(b'abcd', b'54321'), b'TVPVP')\n        self.assertEqual(self.mask(b'ZXCV', b'98765432'), b'c`t`olpd')\n        # Include test cases with \\x00 bytes (to ensure that the C\n        # extension isn't depending on null-terminated strings) and\n        # bytes with the high bit set (to smoke out signedness issues).\n        self.assertEqual(self.mask(b'\\x00\\x01\\x02\\x03',\n                                   b'\\xff\\xfb\\xfd\\xfc\\xfe\\xfa'),\n                         b'\\xff\\xfa\\xff\\xff\\xfe\\xfb')\n        self.assertEqual(self.mask(b'\\xff\\xfb\\xfd\\xfc',\n                                   b'\\x00\\x01\\x02\\x03\\x04\\x05'),\n                         b'\\xff\\xfa\\xff\\xff\\xfb\\xfe')\n\n\nclass PythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return _websocket_mask_python(mask, data)\n\n\n@unittest.skipIf(speedups is None, \"tornado.speedups module not present\")\nclass CythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return speedups.websocket_mask(mask, data)\n",
            "header": {
                "file": {
                    "path": "tornado/test/websocket_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "e4506653",
                "new_commit_hash": "648e5d8c",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/websocket_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/websocket_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 114,
                            "length": 25
                        },
                        "new_range": {
                            "start": 114,
                            "length": 23
                        },
                        "section": "class WebSocketTest(AsyncHTTPTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    def test_websocket_network_timeout(self):",
                                "type": "context"
                            },
                            {
                                "content": "        sock, port = bind_unused_port()",
                                "type": "context"
                            },
                            {
                                "content": "        sock.close()",
                                "type": "context"
                            },
                            {
                                "content": "        with self.assertRaises(HTTPError) as cm:",
                                "type": "deleted"
                            },
                            {
                                "content": "        with self.assertRaises(IOError) as cm:",
                                "type": "added"
                            },
                            {
                                "content": "            with ExpectLog(gen_log, \".*\"):",
                                "type": "context"
                            },
                            {
                                "content": "                yield websocket_connect(",
                                "type": "context"
                            },
                            {
                                "content": "                    'ws://localhost:%d/' % port,",
                                "type": "context"
                            },
                            {
                                "content": "                    io_loop=self.io_loop,",
                                "type": "context"
                            },
                            {
                                "content": "                    connect_timeout=0.01)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(cm.exception.code, 599)",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "context"
                            },
                            {
                                "content": "    def test_websocket_network_fail(self):",
                                "type": "context"
                            },
                            {
                                "content": "        sock, port = bind_unused_port()",
                                "type": "context"
                            },
                            {
                                "content": "        sock.close()",
                                "type": "context"
                            },
                            {
                                "content": "        with self.assertRaises(HTTPError) as cm:",
                                "type": "deleted"
                            },
                            {
                                "content": "        with self.assertRaises(IOError) as cm:",
                                "type": "added"
                            },
                            {
                                "content": "            with ExpectLog(gen_log, \".*\"):",
                                "type": "context"
                            },
                            {
                                "content": "                yield websocket_connect(",
                                "type": "context"
                            },
                            {
                                "content": "                    'ws://localhost:%d/' % port,",
                                "type": "context"
                            },
                            {
                                "content": "                    io_loop=self.io_loop,",
                                "type": "context"
                            },
                            {
                                "content": "                    connect_timeout=3600)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(cm.exception.code, 599)",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "context"
                            },
                            {
                                "content": "    def test_websocket_close_buffered_data(self):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/websocket_test.py",
                            "type": "method",
                            "name": "WebSocketTest.test_websocket_network_timeout",
                            "content": "class WebSocketTest(AsyncHTTPTestCase):\n    def get_app(self):\n        self.close_future = Future()\n        return Application([\n            ('/echo', EchoHandler, dict(close_future=self.close_future)),\n            ('/non_ws', NonWebSocketHandler),\n            ('/header', HeaderHandler, dict(close_future=self.close_future)),\n            ('/close_reason', CloseReasonHandler,\n             dict(close_future=self.close_future)),\n        ])\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop)\n        ws.write_message('hello')\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop, callback=self.stop)\n        ws = self.wait().result()\n        ws.write_message('hello')\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, 'hello')\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(\n                'ws://localhost:%d/notfound' % self.get_http_port(),\n                io_loop=self.io_loop)\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield websocket_connect(\n                'ws://localhost:%d/non_ws' % self.get_http_port(),\n                io_loop=self.io_loop)\n\n    @skipOnTravis\n    @gen_test\n    def test_websocket_network_timeout(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=0.01)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=3600)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.write_message('hello')\n        ws.write_message('world')\n        ws.stream.close()\n        yield self.close_future\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest('ws://localhost:%d/header' % self.get_http_port(),\n                        headers={'X-Test': 'hello'}))\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/close_reason' % self.get_http_port())\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.close(1001, 'goodbye')\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, 'goodbye')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 114,
                            "end_lineno": 123,
                            "parent": {
                                "file_name": "tornado/test/websocket_test.py",
                                "type": "class",
                                "name": "WebSocketTest",
                                "content": "class WebSocketTest(AsyncHTTPTestCase):\n    def get_app(self):\n        self.close_future = Future()\n        return Application([\n            ('/echo', EchoHandler, dict(close_future=self.close_future)),\n            ('/non_ws', NonWebSocketHandler),\n            ('/header', HeaderHandler, dict(close_future=self.close_future)),\n            ('/close_reason', CloseReasonHandler,\n             dict(close_future=self.close_future)),\n        ])\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop)\n        ws.write_message('hello')\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop, callback=self.stop)\n        ws = self.wait().result()\n        ws.write_message('hello')\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, 'hello')\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(\n                'ws://localhost:%d/notfound' % self.get_http_port(),\n                io_loop=self.io_loop)\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield websocket_connect(\n                'ws://localhost:%d/non_ws' % self.get_http_port(),\n                io_loop=self.io_loop)\n\n    @skipOnTravis\n    @gen_test\n    def test_websocket_network_timeout(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=0.01)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=3600)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.write_message('hello')\n        ws.write_message('world')\n        ws.stream.close()\n        yield self.close_future\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest('ws://localhost:%d/header' % self.get_http_port(),\n                        headers={'X-Test': 'hello'}))\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/close_reason' % self.get_http_port())\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.close(1001, 'goodbye')\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, 'goodbye')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 62,
                                "end_lineno": 174,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/websocket_test.py",
                            "type": "class",
                            "name": "WebSocketTest",
                            "content": "class WebSocketTest(AsyncHTTPTestCase):\n    def get_app(self):\n        self.close_future = Future()\n        return Application([\n            ('/echo', EchoHandler, dict(close_future=self.close_future)),\n            ('/non_ws', NonWebSocketHandler),\n            ('/header', HeaderHandler, dict(close_future=self.close_future)),\n            ('/close_reason', CloseReasonHandler,\n             dict(close_future=self.close_future)),\n        ])\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop)\n        ws.write_message('hello')\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop, callback=self.stop)\n        ws = self.wait().result()\n        ws.write_message('hello')\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, 'hello')\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(\n                'ws://localhost:%d/notfound' % self.get_http_port(),\n                io_loop=self.io_loop)\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield websocket_connect(\n                'ws://localhost:%d/non_ws' % self.get_http_port(),\n                io_loop=self.io_loop)\n\n    @skipOnTravis\n    @gen_test\n    def test_websocket_network_timeout(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=0.01)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=3600)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.write_message('hello')\n        ws.write_message('world')\n        ws.stream.close()\n        yield self.close_future\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest('ws://localhost:%d/header' % self.get_http_port(),\n                        headers={'X-Test': 'hello'}))\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/close_reason' % self.get_http_port())\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.close(1001, 'goodbye')\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, 'goodbye')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 62,
                            "end_lineno": 174,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/websocket_test.py",
                            "type": "method",
                            "name": "WebSocketTest.test_websocket_network_fail",
                            "content": "class WebSocketTest(AsyncHTTPTestCase):\n    def get_app(self):\n        self.close_future = Future()\n        return Application([\n            ('/echo', EchoHandler, dict(close_future=self.close_future)),\n            ('/non_ws', NonWebSocketHandler),\n            ('/header', HeaderHandler, dict(close_future=self.close_future)),\n            ('/close_reason', CloseReasonHandler,\n             dict(close_future=self.close_future)),\n        ])\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop)\n        ws.write_message('hello')\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop, callback=self.stop)\n        ws = self.wait().result()\n        ws.write_message('hello')\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, 'hello')\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(\n                'ws://localhost:%d/notfound' % self.get_http_port(),\n                io_loop=self.io_loop)\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield websocket_connect(\n                'ws://localhost:%d/non_ws' % self.get_http_port(),\n                io_loop=self.io_loop)\n\n    @skipOnTravis\n    @gen_test\n    def test_websocket_network_timeout(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=0.01)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=3600)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.write_message('hello')\n        ws.write_message('world')\n        ws.stream.close()\n        yield self.close_future\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest('ws://localhost:%d/header' % self.get_http_port(),\n                        headers={'X-Test': 'hello'}))\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/close_reason' % self.get_http_port())\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.close(1001, 'goodbye')\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, 'goodbye')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 126,
                            "end_lineno": 135,
                            "parent": {
                                "file_name": "tornado/test/websocket_test.py",
                                "type": "class",
                                "name": "WebSocketTest",
                                "content": "class WebSocketTest(AsyncHTTPTestCase):\n    def get_app(self):\n        self.close_future = Future()\n        return Application([\n            ('/echo', EchoHandler, dict(close_future=self.close_future)),\n            ('/non_ws', NonWebSocketHandler),\n            ('/header', HeaderHandler, dict(close_future=self.close_future)),\n            ('/close_reason', CloseReasonHandler,\n             dict(close_future=self.close_future)),\n        ])\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop)\n        ws.write_message('hello')\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop, callback=self.stop)\n        ws = self.wait().result()\n        ws.write_message('hello')\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, 'hello')\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(\n                'ws://localhost:%d/notfound' % self.get_http_port(),\n                io_loop=self.io_loop)\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield websocket_connect(\n                'ws://localhost:%d/non_ws' % self.get_http_port(),\n                io_loop=self.io_loop)\n\n    @skipOnTravis\n    @gen_test\n    def test_websocket_network_timeout(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=0.01)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(HTTPError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=3600)\n        self.assertEqual(cm.exception.code, 599)\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.write_message('hello')\n        ws.write_message('world')\n        ws.stream.close()\n        yield self.close_future\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest('ws://localhost:%d/header' % self.get_http_port(),\n                        headers={'X-Test': 'hello'}))\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/close_reason' % self.get_http_port())\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.close(1001, 'goodbye')\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, 'goodbye')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 62,
                                "end_lineno": 174,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "292f8fd618befb8cfbf7c307f50a25b19f9e4b77^",
    "new_commit_hash": "292f8fd618befb8cfbf7c307f50a25b19f9e4b77",
    "commit_message": "Changed tornado/simple_httpclient.py to raise the error instead of\nstoring the error message and then raising an HTTPError. \nChanged the websocket tests for network_fail and network timeout to\nexpect an IOError instead of an HTTPError.",
    "commit_date": "2014-05-04T23:52:05+05:30",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "292f8fd618befb8cfbf7c307f50a25b19f9e4b77",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function, with_statement\n\nimport traceback\n\nfrom tornado.concurrent import Future\nfrom tornado.httpclient import HTTPError, HTTPRequest\nfrom tornado.log import gen_log\nfrom tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler\n\ntry:\n    import tornado.websocket\nexcept ImportError:\n    # The unittest module presents misleading errors on ImportError\n    # (it acts as if websocket_test could not be found, hiding the underlying\n    # error).  If we get an ImportError here (which could happen due to\n    # TORNADO_EXTENSION=1), print some extra information before failing.\n    traceback.print_exc()\n    raise\n\nfrom tornado.websocket import WebSocketHandler, websocket_connect, WebSocketError, _websocket_mask_python\n\ntry:\n    from tornado import speedups\nexcept ImportError:\n    speedups = None\n\n\nclass TestWebSocketHandler(WebSocketHandler):\n    \"\"\"Base class for testing handlers that exposes the on_close event.\n\n    This allows for deterministic cleanup of the associated socket.\n    \"\"\"\n    def initialize(self, close_future):\n        self.close_future = close_future\n\n    def on_close(self):\n        self.close_future.set_result((self.close_code, self.close_reason))\n\n\nclass EchoHandler(TestWebSocketHandler):\n    def on_message(self, message):\n        self.write_message(message, isinstance(message, bytes))\n\n\nclass HeaderHandler(TestWebSocketHandler):\n    def open(self):\n        self.write_message(self.request.headers.get('X-Test', ''))\n\n\nclass NonWebSocketHandler(RequestHandler):\n    def get(self):\n        self.write('ok')\n\n\nclass CloseReasonHandler(TestWebSocketHandler):\n    def open(self):\n        self.close(1001, \"goodbye\")\n\n\nclass WebSocketTest(AsyncHTTPTestCase):\n    def get_app(self):\n        self.close_future = Future()\n        return Application([\n            ('/echo', EchoHandler, dict(close_future=self.close_future)),\n            ('/non_ws', NonWebSocketHandler),\n            ('/header', HeaderHandler, dict(close_future=self.close_future)),\n            ('/close_reason', CloseReasonHandler,\n             dict(close_future=self.close_future)),\n        ])\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop)\n        ws.write_message('hello')\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port(),\n            io_loop=self.io_loop, callback=self.stop)\n        ws = self.wait().result()\n        ws.write_message('hello')\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, 'hello')\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(\n                'ws://localhost:%d/notfound' % self.get_http_port(),\n                io_loop=self.io_loop)\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield websocket_connect(\n                'ws://localhost:%d/non_ws' % self.get_http_port(),\n                io_loop=self.io_loop)\n\n    @skipOnTravis\n    @gen_test\n    def test_websocket_network_timeout(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=0.01)\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError) as cm:\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    'ws://localhost:%d/' % port,\n                    io_loop=self.io_loop,\n                    connect_timeout=3600)\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.write_message('hello')\n        ws.write_message('world')\n        ws.stream.close()\n        yield self.close_future\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest('ws://localhost:%d/header' % self.get_http_port(),\n                        headers={'X-Test': 'hello'}))\n        response = yield ws.read_message()\n        self.assertEqual(response, 'hello')\n        ws.close()\n        yield self.close_future\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/close_reason' % self.get_http_port())\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield websocket_connect(\n            'ws://localhost:%d/echo' % self.get_http_port())\n        ws.close(1001, 'goodbye')\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, 'goodbye')\n\n\nclass MaskFunctionMixin(object):\n    # Subclasses should define self.mask(mask, data)\n    def test_mask(self):\n        self.assertEqual(self.mask(b'abcd', b''), b'')\n        self.assertEqual(self.mask(b'abcd', b'b'), b'\\x03')\n        self.assertEqual(self.mask(b'abcd', b'54321'), b'TVPVP')\n        self.assertEqual(self.mask(b'ZXCV', b'98765432'), b'c`t`olpd')\n        # Include test cases with \\x00 bytes (to ensure that the C\n        # extension isn't depending on null-terminated strings) and\n        # bytes with the high bit set (to smoke out signedness issues).\n        self.assertEqual(self.mask(b'\\x00\\x01\\x02\\x03',\n                                   b'\\xff\\xfb\\xfd\\xfc\\xfe\\xfa'),\n                         b'\\xff\\xfa\\xff\\xff\\xfe\\xfb')\n        self.assertEqual(self.mask(b'\\xff\\xfb\\xfd\\xfc',\n                                   b'\\x00\\x01\\x02\\x03\\x04\\x05'),\n                         b'\\xff\\xfa\\xff\\xff\\xfb\\xfe')\n\n\nclass PythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return _websocket_mask_python(mask, data)\n\n\n@unittest.skipIf(speedups is None, \"tornado.speedups module not present\")\nclass CythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return speedups.websocket_mask(mask, data)\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 1.03s\nPrepared 1 package in 987ms\nInstalled 1 package in 11ms\n + tornado==3.3.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77)\nResolved 29 packages in 17ms\nInstalled 29 packages in 127ms\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_292f8fd618befb8cfbf7c307f50a25b19f9e4b77\n............\ncollected 12 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::CythonMaskFunctionTest::test_mask\nPASSED r2e_tests.test_1::PythonMaskFunctionTest::test_mask\nPASSED r2e_tests.test_1::WebSocketTest::test_client_close_reason\nPASSED r2e_tests.test_1::WebSocketTest::test_server_close_reason\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_callbacks\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_close_buffered_data\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_gen\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_headers\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_http_fail\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_http_success\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_network_fail\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_network_timeout\n=================== 12 passed in 0.02s ===================\n",
    "new_commit_res_stderr": "WARNING:tornado.access:404 GET /notfound (127.0.0.1) 0.27ms\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77\n............\ncollected 12 items\n\n=================================== ERRORS =====================================\n__________ WebSocketTest.test_websocket_network_fail __________\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_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/testing.py\", line 118, in __call__\n    result = self.orig_method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/testing.py\", line 486, in post_coroutine\n    return self.io_loop.run_sync(\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/ioloop.py\", line 415, in run_sync\n    return future_cell[0].result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/concurrent.py\", line 79, in result\n    raise_exc_info(self._exc_info)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/gen.py\", line 505, in run\n    yielded = self.gen.throw(*sys.exc_info())\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/r2e_tests/test_1.py\", line 130, in test_websocket_network_fail\n    yield websocket_connect(\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/gen.py\", line 502, in run\n    value = future.result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/concurrent.py\", line 81, in result\n    raise self._exception\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/stack_context.py\", line 314, in wrapped\n    ret = fn(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/websocket.py\", line 853, in _on_close\n    super(WebSocketClientConnection, self)._on_close()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/simple_httpclient.py\", line 375, in _on_close\n    raise HTTPError(599, message)\ntornado.httpclient.HTTPError: HTTP 599: [Errno 111] Connection refused\n__________ WebSocketTest.test_websocket_network_timeout __________\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_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/testing.py\", line 118, in __call__\n    result = self.orig_method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/testing.py\", line 486, in post_coroutine\n    return self.io_loop.run_sync(\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/ioloop.py\", line 415, in run_sync\n    return future_cell[0].result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/concurrent.py\", line 79, in result\n    raise_exc_info(self._exc_info)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/gen.py\", line 505, in run\n    yielded = self.gen.throw(*sys.exc_info())\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/r2e_tests/test_1.py\", line 119, in test_websocket_network_timeout\n    yield websocket_connect(\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/gen.py\", line 502, in run\n    value = future.result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/concurrent.py\", line 81, in result\n    raise self._exception\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/stack_context.py\", line 314, in wrapped\n    ret = fn(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/websocket.py\", line 853, in _on_close\n    super(WebSocketClientConnection, self)._on_close()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_292f8fd618befb8cfbf7c307f50a25b19f9e4b77/tornado/simple_httpclient.py\", line 375, in _on_close\n    raise HTTPError(599, message)\ntornado.httpclient.HTTPError: HTTP 599: [Errno 111] Connection refused\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::CythonMaskFunctionTest::test_mask\nPASSED r2e_tests.test_1::PythonMaskFunctionTest::test_mask\nPASSED r2e_tests.test_1::WebSocketTest::test_client_close_reason\nPASSED r2e_tests.test_1::WebSocketTest::test_server_close_reason\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_callbacks\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_close_buffered_data\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_gen\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_headers\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_http_fail\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_http_success\nERROR r2e_tests.test_1::WebSocketTest::test_websocket_network_fail\nERROR r2e_tests.test_1::WebSocketTest::test_websocket_network_timeout\n=================== 2 errors, 10 passed in 0.01s ===================\n",
    "old_commit_res_stderr": "WARNING:tornado.access:404 GET /notfound (127.0.0.1) 0.19ms\n"
}
tornado/simple_httpclient.py tornado/test/websocket_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** WebSocket network failures raise HTTPError instead of IOError

**Description:**
When a WebSocket connection experiences a network failure or timeout, it incorrectly raises an `HTTPError` instead of an `IOError`. This unexpected exception type disrupts proper error handling for network-related issues.

**Example Code:**
```python
sock, port = bind_unused_port()
sock.close()
with self.assertRaises(IOError):
    websocket_connect(f'ws://localhost:{port}/', io_loop=self.io_loop, connect_timeout=3600)
```

**Expected Behavior:**
An `IOError` should be raised to indicate a network failure, allowing developers to handle such exceptions appropriately.

**Actual Behavior:**
An `HTTPError` with a status code (e.g., 599) and a message like "[Errno 111] Connection refused" is raised instead of an `IOError`. This causes tests expecting an `IOError` to fail, leading to confusion and improper error handling in applications.

[/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/simple_httpclient.py
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, with_statement

from tornado.escape import utf8, _unicode, native_str
from tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy
from tornado.httputil import HTTPHeaders
from tornado.iostream import IOStream, SSLIOStream
from tornado.netutil import Resolver, OverrideResolver
from tornado.log import gen_log
from tornado import stack_context
from tornado.util import GzipDecompressor

import base64
import collections
import copy
import functools
import os.path
import re
import socket
import ssl
import sys

try:
    from io import BytesIO  # python 3
except ImportError:
    from cStringIO import StringIO as BytesIO  # python 2

try:
    import urlparse  # py2
except ImportError:
    import urllib.parse as urlparse  # py3

_DEFAULT_CA_CERTS = os.path.dirname(__file__) + '/ca-certificates.crt'


class SimpleAsyncHTTPClient(AsyncHTTPClient):
    """Non-blocking HTTP client with no external dependencies.

    This class implements an HTTP 1.1 client on top of Tornado's IOStreams.
    It does not currently implement all applicable parts of the HTTP
    specification, but it does enough to work with major web service APIs.

    Some features found in the curl-based AsyncHTTPClient are not yet
    supported.  In particular, proxies are not supported, connections
    are not reused, and callers cannot select the network interface to be
    used.
    """
    def initialize(self, io_loop, max_clients=10,
                   hostname_mapping=None, max_buffer_size=104857600,
                   resolver=None, defaults=None):
        """Creates a AsyncHTTPClient.

        Only a single AsyncHTTPClient instance exists per IOLoop
        in order to provide limitations on the number of pending connections.
        force_instance=True may be used to suppress this behavior.

        max_clients is the number of concurrent requests that can be
        in progress.  Note that this arguments are only used when the
        client is first created, and will be ignored when an existing
        client is reused.

        hostname_mapping is a dictionary mapping hostnames to IP addresses.
        It can be used to make local DNS changes when modifying system-wide
        settings like /etc/hosts is not possible or desirable (e.g. in
        unittests).

        max_buffer_size is the number of bytes that can be read by IOStream. It
        defaults to 100mb.
        """
        super(SimpleAsyncHTTPClient, self).initialize(io_loop,
                                                      defaults=defaults)
        self.max_clients = max_clients
        self.queue = collections.deque()
        self.active = {}
        self.waiting = {}
        self.max_buffer_size = max_buffer_size
        if resolver:
            self.resolver = resolver
            self.own_resolver = False
        else:
            self.resolver = Resolver(io_loop=io_loop)
            self.own_resolver = True
        if hostname_mapping is not None:
            self.resolver = OverrideResolver(resolver=self.resolver,
                                             mapping=hostname_mapping)

    def close(self):
        super(SimpleAsyncHTTPClient, self).close()
        if self.own_resolver:
            self.resolver.close()

    def fetch_impl(self, request, callback):
        key = object()
        self.queue.append((key, request, callback))
        if not len(self.active) < self.max_clients:
            timeout_handle = self.io_loop.add_timeout(
                self.io_loop.time() + min(request.connect_timeout,
                                          request.request_timeout),
                functools.partial(self._on_timeout, key))
        else:
            timeout_handle = None
        self.waiting[key] = (request, callback, timeout_handle)
        self._process_queue()
        if self.queue:
            gen_log.debug("max_clients limit reached, request queued. "
                          "%d active, %d queued requests." % (
                              len(self.active), len(self.queue)))

    def _process_queue(self):
        with stack_context.NullContext():
            while self.queue and len(self.active) < self.max_clients:
                key, request, callback = self.queue.popleft()
                if key not in self.waiting:
                    continue
                self._remove_timeout(key)
                self.active[key] = (request, callback)
                release_callback = functools.partial(self._release_fetch, key)
                self._handle_request(request, release_callback, callback)

    def _handle_request(self, request, release_callback, final_callback):
        _HTTPConnection(self.io_loop, self, request, release_callback,
                        final_callback, self.max_buffer_size, self.resolver)

    def _release_fetch(self, key):
        del self.active[key]
        self._process_queue()

    def _remove_timeout(self, key):
        if key in self.waiting:
            request, callback, timeout_handle = self.waiting[key]
            if timeout_handle is not None:
                self.io_loop.remove_timeout(timeout_handle)
            del self.waiting[key]

    def _on_timeout(self, key):
        request, callback, timeout_handle = self.waiting[key]
        self.queue.remove((key, request, callback))
        timeout_response = HTTPResponse(
            request, 599, error=HTTPError(599, "Timeout"),
            request_time=self.io_loop.time() - request.start_time)
        self.io_loop.add_callback(callback, timeout_response)
        del self.waiting[key]


class _HTTPConnection(object):
    _SUPPORTED_METHODS = set(["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])

    def __init__(self, io_loop, client, request, release_callback,
                 final_callback, max_buffer_size, resolver):
        self.start_time = io_loop.time()
        self.io_loop = io_loop
        self.client = client
        self.request = request
        self.release_callback = release_callback
        self.final_callback = final_callback
        self.max_buffer_size = max_buffer_size
        self.resolver = resolver
        self.code = None
        self.headers = None
        self.chunks = None
        self._decompressor = None
        # Timeout handle returned by IOLoop.add_timeout
        self._timeout = None
        with stack_context.ExceptionStackContext(self._handle_exception):
            self.parsed = urlparse.urlsplit(_unicode(self.request.url))
            if self.parsed.scheme not in ("http", "https"):
                raise ValueError("Unsupported url scheme: %s" %
                                 self.request.url)
            # urlsplit results have hostname and port results, but they
            # didn't support ipv6 literals until python 2.7.
            netloc = self.parsed.netloc
            if "@" in netloc:
                userpass, _, netloc = netloc.rpartition("@")
            match = re.match(r'^(.+):(\d+)$', netloc)
            if match:
                host = match.group(1)
                port = int(match.group(2))
            else:
                host = netloc
                port = 443 if self.parsed.scheme == "https" else 80
            if re.match(r'^\[.*\]$', host):
                # raw ipv6 addresses in urls are enclosed in brackets
                host = host[1:-1]
            self.parsed_hostname = host  # save final host for _on_connect

            if request.allow_ipv6:
                af = socket.AF_UNSPEC
            else:
                # We only try the first IP we get from getaddrinfo,
                # so restrict to ipv4 by default.
                af = socket.AF_INET

            timeout = min(self.request.connect_timeout, self.request.request_timeout)
            if timeout:
                self._timeout = self.io_loop.add_timeout(
                    self.start_time + timeout,
                    stack_context.wrap(self._on_timeout))
            self.resolver.resolve(host, port, af, callback=self._on_resolve)

    def _on_resolve(self, addrinfo):
        if self.final_callback is None:
            # final_callback is cleared if we've hit our timeout
            return
        self.stream = self._create_stream(addrinfo)
        self.stream.set_close_callback(self._on_close)
        # ipv6 addresses are broken (in self.parsed.hostname) until
        # 2.7, here is correctly parsed value calculated in __init__
        sockaddr = addrinfo[0][1]
        self.stream.connect(sockaddr, self._on_connect,
                            server_hostname=self.parsed_hostname)

    def _create_stream(self, addrinfo):
        af = addrinfo[0][0]
        if self.parsed.scheme == "https":
            ssl_options = {}
            if self.request.validate_cert:
                ssl_options["cert_reqs"] = ssl.CERT_REQUIRED
            if self.request.ca_certs is not None:
                ssl_options["ca_certs"] = self.request.ca_certs
            else:
                ssl_options["ca_certs"] = _DEFAULT_CA_CERTS
            if self.request.client_key is not None:
                ssl_options["keyfile"] = self.request.client_key
            if self.request.client_cert is not None:
                ssl_options["certfile"] = self.request.client_cert

            # SSL interoperability is tricky.  We want to disable
            # SSLv2 for security reasons; it wasn't disabled by default
            # until openssl 1.0.  The best way to do this is to use
            # the SSL_OP_NO_SSLv2, but that wasn't exposed to python
            # until 3.2.  Python 2.7 adds the ciphers argument, which
            # can also be used to disable SSLv2.  As a last resort
            # on python 2.6, we set ssl_version to TLSv1.  This is
            # more narrow than we'd like since it also breaks
            # compatibility with servers configured for SSLv3 only,
            # but nearly all servers support both SSLv3 and TLSv1:
            # http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html
            if sys.version_info >= (2, 7):
                # In addition to disabling SSLv2, we also exclude certain
                # classes of insecure ciphers.
                ssl_options["ciphers"] = "DEFAULT:!SSLv2:!EXPORT:!DES"
            else:
                # This is really only necessary for pre-1.0 versions
                # of openssl, but python 2.6 doesn't expose version
                # information.
                ssl_options["ssl_version"] = ssl.PROTOCOL_TLSv1

            return SSLIOStream(socket.socket(af),
                               io_loop=self.io_loop,
                               ssl_options=ssl_options,
                               max_buffer_size=self.max_buffer_size)
        else:
            return IOStream(socket.socket(af),
                            io_loop=self.io_loop,
                            max_buffer_size=self.max_buffer_size)

    def _on_timeout(self):
        self._timeout = None
        if self.final_callback is not None:
            raise HTTPError(599, "Timeout")

    def _remove_timeout(self):
        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

    def _on_connect(self):
        self._remove_timeout()
        if self.final_callback is None:
            return
        if self.request.request_timeout:
            self._timeout = self.io_loop.add_timeout(
                self.start_time + self.request.request_timeout,
                stack_context.wrap(self._on_timeout))
        if (self.request.method not in self._SUPPORTED_METHODS and
                not self.request.allow_nonstandard_methods):
            raise KeyError("unknown method %s" % self.request.method)
        for key in ('network_interface',
                    'proxy_host', 'proxy_port',
                    'proxy_username', 'proxy_password'):
            if getattr(self.request, key, None):
                raise NotImplementedError('%s not supported' % key)
        if "Connection" not in self.request.headers:
            self.request.headers["Connection"] = "close"
        if "Host" not in self.request.headers:
            if '@' in self.parsed.netloc:
                self.request.headers["Host"] = self.parsed.netloc.rpartition('@')[-1]
            else:
                self.request.headers["Host"] = self.parsed.netloc
        username, password = None, None
        if self.parsed.username is not None:
            username, password = self.parsed.username, self.parsed.password
        elif self.request.auth_username is not None:
            username = self.request.auth_username
            password = self.request.auth_password or ''
        if username is not None:
            if self.request.auth_mode not in (None, "basic"):
                raise ValueError("unsupported auth_mode %s",
                                 self.request.auth_mode)
            auth = utf8(username) + b":" + utf8(password)
            self.request.headers["Authorization"] = (b"Basic " +
                                                     base64.b64encode(auth))
        if self.request.user_agent:
            self.request.headers["User-Agent"] = self.request.user_agent
        if not self.request.allow_nonstandard_methods:
            if self.request.method in ("POST", "PATCH", "PUT"):
                if self.request.body is None:
                    raise AssertionError(
                        'Body must not be empty for "%s" request'
                        % self.request.method)
            else:
                if self.request.body is not None:
                    raise AssertionError(
                        'Body must be empty for "%s" request'
                        % self.request.method)
        if self.request.body is not None:
            self.request.headers["Content-Length"] = str(len(
                self.request.body))
        if (self.request.method == "POST" and
                "Content-Type" not in self.request.headers):
            self.request.headers["Content-Type"] = "application/x-www-form-urlencoded"
        if self.request.use_gzip:
            self.request.headers["Accept-Encoding"] = "gzip"
        req_path = ((self.parsed.path or '/') +
                   (('?' + self.parsed.query) if self.parsed.query else ''))
        request_lines = [utf8("%s %s HTTP/1.1" % (self.request.method,
                                                  req_path))]
        for k, v in self.request.headers.get_all():
            line = utf8(k) + b": " + utf8(v)
            if b'\n' in line:
                raise ValueError('Newline in header: ' + repr(line))
            request_lines.append(line)
        request_str = b"\r\n".join(request_lines) + b"\r\n\r\n"
        if self.request.body is not None:
            request_str += self.request.body
        self.stream.set_nodelay(True)
        self.stream.write(request_str)
        self.stream.read_until_regex(b"\r?\n\r?\n", self._on_headers)

    def _release(self):
        if self.release_callback is not None:
            release_callback = self.release_callback
            self.release_callback = None
            release_callback()

    def _run_callback(self, response):
        self._release()
        if self.final_callback is not None:
            final_callback = self.final_callback
            self.final_callback = None
            self.io_loop.add_callback(final_callback, response)

    def _handle_exception(self, typ, value, tb):
        if self.final_callback:
            self._remove_timeout()
            self._run_callback(HTTPResponse(self.request, 599, error=value,
                                            request_time=self.io_loop.time() - self.start_time,
                                            ))

            if hasattr(self, "stream"):
                self.stream.close()
            return True
        else:
            # If our callback has already been called, we are probably
            # catching an exception that is not caused by us but rather
            # some child of our callback. Rather than drop it on the floor,
            # pass it along.
            return False

    def _on_close(self):
        if self.final_callback is not None:
            message = "Connection closed"
            if self.stream.error:
                message = str(self.stream.error)
            raise HTTPError(599, message)

    def _handle_1xx(self, code):
        self.stream.read_until_regex(b"\r?\n\r?\n", self._on_headers)

    def _on_headers(self, data):
        data = native_str(data.decode("latin1"))
        first_line, _, header_data = data.partition("\n")
        match = re.match("HTTP/1.[01] ([0-9]+) ([^\r]*)", first_line)
        assert match
        code = int(match.group(1))
        self.headers = HTTPHeaders.parse(header_data)
        if 100 <= code < 200:
            self._handle_1xx(code)
            return
        else:
            self.code = code
            self.reason = match.group(2)

        if "Content-Length" in self.headers:
            if "," in self.headers["Content-Length"]:
                # Proxies sometimes cause Content-Length headers to get
                # duplicated.  If all the values are identical then we can
                # use them but if they differ it's an error.
                pieces = re.split(r',\s*', self.headers["Content-Length"])
                if any(i != pieces[0] for i in pieces):
                    raise ValueError("Multiple unequal Content-Lengths: %r" %
                                     self.headers["Content-Length"])
                self.headers["Content-Length"] = pieces[0]
            content_length = int(self.headers["Content-Length"])
        else:
            content_length = None

        if self.request.header_callback is not None:
            # re-attach the newline we split on earlier
            self.request.header_callback(first_line + _)
            for k, v in self.headers.get_all():
                self.request.header_callback("%s: %s\r\n" % (k, v))
            self.request.header_callback('\r\n')

        if self.request.method == "HEAD" or self.code == 304:
            # HEAD requests and 304 responses never have content, even
            # though they may have content-length headers
            self._on_body(b"")
            return
        if 100 <= self.code < 200 or self.code == 204:
            # These response codes never have bodies
            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
            if ("Transfer-Encoding" in self.headers or
                    content_length not in (None, 0)):
                raise ValueError("Response with code %d should not have body" %
                                 self.code)
            self._on_body(b"")
            return

        if (self.request.use_gzip and
                self.headers.get("Content-Encoding") == "gzip"):
            self._decompressor = GzipDecompressor()
        if self.headers.get("Transfer-Encoding") == "chunked":
            self.chunks = []
            self.stream.read_until(b"\r\n", self._on_chunk_length)
        elif content_length is not None:
            self.stream.read_bytes(content_length, self._on_body)
        else:
            self.stream.read_until_close(self._on_body)

    def _on_body(self, data):
        self._remove_timeout()
        original_request = getattr(self.request, "original_request",
                                   self.request)
        if (self.request.follow_redirects and
            self.request.max_redirects > 0 and
                self.code in (301, 302, 303, 307)):
            assert isinstance(self.request, _RequestProxy)
            new_request = copy.copy(self.request.request)
            new_request.url = urlparse.urljoin(self.request.url,
                                               self.headers["Location"])
            new_request.max_redirects = self.request.max_redirects - 1
            del new_request.headers["Host"]
            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
            # Client SHOULD make a GET request after a 303.
            # According to the spec, 302 should be followed by the same
            # method as the original request, but in practice browsers
            # treat 302 the same as 303, and many servers use 302 for
            # compatibility with pre-HTTP/1.1 user agents which don't
            # understand the 303 status.
            if self.code in (302, 303):
                new_request.method = "GET"
                new_request.body = None
                for h in ["Content-Length", "Content-Type",
                          "Content-Encoding", "Transfer-Encoding"]:
                    try:
                        del self.request.headers[h]
                    except KeyError:
                        pass
            new_request.original_request = original_request
            final_callback = self.final_callback
            self.final_callback = None
            self._release()
            self.client.fetch(new_request, final_callback)
            self._on_end_request()
            return
        if self._decompressor:
            data = (self._decompressor.decompress(data) +
                    self._decompressor.flush())
        if self.request.streaming_callback:
            if self.chunks is None:
                # if chunks is not None, we already called streaming_callback
                # in _on_chunk_data
                self.request.streaming_callback(data)
            buffer = BytesIO()
        else:
            buffer = BytesIO(data)  # TODO: don't require one big string?
        response = HTTPResponse(original_request,
                                self.code, reason=self.reason,
                                headers=self.headers,
                                request_time=self.io_loop.time() - self.start_time,
                                buffer=buffer,
                                effective_url=self.request.url)
        self._run_callback(response)
        self._on_end_request()

    def _on_end_request(self):
        self.stream.close()

    def _on_chunk_length(self, data):
        # TODO: "chunk extensions" http://tools.ietf.org/html/rfc2616#section-3.6.1
        length = int(data.strip(), 16)
        if length == 0:
            if self._decompressor is not None:
                tail = self._decompressor.flush()
                if tail:
                    # I believe the tail will always be empty (i.e.
                    # decompress will return all it can).  The purpose
                    # of the flush call is to detect errors such
                    # as truncated input.  But in case it ever returns
                    # anything, treat it as an extra chunk
                    if self.request.streaming_callback is not None:
                        self.request.streaming_callback(tail)
                    else:
                        self.chunks.append(tail)
                # all the data has been decompressed, so we don't need to
                # decompress again in _on_body
                self._decompressor = None
            self._on_body(b''.join(self.chunks))
        else:
            self.stream.read_bytes(length + 2,  # chunk ends with \r\n
                                   self._on_chunk_data)

    def _on_chunk_data(self, data):
        assert data[-2:] == b"\r\n"
        chunk = data[:-2]
        if self._decompressor:
            chunk = self._decompressor.decompress(chunk)
        if self.request.streaming_callback is not None:
            self.request.streaming_callback(chunk)
        else:
            self.chunks.append(chunk)
        self.stream.read_until(b"\r\n", self._on_chunk_length)


if __name__ == "__main__":
    AsyncHTTPClient.configure(SimpleAsyncHTTPClient)
    main()

```
--- END FILE ---

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

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

Here is an example:

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

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** WebSocket network failures raise HTTPError instead of IOError

**Description:**
When a WebSocket connection experiences a network failure or timeout, it incorrectly raises an `HTTPError` instead of an `IOError`. This unexpected exception type disrupts proper error handling for network-related issues.

**Example Code:**
```python
sock, port = bind_unused_port()
sock.close()
with self.assertRaises(IOError):
    websocket_connect(f'ws://localhost:{port}/', io_loop=self.io_loop, connect_timeout=3600)
```

**Expected Behavior:**
An `IOError` should be raised to indicate a network failure, allowing developers to handle such exceptions appropriately.

**Actual Behavior:**
An `HTTPError` with a status code (e.g., 599) and a message like "[Errno 111] Connection refused" is raised instead of an `IOError`. This causes tests expecting an `IOError` to fail, leading to confusion and improper error handling in applications.

[/ISSUE]
{
    "CythonMaskFunctionTest.test_mask": "PASSED",
    "PythonMaskFunctionTest.test_mask": "PASSED",
    "WebSocketTest.test_client_close_reason": "PASSED",
    "WebSocketTest.test_server_close_reason": "PASSED",
    "WebSocketTest.test_websocket_callbacks": "PASSED",
    "WebSocketTest.test_websocket_close_buffered_data": "PASSED",
    "WebSocketTest.test_websocket_gen": "PASSED",
    "WebSocketTest.test_websocket_headers": "PASSED",
    "WebSocketTest.test_websocket_http_fail": "PASSED",
    "WebSocketTest.test_websocket_http_success": "PASSED",
    "WebSocketTest.test_websocket_network_fail": "PASSED",
    "WebSocketTest.test_websocket_network_timeout": "PASSED"
}
diff --git a/tornado/simple_httpclient.py b/tornado/simple_httpclient.py
index c7e6f1a9..d5b98061 100644
--- a/tornado/simple_httpclient.py
+++ b/tornado/simple_httpclient.py
@@ -371,7 +371,7 @@ class _HTTPConnection(object):
         if self.final_callback is not None:
             message = "Connection closed"
             if self.stream.error:
-                message = str(self.stream.error)
+                raise self.stream.error
             raise HTTPError(599, message)
 
     def _handle_1xx(self, code):

{"tornado/simple_httpclient.py": "#!/usr/bin/env python\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nfrom tornado.escape import utf8, _unicode, native_str\nfrom tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy\nfrom tornado.httputil import HTTPHeaders\nfrom tornado.iostream import IOStream, SSLIOStream\nfrom tornado.netutil import Resolver, OverrideResolver\nfrom tornado.log import gen_log\nfrom tornado import stack_context\nfrom tornado.util import GzipDecompressor\n\nimport base64\nimport collections\nimport copy\nimport functools\nimport os.path\nimport re\nimport socket\nimport ssl\nimport sys\n\ntry:\n    from io import BytesIO  # python 3\nexcept ImportError:\n    from cStringIO import StringIO as BytesIO  # python 2\n\ntry:\n    import urlparse  # py2\nexcept ImportError:\n    import urllib.parse as urlparse  # py3\n\n_DEFAULT_CA_CERTS = os.path.dirname(__file__) + '/ca-certificates.crt'\n\n\nclass SimpleAsyncHTTPClient(AsyncHTTPClient):\n    \"\"\"Non-blocking HTTP client with no external dependencies.\n\n    This class implements an HTTP 1.1 client on top of Tornado's IOStreams.\n    It does not currently implement all applicable parts of the HTTP\n    specification, but it does enough to work with major web service APIs.\n\n    Some features found in the curl-based AsyncHTTPClient are not yet\n    supported.  In particular, proxies are not supported, connections\n    are not reused, and callers cannot select the network interface to be\n    used.\n    \"\"\"\n    def initialize(self, io_loop, max_clients=10,\n                   hostname_mapping=None, max_buffer_size=104857600,\n                   resolver=None, defaults=None):\n        \"\"\"Creates a AsyncHTTPClient.\n\n        Only a single AsyncHTTPClient instance exists per IOLoop\n        in order to provide limitations on the number of pending connections.\n        force_instance=True may be used to suppress this behavior.\n\n        max_clients is the number of concurrent requests that can be\n        in progress.  Note that this arguments are only used when the\n        client is first created, and will be ignored when an existing\n        client is reused.\n\n        hostname_mapping is a dictionary mapping hostnames to IP addresses.\n        It can be used to make local DNS changes when modifying system-wide\n        settings like /etc/hosts is not possible or desirable (e.g. in\n        unittests).\n\n        max_buffer_size is the number of bytes that can be read by IOStream. It\n        defaults to 100mb.\n        \"\"\"\n        super(SimpleAsyncHTTPClient, self).initialize(io_loop,\n                                                      defaults=defaults)\n        self.max_clients = max_clients\n        self.queue = collections.deque()\n        self.active = {}\n        self.waiting = {}\n        self.max_buffer_size = max_buffer_size\n        if resolver:\n            self.resolver = resolver\n            self.own_resolver = False\n        else:\n            self.resolver = Resolver(io_loop=io_loop)\n            self.own_resolver = True\n        if hostname_mapping is not None:\n            self.resolver = OverrideResolver(resolver=self.resolver,\n                                             mapping=hostname_mapping)\n\n    def close(self):\n        super(SimpleAsyncHTTPClient, self).close()\n        if self.own_resolver:\n            self.resolver.close()\n\n    def fetch_impl(self, request, callback):\n        key = object()\n        self.queue.append((key, request, callback))\n        if not len(self.active) < self.max_clients:\n            timeout_handle = self.io_loop.add_timeout(\n                self.io_loop.time() + min(request.connect_timeout,\n                                          request.request_timeout),\n                functools.partial(self._on_timeout, key))\n        else:\n            timeout_handle = None\n        self.waiting[key] = (request, callback, timeout_handle)\n        self._process_queue()\n        if self.queue:\n            gen_log.debug(\"max_clients limit reached, request queued. \"\n                          \"%d active, %d queued requests.\" % (\n                              len(self.active), len(self.queue)))\n\n    def _process_queue(self):\n        with stack_context.NullContext():\n            while self.queue and len(self.active) < self.max_clients:\n                key, request, callback = self.queue.popleft()\n                if key not in self.waiting:\n                    continue\n                self._remove_timeout(key)\n                self.active[key] = (request, callback)\n                release_callback = functools.partial(self._release_fetch, key)\n                self._handle_request(request, release_callback, callback)\n\n    def _handle_request(self, request, release_callback, final_callback):\n        _HTTPConnection(self.io_loop, self, request, release_callback,\n                        final_callback, self.max_buffer_size, self.resolver)\n\n    def _release_fetch(self, key):\n        del self.active[key]\n        self._process_queue()\n\n    def _remove_timeout(self, key):\n        if key in self.waiting:\n            request, callback, timeout_handle = self.waiting[key]\n            if timeout_handle is not None:\n                self.io_loop.remove_timeout(timeout_handle)\n            del self.waiting[key]\n\n    def _on_timeout(self, key):\n        request, callback, timeout_handle = self.waiting[key]\n        self.queue.remove((key, request, callback))\n        timeout_response = HTTPResponse(\n            request, 599, error=HTTPError(599, \"Timeout\"),\n            request_time=self.io_loop.time() - request.start_time)\n        self.io_loop.add_callback(callback, timeout_response)\n        del self.waiting[key]\n\n\nclass _HTTPConnection(object):\n    _SUPPORTED_METHODS = set([\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"])\n\n    def __init__(self, io_loop, client, request, release_callback,\n                 final_callback, max_buffer_size, resolver):\n        self.start_time = io_loop.time()\n        self.io_loop = io_loop\n        self.client = client\n        self.request = request\n        self.release_callback = release_callback\n        self.final_callback = final_callback\n        self.max_buffer_size = max_buffer_size\n        self.resolver = resolver\n        self.code = None\n        self.headers = None\n        self.chunks = None\n        self._decompressor = None\n        # Timeout handle returned by IOLoop.add_timeout\n        self._timeout = None\n        with stack_context.ExceptionStackContext(self._handle_exception):\n            self.parsed = urlparse.urlsplit(_unicode(self.request.url))\n            if self.parsed.scheme not in (\"http\", \"https\"):\n                raise ValueError(\"Unsupported url scheme: %s\" %\n                                 self.request.url)\n            # urlsplit results have hostname and port results, but they\n            # didn't support ipv6 literals until python 2.7.\n            netloc = self.parsed.netloc\n            if \"@\" in netloc:\n                userpass, _, netloc = netloc.rpartition(\"@\")\n            match = re.match(r'^(.+):(\\d+)$', netloc)\n            if match:\n                host = match.group(1)\n                port = int(match.group(2))\n            else:\n                host = netloc\n                port = 443 if self.parsed.scheme == \"https\" else 80\n            if re.match(r'^\\[.*\\]$', host):\n                # raw ipv6 addresses in urls are enclosed in brackets\n                host = host[1:-1]\n            self.parsed_hostname = host  # save final host for _on_connect\n\n            if request.allow_ipv6:\n                af = socket.AF_UNSPEC\n            else:\n                # We only try the first IP we get from getaddrinfo,\n                # so restrict to ipv4 by default.\n                af = socket.AF_INET\n\n            timeout = min(self.request.connect_timeout, self.request.request_timeout)\n            if timeout:\n                self._timeout = self.io_loop.add_timeout(\n                    self.start_time + timeout,\n                    stack_context.wrap(self._on_timeout))\n            self.resolver.resolve(host, port, af, callback=self._on_resolve)\n\n    def _on_resolve(self, addrinfo):\n        if self.final_callback is None:\n            # final_callback is cleared if we've hit our timeout\n            return\n        self.stream = self._create_stream(addrinfo)\n        self.stream.set_close_callback(self._on_close)\n        # ipv6 addresses are broken (in self.parsed.hostname) until\n        # 2.7, here is correctly parsed value calculated in __init__\n        sockaddr = addrinfo[0][1]\n        self.stream.connect(sockaddr, self._on_connect,\n                            server_hostname=self.parsed_hostname)\n\n    def _create_stream(self, addrinfo):\n        af = addrinfo[0][0]\n        if self.parsed.scheme == \"https\":\n            ssl_options = {}\n            if self.request.validate_cert:\n                ssl_options[\"cert_reqs\"] = ssl.CERT_REQUIRED\n            if self.request.ca_certs is not None:\n                ssl_options[\"ca_certs\"] = self.request.ca_certs\n            else:\n                ssl_options[\"ca_certs\"] = _DEFAULT_CA_CERTS\n            if self.request.client_key is not None:\n                ssl_options[\"keyfile\"] = self.request.client_key\n            if self.request.client_cert is not None:\n                ssl_options[\"certfile\"] = self.request.client_cert\n\n            # SSL interoperability is tricky.  We want to disable\n            # SSLv2 for security reasons; it wasn't disabled by default\n            # until openssl 1.0.  The best way to do this is to use\n            # the SSL_OP_NO_SSLv2, but that wasn't exposed to python\n            # until 3.2.  Python 2.7 adds the ciphers argument, which\n            # can also be used to disable SSLv2.  As a last resort\n            # on python 2.6, we set ssl_version to TLSv1.  This is\n            # more narrow than we'd like since it also breaks\n            # compatibility with servers configured for SSLv3 only,\n            # but nearly all servers support both SSLv3 and TLSv1:\n            # http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html\n            if sys.version_info >= (2, 7):\n                # In addition to disabling SSLv2, we also exclude certain\n                # classes of insecure ciphers.\n                ssl_options[\"ciphers\"] = \"DEFAULT:!SSLv2:!EXPORT:!DES\"\n            else:\n                # This is really only necessary for pre-1.0 versions\n                # of openssl, but python 2.6 doesn't expose version\n                # information.\n                ssl_options[\"ssl_version\"] = ssl.PROTOCOL_TLSv1\n\n            return SSLIOStream(socket.socket(af),\n                               io_loop=self.io_loop,\n                               ssl_options=ssl_options,\n                               max_buffer_size=self.max_buffer_size)\n        else:\n            return IOStream(socket.socket(af),\n                            io_loop=self.io_loop,\n                            max_buffer_size=self.max_buffer_size)\n\n    def _on_timeout(self):\n        self._timeout = None\n        if self.final_callback is not None:\n            raise HTTPError(599, \"Timeout\")\n\n    def _remove_timeout(self):\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def _on_connect(self):\n        self._remove_timeout()\n        if self.final_callback is None:\n            return\n        if self.request.request_timeout:\n            self._timeout = self.io_loop.add_timeout(\n                self.start_time + self.request.request_timeout,\n                stack_context.wrap(self._on_timeout))\n        if (self.request.method not in self._SUPPORTED_METHODS and\n                not self.request.allow_nonstandard_methods):\n            raise KeyError(\"unknown method %s\" % self.request.method)\n        for key in ('network_interface',\n                    'proxy_host', 'proxy_port',\n                    'proxy_username', 'proxy_password'):\n            if getattr(self.request, key, None):\n                raise NotImplementedError('%s not supported' % key)\n        if \"Connection\" not in self.request.headers:\n            self.request.headers[\"Connection\"] = \"close\"\n        if \"Host\" not in self.request.headers:\n            if '@' in self.parsed.netloc:\n                self.request.headers[\"Host\"] = self.parsed.netloc.rpartition('@')[-1]\n            else:\n                self.request.headers[\"Host\"] = self.parsed.netloc\n        username, password = None, None\n        if self.parsed.username is not None:\n            username, password = self.parsed.username, self.parsed.password\n        elif self.request.auth_username is not None:\n            username = self.request.auth_username\n            password = self.request.auth_password or ''\n        if username is not None:\n            if self.request.auth_mode not in (None, \"basic\"):\n                raise ValueError(\"unsupported auth_mode %s\",\n                                 self.request.auth_mode)\n            auth = utf8(username) + b\":\" + utf8(password)\n            self.request.headers[\"Authorization\"] = (b\"Basic \" +\n                                                     base64.b64encode(auth))\n        if self.request.user_agent:\n            self.request.headers[\"User-Agent\"] = self.request.user_agent\n        if not self.request.allow_nonstandard_methods:\n            if self.request.method in (\"POST\", \"PATCH\", \"PUT\"):\n                if self.request.body is None:\n                    raise AssertionError(\n                        'Body must not be empty for \"%s\" request'\n                        % self.request.method)\n            else:\n                if self.request.body is not None:\n                    raise AssertionError(\n                        'Body must be empty for \"%s\" request'\n                        % self.request.method)\n        if self.request.body is not None:\n            self.request.headers[\"Content-Length\"] = str(len(\n                self.request.body))\n        if (self.request.method == \"POST\" and\n                \"Content-Type\" not in self.request.headers):\n            self.request.headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n        if self.request.use_gzip:\n            self.request.headers[\"Accept-Encoding\"] = \"gzip\"\n        req_path = ((self.parsed.path or '/') +\n                   (('?' + self.parsed.query) if self.parsed.query else ''))\n        request_lines = [utf8(\"%s %s HTTP/1.1\" % (self.request.method,\n                                                  req_path))]\n        for k, v in self.request.headers.get_all():\n            line = utf8(k) + b\": \" + utf8(v)\n            if b'\\n' in line:\n                raise ValueError('Newline in header: ' + repr(line))\n            request_lines.append(line)\n        request_str = b\"\\r\\n\".join(request_lines) + b\"\\r\\n\\r\\n\"\n        if self.request.body is not None:\n            request_str += self.request.body\n        self.stream.set_nodelay(True)\n        self.stream.write(request_str)\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _release(self):\n        if self.release_callback is not None:\n            release_callback = self.release_callback\n            self.release_callback = None\n            release_callback()\n\n    def _run_callback(self, response):\n        self._release()\n        if self.final_callback is not None:\n            final_callback = self.final_callback\n            self.final_callback = None\n            self.io_loop.add_callback(final_callback, response)\n\n    def _handle_exception(self, typ, value, tb):\n        if self.final_callback:\n            self._remove_timeout()\n            self._run_callback(HTTPResponse(self.request, 599, error=value,\n                                            request_time=self.io_loop.time() - self.start_time,\n                                            ))\n\n            if hasattr(self, \"stream\"):\n                self.stream.close()\n            return True\n        else:\n            # If our callback has already been called, we are probably\n            # catching an exception that is not caused by us but rather\n            # some child of our callback. Rather than drop it on the floor,\n            # pass it along.\n            return False\n\n    def _on_close(self):\n        if self.final_callback is not None:\n            message = \"Connection closed\"\n            if self.stream.error:\n                message = str(self.stream.error)\n            raise HTTPError(599, message)\n\n    def _handle_1xx(self, code):\n        self.stream.read_until_regex(b\"\\r?\\n\\r?\\n\", self._on_headers)\n\n    def _on_headers(self, data):\n        data = native_str(data.decode(\"latin1\"))\n        first_line, _, header_data = data.partition(\"\\n\")\n        match = re.match(\"HTTP/1.[01] ([0-9]+) ([^\\r]*)\", first_line)\n        assert match\n        code = int(match.group(1))\n        self.headers = HTTPHeaders.parse(header_data)\n        if 100 <= code < 200:\n            self._handle_1xx(code)\n            return\n        else:\n            self.code = code\n            self.reason = match.group(2)\n\n        if \"Content-Length\" in self.headers:\n            if \",\" in self.headers[\"Content-Length\"]:\n                # Proxies sometimes cause Content-Length headers to get\n                # duplicated.  If all the values are identical then we can\n                # use them but if they differ it's an error.\n                pieces = re.split(r',\\s*', self.headers[\"Content-Length\"])\n                if any(i != pieces[0] for i in pieces):\n                    raise ValueError(\"Multiple unequal Content-Lengths: %r\" %\n                                     self.headers[\"Content-Length\"])\n                self.headers[\"Content-Length\"] = pieces[0]\n            content_length = int(self.headers[\"Content-Length\"])\n        else:\n            content_length = None\n\n        if self.request.header_callback is not None:\n            # re-attach the newline we split on earlier\n            self.request.header_callback(first_line + _)\n            for k, v in self.headers.get_all():\n                self.request.header_callback(\"%s: %s\\r\\n\" % (k, v))\n            self.request.header_callback('\\r\\n')\n\n        if self.request.method == \"HEAD\" or self.code == 304:\n            # HEAD requests and 304 responses never have content, even\n            # though they may have content-length headers\n            self._on_body(b\"\")\n            return\n        if 100 <= self.code < 200 or self.code == 204:\n            # These response codes never have bodies\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3\n            if (\"Transfer-Encoding\" in self.headers or\n                    content_length not in (None, 0)):\n                raise ValueError(\"Response with code %d should not have body\" %\n                                 self.code)\n            self._on_body(b\"\")\n            return\n\n        if (self.request.use_gzip and\n                self.headers.get(\"Content-Encoding\") == \"gzip\"):\n            self._decompressor = GzipDecompressor()\n        if self.headers.get(\"Transfer-Encoding\") == \"chunked\":\n            self.chunks = []\n            self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)\n        elif content_length is not None:\n            self.stream.read_bytes(content_length, self._on_body)\n        else:\n            self.stream.read_until_close(self._on_body)\n\n    def _on_body(self, data):\n        self._remove_timeout()\n        original_request = getattr(self.request, \"original_request\",\n                                   self.request)\n        if (self.request.follow_redirects and\n            self.request.max_redirects > 0 and\n                self.code in (301, 302, 303, 307)):\n            assert isinstance(self.request, _RequestProxy)\n            new_request = copy.copy(self.request.request)\n            new_request.url = urlparse.urljoin(self.request.url,\n                                               self.headers[\"Location\"])\n            new_request.max_redirects = self.request.max_redirects - 1\n            del new_request.headers[\"Host\"]\n            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4\n            # Client SHOULD make a GET request after a 303.\n            # According to the spec, 302 should be followed by the same\n            # method as the original request, but in practice browsers\n            # treat 302 the same as 303, and many servers use 302 for\n            # compatibility with pre-HTTP/1.1 user agents which don't\n            # understand the 303 status.\n            if self.code in (302, 303):\n                new_request.method = \"GET\"\n                new_request.body = None\n                for h in [\"Content-Length\", \"Content-Type\",\n                          \"Content-Encoding\", \"Transfer-Encoding\"]:\n                    try:\n                        del self.request.headers[h]\n                    except KeyError:\n                        pass\n            new_request.original_request = original_request\n            final_callback = self.final_callback\n            self.final_callback = None\n            self._release()\n            self.client.fetch(new_request, final_callback)\n            self._on_end_request()\n            return\n        if self._decompressor:\n            data = (self._decompressor.decompress(data) +\n                    self._decompressor.flush())\n        if self.request.streaming_callback:\n            if self.chunks is None:\n                # if chunks is not None, we already called streaming_callback\n                # in _on_chunk_data\n                self.request.streaming_callback(data)\n            buffer = BytesIO()\n        else:\n            buffer = BytesIO(data)  # TODO: don't require one big string?\n        response = HTTPResponse(original_request,\n                                self.code, reason=self.reason,\n                                headers=self.headers,\n                                request_time=self.io_loop.time() - self.start_time,\n                                buffer=buffer,\n                                effective_url=self.request.url)\n        self._run_callback(response)\n        self._on_end_request()\n\n    def _on_end_request(self):\n        self.stream.close()\n\n    def _on_chunk_length(self, data):\n        # TODO: \"chunk extensions\" http://tools.ietf.org/html/rfc2616#section-3.6.1\n        length = int(data.strip(), 16)\n        if length == 0:\n            if self._decompressor is not None:\n                tail = self._decompressor.flush()\n                if tail:\n                    # I believe the tail will always be empty (i.e.\n                    # decompress will return all it can).  The purpose\n                    # of the flush call is to detect errors such\n                    # as truncated input.  But in case it ever returns\n                    # anything, treat it as an extra chunk\n                    if self.request.streaming_callback is not None:\n                        self.request.streaming_callback(tail)\n                    else:\n                        self.chunks.append(tail)\n                # all the data has been decompressed, so we don't need to\n                # decompress again in _on_body\n                self._decompressor = None\n            self._on_body(b''.join(self.chunks))\n        else:\n            self.stream.read_bytes(length + 2,  # chunk ends with \\r\\n\n                                   self._on_chunk_data)\n\n    def _on_chunk_data(self, data):\n        assert data[-2:] == b\"\\r\\n\"\n        chunk = data[:-2]\n        if self._decompressor:\n            chunk = self._decompressor.decompress(chunk)\n        if self.request.streaming_callback is not None:\n            self.request.streaming_callback(chunk)\n        else:\n            self.chunks.append(chunk)\n        self.stream.read_until(b\"\\r\\n\", self._on_chunk_length)\n\n\nif __name__ == \"__main__\":\n    AsyncHTTPClient.configure(SimpleAsyncHTTPClient)\n    main()\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** WebSocket network failures raise HTTPError instead of IOError

**Description:**
When a WebSocket connection experiences a network failure or timeout, it incorrectly raises an `HTTPError` instead of an `IOError`. This unexpected exception type disrupts proper error handling for network-related issues.

**Example Code:**
```python
sock, port = bind_unused_port()
sock.close()
with self.assertRaises(IOError):
    websocket_connect(f'ws://localhost:{port}/', io_loop=self.io_loop, connect_timeout=3600)
```

**Expected Behavior:**
An `IOError` should be raised to indicate a network failure, allowing developers to handle such exceptions appropriately.

**Actual Behavior:**
An `HTTPError` with a status code (e.g., 599) and a message like "[Errno 111] Connection refused" is raised instead of an `IOError`. This causes tests expecting an `IOError` to fail, leading to confusion and improper error handling in applications.

[/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/simple_httpclient.py
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, with_statement

from tornado.escape import utf8, _unicode, native_str
from tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy
from tornado.httputil import HTTPHeaders
from tornado.iostream import IOStream, SSLIOStream
from tornado.netutil import Resolver, OverrideResolver
from tornado.log import gen_log
from tornado import stack_context
from tornado.util import GzipDecompressor

import base64
import collections
import copy
import functools
import os.path
import re
import socket
import ssl
import sys

try:
    from io import BytesIO  # python 3
except ImportError:
    from cStringIO import StringIO as BytesIO  # python 2

try:
    import urlparse  # py2
except ImportError:
    import urllib.parse as urlparse  # py3

_DEFAULT_CA_CERTS = os.path.dirname(__file__) + '/ca-certificates.crt'


class SimpleAsyncHTTPClient(AsyncHTTPClient):
    """Non-blocking HTTP client with no external dependencies.

    This class implements an HTTP 1.1 client on top of Tornado's IOStreams.
    It does not currently implement all applicable parts of the HTTP
    specification, but it does enough to work with major web service APIs.

    Some features found in the curl-based AsyncHTTPClient are not yet
    supported.  In particular, proxies are not supported, connections
    are not reused, and callers cannot select the network interface to be
    used.
    """
    def initialize(self, io_loop, max_clients=10,
                   hostname_mapping=None, max_buffer_size=104857600,
                   resolver=None, defaults=None):
        """Creates a AsyncHTTPClient.

        Only a single AsyncHTTPClient instance exists per IOLoop
        in order to provide limitations on the number of pending connections.
        force_instance=True may be used to suppress this behavior.

        max_clients is the number of concurrent requests that can be
        in progress.  Note that this arguments are only used when the
        client is first created, and will be ignored when an existing
        client is reused.

        hostname_mapping is a dictionary mapping hostnames to IP addresses.
        It can be used to make local DNS changes when modifying system-wide
        settings like /etc/hosts is not possible or desirable (e.g. in
        unittests).

        max_buffer_size is the number of bytes that can be read by IOStream. It
        defaults to 100mb.
        """
        super(SimpleAsyncHTTPClient, self).initialize(io_loop,
                                                      defaults=defaults)
        self.max_clients = max_clients
        self.queue = collections.deque()
        self.active = {}
        self.waiting = {}
        self.max_buffer_size = max_buffer_size
        if resolver:
            self.resolver = resolver
            self.own_resolver = False
        else:
            self.resolver = Resolver(io_loop=io_loop)
            self.own_resolver = True
        if hostname_mapping is not None:
            self.resolver = OverrideResolver(resolver=self.resolver,
                                             mapping=hostname_mapping)

    def close(self):
        super(SimpleAsyncHTTPClient, self).close()
        if self.own_resolver:
            self.resolver.close()

    def fetch_impl(self, request, callback):
        key = object()
        self.queue.append((key, request, callback))
        if not len(self.active) < self.max_clients:
            timeout_handle = self.io_loop.add_timeout(
                self.io_loop.time() + min(request.connect_timeout,
                                          request.request_timeout),
                functools.partial(self._on_timeout, key))
        else:
            timeout_handle = None
        self.waiting[key] = (request, callback, timeout_handle)
        self._process_queue()
        if self.queue:
            gen_log.debug("max_clients limit reached, request queued. "
                          "%d active, %d queued requests." % (
                              len(self.active), len(self.queue)))

    def _process_queue(self):
        with stack_context.NullContext():
            while self.queue and len(self.active) < self.max_clients:
                key, request, callback = self.queue.popleft()
                if key not in self.waiting:
                    continue
                self._remove_timeout(key)
                self.active[key] = (request, callback)
                release_callback = functools.partial(self._release_fetch, key)
                self._handle_request(request, release_callback, callback)

    def _handle_request(self, request, release_callback, final_callback):
        _HTTPConnection(self.io_loop, self, request, release_callback,
                        final_callback, self.max_buffer_size, self.resolver)

    def _release_fetch(self, key):
        del self.active[key]
        self._process_queue()

    def _remove_timeout(self, key):
        if key in self.waiting:
            request, callback, timeout_handle = self.waiting[key]
            if timeout_handle is not None:
                self.io_loop.remove_timeout(timeout_handle)
            del self.waiting[key]

    def _on_timeout(self, key):
        request, callback, timeout_handle = self.waiting[key]
        self.queue.remove((key, request, callback))
        timeout_response = HTTPResponse(
            request, 599, error=HTTPError(599, "Timeout"),
            request_time=self.io_loop.time() - request.start_time)
        self.io_loop.add_callback(callback, timeout_response)
        del self.waiting[key]


class _HTTPConnection(object):
    _SUPPORTED_METHODS = set(["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])

    def __init__(self, io_loop, client, request, release_callback,
                 final_callback, max_buffer_size, resolver):
        self.start_time = io_loop.time()
        self.io_loop = io_loop
        self.client = client
        self.request = request
        self.release_callback = release_callback
        self.final_callback = final_callback
        self.max_buffer_size = max_buffer_size
        self.resolver = resolver
        self.code = None
        self.headers = None
        self.chunks = None
        self._decompressor = None
        # Timeout handle returned by IOLoop.add_timeout
        self._timeout = None
        with stack_context.ExceptionStackContext(self._handle_exception):
            self.parsed = urlparse.urlsplit(_unicode(self.request.url))
            if self.parsed.scheme not in ("http", "https"):
                raise ValueError("Unsupported url scheme: %s" %
                                 self.request.url)
            # urlsplit results have hostname and port results, but they
            # didn't support ipv6 literals until python 2.7.
            netloc = self.parsed.netloc
            if "@" in netloc:
                userpass, _, netloc = netloc.rpartition("@")
            match = re.match(r'^(.+):(\d+)$', netloc)
            if match:
                host = match.group(1)
                port = int(match.group(2))
            else:
                host = netloc
                port = 443 if self.parsed.scheme == "https" else 80
            if re.match(r'^\[.*\]$', host):
                # raw ipv6 addresses in urls are enclosed in brackets
                host = host[1:-1]
            self.parsed_hostname = host  # save final host for _on_connect

            if request.allow_ipv6:
                af = socket.AF_UNSPEC
            else:
                # We only try the first IP we get from getaddrinfo,
                # so restrict to ipv4 by default.
                af = socket.AF_INET

            timeout = min(self.request.connect_timeout, self.request.request_timeout)
            if timeout:
                self._timeout = self.io_loop.add_timeout(
                    self.start_time + timeout,
                    stack_context.wrap(self._on_timeout))
            self.resolver.resolve(host, port, af, callback=self._on_resolve)

    def _on_resolve(self, addrinfo):
        if self.final_callback is None:
            # final_callback is cleared if we've hit our timeout
            return
        self.stream = self._create_stream(addrinfo)
        self.stream.set_close_callback(self._on_close)
        # ipv6 addresses are broken (in self.parsed.hostname) until
        # 2.7, here is correctly parsed value calculated in __init__
        sockaddr = addrinfo[0][1]
        self.stream.connect(sockaddr, self._on_connect,
                            server_hostname=self.parsed_hostname)

    def _create_stream(self, addrinfo):
        af = addrinfo[0][0]
        if self.parsed.scheme == "https":
            ssl_options = {}
            if self.request.validate_cert:
                ssl_options["cert_reqs"] = ssl.CERT_REQUIRED
            if self.request.ca_certs is not None:
                ssl_options["ca_certs"] = self.request.ca_certs
            else:
                ssl_options["ca_certs"] = _DEFAULT_CA_CERTS
            if self.request.client_key is not None:
                ssl_options["keyfile"] = self.request.client_key
            if self.request.client_cert is not None:
                ssl_options["certfile"] = self.request.client_cert

            # SSL interoperability is tricky.  We want to disable
            # SSLv2 for security reasons; it wasn't disabled by default
            # until openssl 1.0.  The best way to do this is to use
            # the SSL_OP_NO_SSLv2, but that wasn't exposed to python
            # until 3.2.  Python 2.7 adds the ciphers argument, which
            # can also be used to disable SSLv2.  As a last resort
            # on python 2.6, we set ssl_version to TLSv1.  This is
            # more narrow than we'd like since it also breaks
            # compatibility with servers configured for SSLv3 only,
            # but nearly all servers support both SSLv3 and TLSv1:
            # http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html
            if sys.version_info >= (2, 7):
                # In addition to disabling SSLv2, we also exclude certain
                # classes of insecure ciphers.
                ssl_options["ciphers"] = "DEFAULT:!SSLv2:!EXPORT:!DES"
            else:
                # This is really only necessary for pre-1.0 versions
                # of openssl, but python 2.6 doesn't expose version
                # information.
                ssl_options["ssl_version"] = ssl.PROTOCOL_TLSv1

            return SSLIOStream(socket.socket(af),
                               io_loop=self.io_loop,
                               ssl_options=ssl_options,
                               max_buffer_size=self.max_buffer_size)
        else:
            return IOStream(socket.socket(af),
                            io_loop=self.io_loop,
                            max_buffer_size=self.max_buffer_size)

    def _on_timeout(self):
        self._timeout = None
        if self.final_callback is not None:
            raise HTTPError(599, "Timeout")

    def _remove_timeout(self):
        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

    def _on_connect(self):
        self._remove_timeout()
        if self.final_callback is None:
            return
        if self.request.request_timeout:
            self._timeout = self.io_loop.add_timeout(
                self.start_time + self.request.request_timeout,
                stack_context.wrap(self._on_timeout))
        if (self.request.method not in self._SUPPORTED_METHODS and
                not self.request.allow_nonstandard_methods):
            raise KeyError("unknown method %s" % self.request.method)
        for key in ('network_interface',
                    'proxy_host', 'proxy_port',
                    'proxy_username', 'proxy_password'):
            if getattr(self.request, key, None):
                raise NotImplementedError('%s not supported' % key)
        if "Connection" not in self.request.headers:
            self.request.headers["Connection"] = "close"
        if "Host" not in self.request.headers:
            if '@' in self.parsed.netloc:
                self.request.headers["Host"] = self.parsed.netloc.rpartition('@')[-1]
            else:
                self.request.headers["Host"] = self.parsed.netloc
        username, password = None, None
        if self.parsed.username is not None:
            username, password = self.parsed.username, self.parsed.password
        elif self.request.auth_username is not None:
            username = self.request.auth_username
            password = self.request.auth_password or ''
        if username is not None:
            if self.request.auth_mode not in (None, "basic"):
                raise ValueError("unsupported auth_mode %s",
                                 self.request.auth_mode)
            auth = utf8(username) + b":" + utf8(password)
            self.request.headers["Authorization"] = (b"Basic " +
                                                     base64.b64encode(auth))
        if self.request.user_agent:
            self.request.headers["User-Agent"] = self.request.user_agent
        if not self.request.allow_nonstandard_methods:
            if self.request.method in ("POST", "PATCH", "PUT"):
                if self.request.body is None:
                    raise AssertionError(
                        'Body must not be empty for "%s" request'
                        % self.request.method)
            else:
                if self.request.body is not None:
                    raise AssertionError(
                        'Body must be empty for "%s" request'
                        % self.request.method)
        if self.request.body is not None:
            self.request.headers["Content-Length"] = str(len(
                self.request.body))
        if (self.request.method == "POST" and
                "Content-Type" not in self.request.headers):
            self.request.headers["Content-Type"] = "application/x-www-form-urlencoded"
        if self.request.use_gzip:
            self.request.headers["Accept-Encoding"] = "gzip"
        req_path = ((self.parsed.path or '/') +
                   (('?' + self.parsed.query) if self.parsed.query else ''))
        request_lines = [utf8("%s %s HTTP/1.1" % (self.request.method,
                                                  req_path))]
        for k, v in self.request.headers.get_all():
            line = utf8(k) + b": " + utf8(v)
            if b'\n' in line:
                raise ValueError('Newline in header: ' + repr(line))
            request_lines.append(line)
        request_str = b"\r\n".join(request_lines) + b"\r\n\r\n"
        if self.request.body is not None:
            request_str += self.request.body
        self.stream.set_nodelay(True)
        self.stream.write(request_str)
        self.stream.read_until_regex(b"\r?\n\r?\n", self._on_headers)

    def _release(self):
        if self.release_callback is not None:
            release_callback = self.release_callback
            self.release_callback = None
            release_callback()

    def _run_callback(self, response):
        self._release()
        if self.final_callback is not None:
            final_callback = self.final_callback
            self.final_callback = None
            self.io_loop.add_callback(final_callback, response)

    def _handle_exception(self, typ, value, tb):
        if self.final_callback:
            self._remove_timeout()
            self._run_callback(HTTPResponse(self.request, 599, error=value,
                                            request_time=self.io_loop.time() - self.start_time,
                                            ))

            if hasattr(self, "stream"):
                self.stream.close()
            return True
        else:
            # If our callback has already been called, we are probably
            # catching an exception that is not caused by us but rather
            # some child of our callback. Rather than drop it on the floor,
            # pass it along.
            return False

    def _on_close(self):
        if self.final_callback is not None:
            message = "Connection closed"
            if self.stream.error:
                message = str(self.stream.error)
            raise HTTPError(599, message)

    def _handle_1xx(self, code):
        self.stream.read_until_regex(b"\r?\n\r?\n", self._on_headers)

    def _on_headers(self, data):
        data = native_str(data.decode("latin1"))
        first_line, _, header_data = data.partition("\n")
        match = re.match("HTTP/1.[01] ([0-9]+) ([^\r]*)", first_line)
        assert match
        code = int(match.group(1))
        self.headers = HTTPHeaders.parse(header_data)
        if 100 <= code < 200:
            self._handle_1xx(code)
            return
        else:
            self.code = code
            self.reason = match.group(2)

        if "Content-Length" in self.headers:
            if "," in self.headers["Content-Length"]:
                # Proxies sometimes cause Content-Length headers to get
                # duplicated.  If all the values are identical then we can
                # use them but if they differ it's an error.
                pieces = re.split(r',\s*', self.headers["Content-Length"])
                if any(i != pieces[0] for i in pieces):
                    raise ValueError("Multiple unequal Content-Lengths: %r" %
                                     self.headers["Content-Length"])
                self.headers["Content-Length"] = pieces[0]
            content_length = int(self.headers["Content-Length"])
        else:
            content_length = None

        if self.request.header_callback is not None:
            # re-attach the newline we split on earlier
            self.request.header_callback(first_line + _)
            for k, v in self.headers.get_all():
                self.request.header_callback("%s: %s\r\n" % (k, v))
            self.request.header_callback('\r\n')

        if self.request.method == "HEAD" or self.code == 304:
            # HEAD requests and 304 responses never have content, even
            # though they may have content-length headers
            self._on_body(b"")
            return
        if 100 <= self.code < 200 or self.code == 204:
            # These response codes never have bodies
            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
            if ("Transfer-Encoding" in self.headers or
                    content_length not in (None, 0)):
                raise ValueError("Response with code %d should not have body" %
                                 self.code)
            self._on_body(b"")
            return

        if (self.request.use_gzip and
                self.headers.get("Content-Encoding") == "gzip"):
            self._decompressor = GzipDecompressor()
        if self.headers.get("Transfer-Encoding") == "chunked":
            self.chunks = []
            self.stream.read_until(b"\r\n", self._on_chunk_length)
        elif content_length is not None:
            self.stream.read_bytes(content_length, self._on_body)
        else:
            self.stream.read_until_close(self._on_body)

    def _on_body(self, data):
        self._remove_timeout()
        original_request = getattr(self.request, "original_request",
                                   self.request)
        if (self.request.follow_redirects and
            self.request.max_redirects > 0 and
                self.code in (301, 302, 303, 307)):
            assert isinstance(self.request, _RequestProxy)
            new_request = copy.copy(self.request.request)
            new_request.url = urlparse.urljoin(self.request.url,
                                               self.headers["Location"])
            new_request.max_redirects = self.request.max_redirects - 1
            del new_request.headers["Host"]
            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
            # Client SHOULD make a GET request after a 303.
            # According to the spec, 302 should be followed by the same
            # method as the original request, but in practice browsers
            # treat 302 the same as 303, and many servers use 302 for
            # compatibility with pre-HTTP/1.1 user agents which don't
            # understand the 303 status.
            if self.code in (302, 303):
                new_request.method = "GET"
                new_request.body = None
                for h in ["Content-Length", "Content-Type",
                          "Content-Encoding", "Transfer-Encoding"]:
                    try:
                        del self.request.headers[h]
                    except KeyError:
                        pass
            new_request.original_request = original_request
            final_callback = self.final_callback
            self.final_callback = None
            self._release()
            self.client.fetch(new_request, final_callback)
            self._on_end_request()
            return
        if self._decompressor:
            data = (self._decompressor.decompress(data) +
                    self._decompressor.flush())
        if self.request.streaming_callback:
            if self.chunks is None:
                # if chunks is not None, we already called streaming_callback
                # in _on_chunk_data
                self.request.streaming_callback(data)
            buffer = BytesIO()
        else:
            buffer = BytesIO(data)  # TODO: don't require one big string?
        response = HTTPResponse(original_request,
                                self.code, reason=self.reason,
                                headers=self.headers,
                                request_time=self.io_loop.time() - self.start_time,
                                buffer=buffer,
                                effective_url=self.request.url)
        self._run_callback(response)
        self._on_end_request()

    def _on_end_request(self):
        self.stream.close()

    def _on_chunk_length(self, data):
        # TODO: "chunk extensions" http://tools.ietf.org/html/rfc2616#section-3.6.1
        length = int(data.strip(), 16)
        if length == 0:
            if self._decompressor is not None:
                tail = self._decompressor.flush()
                if tail:
                    # I believe the tail will always be empty (i.e.
                    # decompress will return all it can).  The purpose
                    # of the flush call is to detect errors such
                    # as truncated input.  But in case it ever returns
                    # anything, treat it as an extra chunk
                    if self.request.streaming_callback is not None:
                        self.request.streaming_callback(tail)
                    else:
                        self.chunks.append(tail)
                # all the data has been decompressed, so we don't need to
                # decompress again in _on_body
                self._decompressor = None
            self._on_body(b''.join(self.chunks))
        else:
            self.stream.read_bytes(length + 2,  # chunk ends with \r\n
                                   self._on_chunk_data)

    def _on_chunk_data(self, data):
        assert data[-2:] == b"\r\n"
        chunk = data[:-2]
        if self._decompressor:
            chunk = self._decompressor.decompress(chunk)
        if self.request.streaming_callback is not None:
            self.request.streaming_callback(chunk)
        else:
            self.chunks.append(chunk)
        self.stream.read_until(b"\r\n", self._on_chunk_length)


if __name__ == "__main__":
    AsyncHTTPClient.configure(SimpleAsyncHTTPClient)
    main()

```
--- END FILE ---

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

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

Here is an example:

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

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