{
    "file_diffs": [
        {
            "old_file_content": "import asyncio\nimport aiohttp\nimport functools\nimport http.cookies\nimport ssl\nimport socket\nimport sys\nimport traceback\nimport warnings\n\n\nfrom . import hdrs\nfrom .client import ClientRequest\nfrom .errors import ServerDisconnectedError\nfrom .errors import HttpProxyError, ProxyConnectionError\nfrom .errors import ClientOSError, ClientTimeoutError\nfrom .helpers import BasicAuth\n\n\n__all__ = ('BaseConnector', 'TCPConnector', 'ProxyConnector', 'UnixConnector')\n\nPY_34 = sys.version_info >= (3, 4)\nPY_343 = sys.version_info >= (3, 4, 3)\n\n\nclass Connection(object):\n\n    _source_traceback = None\n    _transport = None\n\n    def __init__(self, connector, key, request, transport, protocol, loop):\n        self._key = key\n        self._connector = connector\n        self._request = request\n        self._transport = transport\n        self._protocol = protocol\n        self._loop = loop\n        self.reader = protocol.reader\n        self.writer = protocol.writer\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n    if PY_34:\n        def __del__(self):\n            if self._transport is not None:\n                self._connector._release(\n                    self._key, self._request, self._transport, self._protocol,\n                    should_close=True)\n\n                warnings.warn(\"Unclosed connection {!r}\".format(self),\n                              ResourceWarning)\n                context = {'client_connection': self,\n                           'message': 'Unclosed connection'}\n                if self._source_traceback is not None:\n                    context['source_traceback'] = self._source_traceback\n                self._loop.call_exception_handler(context)\n\n    @property\n    def loop(self):\n        return self._loop\n\n    def close(self):\n        if self._transport is not None:\n            self._connector._release(\n                self._key, self._request, self._transport, self._protocol,\n                should_close=True)\n            self._transport = None\n\n    def release(self):\n        if self._transport is not None:\n            self._connector._release(\n                self._key, self._request, self._transport, self._protocol,\n                should_close=False)\n            self._transport = None\n\n    def detach(self):\n        self._transport = None\n\n    @property\n    def closed(self):\n        return self._transport is None\n\n\nclass BaseConnector(object):\n    \"\"\"Base connector class.\n\n    :param conn_timeout: (optional) Connect timeout.\n    :param keepalive_timeout: (optional) Keep-alive timeout.\n    :param bool force_close: Set to True to force close and do reconnect\n        after each request (and between redirects).\n    :param loop: Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,\n                 share_cookies=False, force_close=False, loop=None):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        self._conns = {}\n        self._conn_timeout = conn_timeout\n        self._keepalive_timeout = keepalive_timeout\n        if share_cookies:\n            warnings.warn(\n                'Using `share_cookies` is deprecated. '\n                'Use Session object instead', DeprecationWarning)\n        self._share_cookies = share_cookies\n        self._cleanup_handle = None\n        self._force_close = force_close\n\n        self._loop = loop\n        self._factory = functools.partial(\n            aiohttp.StreamProtocol, loop=loop,\n            disconnect_error=ServerDisconnectedError)\n\n        self.cookies = http.cookies.SimpleCookie()\n\n    if PY_34:\n        def __del__(self):\n            if self._closed:\n                return\n            if not self._conns:\n                return\n\n            loop_is_not_closed = not self._loop.is_closed()\n\n            for key, data in self._conns.items():\n                for transport, proto, t0 in data:\n                    if loop_is_not_closed:\n                        transport.close()\n            self._conns.clear()\n\n            # N.B.\n            # Don't check for self._cleanup_handle!\n            # The reason is: if self._cleanup_handle was scheduled\n            # a reference to self is stored in event loop.\n            # Thus __del__ will not be called until cleanup handler executes.\n\n            warnings.warn(\"Unclosed connector {!r}\".format(self),\n                          ResourceWarning)\n            context = {'connector': self,\n                       'message': 'Unclosed connector'}\n            if self._source_traceback is not None:\n                context['source_traceback'] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def _cleanup(self):\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n        now = self._loop.time()\n\n        connections = {}\n        for key, conns in self._conns.items():\n            alive = []\n            for transport, proto, t0 in conns:\n                if transport is not None:\n                    if proto and not proto.is_connected():\n                        transport = None\n                    elif (now - t0) > self._keepalive_timeout:\n                        transport.close()\n                        transport = None\n\n                if transport:\n                    alive.append((transport, proto, t0))\n            if alive:\n                connections[key] = alive\n\n        if connections:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n        self._conns = connections\n\n    def _start_cleanup_task(self):\n        if self._cleanup_handle is None:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n    def close(self):\n        \"\"\"Close all opened transports.\"\"\"\n        if self._closed:\n            return\n        self._closed = True\n\n        for key, data in self._conns.items():\n            for transport, proto, t0 in data:\n                transport.close()\n\n        self._conns.clear()\n\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n    @property\n    def closed(self):\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def update_cookies(self, cookies):\n        \"\"\"Update shared cookies.\n\n        Deprecated, use ClientSession instead.\n        \"\"\"\n        if isinstance(cookies, dict):\n            cookies = cookies.items()\n\n        for name, value in cookies:\n            if PY_343:\n                self.cookies[name] = value\n            else:\n                if isinstance(value, http.cookies.Morsel):\n                    # use dict method because SimpleCookie class modifies value\n                    dict.__setitem__(self.cookies, name, value)\n                else:\n                    self.cookies[name] = value\n\n    @asyncio.coroutine\n    def connect(self, req):\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = (req.host, req.port, req.ssl)\n\n        transport, proto = self._get(key)\n        if transport is None:\n            try:\n                if self._conn_timeout:\n                    transport, proto = yield from asyncio.wait_for(\n                        self._create_connection(req),\n                        self._conn_timeout, loop=self._loop)\n                else:\n                    transport, proto = yield from self._create_connection(req)\n            except asyncio.TimeoutError as exc:\n                raise ClientTimeoutError(\n                    'Connection timeout to host %s:%s ssl:%s' % key) from exc\n            except OSError as exc:\n                raise ClientOSError(\n                    'Cannot connect to host %s:%s ssl:%s' % key) from exc\n\n        return Connection(self, key, req, transport, proto, self._loop)\n\n    def _get(self, key):\n        conns = self._conns.get(key)\n        t1 = self._loop.time()\n        while conns:\n            transport, proto, t0 = conns.pop()\n            if transport is not None and proto.is_connected():\n                if t1 - t0 > self._keepalive_timeout:\n                    transport.close()\n                    transport = None\n                else:\n                    return transport, proto\n\n        return None, None\n\n    def _release(self, key, req, transport, protocol, *, should_close=False):\n        resp = req.response\n\n        if not should_close:\n            if resp is not None:\n                if resp.message is None:\n                    should_close = True\n                else:\n                    should_close = resp.message.should_close\n\n            if self._force_close:\n                should_close = True\n\n        reader = protocol.reader\n        if should_close or (reader.output and not reader.output.at_eof()):\n            conns = self._conns.get(key)\n            if conns is not None and len(conns) == 0:\n                # Issue #253: An empty array will eventually be\n                # removed by cleanup, but it's better to pop straight\n                # away, because cleanup might not get called (e.g. if\n                # keepalive is False).\n                self._conns.pop(key, None)\n\n            transport.close()\n        else:\n            conns = self._conns.get(key)\n            if conns is None:\n                conns = self._conns[key] = []\n            conns.append((transport, protocol, self._loop.time()))\n            reader.unset_parser()\n\n            self._start_cleanup_task()\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        raise NotImplementedError()\n\n\n_SSL_OP_NO_COMPRESSION = getattr(ssl, \"OP_NO_COMPRESSION\", 0)\n_SSH_HAS_CREATE_DEFAULT_CONTEXT = hasattr(ssl, 'create_default_context')\n\n\nclass TCPConnector(BaseConnector):\n    \"\"\"TCP connector.\n\n    :param bool verify_ssl: Set to True to check ssl certifications.\n    :param bool resolve: Set to True to do DNS lookup for host name.\n    :param family: socket address family\n    :param args: see :class:`BaseConnector`\n    :param kwargs: see :class:`BaseConnector`\n    \"\"\"\n\n    def __init__(self, *args, verify_ssl=True,\n                 resolve=False, family=socket.AF_INET, ssl_context=None,\n                 **kwargs):\n        super().__init__(*args, **kwargs)\n\n        if not verify_ssl and ssl_context is not None:\n            raise ValueError(\n                \"Either disable ssl certificate validation by \"\n                \"verify_ssl=False or specify ssl_context, not both.\")\n\n        self._verify_ssl = verify_ssl\n        self._ssl_context = ssl_context\n        self._family = family\n        self._resolve = resolve\n        self._resolved_hosts = {}\n\n    @property\n    def verify_ssl(self):\n        \"\"\"Do check for ssl certifications?\"\"\"\n        return self._verify_ssl\n\n    @property\n    def ssl_context(self):\n        \"\"\"SSLContext instance for https requests.\n\n        Lazy property, creates context on demand.\n        \"\"\"\n        if self._ssl_context is None:\n            if not self._verify_ssl:\n                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n                sslcontext.options |= ssl.OP_NO_SSLv2\n                sslcontext.options |= ssl.OP_NO_SSLv3\n                sslcontext.options |= _SSL_OP_NO_COMPRESSION\n                sslcontext.set_default_verify_paths()\n            elif _SSH_HAS_CREATE_DEFAULT_CONTEXT:\n                # Python 3.4+\n                sslcontext = ssl.create_default_context()\n            else:\n                # Fallback for Python 3.3.\n                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n                sslcontext.options |= ssl.OP_NO_SSLv2\n                sslcontext.options |= ssl.OP_NO_SSLv3\n                sslcontext.options |= _SSL_OP_NO_COMPRESSION\n                sslcontext.set_default_verify_paths()\n                sslcontext.verify_mode = ssl.CERT_REQUIRED\n            self._ssl_context = sslcontext\n        return self._ssl_context\n\n    @property\n    def family(self):\n        \"\"\"Socket family like AF_INET.\"\"\"\n        return self._family\n\n    @property\n    def resolve(self):\n        \"\"\"Do DNS lookup for host name?\"\"\"\n        return self._resolve\n\n    @property\n    def resolved_hosts(self):\n        \"\"\"The dict of (host, port) -> (ipaddr, port) pairs.\"\"\"\n        return dict(self._resolved_hosts)\n\n    def clear_resolved_hosts(self, host=None, port=None):\n        \"\"\"Remove specified host/port or clear all resolve cache.\"\"\"\n        if host is not None and port is not None:\n            key = (host, port)\n            if key in self._resolved_hosts:\n                del self._resolved_hosts[key]\n        else:\n            self._resolved_hosts.clear()\n\n    @asyncio.coroutine\n    def _resolve_host(self, host, port):\n        if self._resolve:\n            key = (host, port)\n\n            if key not in self._resolved_hosts:\n                infos = yield from self._loop.getaddrinfo(\n                    host, port, type=socket.SOCK_STREAM, family=self._family)\n\n                hosts = []\n                for family, _, proto, _, address in infos:\n                    hosts.append(\n                        {'hostname': host,\n                         'host': address[0], 'port': address[1],\n                         'family': family, 'proto': proto,\n                         'flags': socket.AI_NUMERICHOST})\n                self._resolved_hosts[key] = hosts\n\n            return list(self._resolved_hosts[key])\n        else:\n            return [{'hostname': host, 'host': host, 'port': port,\n                     'family': self._family, 'proto': 0, 'flags': 0}]\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        \"\"\"Create connection.\n\n        Has same keyword arguments as BaseEventLoop.create_connection.\n        \"\"\"\n        if req.ssl:\n            sslcontext = self.ssl_context\n        else:\n            sslcontext = None\n\n        hosts = yield from self._resolve_host(req.host, req.port)\n\n        while hosts:\n            hinfo = hosts.pop()\n            try:\n                return (yield from self._loop.create_connection(\n                    self._factory, hinfo['host'], hinfo['port'],\n                    ssl=sslcontext, family=hinfo['family'],\n                    proto=hinfo['proto'], flags=hinfo['flags'],\n                    server_hostname=hinfo['hostname'] if sslcontext else None))\n            except OSError as exc:\n                if not hosts:\n                    raise ClientOSError('Can not connect to %s:%s' %\n                                        (req.host, req.port)) from exc\n\n\nclass ProxyConnector(TCPConnector):\n    \"\"\"Http Proxy connector.\n\n    :param str proxy: Proxy URL address. Only http proxy supported.\n    :param proxy_auth: (optional) Proxy HTTP Basic Auth\n    :type proxy_auth: aiohttp.helpers.BasicAuth\n    :param args: see :class:`TCPConnector`\n    :param kwargs: see :class:`TCPConnector`\n\n    Usage:\n\n    >>> conn = ProxyConnector(proxy=\"http://some.proxy.com\")\n    >>> session = ClientSession(connector=conn)\n    >>> resp = yield from session.get('http://python.org')\n\n    \"\"\"\n\n    def __init__(self, proxy, *args, proxy_auth=None, **kwargs):\n        super().__init__(*args, **kwargs)\n        self._proxy = proxy\n        self._proxy_auth = proxy_auth\n        assert proxy.startswith('http://'), (\n            \"Only http proxy supported\", proxy)\n        assert proxy_auth is None or isinstance(proxy_auth, BasicAuth), (\n            \"proxy_auth must be None or BasicAuth() tuple\", proxy_auth)\n\n    @property\n    def proxy(self):\n        \"\"\"Proxy URL.\"\"\"\n        return self._proxy\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        proxy_req = ClientRequest(\n            hdrs.METH_GET, self._proxy,\n            headers={hdrs.HOST: req.host},\n            auth=self._proxy_auth,\n            loop=self._loop)\n        try:\n            transport, proto = yield from super()._create_connection(proxy_req)\n        except OSError as exc:\n            raise ProxyConnectionError(*exc.args) from exc\n\n        if not req.ssl:\n            req.path = '{scheme}://{host}{path}'.format(scheme=req.scheme,\n                                                        host=req.netloc,\n                                                        path=req.path)\n        if hdrs.AUTHORIZATION in proxy_req.headers:\n            auth = proxy_req.headers[hdrs.AUTHORIZATION]\n            del proxy_req.headers[hdrs.AUTHORIZATION]\n            req.headers[hdrs.PROXY_AUTHORIZATION] = auth\n\n        if req.ssl:\n            # For HTTPS requests over HTTP proxy\n            # we must notify proxy to tunnel connection\n            # so we send CONNECT command:\n            #   CONNECT www.python.org:443 HTTP/1.1\n            #   Host: www.python.org\n            #\n            # next we must do TLS handshake and so on\n            # to do this we must wrap raw socket into secure one\n            # asyncio handles this perfectly\n            proxy_req.method = hdrs.METH_CONNECT\n            proxy_req.path = '{}:{}'.format(req.host, req.port)\n            key = (req.host, req.port, req.ssl)\n            conn = Connection(self, key, proxy_req,\n                              transport, proto, self._loop)\n            proxy_resp = proxy_req.send(conn.writer, conn.reader)\n            try:\n                resp = yield from proxy_resp.start(conn, True)\n            except:\n                proxy_resp.close()\n                conn.close()\n                raise\n            else:\n                conn.detach()\n                if resp.status != 200:\n                    raise HttpProxyError(code=resp.status, message=resp.reason)\n                rawsock = transport.get_extra_info('socket', default=None)\n                if rawsock is None:\n                    raise RuntimeError(\n                        \"Transport does not expose socket instance\")\n                transport.pause_reading()\n                transport, proto = yield from self._loop.create_connection(\n                    self._factory, ssl=True, sock=rawsock,\n                    server_hostname=req.host)\n\n        return transport, proto\n\n\nclass UnixConnector(BaseConnector):\n    \"\"\"Unix socket connector.\n\n    :param str path: Unix socket path.\n    :param args: see :class:`BaseConnector`\n    :param kwargs: see :class:`BaseConnector`\n\n    Usage:\n\n    >>> conn = UnixConnector(path='/path/to/socket')\n    >>> session = ClientSession(connector=conn)\n    >>> resp = yield from session.get('http://python.org')\n\n    \"\"\"\n\n    def __init__(self, path, *args, **kw):\n        super().__init__(*args, **kw)\n        self._path = path\n\n    @property\n    def path(self):\n        \"\"\"Path to unix socket.\"\"\"\n        return self._path\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        return (yield from self._loop.create_unix_connection(\n            self._factory, self._path))\n",
            "new_file_content": "import asyncio\nimport aiohttp\nimport functools\nimport http.cookies\nimport ssl\nimport socket\nimport sys\nimport traceback\nimport warnings\n\nfrom math import ceil\n\nfrom . import hdrs\nfrom .client import ClientRequest\nfrom .errors import ServerDisconnectedError\nfrom .errors import HttpProxyError, ProxyConnectionError\nfrom .errors import ClientOSError, ClientTimeoutError\nfrom .helpers import BasicAuth\n\n\n__all__ = ('BaseConnector', 'TCPConnector', 'ProxyConnector', 'UnixConnector')\n\nPY_34 = sys.version_info >= (3, 4)\nPY_343 = sys.version_info >= (3, 4, 3)\n\n\nclass Connection(object):\n\n    _source_traceback = None\n    _transport = None\n\n    def __init__(self, connector, key, request, transport, protocol, loop):\n        self._key = key\n        self._connector = connector\n        self._request = request\n        self._transport = transport\n        self._protocol = protocol\n        self._loop = loop\n        self.reader = protocol.reader\n        self.writer = protocol.writer\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n    if PY_34:\n        def __del__(self):\n            if self._transport is not None:\n                self._connector._release(\n                    self._key, self._request, self._transport, self._protocol,\n                    should_close=True)\n\n                warnings.warn(\"Unclosed connection {!r}\".format(self),\n                              ResourceWarning)\n                context = {'client_connection': self,\n                           'message': 'Unclosed connection'}\n                if self._source_traceback is not None:\n                    context['source_traceback'] = self._source_traceback\n                self._loop.call_exception_handler(context)\n\n    @property\n    def loop(self):\n        return self._loop\n\n    def close(self):\n        if self._transport is not None:\n            self._connector._release(\n                self._key, self._request, self._transport, self._protocol,\n                should_close=True)\n            self._transport = None\n\n    def release(self):\n        if self._transport is not None:\n            self._connector._release(\n                self._key, self._request, self._transport, self._protocol,\n                should_close=False)\n            self._transport = None\n\n    def detach(self):\n        self._transport = None\n\n    @property\n    def closed(self):\n        return self._transport is None\n\n\nclass BaseConnector(object):\n    \"\"\"Base connector class.\n\n    :param conn_timeout: (optional) Connect timeout.\n    :param keepalive_timeout: (optional) Keep-alive timeout.\n    :param bool force_close: Set to True to force close and do reconnect\n        after each request (and between redirects).\n    :param loop: Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,\n                 share_cookies=False, force_close=False, loop=None):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        self._conns = {}\n        self._conn_timeout = conn_timeout\n        self._keepalive_timeout = keepalive_timeout\n        if share_cookies:\n            warnings.warn(\n                'Using `share_cookies` is deprecated. '\n                'Use Session object instead', DeprecationWarning)\n        self._share_cookies = share_cookies\n        self._cleanup_handle = None\n        self._force_close = force_close\n\n        self._loop = loop\n        self._factory = functools.partial(\n            aiohttp.StreamProtocol, loop=loop,\n            disconnect_error=ServerDisconnectedError)\n\n        self.cookies = http.cookies.SimpleCookie()\n\n    if PY_34:\n        def __del__(self):\n            if self._closed:\n                return\n            if not self._conns:\n                return\n\n            loop_is_not_closed = not self._loop.is_closed()\n\n            for key, data in self._conns.items():\n                for transport, proto, t0 in data:\n                    if loop_is_not_closed:\n                        transport.close()\n            self._conns.clear()\n\n            # N.B.\n            # Don't check for self._cleanup_handle!\n            # The reason is: if self._cleanup_handle was scheduled\n            # a reference to self is stored in event loop.\n            # Thus __del__ will not be called until cleanup handler executes.\n\n            warnings.warn(\"Unclosed connector {!r}\".format(self),\n                          ResourceWarning)\n            context = {'connector': self,\n                       'message': 'Unclosed connector'}\n            if self._source_traceback is not None:\n                context['source_traceback'] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def _cleanup(self):\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n        now = self._loop.time()\n\n        connections = {}\n        for key, conns in self._conns.items():\n            alive = []\n            for transport, proto, t0 in conns:\n                if transport is not None:\n                    if proto and not proto.is_connected():\n                        transport = None\n                    elif (now - t0) > self._keepalive_timeout:\n                        transport.close()\n                        transport = None\n\n                if transport is not None:\n                    alive.append((transport, proto, t0))\n            if alive:\n                connections[key] = alive\n\n        if connections:\n            self._cleanup_handle = self._loop.call_at(\n                ceil(now + self._keepalive_timeout), self._cleanup)\n\n        self._conns = connections\n\n    def _start_cleanup_task(self):\n        if self._cleanup_handle is None:\n            now = self._loop.time()\n            self._cleanup_handle = self._loop.call_at(\n                ceil(now + self._keepalive_timeout), self._cleanup)\n\n    def close(self):\n        \"\"\"Close all opened transports.\"\"\"\n        if self._closed:\n            return\n        self._closed = True\n\n        for key, data in self._conns.items():\n            for transport, proto, t0 in data:\n                transport.close()\n\n        self._conns.clear()\n\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n    @property\n    def closed(self):\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def update_cookies(self, cookies):\n        \"\"\"Update shared cookies.\n\n        Deprecated, use ClientSession instead.\n        \"\"\"\n        if isinstance(cookies, dict):\n            cookies = cookies.items()\n\n        for name, value in cookies:\n            if PY_343:\n                self.cookies[name] = value\n            else:\n                if isinstance(value, http.cookies.Morsel):\n                    # use dict method because SimpleCookie class modifies value\n                    dict.__setitem__(self.cookies, name, value)\n                else:\n                    self.cookies[name] = value\n\n    @asyncio.coroutine\n    def connect(self, req):\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = (req.host, req.port, req.ssl)\n\n        transport, proto = self._get(key)\n        if transport is None:\n            try:\n                if self._conn_timeout:\n                    transport, proto = yield from asyncio.wait_for(\n                        self._create_connection(req),\n                        self._conn_timeout, loop=self._loop)\n                else:\n                    transport, proto = yield from self._create_connection(req)\n            except asyncio.TimeoutError as exc:\n                raise ClientTimeoutError(\n                    'Connection timeout to host %s:%s ssl:%s' % key) from exc\n            except OSError as exc:\n                raise ClientOSError(\n                    'Cannot connect to host %s:%s ssl:%s' % key) from exc\n\n        return Connection(self, key, req, transport, proto, self._loop)\n\n    def _get(self, key):\n        conns = self._conns.get(key)\n        t1 = self._loop.time()\n        while conns:\n            transport, proto, t0 = conns.pop()\n            if transport is not None and proto.is_connected():\n                if t1 - t0 > self._keepalive_timeout:\n                    transport.close()\n                    transport = None\n                else:\n                    return transport, proto\n\n        return None, None\n\n    def _release(self, key, req, transport, protocol, *, should_close=False):\n        resp = req.response\n\n        if not should_close:\n            if resp is not None:\n                if resp.message is None:\n                    should_close = True\n                else:\n                    should_close = resp.message.should_close\n\n            if self._force_close:\n                should_close = True\n\n        reader = protocol.reader\n        if should_close or (reader.output and not reader.output.at_eof()):\n            conns = self._conns.get(key)\n            if conns is not None and len(conns) == 0:\n                # Issue #253: An empty array will eventually be\n                # removed by cleanup, but it's better to pop straight\n                # away, because cleanup might not get called (e.g. if\n                # keepalive is False).\n                self._conns.pop(key, None)\n\n            transport.close()\n        else:\n            conns = self._conns.get(key)\n            if conns is None:\n                conns = self._conns[key] = []\n            conns.append((transport, protocol, self._loop.time()))\n            reader.unset_parser()\n\n            self._start_cleanup_task()\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        raise NotImplementedError()\n\n\n_SSL_OP_NO_COMPRESSION = getattr(ssl, \"OP_NO_COMPRESSION\", 0)\n_SSH_HAS_CREATE_DEFAULT_CONTEXT = hasattr(ssl, 'create_default_context')\n\n\nclass TCPConnector(BaseConnector):\n    \"\"\"TCP connector.\n\n    :param bool verify_ssl: Set to True to check ssl certifications.\n    :param bool resolve: Set to True to do DNS lookup for host name.\n    :param family: socket address family\n    :param args: see :class:`BaseConnector`\n    :param kwargs: see :class:`BaseConnector`\n    \"\"\"\n\n    def __init__(self, *args, verify_ssl=True,\n                 resolve=False, family=socket.AF_INET, ssl_context=None,\n                 **kwargs):\n        super().__init__(*args, **kwargs)\n\n        if not verify_ssl and ssl_context is not None:\n            raise ValueError(\n                \"Either disable ssl certificate validation by \"\n                \"verify_ssl=False or specify ssl_context, not both.\")\n\n        self._verify_ssl = verify_ssl\n        self._ssl_context = ssl_context\n        self._family = family\n        self._resolve = resolve\n        self._resolved_hosts = {}\n\n    @property\n    def verify_ssl(self):\n        \"\"\"Do check for ssl certifications?\"\"\"\n        return self._verify_ssl\n\n    @property\n    def ssl_context(self):\n        \"\"\"SSLContext instance for https requests.\n\n        Lazy property, creates context on demand.\n        \"\"\"\n        if self._ssl_context is None:\n            if not self._verify_ssl:\n                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n                sslcontext.options |= ssl.OP_NO_SSLv2\n                sslcontext.options |= ssl.OP_NO_SSLv3\n                sslcontext.options |= _SSL_OP_NO_COMPRESSION\n                sslcontext.set_default_verify_paths()\n            elif _SSH_HAS_CREATE_DEFAULT_CONTEXT:\n                # Python 3.4+\n                sslcontext = ssl.create_default_context()\n            else:\n                # Fallback for Python 3.3.\n                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n                sslcontext.options |= ssl.OP_NO_SSLv2\n                sslcontext.options |= ssl.OP_NO_SSLv3\n                sslcontext.options |= _SSL_OP_NO_COMPRESSION\n                sslcontext.set_default_verify_paths()\n                sslcontext.verify_mode = ssl.CERT_REQUIRED\n            self._ssl_context = sslcontext\n        return self._ssl_context\n\n    @property\n    def family(self):\n        \"\"\"Socket family like AF_INET.\"\"\"\n        return self._family\n\n    @property\n    def resolve(self):\n        \"\"\"Do DNS lookup for host name?\"\"\"\n        return self._resolve\n\n    @property\n    def resolved_hosts(self):\n        \"\"\"The dict of (host, port) -> (ipaddr, port) pairs.\"\"\"\n        return dict(self._resolved_hosts)\n\n    def clear_resolved_hosts(self, host=None, port=None):\n        \"\"\"Remove specified host/port or clear all resolve cache.\"\"\"\n        if host is not None and port is not None:\n            key = (host, port)\n            if key in self._resolved_hosts:\n                del self._resolved_hosts[key]\n        else:\n            self._resolved_hosts.clear()\n\n    @asyncio.coroutine\n    def _resolve_host(self, host, port):\n        if self._resolve:\n            key = (host, port)\n\n            if key not in self._resolved_hosts:\n                infos = yield from self._loop.getaddrinfo(\n                    host, port, type=socket.SOCK_STREAM, family=self._family)\n\n                hosts = []\n                for family, _, proto, _, address in infos:\n                    hosts.append(\n                        {'hostname': host,\n                         'host': address[0], 'port': address[1],\n                         'family': family, 'proto': proto,\n                         'flags': socket.AI_NUMERICHOST})\n                self._resolved_hosts[key] = hosts\n\n            return list(self._resolved_hosts[key])\n        else:\n            return [{'hostname': host, 'host': host, 'port': port,\n                     'family': self._family, 'proto': 0, 'flags': 0}]\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        \"\"\"Create connection.\n\n        Has same keyword arguments as BaseEventLoop.create_connection.\n        \"\"\"\n        if req.ssl:\n            sslcontext = self.ssl_context\n        else:\n            sslcontext = None\n\n        hosts = yield from self._resolve_host(req.host, req.port)\n\n        while hosts:\n            hinfo = hosts.pop()\n            try:\n                return (yield from self._loop.create_connection(\n                    self._factory, hinfo['host'], hinfo['port'],\n                    ssl=sslcontext, family=hinfo['family'],\n                    proto=hinfo['proto'], flags=hinfo['flags'],\n                    server_hostname=hinfo['hostname'] if sslcontext else None))\n            except OSError as exc:\n                if not hosts:\n                    raise ClientOSError('Can not connect to %s:%s' %\n                                        (req.host, req.port)) from exc\n\n\nclass ProxyConnector(TCPConnector):\n    \"\"\"Http Proxy connector.\n\n    :param str proxy: Proxy URL address. Only http proxy supported.\n    :param proxy_auth: (optional) Proxy HTTP Basic Auth\n    :type proxy_auth: aiohttp.helpers.BasicAuth\n    :param args: see :class:`TCPConnector`\n    :param kwargs: see :class:`TCPConnector`\n\n    Usage:\n\n    >>> conn = ProxyConnector(proxy=\"http://some.proxy.com\")\n    >>> session = ClientSession(connector=conn)\n    >>> resp = yield from session.get('http://python.org')\n\n    \"\"\"\n\n    def __init__(self, proxy, *args, proxy_auth=None, **kwargs):\n        super().__init__(*args, **kwargs)\n        self._proxy = proxy\n        self._proxy_auth = proxy_auth\n        assert proxy.startswith('http://'), (\n            \"Only http proxy supported\", proxy)\n        assert proxy_auth is None or isinstance(proxy_auth, BasicAuth), (\n            \"proxy_auth must be None or BasicAuth() tuple\", proxy_auth)\n\n    @property\n    def proxy(self):\n        \"\"\"Proxy URL.\"\"\"\n        return self._proxy\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        proxy_req = ClientRequest(\n            hdrs.METH_GET, self._proxy,\n            headers={hdrs.HOST: req.host},\n            auth=self._proxy_auth,\n            loop=self._loop)\n        try:\n            transport, proto = yield from super()._create_connection(proxy_req)\n        except OSError as exc:\n            raise ProxyConnectionError(*exc.args) from exc\n\n        if not req.ssl:\n            req.path = '{scheme}://{host}{path}'.format(scheme=req.scheme,\n                                                        host=req.netloc,\n                                                        path=req.path)\n        if hdrs.AUTHORIZATION in proxy_req.headers:\n            auth = proxy_req.headers[hdrs.AUTHORIZATION]\n            del proxy_req.headers[hdrs.AUTHORIZATION]\n            req.headers[hdrs.PROXY_AUTHORIZATION] = auth\n\n        if req.ssl:\n            # For HTTPS requests over HTTP proxy\n            # we must notify proxy to tunnel connection\n            # so we send CONNECT command:\n            #   CONNECT www.python.org:443 HTTP/1.1\n            #   Host: www.python.org\n            #\n            # next we must do TLS handshake and so on\n            # to do this we must wrap raw socket into secure one\n            # asyncio handles this perfectly\n            proxy_req.method = hdrs.METH_CONNECT\n            proxy_req.path = '{}:{}'.format(req.host, req.port)\n            key = (req.host, req.port, req.ssl)\n            conn = Connection(self, key, proxy_req,\n                              transport, proto, self._loop)\n            proxy_resp = proxy_req.send(conn.writer, conn.reader)\n            try:\n                resp = yield from proxy_resp.start(conn, True)\n            except:\n                proxy_resp.close()\n                conn.close()\n                raise\n            else:\n                conn.detach()\n                if resp.status != 200:\n                    raise HttpProxyError(code=resp.status, message=resp.reason)\n                rawsock = transport.get_extra_info('socket', default=None)\n                if rawsock is None:\n                    raise RuntimeError(\n                        \"Transport does not expose socket instance\")\n                transport.pause_reading()\n                transport, proto = yield from self._loop.create_connection(\n                    self._factory, ssl=True, sock=rawsock,\n                    server_hostname=req.host)\n\n        return transport, proto\n\n\nclass UnixConnector(BaseConnector):\n    \"\"\"Unix socket connector.\n\n    :param str path: Unix socket path.\n    :param args: see :class:`BaseConnector`\n    :param kwargs: see :class:`BaseConnector`\n\n    Usage:\n\n    >>> conn = UnixConnector(path='/path/to/socket')\n    >>> session = ClientSession(connector=conn)\n    >>> resp = yield from session.get('http://python.org')\n\n    \"\"\"\n\n    def __init__(self, path, *args, **kw):\n        super().__init__(*args, **kw)\n        self._path = path\n\n    @property\n    def path(self):\n        \"\"\"Path to unix socket.\"\"\"\n        return self._path\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        return (yield from self._loop.create_unix_connection(\n            self._factory, self._path))\n",
            "header": {
                "file": {
                    "path": "aiohttp/connector.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "98583b52",
                "new_commit_hash": "5e47ce59",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/aiohttp/connector.py"
            },
            "plus_file": {
                "path": "b/aiohttp/connector.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 8,
                            "length": 6
                        },
                        "new_range": {
                            "start": 8,
                            "length": 7
                        },
                        "section": "import sys"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import traceback",
                                "type": "context"
                            },
                            {
                                "content": "import warnings",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from math import ceil",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from . import hdrs",
                                "type": "context"
                            },
                            {
                                "content": "from .client import ClientRequest",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "aiohttp/connector.py",
                            "type": "statement",
                            "name": "",
                            "content": "from math import ceil",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 11,
                            "end_lineno": 11,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 170,
                            "length": 21
                        },
                        "new_range": {
                            "start": 171,
                            "length": 22
                        },
                        "section": "class BaseConnector(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                        transport.close()",
                                "type": "context"
                            },
                            {
                                "content": "                        transport = None",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "                if transport:",
                                "type": "deleted"
                            },
                            {
                                "content": "                if transport is not None:",
                                "type": "added"
                            },
                            {
                                "content": "                    alive.append((transport, proto, t0))",
                                "type": "context"
                            },
                            {
                                "content": "            if alive:",
                                "type": "context"
                            },
                            {
                                "content": "                connections[key] = alive",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        if connections:",
                                "type": "context"
                            },
                            {
                                "content": "            self._cleanup_handle = self._loop.call_later(",
                                "type": "deleted"
                            },
                            {
                                "content": "                self._keepalive_timeout, self._cleanup)",
                                "type": "deleted"
                            },
                            {
                                "content": "            self._cleanup_handle = self._loop.call_at(",
                                "type": "added"
                            },
                            {
                                "content": "                ceil(now + self._keepalive_timeout), self._cleanup)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self._conns = connections",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def _start_cleanup_task(self):",
                                "type": "context"
                            },
                            {
                                "content": "        if self._cleanup_handle is None:",
                                "type": "context"
                            },
                            {
                                "content": "            self._cleanup_handle = self._loop.call_later(",
                                "type": "deleted"
                            },
                            {
                                "content": "                self._keepalive_timeout, self._cleanup)",
                                "type": "deleted"
                            },
                            {
                                "content": "            now = self._loop.time()",
                                "type": "added"
                            },
                            {
                                "content": "            self._cleanup_handle = self._loop.call_at(",
                                "type": "added"
                            },
                            {
                                "content": "                ceil(now + self._keepalive_timeout), self._cleanup)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def close(self):",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"Close all opened transports.\"\"\"",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/connector.py",
                            "type": "method",
                            "name": "BaseConnector._cleanup",
                            "content": "class BaseConnector(object):\n    \"\"\"Base connector class.\n\n    :param conn_timeout: (optional) Connect timeout.\n    :param keepalive_timeout: (optional) Keep-alive timeout.\n    :param bool force_close: Set to True to force close and do reconnect\n        after each request (and between redirects).\n    :param loop: Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,\n                 share_cookies=False, force_close=False, loop=None):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        self._conns = {}\n        self._conn_timeout = conn_timeout\n        self._keepalive_timeout = keepalive_timeout\n        if share_cookies:\n            warnings.warn(\n                'Using `share_cookies` is deprecated. '\n                'Use Session object instead', DeprecationWarning)\n        self._share_cookies = share_cookies\n        self._cleanup_handle = None\n        self._force_close = force_close\n\n        self._loop = loop\n        self._factory = functools.partial(\n            aiohttp.StreamProtocol, loop=loop,\n            disconnect_error=ServerDisconnectedError)\n\n        self.cookies = http.cookies.SimpleCookie()\n\n    if PY_34:\n        def __del__(self):\n            if self._closed:\n                return\n            if not self._conns:\n                return\n\n            loop_is_not_closed = not self._loop.is_closed()\n\n            for key, data in self._conns.items():\n                for transport, proto, t0 in data:\n                    if loop_is_not_closed:\n                        transport.close()\n            self._conns.clear()\n\n            # N.B.\n            # Don't check for self._cleanup_handle!\n            # The reason is: if self._cleanup_handle was scheduled\n            # a reference to self is stored in event loop.\n            # Thus __del__ will not be called until cleanup handler executes.\n\n            warnings.warn(\"Unclosed connector {!r}\".format(self),\n                          ResourceWarning)\n            context = {'connector': self,\n                       'message': 'Unclosed connector'}\n            if self._source_traceback is not None:\n                context['source_traceback'] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def _cleanup(self):\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n        now = self._loop.time()\n\n        connections = {}\n        for key, conns in self._conns.items():\n            alive = []\n            for transport, proto, t0 in conns:\n                if transport is not None:\n                    if proto and not proto.is_connected():\n                        transport = None\n                    elif (now - t0) > self._keepalive_timeout:\n                        transport.close()\n                        transport = None\n\n                if transport:\n                    alive.append((transport, proto, t0))\n            if alive:\n                connections[key] = alive\n\n        if connections:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n        self._conns = connections\n\n    def _start_cleanup_task(self):\n        if self._cleanup_handle is None:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n    def close(self):\n        \"\"\"Close all opened transports.\"\"\"\n        if self._closed:\n            return\n        self._closed = True\n\n        for key, data in self._conns.items():\n            for transport, proto, t0 in data:\n                transport.close()\n\n        self._conns.clear()\n\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n    @property\n    def closed(self):\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def update_cookies(self, cookies):\n        \"\"\"Update shared cookies.\n\n        Deprecated, use ClientSession instead.\n        \"\"\"\n        if isinstance(cookies, dict):\n            cookies = cookies.items()\n\n        for name, value in cookies:\n            if PY_343:\n                self.cookies[name] = value\n            else:\n                if isinstance(value, http.cookies.Morsel):\n                    # use dict method because SimpleCookie class modifies value\n                    dict.__setitem__(self.cookies, name, value)\n                else:\n                    self.cookies[name] = value\n\n    @asyncio.coroutine\n    def connect(self, req):\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = (req.host, req.port, req.ssl)\n\n        transport, proto = self._get(key)\n        if transport is None:\n            try:\n                if self._conn_timeout:\n                    transport, proto = yield from asyncio.wait_for(\n                        self._create_connection(req),\n                        self._conn_timeout, loop=self._loop)\n                else:\n                    transport, proto = yield from self._create_connection(req)\n            except asyncio.TimeoutError as exc:\n                raise ClientTimeoutError(\n                    'Connection timeout to host %s:%s ssl:%s' % key) from exc\n            except OSError as exc:\n                raise ClientOSError(\n                    'Cannot connect to host %s:%s ssl:%s' % key) from exc\n\n        return Connection(self, key, req, transport, proto, self._loop)\n\n    def _get(self, key):\n        conns = self._conns.get(key)\n        t1 = self._loop.time()\n        while conns:\n            transport, proto, t0 = conns.pop()\n            if transport is not None and proto.is_connected():\n                if t1 - t0 > self._keepalive_timeout:\n                    transport.close()\n                    transport = None\n                else:\n                    return transport, proto\n\n        return None, None\n\n    def _release(self, key, req, transport, protocol, *, should_close=False):\n        resp = req.response\n\n        if not should_close:\n            if resp is not None:\n                if resp.message is None:\n                    should_close = True\n                else:\n                    should_close = resp.message.should_close\n\n            if self._force_close:\n                should_close = True\n\n        reader = protocol.reader\n        if should_close or (reader.output and not reader.output.at_eof()):\n            conns = self._conns.get(key)\n            if conns is not None and len(conns) == 0:\n                # Issue #253: An empty array will eventually be\n                # removed by cleanup, but it's better to pop straight\n                # away, because cleanup might not get called (e.g. if\n                # keepalive is False).\n                self._conns.pop(key, None)\n\n            transport.close()\n        else:\n            conns = self._conns.get(key)\n            if conns is None:\n                conns = self._conns[key] = []\n            conns.append((transport, protocol, self._loop.time()))\n            reader.unset_parser()\n\n            self._start_cleanup_task()\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        raise NotImplementedError()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 154,
                            "end_lineno": 182,
                            "parent": {
                                "file_name": "aiohttp/connector.py",
                                "type": "class",
                                "name": "BaseConnector",
                                "content": "class BaseConnector(object):\n    \"\"\"Base connector class.\n\n    :param conn_timeout: (optional) Connect timeout.\n    :param keepalive_timeout: (optional) Keep-alive timeout.\n    :param bool force_close: Set to True to force close and do reconnect\n        after each request (and between redirects).\n    :param loop: Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,\n                 share_cookies=False, force_close=False, loop=None):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        self._conns = {}\n        self._conn_timeout = conn_timeout\n        self._keepalive_timeout = keepalive_timeout\n        if share_cookies:\n            warnings.warn(\n                'Using `share_cookies` is deprecated. '\n                'Use Session object instead', DeprecationWarning)\n        self._share_cookies = share_cookies\n        self._cleanup_handle = None\n        self._force_close = force_close\n\n        self._loop = loop\n        self._factory = functools.partial(\n            aiohttp.StreamProtocol, loop=loop,\n            disconnect_error=ServerDisconnectedError)\n\n        self.cookies = http.cookies.SimpleCookie()\n\n    if PY_34:\n        def __del__(self):\n            if self._closed:\n                return\n            if not self._conns:\n                return\n\n            loop_is_not_closed = not self._loop.is_closed()\n\n            for key, data in self._conns.items():\n                for transport, proto, t0 in data:\n                    if loop_is_not_closed:\n                        transport.close()\n            self._conns.clear()\n\n            # N.B.\n            # Don't check for self._cleanup_handle!\n            # The reason is: if self._cleanup_handle was scheduled\n            # a reference to self is stored in event loop.\n            # Thus __del__ will not be called until cleanup handler executes.\n\n            warnings.warn(\"Unclosed connector {!r}\".format(self),\n                          ResourceWarning)\n            context = {'connector': self,\n                       'message': 'Unclosed connector'}\n            if self._source_traceback is not None:\n                context['source_traceback'] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def _cleanup(self):\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n        now = self._loop.time()\n\n        connections = {}\n        for key, conns in self._conns.items():\n            alive = []\n            for transport, proto, t0 in conns:\n                if transport is not None:\n                    if proto and not proto.is_connected():\n                        transport = None\n                    elif (now - t0) > self._keepalive_timeout:\n                        transport.close()\n                        transport = None\n\n                if transport:\n                    alive.append((transport, proto, t0))\n            if alive:\n                connections[key] = alive\n\n        if connections:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n        self._conns = connections\n\n    def _start_cleanup_task(self):\n        if self._cleanup_handle is None:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n    def close(self):\n        \"\"\"Close all opened transports.\"\"\"\n        if self._closed:\n            return\n        self._closed = True\n\n        for key, data in self._conns.items():\n            for transport, proto, t0 in data:\n                transport.close()\n\n        self._conns.clear()\n\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n    @property\n    def closed(self):\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def update_cookies(self, cookies):\n        \"\"\"Update shared cookies.\n\n        Deprecated, use ClientSession instead.\n        \"\"\"\n        if isinstance(cookies, dict):\n            cookies = cookies.items()\n\n        for name, value in cookies:\n            if PY_343:\n                self.cookies[name] = value\n            else:\n                if isinstance(value, http.cookies.Morsel):\n                    # use dict method because SimpleCookie class modifies value\n                    dict.__setitem__(self.cookies, name, value)\n                else:\n                    self.cookies[name] = value\n\n    @asyncio.coroutine\n    def connect(self, req):\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = (req.host, req.port, req.ssl)\n\n        transport, proto = self._get(key)\n        if transport is None:\n            try:\n                if self._conn_timeout:\n                    transport, proto = yield from asyncio.wait_for(\n                        self._create_connection(req),\n                        self._conn_timeout, loop=self._loop)\n                else:\n                    transport, proto = yield from self._create_connection(req)\n            except asyncio.TimeoutError as exc:\n                raise ClientTimeoutError(\n                    'Connection timeout to host %s:%s ssl:%s' % key) from exc\n            except OSError as exc:\n                raise ClientOSError(\n                    'Cannot connect to host %s:%s ssl:%s' % key) from exc\n\n        return Connection(self, key, req, transport, proto, self._loop)\n\n    def _get(self, key):\n        conns = self._conns.get(key)\n        t1 = self._loop.time()\n        while conns:\n            transport, proto, t0 = conns.pop()\n            if transport is not None and proto.is_connected():\n                if t1 - t0 > self._keepalive_timeout:\n                    transport.close()\n                    transport = None\n                else:\n                    return transport, proto\n\n        return None, None\n\n    def _release(self, key, req, transport, protocol, *, should_close=False):\n        resp = req.response\n\n        if not should_close:\n            if resp is not None:\n                if resp.message is None:\n                    should_close = True\n                else:\n                    should_close = resp.message.should_close\n\n            if self._force_close:\n                should_close = True\n\n        reader = protocol.reader\n        if should_close or (reader.output and not reader.output.at_eof()):\n            conns = self._conns.get(key)\n            if conns is not None and len(conns) == 0:\n                # Issue #253: An empty array will eventually be\n                # removed by cleanup, but it's better to pop straight\n                # away, because cleanup might not get called (e.g. if\n                # keepalive is False).\n                self._conns.pop(key, None)\n\n            transport.close()\n        else:\n            conns = self._conns.get(key)\n            if conns is None:\n                conns = self._conns[key] = []\n            conns.append((transport, protocol, self._loop.time()))\n            reader.unset_parser()\n\n            self._start_cleanup_task()\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        raise NotImplementedError()",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 85,
                                "end_lineno": 303,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "aiohttp/connector.py",
                            "type": "method",
                            "name": "BaseConnector._start_cleanup_task",
                            "content": "class BaseConnector(object):\n    \"\"\"Base connector class.\n\n    :param conn_timeout: (optional) Connect timeout.\n    :param keepalive_timeout: (optional) Keep-alive timeout.\n    :param bool force_close: Set to True to force close and do reconnect\n        after each request (and between redirects).\n    :param loop: Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,\n                 share_cookies=False, force_close=False, loop=None):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        self._conns = {}\n        self._conn_timeout = conn_timeout\n        self._keepalive_timeout = keepalive_timeout\n        if share_cookies:\n            warnings.warn(\n                'Using `share_cookies` is deprecated. '\n                'Use Session object instead', DeprecationWarning)\n        self._share_cookies = share_cookies\n        self._cleanup_handle = None\n        self._force_close = force_close\n\n        self._loop = loop\n        self._factory = functools.partial(\n            aiohttp.StreamProtocol, loop=loop,\n            disconnect_error=ServerDisconnectedError)\n\n        self.cookies = http.cookies.SimpleCookie()\n\n    if PY_34:\n        def __del__(self):\n            if self._closed:\n                return\n            if not self._conns:\n                return\n\n            loop_is_not_closed = not self._loop.is_closed()\n\n            for key, data in self._conns.items():\n                for transport, proto, t0 in data:\n                    if loop_is_not_closed:\n                        transport.close()\n            self._conns.clear()\n\n            # N.B.\n            # Don't check for self._cleanup_handle!\n            # The reason is: if self._cleanup_handle was scheduled\n            # a reference to self is stored in event loop.\n            # Thus __del__ will not be called until cleanup handler executes.\n\n            warnings.warn(\"Unclosed connector {!r}\".format(self),\n                          ResourceWarning)\n            context = {'connector': self,\n                       'message': 'Unclosed connector'}\n            if self._source_traceback is not None:\n                context['source_traceback'] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def _cleanup(self):\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n        now = self._loop.time()\n\n        connections = {}\n        for key, conns in self._conns.items():\n            alive = []\n            for transport, proto, t0 in conns:\n                if transport is not None:\n                    if proto and not proto.is_connected():\n                        transport = None\n                    elif (now - t0) > self._keepalive_timeout:\n                        transport.close()\n                        transport = None\n\n                if transport:\n                    alive.append((transport, proto, t0))\n            if alive:\n                connections[key] = alive\n\n        if connections:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n        self._conns = connections\n\n    def _start_cleanup_task(self):\n        if self._cleanup_handle is None:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n    def close(self):\n        \"\"\"Close all opened transports.\"\"\"\n        if self._closed:\n            return\n        self._closed = True\n\n        for key, data in self._conns.items():\n            for transport, proto, t0 in data:\n                transport.close()\n\n        self._conns.clear()\n\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n    @property\n    def closed(self):\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def update_cookies(self, cookies):\n        \"\"\"Update shared cookies.\n\n        Deprecated, use ClientSession instead.\n        \"\"\"\n        if isinstance(cookies, dict):\n            cookies = cookies.items()\n\n        for name, value in cookies:\n            if PY_343:\n                self.cookies[name] = value\n            else:\n                if isinstance(value, http.cookies.Morsel):\n                    # use dict method because SimpleCookie class modifies value\n                    dict.__setitem__(self.cookies, name, value)\n                else:\n                    self.cookies[name] = value\n\n    @asyncio.coroutine\n    def connect(self, req):\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = (req.host, req.port, req.ssl)\n\n        transport, proto = self._get(key)\n        if transport is None:\n            try:\n                if self._conn_timeout:\n                    transport, proto = yield from asyncio.wait_for(\n                        self._create_connection(req),\n                        self._conn_timeout, loop=self._loop)\n                else:\n                    transport, proto = yield from self._create_connection(req)\n            except asyncio.TimeoutError as exc:\n                raise ClientTimeoutError(\n                    'Connection timeout to host %s:%s ssl:%s' % key) from exc\n            except OSError as exc:\n                raise ClientOSError(\n                    'Cannot connect to host %s:%s ssl:%s' % key) from exc\n\n        return Connection(self, key, req, transport, proto, self._loop)\n\n    def _get(self, key):\n        conns = self._conns.get(key)\n        t1 = self._loop.time()\n        while conns:\n            transport, proto, t0 = conns.pop()\n            if transport is not None and proto.is_connected():\n                if t1 - t0 > self._keepalive_timeout:\n                    transport.close()\n                    transport = None\n                else:\n                    return transport, proto\n\n        return None, None\n\n    def _release(self, key, req, transport, protocol, *, should_close=False):\n        resp = req.response\n\n        if not should_close:\n            if resp is not None:\n                if resp.message is None:\n                    should_close = True\n                else:\n                    should_close = resp.message.should_close\n\n            if self._force_close:\n                should_close = True\n\n        reader = protocol.reader\n        if should_close or (reader.output and not reader.output.at_eof()):\n            conns = self._conns.get(key)\n            if conns is not None and len(conns) == 0:\n                # Issue #253: An empty array will eventually be\n                # removed by cleanup, but it's better to pop straight\n                # away, because cleanup might not get called (e.g. if\n                # keepalive is False).\n                self._conns.pop(key, None)\n\n            transport.close()\n        else:\n            conns = self._conns.get(key)\n            if conns is None:\n                conns = self._conns[key] = []\n            conns.append((transport, protocol, self._loop.time()))\n            reader.unset_parser()\n\n            self._start_cleanup_task()\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        raise NotImplementedError()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 184,
                            "end_lineno": 187,
                            "parent": {
                                "file_name": "aiohttp/connector.py",
                                "type": "class",
                                "name": "BaseConnector",
                                "content": "class BaseConnector(object):\n    \"\"\"Base connector class.\n\n    :param conn_timeout: (optional) Connect timeout.\n    :param keepalive_timeout: (optional) Keep-alive timeout.\n    :param bool force_close: Set to True to force close and do reconnect\n        after each request (and between redirects).\n    :param loop: Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,\n                 share_cookies=False, force_close=False, loop=None):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        self._conns = {}\n        self._conn_timeout = conn_timeout\n        self._keepalive_timeout = keepalive_timeout\n        if share_cookies:\n            warnings.warn(\n                'Using `share_cookies` is deprecated. '\n                'Use Session object instead', DeprecationWarning)\n        self._share_cookies = share_cookies\n        self._cleanup_handle = None\n        self._force_close = force_close\n\n        self._loop = loop\n        self._factory = functools.partial(\n            aiohttp.StreamProtocol, loop=loop,\n            disconnect_error=ServerDisconnectedError)\n\n        self.cookies = http.cookies.SimpleCookie()\n\n    if PY_34:\n        def __del__(self):\n            if self._closed:\n                return\n            if not self._conns:\n                return\n\n            loop_is_not_closed = not self._loop.is_closed()\n\n            for key, data in self._conns.items():\n                for transport, proto, t0 in data:\n                    if loop_is_not_closed:\n                        transport.close()\n            self._conns.clear()\n\n            # N.B.\n            # Don't check for self._cleanup_handle!\n            # The reason is: if self._cleanup_handle was scheduled\n            # a reference to self is stored in event loop.\n            # Thus __del__ will not be called until cleanup handler executes.\n\n            warnings.warn(\"Unclosed connector {!r}\".format(self),\n                          ResourceWarning)\n            context = {'connector': self,\n                       'message': 'Unclosed connector'}\n            if self._source_traceback is not None:\n                context['source_traceback'] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def _cleanup(self):\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n        now = self._loop.time()\n\n        connections = {}\n        for key, conns in self._conns.items():\n            alive = []\n            for transport, proto, t0 in conns:\n                if transport is not None:\n                    if proto and not proto.is_connected():\n                        transport = None\n                    elif (now - t0) > self._keepalive_timeout:\n                        transport.close()\n                        transport = None\n\n                if transport:\n                    alive.append((transport, proto, t0))\n            if alive:\n                connections[key] = alive\n\n        if connections:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n        self._conns = connections\n\n    def _start_cleanup_task(self):\n        if self._cleanup_handle is None:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n    def close(self):\n        \"\"\"Close all opened transports.\"\"\"\n        if self._closed:\n            return\n        self._closed = True\n\n        for key, data in self._conns.items():\n            for transport, proto, t0 in data:\n                transport.close()\n\n        self._conns.clear()\n\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n    @property\n    def closed(self):\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def update_cookies(self, cookies):\n        \"\"\"Update shared cookies.\n\n        Deprecated, use ClientSession instead.\n        \"\"\"\n        if isinstance(cookies, dict):\n            cookies = cookies.items()\n\n        for name, value in cookies:\n            if PY_343:\n                self.cookies[name] = value\n            else:\n                if isinstance(value, http.cookies.Morsel):\n                    # use dict method because SimpleCookie class modifies value\n                    dict.__setitem__(self.cookies, name, value)\n                else:\n                    self.cookies[name] = value\n\n    @asyncio.coroutine\n    def connect(self, req):\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = (req.host, req.port, req.ssl)\n\n        transport, proto = self._get(key)\n        if transport is None:\n            try:\n                if self._conn_timeout:\n                    transport, proto = yield from asyncio.wait_for(\n                        self._create_connection(req),\n                        self._conn_timeout, loop=self._loop)\n                else:\n                    transport, proto = yield from self._create_connection(req)\n            except asyncio.TimeoutError as exc:\n                raise ClientTimeoutError(\n                    'Connection timeout to host %s:%s ssl:%s' % key) from exc\n            except OSError as exc:\n                raise ClientOSError(\n                    'Cannot connect to host %s:%s ssl:%s' % key) from exc\n\n        return Connection(self, key, req, transport, proto, self._loop)\n\n    def _get(self, key):\n        conns = self._conns.get(key)\n        t1 = self._loop.time()\n        while conns:\n            transport, proto, t0 = conns.pop()\n            if transport is not None and proto.is_connected():\n                if t1 - t0 > self._keepalive_timeout:\n                    transport.close()\n                    transport = None\n                else:\n                    return transport, proto\n\n        return None, None\n\n    def _release(self, key, req, transport, protocol, *, should_close=False):\n        resp = req.response\n\n        if not should_close:\n            if resp is not None:\n                if resp.message is None:\n                    should_close = True\n                else:\n                    should_close = resp.message.should_close\n\n            if self._force_close:\n                should_close = True\n\n        reader = protocol.reader\n        if should_close or (reader.output and not reader.output.at_eof()):\n            conns = self._conns.get(key)\n            if conns is not None and len(conns) == 0:\n                # Issue #253: An empty array will eventually be\n                # removed by cleanup, but it's better to pop straight\n                # away, because cleanup might not get called (e.g. if\n                # keepalive is False).\n                self._conns.pop(key, None)\n\n            transport.close()\n        else:\n            conns = self._conns.get(key)\n            if conns is None:\n                conns = self._conns[key] = []\n            conns.append((transport, protocol, self._loop.time()))\n            reader.unset_parser()\n\n            self._start_cleanup_task()\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        raise NotImplementedError()",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 85,
                                "end_lineno": 303,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "aiohttp/connector.py",
                            "type": "class",
                            "name": "BaseConnector",
                            "content": "class BaseConnector(object):\n    \"\"\"Base connector class.\n\n    :param conn_timeout: (optional) Connect timeout.\n    :param keepalive_timeout: (optional) Keep-alive timeout.\n    :param bool force_close: Set to True to force close and do reconnect\n        after each request (and between redirects).\n    :param loop: Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,\n                 share_cookies=False, force_close=False, loop=None):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        self._conns = {}\n        self._conn_timeout = conn_timeout\n        self._keepalive_timeout = keepalive_timeout\n        if share_cookies:\n            warnings.warn(\n                'Using `share_cookies` is deprecated. '\n                'Use Session object instead', DeprecationWarning)\n        self._share_cookies = share_cookies\n        self._cleanup_handle = None\n        self._force_close = force_close\n\n        self._loop = loop\n        self._factory = functools.partial(\n            aiohttp.StreamProtocol, loop=loop,\n            disconnect_error=ServerDisconnectedError)\n\n        self.cookies = http.cookies.SimpleCookie()\n\n    if PY_34:\n        def __del__(self):\n            if self._closed:\n                return\n            if not self._conns:\n                return\n\n            loop_is_not_closed = not self._loop.is_closed()\n\n            for key, data in self._conns.items():\n                for transport, proto, t0 in data:\n                    if loop_is_not_closed:\n                        transport.close()\n            self._conns.clear()\n\n            # N.B.\n            # Don't check for self._cleanup_handle!\n            # The reason is: if self._cleanup_handle was scheduled\n            # a reference to self is stored in event loop.\n            # Thus __del__ will not be called until cleanup handler executes.\n\n            warnings.warn(\"Unclosed connector {!r}\".format(self),\n                          ResourceWarning)\n            context = {'connector': self,\n                       'message': 'Unclosed connector'}\n            if self._source_traceback is not None:\n                context['source_traceback'] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def _cleanup(self):\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n        now = self._loop.time()\n\n        connections = {}\n        for key, conns in self._conns.items():\n            alive = []\n            for transport, proto, t0 in conns:\n                if transport is not None:\n                    if proto and not proto.is_connected():\n                        transport = None\n                    elif (now - t0) > self._keepalive_timeout:\n                        transport.close()\n                        transport = None\n\n                if transport:\n                    alive.append((transport, proto, t0))\n            if alive:\n                connections[key] = alive\n\n        if connections:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n        self._conns = connections\n\n    def _start_cleanup_task(self):\n        if self._cleanup_handle is None:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n    def close(self):\n        \"\"\"Close all opened transports.\"\"\"\n        if self._closed:\n            return\n        self._closed = True\n\n        for key, data in self._conns.items():\n            for transport, proto, t0 in data:\n                transport.close()\n\n        self._conns.clear()\n\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n    @property\n    def closed(self):\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def update_cookies(self, cookies):\n        \"\"\"Update shared cookies.\n\n        Deprecated, use ClientSession instead.\n        \"\"\"\n        if isinstance(cookies, dict):\n            cookies = cookies.items()\n\n        for name, value in cookies:\n            if PY_343:\n                self.cookies[name] = value\n            else:\n                if isinstance(value, http.cookies.Morsel):\n                    # use dict method because SimpleCookie class modifies value\n                    dict.__setitem__(self.cookies, name, value)\n                else:\n                    self.cookies[name] = value\n\n    @asyncio.coroutine\n    def connect(self, req):\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = (req.host, req.port, req.ssl)\n\n        transport, proto = self._get(key)\n        if transport is None:\n            try:\n                if self._conn_timeout:\n                    transport, proto = yield from asyncio.wait_for(\n                        self._create_connection(req),\n                        self._conn_timeout, loop=self._loop)\n                else:\n                    transport, proto = yield from self._create_connection(req)\n            except asyncio.TimeoutError as exc:\n                raise ClientTimeoutError(\n                    'Connection timeout to host %s:%s ssl:%s' % key) from exc\n            except OSError as exc:\n                raise ClientOSError(\n                    'Cannot connect to host %s:%s ssl:%s' % key) from exc\n\n        return Connection(self, key, req, transport, proto, self._loop)\n\n    def _get(self, key):\n        conns = self._conns.get(key)\n        t1 = self._loop.time()\n        while conns:\n            transport, proto, t0 = conns.pop()\n            if transport is not None and proto.is_connected():\n                if t1 - t0 > self._keepalive_timeout:\n                    transport.close()\n                    transport = None\n                else:\n                    return transport, proto\n\n        return None, None\n\n    def _release(self, key, req, transport, protocol, *, should_close=False):\n        resp = req.response\n\n        if not should_close:\n            if resp is not None:\n                if resp.message is None:\n                    should_close = True\n                else:\n                    should_close = resp.message.should_close\n\n            if self._force_close:\n                should_close = True\n\n        reader = protocol.reader\n        if should_close or (reader.output and not reader.output.at_eof()):\n            conns = self._conns.get(key)\n            if conns is not None and len(conns) == 0:\n                # Issue #253: An empty array will eventually be\n                # removed by cleanup, but it's better to pop straight\n                # away, because cleanup might not get called (e.g. if\n                # keepalive is False).\n                self._conns.pop(key, None)\n\n            transport.close()\n        else:\n            conns = self._conns.get(key)\n            if conns is None:\n                conns = self._conns[key] = []\n            conns.append((transport, protocol, self._loop.time()))\n            reader.unset_parser()\n\n            self._start_cleanup_task()\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        raise NotImplementedError()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 85,
                            "end_lineno": 303,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "\"\"\"Tests of http client with custom Connector\"\"\"\n\nimport asyncio\nimport http.cookies\nimport gc\nimport socket\nimport unittest\nimport ssl\nimport sys\nfrom unittest import mock\n\nimport aiohttp\nfrom aiohttp import client\nfrom aiohttp import test_utils\nfrom aiohttp.client import ClientResponse, ClientRequest\nfrom aiohttp.connector import Connection\n\nfrom tests.test_client_functional import Functional\n\nPY_34 = sys.version_info >= (3, 4)\n\n\nclass TestHttpConnection(unittest.TestCase):\n\n    def setUp(self):\n        self.key = object()\n        self.connector = mock.Mock()\n        self.request = mock.Mock()\n        self.transport = mock.Mock()\n        self.protocol = mock.Mock()\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n        self.connector._release.assert_called_with(self.key,\n                                                   self.request,\n                                                   self.transport,\n                                                   self.protocol,\n                                                   should_close=True)\n        msg = {'client_connection': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connection'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    def test_close(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        self.assertFalse(conn.closed)\n        conn.close()\n        self.assertIsNone(conn._transport)\n        self.connector._release.assert_called_with(\n            self.key, self.request, self.transport, self.protocol,\n            should_close=True)\n        self.assertTrue(conn.closed)\n\n    def test_release(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        self.assertFalse(conn.closed)\n        conn.release()\n        self.assertFalse(self.transport.close.called)\n        self.assertIsNone(conn._transport)\n        self.connector._release.assert_called_with(\n            self.key, self.request, self.transport, self.protocol,\n            should_close=False)\n        self.assertTrue(conn.closed)\n\n    def test_release_released(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        conn.release()\n        self.connector._release.reset_mock()\n        conn.release()\n        self.assertFalse(self.transport.close.called)\n        self.assertIsNone(conn._transport)\n        self.assertFalse(self.connector._release.called)\n\n    def test_detach(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        self.assertFalse(conn.closed)\n        conn.detach()\n        self.assertIsNone(conn._transport)\n        self.assertFalse(self.connector._release.called)\n        self.assertTrue(conn.closed)\n\n\nclass TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        conn = aiohttp.BaseConnector(loop=loop)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_later.assert_called_with(\n            conn._keepalive_timeout, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)\n\n\nclass TestHttpClientConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n    def tearDown(self):\n        # just in case if we have transport close callbacks\n        test_utils.run_briefly(self.loop)\n\n        self.loop.close()\n        gc.collect()\n\n    def test_tcp_connector(self):\n        with test_utils.run_server(self.loop, router=Functional) as httpd:\n            r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=aiohttp.TCPConnector(loop=self.loop),\n                    loop=self.loop))\n            content = self.loop.run_until_complete(r.content.read())\n            content = content.decode()\n            self.assertEqual(r.status, 200)\n            r.close()\n\n    @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'requires unix')\n    def test_unix_connector(self):\n        path = '/tmp/aiohttp_unix.sock'\n\n        connector = aiohttp.UnixConnector(path, loop=self.loop)\n        self.assertEqual(path, connector.path)\n\n        with test_utils.run_server(\n                self.loop, listen_addr=path, router=Functional) as httpd:\n            r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=connector,\n                    loop=self.loop))\n            content = self.loop.run_until_complete(r.content.read())\n            content = content.decode()\n            self.assertEqual(r.status, 200)\n            r.close()\n\n    def test_connector_cookie_deprecation(self):\n        with self.assertWarnsRegex(DeprecationWarning,\n                                   \"^Using `share_cookies` is deprecated\"):\n            aiohttp.TCPConnector(share_cookies=True, loop=self.loop)\n\n\nclass TestProxyConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n    def tearDown(self):\n        # just in case if we have transport close callbacks\n        test_utils.run_briefly(self.loop)\n\n        self.loop.close()\n        gc.collect()\n\n    def _fake_coroutine(self, mock, return_value):\n\n        def coro(*args, **kw):\n            if isinstance(return_value, Exception):\n                raise return_value\n            return return_value\n            yield  # pragma: no cover\n        mock.side_effect = coro\n\n    def test_ctor(self):\n        with self.assertRaises(AssertionError):\n            aiohttp.ProxyConnector('https://localhost:8118', loop=self.loop)\n\n    def test_ctor2(self):\n        connector = aiohttp.ProxyConnector('http://localhost:8118',\n                                           loop=self.loop)\n\n        self.assertEqual('http://localhost:8118', connector.proxy)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_connect(self, ClientRequestMock):\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        self.assertEqual(req.path, '/')\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector('http://proxy.example.com',\n                                           loop=loop_mock)\n        self.assertIs(loop_mock, connector._loop)\n\n        resolve_host = unittest.mock.Mock()\n        self._fake_coroutine(resolve_host, [unittest.mock.MagicMock()])\n        connector._resolve_host = resolve_host\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n        conn = self.loop.run_until_complete(connector.connect(req))\n        self.assertEqual(req.path, 'http://www.python.org/')\n        self.assertIs(conn._transport, tr)\n        self.assertIs(conn._protocol, proto)\n\n        # resolve_host.assert_called_once_with('proxy.example.com', 80)\n        self.assertEqual(tr.mock_calls, [])\n\n        ClientRequestMock.assert_called_with(\n            'GET', 'http://proxy.example.com',\n            auth=None,\n            headers={'HOST': 'www.python.org'},\n            loop=loop_mock)\n        conn.close()\n\n    def test_proxy_auth(self):\n        with self.assertRaises(AssertionError) as ctx:\n            aiohttp.ProxyConnector('http://proxy.example.com',\n                                   proxy_auth=('user', 'pass'),\n                                   loop=unittest.mock.Mock())\n        self.assertEqual(ctx.exception.args[0],\n                         (\"proxy_auth must be None or BasicAuth() tuple\",\n                          ('user', 'pass')))\n\n    def test_proxy_connection_error(self):\n        connector = aiohttp.ProxyConnector('http://proxy.example.com',\n                                           loop=self.loop)\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, OSError('dont take it serious'))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        expected_headers = dict(req.headers)\n        with self.assertRaises(aiohttp.ProxyConnectionError):\n            self.loop.run_until_complete(connector.connect(req))\n        self.assertEqual(req.path, '/')\n        self.assertEqual(dict(req.headers), expected_headers)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_auth(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  auth=aiohttp.helpers.BasicAuth('user',\n                                                                 'pass'),\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n        self.assertIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock,\n            proxy_auth=aiohttp.helpers.BasicAuth('user', 'pass'))\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, [unittest.mock.MagicMock()])\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)\n        conn = self.loop.run_until_complete(connector.connect(req))\n\n        self.assertEqual(req.path, 'http://www.python.org/')\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertIn('PROXY-AUTHORIZATION', req.headers)\n        self.assertNotIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        ClientRequestMock.assert_called_with(\n            'GET', 'http://proxy.example.com',\n            auth=aiohttp.helpers.BasicAuth('user', 'pass'),\n            loop=unittest.mock.ANY, headers=unittest.mock.ANY)\n        conn.close()\n\n    def test_auth_utf8(self):\n        proxy_req = ClientRequest(\n            'GET', 'http://proxy.example.com',\n            auth=aiohttp.helpers.BasicAuth('юзер', 'пасс', 'utf-8'),\n            loop=self.loop)\n        self.assertIn('AUTHORIZATION', proxy_req.headers)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_auth_from_url(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://user:pass@proxy.example.com',\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n        self.assertIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector(\n            'http://user:pass@proxy.example.com', loop=loop_mock)\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, [unittest.mock.MagicMock()])\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)\n        conn = self.loop.run_until_complete(connector.connect(req))\n\n        self.assertEqual(req.path, 'http://www.python.org/')\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertIn('PROXY-AUTHORIZATION', req.headers)\n        self.assertNotIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        ClientRequestMock.assert_called_with(\n            'GET', 'http://user:pass@proxy.example.com',\n            auth=None, loop=unittest.mock.ANY, headers=unittest.mock.ANY)\n        conn.close()\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_auth__not_modifying_request(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://user:pass@proxy.example.com',\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n        proxy_req_headers = dict(proxy_req.headers)\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector(\n            'http://user:pass@proxy.example.com', loop=loop_mock)\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, OSError('nothing personal'))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        req_headers = dict(req.headers)\n        with self.assertRaises(aiohttp.ProxyConnectionError):\n            self.loop.run_until_complete(connector.connect(req))\n        self.assertEqual(req.headers, req_headers)\n        self.assertEqual(req.path, '/')\n        self.assertEqual(proxy_req.headers, proxy_req_headers)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(start_mock, unittest.mock.Mock(status=200))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        self.loop.run_until_complete(connector._create_connection(req))\n\n        self.assertEqual(req.path, '/')\n        self.assertEqual(proxy_req.method, 'CONNECT')\n        self.assertEqual(proxy_req.path, 'www.python.org:443')\n        tr.pause_reading.assert_called_once_with()\n        tr.get_extra_info.assert_called_once_with('socket', default=None)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect_runtime_error(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(start_mock, unittest.mock.Mock(status=200))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        with self.assertRaisesRegex(\n                RuntimeError, \"Transport does not expose socket instance\"):\n            self.loop.run_until_complete(connector._create_connection(req))\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect_http_proxy_error(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(\n            start_mock, unittest.mock.Mock(status=400, reason='bad request'))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        with self.assertRaisesRegex(\n                aiohttp.HttpProxyError, \"400, message='bad request'\"):\n            self.loop.run_until_complete(connector._create_connection(req))\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect_resp_start_error(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(start_mock, OSError(\"error message\"))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        with self.assertRaisesRegex(OSError, \"error message\"):\n            self.loop.run_until_complete(connector._create_connection(req))\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_request_port(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector('http://proxy.example.com',\n                                           loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'http://localhost:1234/path',\n                            loop=self.loop)\n        self.loop.run_until_complete(connector._create_connection(req))\n        self.assertEqual(req.path, 'http://localhost:1234/path')\n",
            "new_file_content": "\"\"\"Tests of http client with custom Connector\"\"\"\n\nimport asyncio\nimport http.cookies\nimport gc\nimport socket\nimport unittest\nimport ssl\nimport sys\nfrom unittest import mock\n\nimport aiohttp\nfrom aiohttp import client\nfrom aiohttp import test_utils\nfrom aiohttp.client import ClientResponse, ClientRequest\nfrom aiohttp.connector import Connection\n\nfrom tests.test_client_functional import Functional\n\nPY_34 = sys.version_info >= (3, 4)\n\n\nclass TestHttpConnection(unittest.TestCase):\n\n    def setUp(self):\n        self.key = object()\n        self.connector = mock.Mock()\n        self.request = mock.Mock()\n        self.transport = mock.Mock()\n        self.protocol = mock.Mock()\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n        self.connector._release.assert_called_with(self.key,\n                                                   self.request,\n                                                   self.transport,\n                                                   self.protocol,\n                                                   should_close=True)\n        msg = {'client_connection': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connection'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    def test_close(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        self.assertFalse(conn.closed)\n        conn.close()\n        self.assertIsNone(conn._transport)\n        self.connector._release.assert_called_with(\n            self.key, self.request, self.transport, self.protocol,\n            should_close=True)\n        self.assertTrue(conn.closed)\n\n    def test_release(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        self.assertFalse(conn.closed)\n        conn.release()\n        self.assertFalse(self.transport.close.called)\n        self.assertIsNone(conn._transport)\n        self.connector._release.assert_called_with(\n            self.key, self.request, self.transport, self.protocol,\n            should_close=False)\n        self.assertTrue(conn.closed)\n\n    def test_release_released(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        conn.release()\n        self.connector._release.reset_mock()\n        conn.release()\n        self.assertFalse(self.transport.close.called)\n        self.assertIsNone(conn._transport)\n        self.assertFalse(self.connector._release.called)\n\n    def test_detach(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        self.assertFalse(conn.closed)\n        conn.detach()\n        self.assertIsNone(conn._transport)\n        self.assertFalse(self.connector._release.called)\n        self.assertTrue(conn.closed)\n\n\nclass TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 1.5\n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_at.assert_called_with(\n            12, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_cleanup2(self):\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300.1\n\n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_at.assert_called_with(\n            311, conn._cleanup)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)\n\n\nclass TestHttpClientConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n    def tearDown(self):\n        # just in case if we have transport close callbacks\n        test_utils.run_briefly(self.loop)\n\n        self.loop.close()\n        gc.collect()\n\n    def test_tcp_connector(self):\n        with test_utils.run_server(self.loop, router=Functional) as httpd:\n            r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=aiohttp.TCPConnector(loop=self.loop),\n                    loop=self.loop))\n            content = self.loop.run_until_complete(r.content.read())\n            content = content.decode()\n            self.assertEqual(r.status, 200)\n            r.close()\n\n    @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'requires unix')\n    def test_unix_connector(self):\n        path = '/tmp/aiohttp_unix.sock'\n\n        connector = aiohttp.UnixConnector(path, loop=self.loop)\n        self.assertEqual(path, connector.path)\n\n        with test_utils.run_server(\n                self.loop, listen_addr=path, router=Functional) as httpd:\n            r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=connector,\n                    loop=self.loop))\n            content = self.loop.run_until_complete(r.content.read())\n            content = content.decode()\n            self.assertEqual(r.status, 200)\n            r.close()\n\n    def test_connector_cookie_deprecation(self):\n        with self.assertWarnsRegex(DeprecationWarning,\n                                   \"^Using `share_cookies` is deprecated\"):\n            aiohttp.TCPConnector(share_cookies=True, loop=self.loop)\n\n\nclass TestProxyConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n    def tearDown(self):\n        # just in case if we have transport close callbacks\n        test_utils.run_briefly(self.loop)\n\n        self.loop.close()\n        gc.collect()\n\n    def _fake_coroutine(self, mock, return_value):\n\n        def coro(*args, **kw):\n            if isinstance(return_value, Exception):\n                raise return_value\n            return return_value\n            yield  # pragma: no cover\n        mock.side_effect = coro\n\n    def test_ctor(self):\n        with self.assertRaises(AssertionError):\n            aiohttp.ProxyConnector('https://localhost:8118', loop=self.loop)\n\n    def test_ctor2(self):\n        connector = aiohttp.ProxyConnector('http://localhost:8118',\n                                           loop=self.loop)\n\n        self.assertEqual('http://localhost:8118', connector.proxy)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_connect(self, ClientRequestMock):\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        self.assertEqual(req.path, '/')\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector('http://proxy.example.com',\n                                           loop=loop_mock)\n        self.assertIs(loop_mock, connector._loop)\n\n        resolve_host = unittest.mock.Mock()\n        self._fake_coroutine(resolve_host, [unittest.mock.MagicMock()])\n        connector._resolve_host = resolve_host\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n        conn = self.loop.run_until_complete(connector.connect(req))\n        self.assertEqual(req.path, 'http://www.python.org/')\n        self.assertIs(conn._transport, tr)\n        self.assertIs(conn._protocol, proto)\n\n        # resolve_host.assert_called_once_with('proxy.example.com', 80)\n        self.assertEqual(tr.mock_calls, [])\n\n        ClientRequestMock.assert_called_with(\n            'GET', 'http://proxy.example.com',\n            auth=None,\n            headers={'HOST': 'www.python.org'},\n            loop=loop_mock)\n        conn.close()\n\n    def test_proxy_auth(self):\n        with self.assertRaises(AssertionError) as ctx:\n            aiohttp.ProxyConnector('http://proxy.example.com',\n                                   proxy_auth=('user', 'pass'),\n                                   loop=unittest.mock.Mock())\n        self.assertEqual(ctx.exception.args[0],\n                         (\"proxy_auth must be None or BasicAuth() tuple\",\n                          ('user', 'pass')))\n\n    def test_proxy_connection_error(self):\n        connector = aiohttp.ProxyConnector('http://proxy.example.com',\n                                           loop=self.loop)\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, OSError('dont take it serious'))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        expected_headers = dict(req.headers)\n        with self.assertRaises(aiohttp.ProxyConnectionError):\n            self.loop.run_until_complete(connector.connect(req))\n        self.assertEqual(req.path, '/')\n        self.assertEqual(dict(req.headers), expected_headers)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_auth(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  auth=aiohttp.helpers.BasicAuth('user',\n                                                                 'pass'),\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n        self.assertIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock,\n            proxy_auth=aiohttp.helpers.BasicAuth('user', 'pass'))\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, [unittest.mock.MagicMock()])\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)\n        conn = self.loop.run_until_complete(connector.connect(req))\n\n        self.assertEqual(req.path, 'http://www.python.org/')\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertIn('PROXY-AUTHORIZATION', req.headers)\n        self.assertNotIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        ClientRequestMock.assert_called_with(\n            'GET', 'http://proxy.example.com',\n            auth=aiohttp.helpers.BasicAuth('user', 'pass'),\n            loop=unittest.mock.ANY, headers=unittest.mock.ANY)\n        conn.close()\n\n    def test_auth_utf8(self):\n        proxy_req = ClientRequest(\n            'GET', 'http://proxy.example.com',\n            auth=aiohttp.helpers.BasicAuth('юзер', 'пасс', 'utf-8'),\n            loop=self.loop)\n        self.assertIn('AUTHORIZATION', proxy_req.headers)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_auth_from_url(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://user:pass@proxy.example.com',\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n        self.assertIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector(\n            'http://user:pass@proxy.example.com', loop=loop_mock)\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, [unittest.mock.MagicMock()])\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)\n        conn = self.loop.run_until_complete(connector.connect(req))\n\n        self.assertEqual(req.path, 'http://www.python.org/')\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertIn('PROXY-AUTHORIZATION', req.headers)\n        self.assertNotIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        ClientRequestMock.assert_called_with(\n            'GET', 'http://user:pass@proxy.example.com',\n            auth=None, loop=unittest.mock.ANY, headers=unittest.mock.ANY)\n        conn.close()\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_auth__not_modifying_request(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://user:pass@proxy.example.com',\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n        proxy_req_headers = dict(proxy_req.headers)\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector(\n            'http://user:pass@proxy.example.com', loop=loop_mock)\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, OSError('nothing personal'))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        req_headers = dict(req.headers)\n        with self.assertRaises(aiohttp.ProxyConnectionError):\n            self.loop.run_until_complete(connector.connect(req))\n        self.assertEqual(req.headers, req_headers)\n        self.assertEqual(req.path, '/')\n        self.assertEqual(proxy_req.headers, proxy_req_headers)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(start_mock, unittest.mock.Mock(status=200))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        self.loop.run_until_complete(connector._create_connection(req))\n\n        self.assertEqual(req.path, '/')\n        self.assertEqual(proxy_req.method, 'CONNECT')\n        self.assertEqual(proxy_req.path, 'www.python.org:443')\n        tr.pause_reading.assert_called_once_with()\n        tr.get_extra_info.assert_called_once_with('socket', default=None)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect_runtime_error(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(start_mock, unittest.mock.Mock(status=200))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        with self.assertRaisesRegex(\n                RuntimeError, \"Transport does not expose socket instance\"):\n            self.loop.run_until_complete(connector._create_connection(req))\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect_http_proxy_error(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(\n            start_mock, unittest.mock.Mock(status=400, reason='bad request'))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        with self.assertRaisesRegex(\n                aiohttp.HttpProxyError, \"400, message='bad request'\"):\n            self.loop.run_until_complete(connector._create_connection(req))\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect_resp_start_error(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(start_mock, OSError(\"error message\"))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        with self.assertRaisesRegex(OSError, \"error message\"):\n            self.loop.run_until_complete(connector._create_connection(req))\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_request_port(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector('http://proxy.example.com',\n                                           loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'http://localhost:1234/path',\n                            loop=self.loop)\n        self.loop.run_until_complete(connector._create_connection(req))\n        self.assertEqual(req.path, 'http://localhost:1234/path')\n",
            "header": {
                "file": {
                    "path": "tests/test_connector.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "21eb740b",
                "new_commit_hash": "7a6380d5",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_connector.py"
            },
            "plus_file": {
                "path": "b/tests/test_connector.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 374,
                            "length": 13
                        },
                        "new_range": {
                            "start": 374,
                            "length": 14
                        },
                        "section": "class TestBaseConnector(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_start_cleanup_task(self):",
                                "type": "context"
                            },
                            {
                                "content": "        loop = unittest.mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        conn = aiohttp.BaseConnector(loop=loop)",
                                "type": "deleted"
                            },
                            {
                                "content": "        loop.time.return_value = 1.5",
                                "type": "added"
                            },
                            {
                                "content": "        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsNone(conn._cleanup_handle)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        conn._start_cleanup_task()",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertIsNotNone(conn._cleanup_handle)",
                                "type": "context"
                            },
                            {
                                "content": "        loop.call_later.assert_called_with(",
                                "type": "deleted"
                            },
                            {
                                "content": "            conn._keepalive_timeout, conn._cleanup)",
                                "type": "deleted"
                            },
                            {
                                "content": "        loop.call_at.assert_called_with(",
                                "type": "added"
                            },
                            {
                                "content": "            12, conn._cleanup)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_cleanup(self):",
                                "type": "context"
                            },
                            {
                                "content": "        testset = {",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_connector.py",
                            "type": "class",
                            "name": "TestBaseConnector",
                            "content": "class TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        conn = aiohttp.BaseConnector(loop=loop)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_later.assert_called_with(\n            conn._keepalive_timeout, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 105,
                            "end_lineno": 483,
                            "parent": null
                        },
                        {
                            "file_name": "tests/test_connector.py",
                            "type": "method",
                            "name": "TestBaseConnector.test_start_cleanup_task",
                            "content": "class TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        conn = aiohttp.BaseConnector(loop=loop)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_later.assert_called_with(\n            conn._keepalive_timeout, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 375,
                            "end_lineno": 383,
                            "parent": {
                                "file_name": "tests/test_connector.py",
                                "type": "class",
                                "name": "TestBaseConnector",
                                "content": "class TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        conn = aiohttp.BaseConnector(loop=loop)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_later.assert_called_with(\n            conn._keepalive_timeout, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 105,
                                "end_lineno": 483,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 402,
                            "length": 15
                        },
                        "new_range": {
                            "start": 403,
                            "length": 21
                        },
                        "section": "class TestBaseConnector(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.assertEqual(conn._conns, {})",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertIsNone(conn._cleanup_handle)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_cleanup2(self):",
                                "type": "added"
                            },
                            {
                                "content": "        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}",
                                "type": "context"
                            },
                            {
                                "content": "        testset[1][0][1].is_connected.return_value = True",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        conn = aiohttp.BaseConnector(loop=loop)",
                                "type": "deleted"
                            },
                            {
                                "content": "        loop = unittest.mock.Mock()",
                                "type": "added"
                            },
                            {
                                "content": "        loop.time.return_value = 300.1",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)",
                                "type": "added"
                            },
                            {
                                "content": "        conn._conns = testset",
                                "type": "context"
                            },
                            {
                                "content": "        conn._cleanup()",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(conn._conns, testset)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertIsNotNone(conn._cleanup_handle)",
                                "type": "context"
                            },
                            {
                                "content": "        loop.call_at.assert_called_with(",
                                "type": "added"
                            },
                            {
                                "content": "            311, conn._cleanup)",
                                "type": "added"
                            },
                            {
                                "content": "        conn.close()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_tcp_connector_ctor(self):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_connector.py",
                            "type": "class",
                            "name": "TestBaseConnector",
                            "content": "class TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        conn = aiohttp.BaseConnector(loop=loop)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_later.assert_called_with(\n            conn._keepalive_timeout, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 105,
                            "end_lineno": 483,
                            "parent": null
                        },
                        {
                            "file_name": "tests/test_connector.py",
                            "type": "method",
                            "name": "TestBaseConnector.test_cleanup",
                            "content": "class TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        conn = aiohttp.BaseConnector(loop=loop)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_later.assert_called_with(\n            conn._keepalive_timeout, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 385,
                            "end_lineno": 414,
                            "parent": {
                                "file_name": "tests/test_connector.py",
                                "type": "class",
                                "name": "TestBaseConnector",
                                "content": "class TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        conn = aiohttp.BaseConnector(loop=loop)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_later.assert_called_with(\n            conn._keepalive_timeout, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 105,
                                "end_lineno": 483,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tests/test_connector.py",
                            "type": "method",
                            "name": "TestBaseConnector.test_cleanup2",
                            "content": "class TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 1.5\n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_at.assert_called_with(\n            12, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_cleanup2(self):\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300.1\n\n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_at.assert_called_with(\n            311, conn._cleanup)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 406,
                            "end_lineno": 421,
                            "parent": {
                                "file_name": "tests/test_connector.py",
                                "type": "class",
                                "name": "TestBaseConnector",
                                "content": "class TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 1.5\n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_at.assert_called_with(\n            12, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_cleanup2(self):\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300.1\n\n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_at.assert_called_with(\n            311, conn._cleanup)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 105,
                                "end_lineno": 490,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "922541b8f49e894bd2d52e0ae7d5b6daf3efa073^",
    "new_commit_hash": "922541b8f49e894bd2d52e0ae7d5b6daf3efa073",
    "commit_message": "Make cleanup procedure granular with 1 second step",
    "commit_date": "2015-05-10T19:28:59+03:00",
    "metadata": {}
}
{
    "repo_name": "aiohttp",
    "new_commit_hash": "922541b8f49e894bd2d52e0ae7d5b6daf3efa073",
    "test_file_codes": [
        "\"\"\"Tests of http client with custom Connector\"\"\"\n\nimport asyncio\nimport http.cookies\nimport gc\nimport socket\nimport unittest\nimport ssl\nimport sys\nfrom unittest import mock\n\nimport aiohttp\nfrom aiohttp import client\nfrom aiohttp import test_utils\nfrom aiohttp.client import ClientResponse, ClientRequest\nfrom aiohttp.connector import Connection\n\nfrom tests.test_client_functional import Functional\n\nPY_34 = sys.version_info >= (3, 4)\n\n\nclass TestHttpConnection(unittest.TestCase):\n\n    def setUp(self):\n        self.key = object()\n        self.connector = mock.Mock()\n        self.request = mock.Mock()\n        self.transport = mock.Mock()\n        self.protocol = mock.Mock()\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n        self.connector._release.assert_called_with(self.key,\n                                                   self.request,\n                                                   self.transport,\n                                                   self.protocol,\n                                                   should_close=True)\n        msg = {'client_connection': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connection'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    def test_close(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        self.assertFalse(conn.closed)\n        conn.close()\n        self.assertIsNone(conn._transport)\n        self.connector._release.assert_called_with(\n            self.key, self.request, self.transport, self.protocol,\n            should_close=True)\n        self.assertTrue(conn.closed)\n\n    def test_release(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        self.assertFalse(conn.closed)\n        conn.release()\n        self.assertFalse(self.transport.close.called)\n        self.assertIsNone(conn._transport)\n        self.connector._release.assert_called_with(\n            self.key, self.request, self.transport, self.protocol,\n            should_close=False)\n        self.assertTrue(conn.closed)\n\n    def test_release_released(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        conn.release()\n        self.connector._release.reset_mock()\n        conn.release()\n        self.assertFalse(self.transport.close.called)\n        self.assertIsNone(conn._transport)\n        self.assertFalse(self.connector._release.called)\n\n    def test_detach(self):\n        conn = Connection(\n            self.connector, self.key, self.request,\n            self.transport, self.protocol, self.loop)\n        self.assertFalse(conn.closed)\n        conn.detach()\n        self.assertIsNone(conn._transport)\n        self.assertFalse(self.connector._release.called)\n        self.assertTrue(conn.closed)\n\n\nclass TestBaseConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.transport = unittest.mock.Mock()\n        self.stream = aiohttp.StreamParser()\n        self.response = ClientResponse('get', 'http://python.org')\n        self.response._loop = self.loop\n\n    def tearDown(self):\n        self.loop.close()\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n        conns_impl = conn._conns\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_scheduled_cleanup(self):\n        conn = aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=0.01)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            yield from asyncio.sleep(0.01)\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        transp.close.assert_called_with()\n        msg = {'connector': unittest.mock.ANY,  # conn was deleted\n               'message': 'Unclosed connector'}\n        if self.loop.get_debug():\n            msg['source_traceback'] = unittest.mock.ANY\n        exc_handler.assert_called_with(self.loop, msg)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_with_closed_loop(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        transp = unittest.mock.Mock()\n        conn._conns['a'] = [(transp, 'proto', 123)]\n\n        conns_impl = conn._conns\n        conn._start_cleanup_task()\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n        self.loop.close()\n\n        with self.assertWarns(ResourceWarning):\n            del conn\n            gc.collect()\n\n        self.assertFalse(conns_impl)\n        self.assertFalse(transp.close.called)\n        self.assertTrue(exc_handler.called)\n\n    @unittest.skipUnless(PY_34, \"Requires Python 3.4+\")\n    def test_del_empty_conector(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n\n        exc_handler = unittest.mock.Mock()\n        self.loop.set_exception_handler(exc_handler)\n\n        del conn\n\n        self.assertFalse(exc_handler.called)\n\n    def test_create_conn(self):\n\n        def go():\n            conn = aiohttp.BaseConnector(loop=self.loop)\n            with self.assertRaises(NotImplementedError):\n                yield from conn._create_connection(object())\n\n        self.loop.run_until_complete(go())\n\n    @unittest.mock.patch('aiohttp.connector.asyncio')\n    def test_ctor_loop(self, asyncio):\n        session = aiohttp.BaseConnector()\n        self.assertIs(session._loop, asyncio.get_event_loop.return_value)\n\n    def test_close(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertFalse(conn.closed)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n    def test_get(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time())]\n        self.assertEqual(conn._get(1), (tr, proto))\n        conn.close()\n\n    def test_get_expired(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        self.assertEqual(conn._get(1), (None, None))\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._conns[1] = [(tr, proto, self.loop.time() - 1000)]\n        self.assertEqual(conn._get(1), (None, None))\n        self.assertEqual(conn._conns[1], [])\n        conn.close()\n\n    def test_release(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task = unittest.mock.Mock()\n        req = unittest.mock.Mock()\n        resp = req.response = unittest.mock.Mock()\n        resp.message.should_close = False\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns[1][0], (tr, proto, 10))\n        self.assertTrue(conn._start_cleanup_task.called)\n        conn.close()\n\n    def test_release_close(self):\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        cookies = resp.cookies = http.cookies.SimpleCookie()\n        cookies['c1'] = 'cookie1'\n        cookies['c2'] = 'cookie2'\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_pop_empty_conns(self):\n        # see issue #253\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        key = ('127.0.0.1', 80, False)\n\n        conn._conns[key] = []\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual({}, conn._conns)\n        self.assertTrue(tr.close.called)\n\n    def test_release_close_do_not_delete_existing_connections(self):\n        key = ('127.0.0.1', 80, False)\n        tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock()\n\n        with self.assertWarns(DeprecationWarning):\n            conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop)\n        conn._conns[key] = [(tr1, proto1, 1)]\n        req = unittest.mock.Mock()\n        resp = unittest.mock.Mock()\n        resp.message.should_close = True\n        req.response = resp\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(key, req, tr, proto)\n        self.assertEqual(conn._conns[key], [(tr1, proto1, 1)])\n        self.assertTrue(tr.close.called)\n        conn.close()\n\n    def test_release_not_started(self):\n        self.loop.time = mock.Mock(return_value=10)\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertEqual(conn._conns, {1: [(tr, proto, 10)]})\n        self.assertFalse(tr.close.called)\n        conn.close()\n\n    def test_release_not_opened(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        req = unittest.mock.Mock()\n        req.response = unittest.mock.Mock()\n        req.response.message = None\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        conn._release(1, req, tr, proto)\n        self.assertTrue(tr.close.called)\n\n    def test_connect(self):\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        proto.is_connected.return_value = True\n\n        class Req:\n            host = 'host'\n            port = 80\n            ssl = False\n            response = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        key = ('host', 80, False)\n        conn._conns[key] = [(tr, proto, self.loop.time())]\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_result((tr, proto))\n\n        connection = self.loop.run_until_complete(conn.connect(Req()))\n        self.assertFalse(conn._create_connection.called)\n        self.assertEqual(connection._transport, tr)\n        self.assertEqual(connection._protocol, proto)\n        self.assertIsInstance(connection, Connection)\n        connection.close()\n\n    def test_connect_timeout(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(\n            asyncio.TimeoutError())\n\n        with self.assertRaises(aiohttp.ClientTimeoutError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_connect_oserr(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._create_connection = unittest.mock.Mock()\n        conn._create_connection.return_value = asyncio.Future(loop=self.loop)\n        conn._create_connection.return_value.set_exception(OSError())\n\n        with self.assertRaises(aiohttp.ClientOSError):\n            req = unittest.mock.Mock()\n            self.loop.run_until_complete(conn.connect(req))\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 1.5\n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        self.assertIsNone(conn._cleanup_handle)\n\n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_at.assert_called_with(\n            12, conn._cleanup)\n\n    def test_cleanup(self):\n        testset = {\n            1: [(unittest.mock.Mock(), unittest.mock.Mock(), 10),\n                (unittest.mock.Mock(), unittest.mock.Mock(), 300),\n                (None, unittest.mock.Mock(), 300)],\n        }\n        testset[1][0][1].is_connected.return_value = True\n        testset[1][1][1].is_connected.return_value = False\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300\n        conn = aiohttp.BaseConnector(loop=loop)\n        conn._conns = testset\n        existing_handle = conn._cleanup_handle = unittest.mock.Mock()\n\n        conn._cleanup()\n        self.assertTrue(existing_handle.cancel.called)\n        self.assertEqual(conn._conns, {})\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_cleanup2(self):\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300.1\n\n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        loop.call_at.assert_called_with(\n            311, conn._cleanup)\n        conn.close()\n\n    def test_tcp_connector_ctor(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        self.assertTrue(conn.verify_ssl)\n        self.assertFalse(conn.resolve)\n        self.assertEqual(conn.family, socket.AF_INET)\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_tcp_connector_clear_resolved_hosts(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        info = object()\n        conn._resolved_hosts[('localhost', 123)] = info\n        conn._resolved_hosts[('localhost', 124)] = info\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts('localhost', 123)\n        self.assertEqual(\n            conn.resolved_hosts, {('localhost', 124): info})\n        conn.clear_resolved_hosts()\n        self.assertEqual(conn.resolved_hosts, {})\n\n    def test_ambigous_verify_ssl_and_ssl_context(self):\n        with self.assertRaises(ValueError):\n            aiohttp.TCPConnector(\n                verify_ssl=False,\n                ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),\n                loop=self.loop)\n\n    def test_dont_recreate_ssl_context(self):\n        conn = aiohttp.TCPConnector(loop=self.loop)\n        ctx = conn.ssl_context\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_respect_precreated_ssl_context(self):\n        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n        conn = aiohttp.TCPConnector(loop=self.loop, ssl_context=ctx)\n        self.assertIs(ctx, conn.ssl_context)\n\n    def test_close_twice(self):\n        tr = unittest.mock.Mock()\n\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._conns[1] = [(tr, object(), object())]\n        conn.close()\n\n        self.assertFalse(conn._conns)\n        self.assertTrue(tr.close.called)\n        self.assertTrue(conn.closed)\n\n        conn._conns = 'Invalid'  # fill with garbage\n        conn.close()\n        self.assertTrue(conn.closed)\n\n    def test_close_cancels_cleanup_handle(self):\n        conn = aiohttp.BaseConnector(loop=self.loop)\n        conn._start_cleanup_task()\n\n        self.assertIsNotNone(conn._cleanup_handle)\n        conn.close()\n        self.assertIsNone(conn._cleanup_handle)\n\n    def test_ctor_with_default_loop(self):\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        self.addCleanup(loop.close)\n        self.addCleanup(asyncio.set_event_loop, None)\n        conn = aiohttp.BaseConnector()\n        self.assertIs(loop, conn._loop)\n\n\nclass TestHttpClientConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n    def tearDown(self):\n        # just in case if we have transport close callbacks\n        test_utils.run_briefly(self.loop)\n\n        self.loop.close()\n        gc.collect()\n\n    def test_tcp_connector(self):\n        with test_utils.run_server(self.loop, router=Functional) as httpd:\n            r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=aiohttp.TCPConnector(loop=self.loop),\n                    loop=self.loop))\n            content = self.loop.run_until_complete(r.content.read())\n            content = content.decode()\n            self.assertEqual(r.status, 200)\n            r.close()\n\n    @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'requires unix')\n    def test_unix_connector(self):\n        path = '/tmp/aiohttp_unix.sock'\n\n        connector = aiohttp.UnixConnector(path, loop=self.loop)\n        self.assertEqual(path, connector.path)\n\n        with test_utils.run_server(\n                self.loop, listen_addr=path, router=Functional) as httpd:\n            r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=connector,\n                    loop=self.loop))\n            content = self.loop.run_until_complete(r.content.read())\n            content = content.decode()\n            self.assertEqual(r.status, 200)\n            r.close()\n\n    def test_connector_cookie_deprecation(self):\n        with self.assertWarnsRegex(DeprecationWarning,\n                                   \"^Using `share_cookies` is deprecated\"):\n            aiohttp.TCPConnector(share_cookies=True, loop=self.loop)\n\n\nclass TestProxyConnector(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n    def tearDown(self):\n        # just in case if we have transport close callbacks\n        test_utils.run_briefly(self.loop)\n\n        self.loop.close()\n        gc.collect()\n\n    def _fake_coroutine(self, mock, return_value):\n\n        def coro(*args, **kw):\n            if isinstance(return_value, Exception):\n                raise return_value\n            return return_value\n            yield  # pragma: no cover\n        mock.side_effect = coro\n\n    def test_ctor(self):\n        with self.assertRaises(AssertionError):\n            aiohttp.ProxyConnector('https://localhost:8118', loop=self.loop)\n\n    def test_ctor2(self):\n        connector = aiohttp.ProxyConnector('http://localhost:8118',\n                                           loop=self.loop)\n\n        self.assertEqual('http://localhost:8118', connector.proxy)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_connect(self, ClientRequestMock):\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        self.assertEqual(req.path, '/')\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector('http://proxy.example.com',\n                                           loop=loop_mock)\n        self.assertIs(loop_mock, connector._loop)\n\n        resolve_host = unittest.mock.Mock()\n        self._fake_coroutine(resolve_host, [unittest.mock.MagicMock()])\n        connector._resolve_host = resolve_host\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n        conn = self.loop.run_until_complete(connector.connect(req))\n        self.assertEqual(req.path, 'http://www.python.org/')\n        self.assertIs(conn._transport, tr)\n        self.assertIs(conn._protocol, proto)\n\n        # resolve_host.assert_called_once_with('proxy.example.com', 80)\n        self.assertEqual(tr.mock_calls, [])\n\n        ClientRequestMock.assert_called_with(\n            'GET', 'http://proxy.example.com',\n            auth=None,\n            headers={'HOST': 'www.python.org'},\n            loop=loop_mock)\n        conn.close()\n\n    def test_proxy_auth(self):\n        with self.assertRaises(AssertionError) as ctx:\n            aiohttp.ProxyConnector('http://proxy.example.com',\n                                   proxy_auth=('user', 'pass'),\n                                   loop=unittest.mock.Mock())\n        self.assertEqual(ctx.exception.args[0],\n                         (\"proxy_auth must be None or BasicAuth() tuple\",\n                          ('user', 'pass')))\n\n    def test_proxy_connection_error(self):\n        connector = aiohttp.ProxyConnector('http://proxy.example.com',\n                                           loop=self.loop)\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, OSError('dont take it serious'))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        expected_headers = dict(req.headers)\n        with self.assertRaises(aiohttp.ProxyConnectionError):\n            self.loop.run_until_complete(connector.connect(req))\n        self.assertEqual(req.path, '/')\n        self.assertEqual(dict(req.headers), expected_headers)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_auth(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  auth=aiohttp.helpers.BasicAuth('user',\n                                                                 'pass'),\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n        self.assertIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock,\n            proxy_auth=aiohttp.helpers.BasicAuth('user', 'pass'))\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, [unittest.mock.MagicMock()])\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)\n        conn = self.loop.run_until_complete(connector.connect(req))\n\n        self.assertEqual(req.path, 'http://www.python.org/')\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertIn('PROXY-AUTHORIZATION', req.headers)\n        self.assertNotIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        ClientRequestMock.assert_called_with(\n            'GET', 'http://proxy.example.com',\n            auth=aiohttp.helpers.BasicAuth('user', 'pass'),\n            loop=unittest.mock.ANY, headers=unittest.mock.ANY)\n        conn.close()\n\n    def test_auth_utf8(self):\n        proxy_req = ClientRequest(\n            'GET', 'http://proxy.example.com',\n            auth=aiohttp.helpers.BasicAuth('юзер', 'пасс', 'utf-8'),\n            loop=self.loop)\n        self.assertIn('AUTHORIZATION', proxy_req.headers)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_auth_from_url(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://user:pass@proxy.example.com',\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n        self.assertIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector(\n            'http://user:pass@proxy.example.com', loop=loop_mock)\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, [unittest.mock.MagicMock()])\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)\n        conn = self.loop.run_until_complete(connector.connect(req))\n\n        self.assertEqual(req.path, 'http://www.python.org/')\n        self.assertNotIn('AUTHORIZATION', req.headers)\n        self.assertIn('PROXY-AUTHORIZATION', req.headers)\n        self.assertNotIn('AUTHORIZATION', proxy_req.headers)\n        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)\n\n        ClientRequestMock.assert_called_with(\n            'GET', 'http://user:pass@proxy.example.com',\n            auth=None, loop=unittest.mock.ANY, headers=unittest.mock.ANY)\n        conn.close()\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_auth__not_modifying_request(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://user:pass@proxy.example.com',\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n        proxy_req_headers = dict(proxy_req.headers)\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector(\n            'http://user:pass@proxy.example.com', loop=loop_mock)\n        connector._resolve_host = resolve_mock = unittest.mock.Mock()\n        self._fake_coroutine(resolve_mock, OSError('nothing personal'))\n\n        req = ClientRequest('GET', 'http://www.python.org', loop=self.loop)\n        req_headers = dict(req.headers)\n        with self.assertRaises(aiohttp.ProxyConnectionError):\n            self.loop.run_until_complete(connector.connect(req))\n        self.assertEqual(req.headers, req_headers)\n        self.assertEqual(req.path, '/')\n        self.assertEqual(proxy_req.headers, proxy_req_headers)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(start_mock, unittest.mock.Mock(status=200))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        self.loop.run_until_complete(connector._create_connection(req))\n\n        self.assertEqual(req.path, '/')\n        self.assertEqual(proxy_req.method, 'CONNECT')\n        self.assertEqual(proxy_req.path, 'www.python.org:443')\n        tr.pause_reading.assert_called_once_with()\n        tr.get_extra_info.assert_called_once_with('socket', default=None)\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect_runtime_error(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(start_mock, unittest.mock.Mock(status=200))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        with self.assertRaisesRegex(\n                RuntimeError, \"Transport does not expose socket instance\"):\n            self.loop.run_until_complete(connector._create_connection(req))\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect_http_proxy_error(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(\n            start_mock, unittest.mock.Mock(status=400, reason='bad request'))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        with self.assertRaisesRegex(\n                aiohttp.HttpProxyError, \"400, message='bad request'\"):\n            self.loop.run_until_complete(connector._create_connection(req))\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_https_connect_resp_start_error(self, ClientRequestMock):\n        loop_mock = unittest.mock.Mock()\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=loop_mock)\n        ClientRequestMock.return_value = proxy_req\n\n        proxy_resp = ClientResponse('get', 'http://proxy.example.com')\n        proxy_resp._loop = loop_mock\n        proxy_req.send = send_mock = unittest.mock.Mock()\n        send_mock.return_value = proxy_resp\n        proxy_resp.start = start_mock = unittest.mock.Mock()\n        self._fake_coroutine(start_mock, OSError(\"error message\"))\n\n        connector = aiohttp.ProxyConnector(\n            'http://proxy.example.com', loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'https://www.python.org', loop=self.loop)\n        with self.assertRaisesRegex(OSError, \"error message\"):\n            self.loop.run_until_complete(connector._create_connection(req))\n\n    @unittest.mock.patch('aiohttp.connector.ClientRequest')\n    def test_request_port(self, ClientRequestMock):\n        proxy_req = ClientRequest('GET', 'http://proxy.example.com',\n                                  loop=self.loop)\n        ClientRequestMock.return_value = proxy_req\n\n        loop_mock = unittest.mock.Mock()\n        connector = aiohttp.ProxyConnector('http://proxy.example.com',\n                                           loop=loop_mock)\n\n        tr, proto = unittest.mock.Mock(), unittest.mock.Mock()\n        tr.get_extra_info.return_value = None\n        self._fake_coroutine(loop_mock.create_connection, (tr, proto))\n\n        req = ClientRequest('GET', 'http://localhost:1234/path',\n                            loop=self.loop)\n        self.loop.run_until_complete(connector._create_connection(req))\n        self.assertEqual(req.path, 'http://localhost:1234/path')\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Transforming aiohttp/worker.py\nTransforming aiohttp/server.py\nTransforming aiohttp/client.py\n",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nmake: *** No rule to make target '.develop'.  Stop.\nResolved 26 packages in 26ms\nInstalled 26 packages in 29ms\n + async-generator==1.10\n + async-timeout==5.0.1\n + brotlipy==0.7.0\n + cffi==1.17.1\n + chardet==5.2.0\n + coverage==7.6.10\n + cryptography==44.0.0\n + cython==3.0.11\n + exceptiongroup==1.2.2\n + gunicorn==23.0.0\n + idna==3.10\n + iniconfig==2.0.0\n + multdict==0.0.5\n + multidict==6.1.0\n + packaging==24.2\n + pluggy==1.5.0\n + propcache==0.2.1\n + pycparser==2.22\n + pytest==8.3.4\n + pytest-asyncio==0.25.0\n + pytest-cov==6.0.0\n + pytest-mock==3.14.0\n + tomli==2.2.1\n + trustme==1.2.1\n + typing-extensions==4.12.2\n + yarl==1.18.3\n",
    "new_commit_res_code": 1,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073\nplugins: asyncio-0.25.0, mock-3.14.0, cov-6.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollected 51 items\n\nr2e_tests/test_1.py ...................................FF..............  [100%]\n\n=================================== FAILURES ===================================\n__________________ TestHttpClientConnector.test_tcp_connector __________________\n\nself = <r2e_tests.test_1.TestHttpClientConnector testMethod=test_tcp_connector>\n\n    def test_tcp_connector(self):\n        with test_utils.run_server(self.loop, router=Functional) as httpd:\n>           r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=aiohttp.TCPConnector(loop=self.loop),\n                    loop=self.loop))\n\nr2e_tests/test_1.py:508: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n../../../../.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/base_events.py:647: in run_until_complete\n    return future.result()\naiohttp/client.py:358: in request\n    resp = yield from session.request(method, url,\naiohttp/client.py:128: in request\n    resp = req.send(conn.writer, conn.reader)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <aiohttp.client.ClientRequest object at 0x7b077ea29100>\nwriter = <StreamWriter transport=<_SelectorSocketTransport closed fd=19> reader=<aiohttp.parsers.StreamParser object at 0x7b077ea29a60>>\nreader = <aiohttp.parsers.StreamParser object at 0x7b077ea29a60>\n\n    def send(self, writer, reader):\n        request = aiohttp.Request(writer, self.method, self.path, self.version)\n    \n        if self.compress:\n            request.add_compression_filter(self.compress)\n    \n        if self.chunked is not None:\n            request.enable_chunked_encoding()\n            request.add_chunking_filter(self.chunked)\n    \n        # set default content-type\n        if (self.method in self.POST_METHODS and\n                hdrs.CONTENT_TYPE not in self.headers):\n            self.headers[hdrs.CONTENT_TYPE] = 'application/octet-stream'\n    \n        request.add_headers(\n            *((k, v)\n              for k, v in ((k, value)\n                           for k, value in self.headers.items())))\n        request.send_headers()\n    \n>       self._writer = asyncio.create_task(\n            self.write_bytes(request, reader), loop=self.loop)\nE       TypeError: create_task() got an unexpected keyword argument 'loop'\n\naiohttp/client.py:798: TypeError\n------------------------------ Captured log call -------------------------------\nERROR    asyncio:base_events.py:1753 Exception in callback run_server.<locals>.TestHttpServer.connection_made(<_SelectorSoc...e, bufsize=0>>)\nhandle: <Handle run_server.<locals>.TestHttpServer.connection_made(<_SelectorSoc...e, bufsize=0>>)>\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/events.py\", line 80, in _run\n    self._context.run(self._callback, *self._args)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/aiohttp/test_utils.py\", line 68, in connection_made\n    super().connection_made(transport)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/aiohttp/server.py\", line 147, in connection_made\n    self._request_handler = asyncio.create_task(self.start(), loop=self._loop)\nTypeError: create_task() got an unexpected keyword argument 'loop'\n_________________ TestHttpClientConnector.test_unix_connector __________________\n\nself = <r2e_tests.test_1.TestHttpClientConnector testMethod=test_unix_connector>\n\n    @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'requires unix')\n    def test_unix_connector(self):\n        path = '/tmp/aiohttp_unix.sock'\n    \n        connector = aiohttp.UnixConnector(path, loop=self.loop)\n        self.assertEqual(path, connector.path)\n    \n        with test_utils.run_server(\n                self.loop, listen_addr=path, router=Functional) as httpd:\n>           r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=connector,\n                    loop=self.loop))\n\nr2e_tests/test_1.py:527: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n../../../../.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/base_events.py:647: in run_until_complete\n    return future.result()\naiohttp/client.py:358: in request\n    resp = yield from session.request(method, url,\naiohttp/client.py:128: in request\n    resp = req.send(conn.writer, conn.reader)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <aiohttp.client.ClientRequest object at 0x7b077e807c10>\nwriter = <StreamWriter transport=<_SelectorSocketTransport closed fd=19> reader=<aiohttp.parsers.StreamParser object at 0x7b077e8070d0>>\nreader = <aiohttp.parsers.StreamParser object at 0x7b077e8070d0>\n\n    def send(self, writer, reader):\n        request = aiohttp.Request(writer, self.method, self.path, self.version)\n    \n        if self.compress:\n            request.add_compression_filter(self.compress)\n    \n        if self.chunked is not None:\n            request.enable_chunked_encoding()\n            request.add_chunking_filter(self.chunked)\n    \n        # set default content-type\n        if (self.method in self.POST_METHODS and\n                hdrs.CONTENT_TYPE not in self.headers):\n            self.headers[hdrs.CONTENT_TYPE] = 'application/octet-stream'\n    \n        request.add_headers(\n            *((k, v)\n              for k, v in ((k, value)\n                           for k, value in self.headers.items())))\n        request.send_headers()\n    \n>       self._writer = asyncio.create_task(\n            self.write_bytes(request, reader), loop=self.loop)\nE       TypeError: create_task() got an unexpected keyword argument 'loop'\n\naiohttp/client.py:798: TypeError\n------------------------------ Captured log call -------------------------------\nERROR    asyncio:base_events.py:1753 Exception in callback run_server.<locals>.TestHttpServer.connection_made(<_SelectorSoc...e, bufsize=0>>)\nhandle: <Handle run_server.<locals>.TestHttpServer.connection_made(<_SelectorSoc...e, bufsize=0>>)>\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/events.py\", line 80, in _run\n    self._context.run(self._callback, *self._args)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/aiohttp/test_utils.py\", line 68, in connection_made\n    super().connection_made(transport)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/aiohttp/server.py\", line 147, in connection_made\n    self._request_handler = asyncio.create_task(self.start(), loop=self._loop)\nTypeError: create_task() got an unexpected keyword argument 'loop'\nERROR    asyncio:base_events.py:1753 Unclosed connection\nclient_connection: <aiohttp.connector.Connection object at 0x7b077ea29ac0>\n==================================== PASSES ====================================\n_________________________ TestProxyConnector.test_auth _________________________\n------------------------------ Captured log call -------------------------------\nERROR    asyncio:base_events.py:1753 Unclosed connection\nclient_connection: <aiohttp.connector.Connection object at 0x7b077e8071c0>\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_close\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_del\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_detach\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_release\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_release_released\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_ambigous_verify_ssl_and_ssl_context\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_cleanup\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_cleanup2\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_close\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_close_cancels_cleanup_handle\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_close_twice\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_connect\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_connect_oserr\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_connect_timeout\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_create_conn\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_ctor_loop\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_ctor_with_default_loop\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_del\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_del_empty_conector\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_del_with_closed_loop\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_del_with_scheduled_cleanup\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_dont_recreate_ssl_context\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_get\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_get_expired\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_close\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_close_do_not_delete_existing_connections\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_not_opened\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_not_started\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_pop_empty_conns\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_respect_precreated_ssl_context\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_start_cleanup_task\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_tcp_connector_clear_resolved_hosts\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_tcp_connector_ctor\nPASSED r2e_tests/test_1.py::TestHttpClientConnector::test_connector_cookie_deprecation\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_auth\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_auth__not_modifying_request\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_auth_from_url\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_auth_utf8\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_connect\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_ctor\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_ctor2\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_https_connect\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_https_connect_http_proxy_error\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_https_connect_resp_start_error\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_https_connect_runtime_error\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_proxy_auth\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_proxy_connection_error\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_request_port\nFAILED r2e_tests/test_1.py::TestHttpClientConnector::test_tcp_connector - Typ...\nFAILED r2e_tests/test_1.py::TestHttpClientConnector::test_unix_connector - Ty...\n========================= 2 failed, 49 passed in 1.41s =========================\n",
    "new_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/.venv/lib/python3.9/site-packages/pytest_asyncio/plugin.py:207: PytestDeprecationWarning: The configuration option \"asyncio_default_fixture_loop_scope\" is unset.\nThe event loop scope for asynchronous fixtures will default to the fixture caching scope. Future versions of pytest-asyncio will default the loop scope for asynchronous fixtures to function scope. Set the default fixture loop scope explicitly in order to avoid unexpected behavior in the future. Valid fixture loop scopes are: \"function\", \"class\", \"module\", \"package\", \"session\"\n\n  warnings.warn(PytestDeprecationWarning(_DEFAULT_FIXTURE_LOOP_SCOPE_UNSET))\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073\nplugins: asyncio-0.25.0, mock-3.14.0, cov-6.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollected 51 items\n\nr2e_tests/test_1.py .......F.......................F...FF..............  [100%]\n\n=================================== FAILURES ===================================\n_______________________ TestBaseConnector.test_cleanup2 ________________________\n\nself = <Mock name='mock.call_at' id='137009154570032'>\nargs = (311, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bedfd3130>>)\nkwargs = {}\nexpected = 'call_at(311, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bedfd3130>>)'\nactual = 'not called.'\nerror_message = 'expected call not found.\\nExpected: call_at(311, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bedfd3130>>)\\nActual: not called.'\n\n    def assert_called_with(self, /, *args, **kwargs):\n        \"\"\"assert that the last call was made with the specified arguments.\n    \n        Raises an AssertionError if the args and keyword args passed in are\n        different to the last call to the mock.\"\"\"\n        if self.call_args is None:\n            expected = self._format_mock_call_signature(args, kwargs)\n            actual = 'not called.'\n            error_message = ('expected call not found.\\nExpected: %s\\nActual: %s'\n                    % (expected, actual))\n>           raise AssertionError(error_message)\nE           AssertionError: expected call not found.\nE           Expected: call_at(311, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bedfd3130>>)\nE           Actual: not called.\n\n../../../../.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/mock.py:898: AssertionError\n\nDuring handling of the above exception, another exception occurred:\n\nself = <r2e_tests.test_1.TestBaseConnector testMethod=test_cleanup2>\n\n    def test_cleanup2(self):\n        testset = {1: [(unittest.mock.Mock(), unittest.mock.Mock(), 300)]}\n        testset[1][0][1].is_connected.return_value = True\n    \n        loop = unittest.mock.Mock()\n        loop.time.return_value = 300.1\n    \n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        conn._conns = testset\n        conn._cleanup()\n        self.assertEqual(conn._conns, testset)\n    \n        self.assertIsNotNone(conn._cleanup_handle)\n>       loop.call_at.assert_called_with(\n            311, conn._cleanup)\nE       AssertionError: expected call not found.\nE       Expected: call_at(311, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bedfd3130>>)\nE       Actual: not called.\n\nr2e_tests/test_1.py:419: AssertionError\n__________________ TestBaseConnector.test_start_cleanup_task ___________________\n\nself = <Mock name='mock.call_at' id='137009152846384'>\nargs = (12, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bede2e730>>)\nkwargs = {}\nexpected = 'call_at(12, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bede2e730>>)'\nactual = 'not called.'\nerror_message = 'expected call not found.\\nExpected: call_at(12, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bede2e730>>)\\nActual: not called.'\n\n    def assert_called_with(self, /, *args, **kwargs):\n        \"\"\"assert that the last call was made with the specified arguments.\n    \n        Raises an AssertionError if the args and keyword args passed in are\n        different to the last call to the mock.\"\"\"\n        if self.call_args is None:\n            expected = self._format_mock_call_signature(args, kwargs)\n            actual = 'not called.'\n            error_message = ('expected call not found.\\nExpected: %s\\nActual: %s'\n                    % (expected, actual))\n>           raise AssertionError(error_message)\nE           AssertionError: expected call not found.\nE           Expected: call_at(12, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bede2e730>>)\nE           Actual: not called.\n\n../../../../.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/mock.py:898: AssertionError\n\nDuring handling of the above exception, another exception occurred:\n\nself = <r2e_tests.test_1.TestBaseConnector testMethod=test_start_cleanup_task>\n\n    def test_start_cleanup_task(self):\n        loop = unittest.mock.Mock()\n        loop.time.return_value = 1.5\n        conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)\n        self.assertIsNone(conn._cleanup_handle)\n    \n        conn._start_cleanup_task()\n        self.assertIsNotNone(conn._cleanup_handle)\n>       loop.call_at.assert_called_with(\n            12, conn._cleanup)\nE       AssertionError: expected call not found.\nE       Expected: call_at(12, <bound method BaseConnector._cleanup of <aiohttp.connector.BaseConnector object at 0x7c9bede2e730>>)\nE       Actual: not called.\n\nr2e_tests/test_1.py:383: AssertionError\n__________________ TestHttpClientConnector.test_tcp_connector __________________\n\nself = <r2e_tests.test_1.TestHttpClientConnector testMethod=test_tcp_connector>\n\n    def test_tcp_connector(self):\n        with test_utils.run_server(self.loop, router=Functional) as httpd:\n>           r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=aiohttp.TCPConnector(loop=self.loop),\n                    loop=self.loop))\n\nr2e_tests/test_1.py:508: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n../../../../.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/base_events.py:647: in run_until_complete\n    return future.result()\naiohttp/client.py:358: in request\n    resp = yield from session.request(method, url,\naiohttp/client.py:128: in request\n    resp = req.send(conn.writer, conn.reader)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <aiohttp.client.ClientRequest object at 0x7c9bedd63970>\nwriter = <StreamWriter transport=<_SelectorSocketTransport closed fd=19> reader=<aiohttp.parsers.StreamParser object at 0x7c9bedebfd60>>\nreader = <aiohttp.parsers.StreamParser object at 0x7c9bedebfd60>\n\n    def send(self, writer, reader):\n        request = aiohttp.Request(writer, self.method, self.path, self.version)\n    \n        if self.compress:\n            request.add_compression_filter(self.compress)\n    \n        if self.chunked is not None:\n            request.enable_chunked_encoding()\n            request.add_chunking_filter(self.chunked)\n    \n        # set default content-type\n        if (self.method in self.POST_METHODS and\n                hdrs.CONTENT_TYPE not in self.headers):\n            self.headers[hdrs.CONTENT_TYPE] = 'application/octet-stream'\n    \n        request.add_headers(\n            *((k, v)\n              for k, v in ((k, value)\n                           for k, value in self.headers.items())))\n        request.send_headers()\n    \n>       self._writer = asyncio.create_task(\n            self.write_bytes(request, reader), loop=self.loop)\nE       TypeError: create_task() got an unexpected keyword argument 'loop'\n\naiohttp/client.py:798: TypeError\n------------------------------ Captured log call -------------------------------\nERROR    asyncio:base_events.py:1753 Exception in callback run_server.<locals>.TestHttpServer.connection_made(<_SelectorSoc...e, bufsize=0>>)\nhandle: <Handle run_server.<locals>.TestHttpServer.connection_made(<_SelectorSoc...e, bufsize=0>>)>\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/events.py\", line 80, in _run\n    self._context.run(self._callback, *self._args)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/aiohttp/test_utils.py\", line 68, in connection_made\n    super().connection_made(transport)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/aiohttp/server.py\", line 147, in connection_made\n    self._request_handler = asyncio.create_task(self.start(), loop=self._loop)\nTypeError: create_task() got an unexpected keyword argument 'loop'\n_________________ TestHttpClientConnector.test_unix_connector __________________\n\nself = <r2e_tests.test_1.TestHttpClientConnector testMethod=test_unix_connector>\n\n    @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'requires unix')\n    def test_unix_connector(self):\n        path = '/tmp/aiohttp_unix.sock'\n    \n        connector = aiohttp.UnixConnector(path, loop=self.loop)\n        self.assertEqual(path, connector.path)\n    \n        with test_utils.run_server(\n                self.loop, listen_addr=path, router=Functional) as httpd:\n>           r = self.loop.run_until_complete(\n                client.request(\n                    'get', httpd.url('method', 'get'),\n                    connector=connector,\n                    loop=self.loop))\n\nr2e_tests/test_1.py:527: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n../../../../.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/base_events.py:647: in run_until_complete\n    return future.result()\naiohttp/client.py:358: in request\n    resp = yield from session.request(method, url,\naiohttp/client.py:128: in request\n    resp = req.send(conn.writer, conn.reader)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <aiohttp.client.ClientRequest object at 0x7c9bedeb8be0>\nwriter = <StreamWriter transport=<_SelectorSocketTransport closed fd=19> reader=<aiohttp.parsers.StreamParser object at 0x7c9bedeb8cd0>>\nreader = <aiohttp.parsers.StreamParser object at 0x7c9bedeb8cd0>\n\n    def send(self, writer, reader):\n        request = aiohttp.Request(writer, self.method, self.path, self.version)\n    \n        if self.compress:\n            request.add_compression_filter(self.compress)\n    \n        if self.chunked is not None:\n            request.enable_chunked_encoding()\n            request.add_chunking_filter(self.chunked)\n    \n        # set default content-type\n        if (self.method in self.POST_METHODS and\n                hdrs.CONTENT_TYPE not in self.headers):\n            self.headers[hdrs.CONTENT_TYPE] = 'application/octet-stream'\n    \n        request.add_headers(\n            *((k, v)\n              for k, v in ((k, value)\n                           for k, value in self.headers.items())))\n        request.send_headers()\n    \n>       self._writer = asyncio.create_task(\n            self.write_bytes(request, reader), loop=self.loop)\nE       TypeError: create_task() got an unexpected keyword argument 'loop'\n\naiohttp/client.py:798: TypeError\n------------------------------ Captured log call -------------------------------\nERROR    asyncio:base_events.py:1753 Exception in callback run_server.<locals>.TestHttpServer.connection_made(<_SelectorSoc...e, bufsize=0>>)\nhandle: <Handle run_server.<locals>.TestHttpServer.connection_made(<_SelectorSoc...e, bufsize=0>>)>\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/asyncio/events.py\", line 80, in _run\n    self._context.run(self._callback, *self._args)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/aiohttp/test_utils.py\", line 68, in connection_made\n    super().connection_made(transport)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/aiohttp/server.py\", line 147, in connection_made\n    self._request_handler = asyncio.create_task(self.start(), loop=self._loop)\nTypeError: create_task() got an unexpected keyword argument 'loop'\nERROR    asyncio:base_events.py:1753 Unclosed connection\nclient_connection: <aiohttp.connector.Connection object at 0x7c9bedff0fa0>\n==================================== PASSES ====================================\n_________________________ TestProxyConnector.test_auth _________________________\n------------------------------ Captured log call -------------------------------\nERROR    asyncio:base_events.py:1753 Unclosed connection\nclient_connection: <aiohttp.connector.Connection object at 0x7c9bedeb8b20>\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_close\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_del\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_detach\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_release\nPASSED r2e_tests/test_1.py::TestHttpConnection::test_release_released\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_ambigous_verify_ssl_and_ssl_context\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_cleanup\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_close\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_close_cancels_cleanup_handle\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_close_twice\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_connect\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_connect_oserr\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_connect_timeout\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_create_conn\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_ctor_loop\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_ctor_with_default_loop\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_del\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_del_empty_conector\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_del_with_closed_loop\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_del_with_scheduled_cleanup\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_dont_recreate_ssl_context\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_get\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_get_expired\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_close\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_close_do_not_delete_existing_connections\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_not_opened\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_not_started\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_release_pop_empty_conns\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_respect_precreated_ssl_context\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_tcp_connector_clear_resolved_hosts\nPASSED r2e_tests/test_1.py::TestBaseConnector::test_tcp_connector_ctor\nPASSED r2e_tests/test_1.py::TestHttpClientConnector::test_connector_cookie_deprecation\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_auth\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_auth__not_modifying_request\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_auth_from_url\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_auth_utf8\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_connect\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_ctor\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_ctor2\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_https_connect\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_https_connect_http_proxy_error\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_https_connect_resp_start_error\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_https_connect_runtime_error\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_proxy_auth\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_proxy_connection_error\nPASSED r2e_tests/test_1.py::TestProxyConnector::test_request_port\nFAILED r2e_tests/test_1.py::TestBaseConnector::test_cleanup2 - AssertionError...\nFAILED r2e_tests/test_1.py::TestBaseConnector::test_start_cleanup_task - Asse...\nFAILED r2e_tests/test_1.py::TestHttpClientConnector::test_tcp_connector - Typ...\nFAILED r2e_tests/test_1.py::TestHttpClientConnector::test_unix_connector - Ty...\n========================= 4 failed, 47 passed in 0.65s =========================\n",
    "old_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_922541b8f49e894bd2d52e0ae7d5b6daf3efa073/.venv/lib/python3.9/site-packages/pytest_asyncio/plugin.py:207: PytestDeprecationWarning: The configuration option \"asyncio_default_fixture_loop_scope\" is unset.\nThe event loop scope for asynchronous fixtures will default to the fixture caching scope. Future versions of pytest-asyncio will default the loop scope for asynchronous fixtures to function scope. Set the default fixture loop scope explicitly in order to avoid unexpected behavior in the future. Valid fixture loop scopes are: \"function\", \"class\", \"module\", \"package\", \"session\"\n\n  warnings.warn(PytestDeprecationWarning(_DEFAULT_FIXTURE_LOOP_SCOPE_UNSET))\n"
}
aiohttp/connector.py tests/test_connector.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Cleanup Task Not Scheduled Correctly After Granular Update

**Description:**
After updating the cleanup procedure to be more granular with 1-second steps, the cleanup task is not being scheduled as expected. When initiating the cleanup process, the scheduler fails to invoke the `call_at` method with the correct timestamp, preventing the cleanup function from executing on schedule.

**Example Buggy Code:**
```python
import unittest.mock

def test_cleanup_task():
    loop = unittest.mock.Mock()
    loop.time.return_value = 1.5
    conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)
    conn._start_cleanup_task()
    # Expected call_at to be invoked with time=12 and the cleanup method
    loop.call_at.assert_called_with(12, conn._cleanup)
```

**Expected Behavior:**
The `call_at` method should be called with the calculated timestamp (`ceil(now + keepalive_timeout)`) and the cleanup function, ensuring that the cleanup task is scheduled to run at the correct time.

**Actual Behavior:**
The `call_at` method is not being called, resulting in the cleanup function not being scheduled. This leads to potential delays or failures in resource cleanup.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### aiohttp/connector.py
import asyncio
import aiohttp
import functools
import http.cookies
import ssl
import socket
import sys
import traceback
import warnings


from . import hdrs
from .client import ClientRequest
from .errors import ServerDisconnectedError
from .errors import HttpProxyError, ProxyConnectionError
from .errors import ClientOSError, ClientTimeoutError
from .helpers import BasicAuth


__all__ = ('BaseConnector', 'TCPConnector', 'ProxyConnector', 'UnixConnector')

PY_34 = sys.version_info >= (3, 4)
PY_343 = sys.version_info >= (3, 4, 3)


class Connection(object):

    _source_traceback = None
    _transport = None

    def __init__(self, connector, key, request, transport, protocol, loop):
        self._key = key
        self._connector = connector
        self._request = request
        self._transport = transport
        self._protocol = protocol
        self._loop = loop
        self.reader = protocol.reader
        self.writer = protocol.writer

        if loop.get_debug():
            self._source_traceback = traceback.extract_stack(sys._getframe(1))

    if PY_34:
        def __del__(self):
            if self._transport is not None:
                self._connector._release(
                    self._key, self._request, self._transport, self._protocol,
                    should_close=True)

                warnings.warn("Unclosed connection {!r}".format(self),
                              ResourceWarning)
                context = {'client_connection': self,
                           'message': 'Unclosed connection'}
                if self._source_traceback is not None:
                    context['source_traceback'] = self._source_traceback
                self._loop.call_exception_handler(context)

    @property
    def loop(self):
        return self._loop

    def close(self):
        if self._transport is not None:
            self._connector._release(
                self._key, self._request, self._transport, self._protocol,
                should_close=True)
            self._transport = None

    def release(self):
        if self._transport is not None:
            self._connector._release(
                self._key, self._request, self._transport, self._protocol,
                should_close=False)
            self._transport = None

    def detach(self):
        self._transport = None

    @property
    def closed(self):
        return self._transport is None


class BaseConnector(object):
    """Base connector class.

    :param conn_timeout: (optional) Connect timeout.
    :param keepalive_timeout: (optional) Keep-alive timeout.
    :param bool force_close: Set to True to force close and do reconnect
        after each request (and between redirects).
    :param loop: Optional event loop.
    """

    _closed = True  # prevent AttributeError in __del__ if ctor was failed
    _source_traceback = None

    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,
                 share_cookies=False, force_close=False, loop=None):
        if loop is None:
            loop = asyncio.get_event_loop()

        self._closed = False
        if loop.get_debug():
            self._source_traceback = traceback.extract_stack(sys._getframe(1))

        self._conns = {}
        self._conn_timeout = conn_timeout
        self._keepalive_timeout = keepalive_timeout
        if share_cookies:
            warnings.warn(
                'Using `share_cookies` is deprecated. '
                'Use Session object instead', DeprecationWarning)
        self._share_cookies = share_cookies
        self._cleanup_handle = None
        self._force_close = force_close

        self._loop = loop
        self._factory = functools.partial(
            aiohttp.StreamProtocol, loop=loop,
            disconnect_error=ServerDisconnectedError)

        self.cookies = http.cookies.SimpleCookie()

    if PY_34:
        def __del__(self):
            if self._closed:
                return
            if not self._conns:
                return

            loop_is_not_closed = not self._loop.is_closed()

            for key, data in self._conns.items():
                for transport, proto, t0 in data:
                    if loop_is_not_closed:
                        transport.close()
            self._conns.clear()

            # N.B.
            # Don't check for self._cleanup_handle!
            # The reason is: if self._cleanup_handle was scheduled
            # a reference to self is stored in event loop.
            # Thus __del__ will not be called until cleanup handler executes.

            warnings.warn("Unclosed connector {!r}".format(self),
                          ResourceWarning)
            context = {'connector': self,
                       'message': 'Unclosed connector'}
            if self._source_traceback is not None:
                context['source_traceback'] = self._source_traceback
            self._loop.call_exception_handler(context)

    def _cleanup(self):
        """Cleanup unused transports."""
        if self._cleanup_handle:
            self._cleanup_handle.cancel()
            self._cleanup_handle = None

        now = self._loop.time()

        connections = {}
        for key, conns in self._conns.items():
            alive = []
            for transport, proto, t0 in conns:
                if transport is not None:
                    if proto and not proto.is_connected():
                        transport = None
                    elif (now - t0) > self._keepalive_timeout:
                        transport.close()
                        transport = None

                if transport:
                    alive.append((transport, proto, t0))
            if alive:
                connections[key] = alive

        if connections:
            self._cleanup_handle = self._loop.call_later(
                self._keepalive_timeout, self._cleanup)

        self._conns = connections

    def _start_cleanup_task(self):
        if self._cleanup_handle is None:
            self._cleanup_handle = self._loop.call_later(
                self._keepalive_timeout, self._cleanup)

    def close(self):
        """Close all opened transports."""
        if self._closed:
            return
        self._closed = True

        for key, data in self._conns.items():
            for transport, proto, t0 in data:
                transport.close()

        self._conns.clear()

        if self._cleanup_handle:
            self._cleanup_handle.cancel()
            self._cleanup_handle = None

    @property
    def closed(self):
        """Is connector closed.

        A readonly property.
        """
        return self._closed

    def update_cookies(self, cookies):
        """Update shared cookies.

        Deprecated, use ClientSession instead.
        """
        if isinstance(cookies, dict):
            cookies = cookies.items()

        for name, value in cookies:
            if PY_343:
                self.cookies[name] = value
            else:
                if isinstance(value, http.cookies.Morsel):
                    # use dict method because SimpleCookie class modifies value
                    dict.__setitem__(self.cookies, name, value)
                else:
                    self.cookies[name] = value

    @asyncio.coroutine
    def connect(self, req):
        """Get from pool or create new connection."""
        key = (req.host, req.port, req.ssl)

        transport, proto = self._get(key)
        if transport is None:
            try:
                if self._conn_timeout:
                    transport, proto = yield from asyncio.wait_for(
                        self._create_connection(req),
                        self._conn_timeout, loop=self._loop)
                else:
                    transport, proto = yield from self._create_connection(req)
            except asyncio.TimeoutError as exc:
                raise ClientTimeoutError(
                    'Connection timeout to host %s:%s ssl:%s' % key) from exc
            except OSError as exc:
                raise ClientOSError(
                    'Cannot connect to host %s:%s ssl:%s' % key) from exc

        return Connection(self, key, req, transport, proto, self._loop)

    def _get(self, key):
        conns = self._conns.get(key)
        t1 = self._loop.time()
        while conns:
            transport, proto, t0 = conns.pop()
            if transport is not None and proto.is_connected():
                if t1 - t0 > self._keepalive_timeout:
                    transport.close()
                    transport = None
                else:
                    return transport, proto

        return None, None

    def _release(self, key, req, transport, protocol, *, should_close=False):
        resp = req.response

        if not should_close:
            if resp is not None:
                if resp.message is None:
                    should_close = True
                else:
                    should_close = resp.message.should_close

            if self._force_close:
                should_close = True

        reader = protocol.reader
        if should_close or (reader.output and not reader.output.at_eof()):
            conns = self._conns.get(key)
            if conns is not None and len(conns) == 0:
                # Issue #253: An empty array will eventually be
                # removed by cleanup, but it's better to pop straight
                # away, because cleanup might not get called (e.g. if
                # keepalive is False).
                self._conns.pop(key, None)

            transport.close()
        else:
            conns = self._conns.get(key)
            if conns is None:
                conns = self._conns[key] = []
            conns.append((transport, protocol, self._loop.time()))
            reader.unset_parser()

            self._start_cleanup_task()

    @asyncio.coroutine
    def _create_connection(self, req):
        raise NotImplementedError()


_SSL_OP_NO_COMPRESSION = getattr(ssl, "OP_NO_COMPRESSION", 0)
_SSH_HAS_CREATE_DEFAULT_CONTEXT = hasattr(ssl, 'create_default_context')


class TCPConnector(BaseConnector):
    """TCP connector.

    :param bool verify_ssl: Set to True to check ssl certifications.
    :param bool resolve: Set to True to do DNS lookup for host name.
    :param family: socket address family
    :param args: see :class:`BaseConnector`
    :param kwargs: see :class:`BaseConnector`
    """

    def __init__(self, *args, verify_ssl=True,
                 resolve=False, family=socket.AF_INET, ssl_context=None,
                 **kwargs):
        super().__init__(*args, **kwargs)

        if not verify_ssl and ssl_context is not None:
            raise ValueError(
                "Either disable ssl certificate validation by "
                "verify_ssl=False or specify ssl_context, not both.")

        self._verify_ssl = verify_ssl
        self._ssl_context = ssl_context
        self._family = family
        self._resolve = resolve
        self._resolved_hosts = {}

    @property
    def verify_ssl(self):
        """Do check for ssl certifications?"""
        return self._verify_ssl

    @property
    def ssl_context(self):
        """SSLContext instance for https requests.

        Lazy property, creates context on demand.
        """
        if self._ssl_context is None:
            if not self._verify_ssl:
                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                sslcontext.options |= ssl.OP_NO_SSLv2
                sslcontext.options |= ssl.OP_NO_SSLv3
                sslcontext.options |= _SSL_OP_NO_COMPRESSION
                sslcontext.set_default_verify_paths()
            elif _SSH_HAS_CREATE_DEFAULT_CONTEXT:
                # Python 3.4+
                sslcontext = ssl.create_default_context()
            else:
                # Fallback for Python 3.3.
                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                sslcontext.options |= ssl.OP_NO_SSLv2
                sslcontext.options |= ssl.OP_NO_SSLv3
                sslcontext.options |= _SSL_OP_NO_COMPRESSION
                sslcontext.set_default_verify_paths()
                sslcontext.verify_mode = ssl.CERT_REQUIRED
            self._ssl_context = sslcontext
        return self._ssl_context

    @property
    def family(self):
        """Socket family like AF_INET."""
        return self._family

    @property
    def resolve(self):
        """Do DNS lookup for host name?"""
        return self._resolve

    @property
    def resolved_hosts(self):
        """The dict of (host, port) -> (ipaddr, port) pairs."""
        return dict(self._resolved_hosts)

    def clear_resolved_hosts(self, host=None, port=None):
        """Remove specified host/port or clear all resolve cache."""
        if host is not None and port is not None:
            key = (host, port)
            if key in self._resolved_hosts:
                del self._resolved_hosts[key]
        else:
            self._resolved_hosts.clear()

    @asyncio.coroutine
    def _resolve_host(self, host, port):
        if self._resolve:
            key = (host, port)

            if key not in self._resolved_hosts:
                infos = yield from self._loop.getaddrinfo(
                    host, port, type=socket.SOCK_STREAM, family=self._family)

                hosts = []
                for family, _, proto, _, address in infos:
                    hosts.append(
                        {'hostname': host,
                         'host': address[0], 'port': address[1],
                         'family': family, 'proto': proto,
                         'flags': socket.AI_NUMERICHOST})
                self._resolved_hosts[key] = hosts

            return list(self._resolved_hosts[key])
        else:
            return [{'hostname': host, 'host': host, 'port': port,
                     'family': self._family, 'proto': 0, 'flags': 0}]

    @asyncio.coroutine
    def _create_connection(self, req):
        """Create connection.

        Has same keyword arguments as BaseEventLoop.create_connection.
        """
        if req.ssl:
            sslcontext = self.ssl_context
        else:
            sslcontext = None

        hosts = yield from self._resolve_host(req.host, req.port)

        while hosts:
            hinfo = hosts.pop()
            try:
                return (yield from self._loop.create_connection(
                    self._factory, hinfo['host'], hinfo['port'],
                    ssl=sslcontext, family=hinfo['family'],
                    proto=hinfo['proto'], flags=hinfo['flags'],
                    server_hostname=hinfo['hostname'] if sslcontext else None))
            except OSError as exc:
                if not hosts:
                    raise ClientOSError('Can not connect to %s:%s' %
                                        (req.host, req.port)) from exc


class ProxyConnector(TCPConnector):
    """Http Proxy connector.

    :param str proxy: Proxy URL address. Only http proxy supported.
    :param proxy_auth: (optional) Proxy HTTP Basic Auth
    :type proxy_auth: aiohttp.helpers.BasicAuth
    :param args: see :class:`TCPConnector`
    :param kwargs: see :class:`TCPConnector`

    Usage:

    >>> conn = ProxyConnector(proxy="http://some.proxy.com")
    >>> session = ClientSession(connector=conn)
    >>> resp = yield from session.get('http://python.org')

    """

    def __init__(self, proxy, *args, proxy_auth=None, **kwargs):
        super().__init__(*args, **kwargs)
        self._proxy = proxy
        self._proxy_auth = proxy_auth
        assert proxy.startswith('http://'), (
            "Only http proxy supported", proxy)
        assert proxy_auth is None or isinstance(proxy_auth, BasicAuth), (
            "proxy_auth must be None or BasicAuth() tuple", proxy_auth)

    @property
    def proxy(self):
        """Proxy URL."""
        return self._proxy

    @asyncio.coroutine
    def _create_connection(self, req):
        proxy_req = ClientRequest(
            hdrs.METH_GET, self._proxy,
            headers={hdrs.HOST: req.host},
            auth=self._proxy_auth,
            loop=self._loop)
        try:
            transport, proto = yield from super()._create_connection(proxy_req)
        except OSError as exc:
            raise ProxyConnectionError(*exc.args) from exc

        if not req.ssl:
            req.path = '{scheme}://{host}{path}'.format(scheme=req.scheme,
                                                        host=req.netloc,
                                                        path=req.path)
        if hdrs.AUTHORIZATION in proxy_req.headers:
            auth = proxy_req.headers[hdrs.AUTHORIZATION]
            del proxy_req.headers[hdrs.AUTHORIZATION]
            req.headers[hdrs.PROXY_AUTHORIZATION] = auth

        if req.ssl:
            # For HTTPS requests over HTTP proxy
            # we must notify proxy to tunnel connection
            # so we send CONNECT command:
            #   CONNECT www.python.org:443 HTTP/1.1
            #   Host: www.python.org
            #
            # next we must do TLS handshake and so on
            # to do this we must wrap raw socket into secure one
            # asyncio handles this perfectly
            proxy_req.method = hdrs.METH_CONNECT
            proxy_req.path = '{}:{}'.format(req.host, req.port)
            key = (req.host, req.port, req.ssl)
            conn = Connection(self, key, proxy_req,
                              transport, proto, self._loop)
            proxy_resp = proxy_req.send(conn.writer, conn.reader)
            try:
                resp = yield from proxy_resp.start(conn, True)
            except:
                proxy_resp.close()
                conn.close()
                raise
            else:
                conn.detach()
                if resp.status != 200:
                    raise HttpProxyError(code=resp.status, message=resp.reason)
                rawsock = transport.get_extra_info('socket', default=None)
                if rawsock is None:
                    raise RuntimeError(
                        "Transport does not expose socket instance")
                transport.pause_reading()
                transport, proto = yield from self._loop.create_connection(
                    self._factory, ssl=True, sock=rawsock,
                    server_hostname=req.host)

        return transport, proto


class UnixConnector(BaseConnector):
    """Unix socket connector.

    :param str path: Unix socket path.
    :param args: see :class:`BaseConnector`
    :param kwargs: see :class:`BaseConnector`

    Usage:

    >>> conn = UnixConnector(path='/path/to/socket')
    >>> session = ClientSession(connector=conn)
    >>> resp = yield from session.get('http://python.org')

    """

    def __init__(self, path, *args, **kw):
        super().__init__(*args, **kw)
        self._path = path

    @property
    def path(self):
        """Path to unix socket."""
        return self._path

    @asyncio.coroutine
    def _create_connection(self, req):
        return (yield from self._loop.create_unix_connection(
            self._factory, self._path))

```
--- 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:** Cleanup Task Not Scheduled Correctly After Granular Update

**Description:**
After updating the cleanup procedure to be more granular with 1-second steps, the cleanup task is not being scheduled as expected. When initiating the cleanup process, the scheduler fails to invoke the `call_at` method with the correct timestamp, preventing the cleanup function from executing on schedule.

**Example Buggy Code:**
```python
import unittest.mock

def test_cleanup_task():
    loop = unittest.mock.Mock()
    loop.time.return_value = 1.5
    conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)
    conn._start_cleanup_task()
    # Expected call_at to be invoked with time=12 and the cleanup method
    loop.call_at.assert_called_with(12, conn._cleanup)
```

**Expected Behavior:**
The `call_at` method should be called with the calculated timestamp (`ceil(now + keepalive_timeout)`) and the cleanup function, ensuring that the cleanup task is scheduled to run at the correct time.

**Actual Behavior:**
The `call_at` method is not being called, resulting in the cleanup function not being scheduled. This leads to potential delays or failures in resource cleanup.

[/ISSUE]
{
    "TestHttpConnection.test_close": "PASSED",
    "TestHttpConnection.test_del": "PASSED",
    "TestHttpConnection.test_detach": "PASSED",
    "TestHttpConnection.test_release": "PASSED",
    "TestHttpConnection.test_release_released": "PASSED",
    "TestBaseConnector.test_ambigous_verify_ssl_and_ssl_context": "PASSED",
    "TestBaseConnector.test_cleanup": "PASSED",
    "TestBaseConnector.test_cleanup2": "PASSED",
    "TestBaseConnector.test_close": "PASSED",
    "TestBaseConnector.test_close_cancels_cleanup_handle": "PASSED",
    "TestBaseConnector.test_close_twice": "PASSED",
    "TestBaseConnector.test_connect": "PASSED",
    "TestBaseConnector.test_connect_oserr": "PASSED",
    "TestBaseConnector.test_connect_timeout": "PASSED",
    "TestBaseConnector.test_create_conn": "PASSED",
    "TestBaseConnector.test_ctor_loop": "PASSED",
    "TestBaseConnector.test_ctor_with_default_loop": "PASSED",
    "TestBaseConnector.test_del": "PASSED",
    "TestBaseConnector.test_del_empty_conector": "PASSED",
    "TestBaseConnector.test_del_with_closed_loop": "PASSED",
    "TestBaseConnector.test_del_with_scheduled_cleanup": "PASSED",
    "TestBaseConnector.test_dont_recreate_ssl_context": "PASSED",
    "TestBaseConnector.test_get": "PASSED",
    "TestBaseConnector.test_get_expired": "PASSED",
    "TestBaseConnector.test_release": "PASSED",
    "TestBaseConnector.test_release_close": "PASSED",
    "TestBaseConnector.test_release_close_do_not_delete_existing_connections": "PASSED",
    "TestBaseConnector.test_release_not_opened": "PASSED",
    "TestBaseConnector.test_release_not_started": "PASSED",
    "TestBaseConnector.test_release_pop_empty_conns": "PASSED",
    "TestBaseConnector.test_respect_precreated_ssl_context": "PASSED",
    "TestBaseConnector.test_start_cleanup_task": "PASSED",
    "TestBaseConnector.test_tcp_connector_clear_resolved_hosts": "PASSED",
    "TestBaseConnector.test_tcp_connector_ctor": "PASSED",
    "TestHttpClientConnector.test_connector_cookie_deprecation": "PASSED",
    "TestProxyConnector.test_auth": "PASSED",
    "TestProxyConnector.test_auth__not_modifying_request": "PASSED",
    "TestProxyConnector.test_auth_from_url": "PASSED",
    "TestProxyConnector.test_auth_utf8": "PASSED",
    "TestProxyConnector.test_connect": "PASSED",
    "TestProxyConnector.test_ctor": "PASSED",
    "TestProxyConnector.test_ctor2": "PASSED",
    "TestProxyConnector.test_https_connect": "PASSED",
    "TestProxyConnector.test_https_connect_http_proxy_error": "PASSED",
    "TestProxyConnector.test_https_connect_resp_start_error": "PASSED",
    "TestProxyConnector.test_https_connect_runtime_error": "PASSED",
    "TestProxyConnector.test_proxy_auth": "PASSED",
    "TestProxyConnector.test_proxy_connection_error": "PASSED",
    "TestProxyConnector.test_request_port": "PASSED",
    "TestHttpClientConnector.test_tcp_connector": "FAILED",
    "TestHttpClientConnector.test_unix_connector": "FAILED"
}
diff --git a/aiohttp/connector.py b/aiohttp/connector.py
index 98583b52..5e47ce59 100644
--- a/aiohttp/connector.py
+++ b/aiohttp/connector.py
@@ -8,6 +8,7 @@ import sys
 import traceback
 import warnings
 
+from math import ceil
 
 from . import hdrs
 from .client import ClientRequest
@@ -170,21 +171,22 @@ class BaseConnector(object):
                         transport.close()
                         transport = None
 
-                if transport:
+                if transport is not None:
                     alive.append((transport, proto, t0))
             if alive:
                 connections[key] = alive
 
         if connections:
-            self._cleanup_handle = self._loop.call_later(
-                self._keepalive_timeout, self._cleanup)
+            self._cleanup_handle = self._loop.call_at(
+                ceil(now + self._keepalive_timeout), self._cleanup)
 
         self._conns = connections
 
     def _start_cleanup_task(self):
         if self._cleanup_handle is None:
-            self._cleanup_handle = self._loop.call_later(
-                self._keepalive_timeout, self._cleanup)
+            now = self._loop.time()
+            self._cleanup_handle = self._loop.call_at(
+                ceil(now + self._keepalive_timeout), self._cleanup)
 
     def close(self):
         """Close all opened transports."""

{"aiohttp/connector.py": "import asyncio\nimport aiohttp\nimport functools\nimport http.cookies\nimport ssl\nimport socket\nimport sys\nimport traceback\nimport warnings\n\n\nfrom . import hdrs\nfrom .client import ClientRequest\nfrom .errors import ServerDisconnectedError\nfrom .errors import HttpProxyError, ProxyConnectionError\nfrom .errors import ClientOSError, ClientTimeoutError\nfrom .helpers import BasicAuth\n\n\n__all__ = ('BaseConnector', 'TCPConnector', 'ProxyConnector', 'UnixConnector')\n\nPY_34 = sys.version_info >= (3, 4)\nPY_343 = sys.version_info >= (3, 4, 3)\n\n\nclass Connection(object):\n\n    _source_traceback = None\n    _transport = None\n\n    def __init__(self, connector, key, request, transport, protocol, loop):\n        self._key = key\n        self._connector = connector\n        self._request = request\n        self._transport = transport\n        self._protocol = protocol\n        self._loop = loop\n        self.reader = protocol.reader\n        self.writer = protocol.writer\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n    if PY_34:\n        def __del__(self):\n            if self._transport is not None:\n                self._connector._release(\n                    self._key, self._request, self._transport, self._protocol,\n                    should_close=True)\n\n                warnings.warn(\"Unclosed connection {!r}\".format(self),\n                              ResourceWarning)\n                context = {'client_connection': self,\n                           'message': 'Unclosed connection'}\n                if self._source_traceback is not None:\n                    context['source_traceback'] = self._source_traceback\n                self._loop.call_exception_handler(context)\n\n    @property\n    def loop(self):\n        return self._loop\n\n    def close(self):\n        if self._transport is not None:\n            self._connector._release(\n                self._key, self._request, self._transport, self._protocol,\n                should_close=True)\n            self._transport = None\n\n    def release(self):\n        if self._transport is not None:\n            self._connector._release(\n                self._key, self._request, self._transport, self._protocol,\n                should_close=False)\n            self._transport = None\n\n    def detach(self):\n        self._transport = None\n\n    @property\n    def closed(self):\n        return self._transport is None\n\n\nclass BaseConnector(object):\n    \"\"\"Base connector class.\n\n    :param conn_timeout: (optional) Connect timeout.\n    :param keepalive_timeout: (optional) Keep-alive timeout.\n    :param bool force_close: Set to True to force close and do reconnect\n        after each request (and between redirects).\n    :param loop: Optional event loop.\n    \"\"\"\n\n    _closed = True  # prevent AttributeError in __del__ if ctor was failed\n    _source_traceback = None\n\n    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,\n                 share_cookies=False, force_close=False, loop=None):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n\n        self._closed = False\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        self._conns = {}\n        self._conn_timeout = conn_timeout\n        self._keepalive_timeout = keepalive_timeout\n        if share_cookies:\n            warnings.warn(\n                'Using `share_cookies` is deprecated. '\n                'Use Session object instead', DeprecationWarning)\n        self._share_cookies = share_cookies\n        self._cleanup_handle = None\n        self._force_close = force_close\n\n        self._loop = loop\n        self._factory = functools.partial(\n            aiohttp.StreamProtocol, loop=loop,\n            disconnect_error=ServerDisconnectedError)\n\n        self.cookies = http.cookies.SimpleCookie()\n\n    if PY_34:\n        def __del__(self):\n            if self._closed:\n                return\n            if not self._conns:\n                return\n\n            loop_is_not_closed = not self._loop.is_closed()\n\n            for key, data in self._conns.items():\n                for transport, proto, t0 in data:\n                    if loop_is_not_closed:\n                        transport.close()\n            self._conns.clear()\n\n            # N.B.\n            # Don't check for self._cleanup_handle!\n            # The reason is: if self._cleanup_handle was scheduled\n            # a reference to self is stored in event loop.\n            # Thus __del__ will not be called until cleanup handler executes.\n\n            warnings.warn(\"Unclosed connector {!r}\".format(self),\n                          ResourceWarning)\n            context = {'connector': self,\n                       'message': 'Unclosed connector'}\n            if self._source_traceback is not None:\n                context['source_traceback'] = self._source_traceback\n            self._loop.call_exception_handler(context)\n\n    def _cleanup(self):\n        \"\"\"Cleanup unused transports.\"\"\"\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n        now = self._loop.time()\n\n        connections = {}\n        for key, conns in self._conns.items():\n            alive = []\n            for transport, proto, t0 in conns:\n                if transport is not None:\n                    if proto and not proto.is_connected():\n                        transport = None\n                    elif (now - t0) > self._keepalive_timeout:\n                        transport.close()\n                        transport = None\n\n                if transport:\n                    alive.append((transport, proto, t0))\n            if alive:\n                connections[key] = alive\n\n        if connections:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n        self._conns = connections\n\n    def _start_cleanup_task(self):\n        if self._cleanup_handle is None:\n            self._cleanup_handle = self._loop.call_later(\n                self._keepalive_timeout, self._cleanup)\n\n    def close(self):\n        \"\"\"Close all opened transports.\"\"\"\n        if self._closed:\n            return\n        self._closed = True\n\n        for key, data in self._conns.items():\n            for transport, proto, t0 in data:\n                transport.close()\n\n        self._conns.clear()\n\n        if self._cleanup_handle:\n            self._cleanup_handle.cancel()\n            self._cleanup_handle = None\n\n    @property\n    def closed(self):\n        \"\"\"Is connector closed.\n\n        A readonly property.\n        \"\"\"\n        return self._closed\n\n    def update_cookies(self, cookies):\n        \"\"\"Update shared cookies.\n\n        Deprecated, use ClientSession instead.\n        \"\"\"\n        if isinstance(cookies, dict):\n            cookies = cookies.items()\n\n        for name, value in cookies:\n            if PY_343:\n                self.cookies[name] = value\n            else:\n                if isinstance(value, http.cookies.Morsel):\n                    # use dict method because SimpleCookie class modifies value\n                    dict.__setitem__(self.cookies, name, value)\n                else:\n                    self.cookies[name] = value\n\n    @asyncio.coroutine\n    def connect(self, req):\n        \"\"\"Get from pool or create new connection.\"\"\"\n        key = (req.host, req.port, req.ssl)\n\n        transport, proto = self._get(key)\n        if transport is None:\n            try:\n                if self._conn_timeout:\n                    transport, proto = yield from asyncio.wait_for(\n                        self._create_connection(req),\n                        self._conn_timeout, loop=self._loop)\n                else:\n                    transport, proto = yield from self._create_connection(req)\n            except asyncio.TimeoutError as exc:\n                raise ClientTimeoutError(\n                    'Connection timeout to host %s:%s ssl:%s' % key) from exc\n            except OSError as exc:\n                raise ClientOSError(\n                    'Cannot connect to host %s:%s ssl:%s' % key) from exc\n\n        return Connection(self, key, req, transport, proto, self._loop)\n\n    def _get(self, key):\n        conns = self._conns.get(key)\n        t1 = self._loop.time()\n        while conns:\n            transport, proto, t0 = conns.pop()\n            if transport is not None and proto.is_connected():\n                if t1 - t0 > self._keepalive_timeout:\n                    transport.close()\n                    transport = None\n                else:\n                    return transport, proto\n\n        return None, None\n\n    def _release(self, key, req, transport, protocol, *, should_close=False):\n        resp = req.response\n\n        if not should_close:\n            if resp is not None:\n                if resp.message is None:\n                    should_close = True\n                else:\n                    should_close = resp.message.should_close\n\n            if self._force_close:\n                should_close = True\n\n        reader = protocol.reader\n        if should_close or (reader.output and not reader.output.at_eof()):\n            conns = self._conns.get(key)\n            if conns is not None and len(conns) == 0:\n                # Issue #253: An empty array will eventually be\n                # removed by cleanup, but it's better to pop straight\n                # away, because cleanup might not get called (e.g. if\n                # keepalive is False).\n                self._conns.pop(key, None)\n\n            transport.close()\n        else:\n            conns = self._conns.get(key)\n            if conns is None:\n                conns = self._conns[key] = []\n            conns.append((transport, protocol, self._loop.time()))\n            reader.unset_parser()\n\n            self._start_cleanup_task()\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        raise NotImplementedError()\n\n\n_SSL_OP_NO_COMPRESSION = getattr(ssl, \"OP_NO_COMPRESSION\", 0)\n_SSH_HAS_CREATE_DEFAULT_CONTEXT = hasattr(ssl, 'create_default_context')\n\n\nclass TCPConnector(BaseConnector):\n    \"\"\"TCP connector.\n\n    :param bool verify_ssl: Set to True to check ssl certifications.\n    :param bool resolve: Set to True to do DNS lookup for host name.\n    :param family: socket address family\n    :param args: see :class:`BaseConnector`\n    :param kwargs: see :class:`BaseConnector`\n    \"\"\"\n\n    def __init__(self, *args, verify_ssl=True,\n                 resolve=False, family=socket.AF_INET, ssl_context=None,\n                 **kwargs):\n        super().__init__(*args, **kwargs)\n\n        if not verify_ssl and ssl_context is not None:\n            raise ValueError(\n                \"Either disable ssl certificate validation by \"\n                \"verify_ssl=False or specify ssl_context, not both.\")\n\n        self._verify_ssl = verify_ssl\n        self._ssl_context = ssl_context\n        self._family = family\n        self._resolve = resolve\n        self._resolved_hosts = {}\n\n    @property\n    def verify_ssl(self):\n        \"\"\"Do check for ssl certifications?\"\"\"\n        return self._verify_ssl\n\n    @property\n    def ssl_context(self):\n        \"\"\"SSLContext instance for https requests.\n\n        Lazy property, creates context on demand.\n        \"\"\"\n        if self._ssl_context is None:\n            if not self._verify_ssl:\n                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n                sslcontext.options |= ssl.OP_NO_SSLv2\n                sslcontext.options |= ssl.OP_NO_SSLv3\n                sslcontext.options |= _SSL_OP_NO_COMPRESSION\n                sslcontext.set_default_verify_paths()\n            elif _SSH_HAS_CREATE_DEFAULT_CONTEXT:\n                # Python 3.4+\n                sslcontext = ssl.create_default_context()\n            else:\n                # Fallback for Python 3.3.\n                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n                sslcontext.options |= ssl.OP_NO_SSLv2\n                sslcontext.options |= ssl.OP_NO_SSLv3\n                sslcontext.options |= _SSL_OP_NO_COMPRESSION\n                sslcontext.set_default_verify_paths()\n                sslcontext.verify_mode = ssl.CERT_REQUIRED\n            self._ssl_context = sslcontext\n        return self._ssl_context\n\n    @property\n    def family(self):\n        \"\"\"Socket family like AF_INET.\"\"\"\n        return self._family\n\n    @property\n    def resolve(self):\n        \"\"\"Do DNS lookup for host name?\"\"\"\n        return self._resolve\n\n    @property\n    def resolved_hosts(self):\n        \"\"\"The dict of (host, port) -> (ipaddr, port) pairs.\"\"\"\n        return dict(self._resolved_hosts)\n\n    def clear_resolved_hosts(self, host=None, port=None):\n        \"\"\"Remove specified host/port or clear all resolve cache.\"\"\"\n        if host is not None and port is not None:\n            key = (host, port)\n            if key in self._resolved_hosts:\n                del self._resolved_hosts[key]\n        else:\n            self._resolved_hosts.clear()\n\n    @asyncio.coroutine\n    def _resolve_host(self, host, port):\n        if self._resolve:\n            key = (host, port)\n\n            if key not in self._resolved_hosts:\n                infos = yield from self._loop.getaddrinfo(\n                    host, port, type=socket.SOCK_STREAM, family=self._family)\n\n                hosts = []\n                for family, _, proto, _, address in infos:\n                    hosts.append(\n                        {'hostname': host,\n                         'host': address[0], 'port': address[1],\n                         'family': family, 'proto': proto,\n                         'flags': socket.AI_NUMERICHOST})\n                self._resolved_hosts[key] = hosts\n\n            return list(self._resolved_hosts[key])\n        else:\n            return [{'hostname': host, 'host': host, 'port': port,\n                     'family': self._family, 'proto': 0, 'flags': 0}]\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        \"\"\"Create connection.\n\n        Has same keyword arguments as BaseEventLoop.create_connection.\n        \"\"\"\n        if req.ssl:\n            sslcontext = self.ssl_context\n        else:\n            sslcontext = None\n\n        hosts = yield from self._resolve_host(req.host, req.port)\n\n        while hosts:\n            hinfo = hosts.pop()\n            try:\n                return (yield from self._loop.create_connection(\n                    self._factory, hinfo['host'], hinfo['port'],\n                    ssl=sslcontext, family=hinfo['family'],\n                    proto=hinfo['proto'], flags=hinfo['flags'],\n                    server_hostname=hinfo['hostname'] if sslcontext else None))\n            except OSError as exc:\n                if not hosts:\n                    raise ClientOSError('Can not connect to %s:%s' %\n                                        (req.host, req.port)) from exc\n\n\nclass ProxyConnector(TCPConnector):\n    \"\"\"Http Proxy connector.\n\n    :param str proxy: Proxy URL address. Only http proxy supported.\n    :param proxy_auth: (optional) Proxy HTTP Basic Auth\n    :type proxy_auth: aiohttp.helpers.BasicAuth\n    :param args: see :class:`TCPConnector`\n    :param kwargs: see :class:`TCPConnector`\n\n    Usage:\n\n    >>> conn = ProxyConnector(proxy=\"http://some.proxy.com\")\n    >>> session = ClientSession(connector=conn)\n    >>> resp = yield from session.get('http://python.org')\n\n    \"\"\"\n\n    def __init__(self, proxy, *args, proxy_auth=None, **kwargs):\n        super().__init__(*args, **kwargs)\n        self._proxy = proxy\n        self._proxy_auth = proxy_auth\n        assert proxy.startswith('http://'), (\n            \"Only http proxy supported\", proxy)\n        assert proxy_auth is None or isinstance(proxy_auth, BasicAuth), (\n            \"proxy_auth must be None or BasicAuth() tuple\", proxy_auth)\n\n    @property\n    def proxy(self):\n        \"\"\"Proxy URL.\"\"\"\n        return self._proxy\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        proxy_req = ClientRequest(\n            hdrs.METH_GET, self._proxy,\n            headers={hdrs.HOST: req.host},\n            auth=self._proxy_auth,\n            loop=self._loop)\n        try:\n            transport, proto = yield from super()._create_connection(proxy_req)\n        except OSError as exc:\n            raise ProxyConnectionError(*exc.args) from exc\n\n        if not req.ssl:\n            req.path = '{scheme}://{host}{path}'.format(scheme=req.scheme,\n                                                        host=req.netloc,\n                                                        path=req.path)\n        if hdrs.AUTHORIZATION in proxy_req.headers:\n            auth = proxy_req.headers[hdrs.AUTHORIZATION]\n            del proxy_req.headers[hdrs.AUTHORIZATION]\n            req.headers[hdrs.PROXY_AUTHORIZATION] = auth\n\n        if req.ssl:\n            # For HTTPS requests over HTTP proxy\n            # we must notify proxy to tunnel connection\n            # so we send CONNECT command:\n            #   CONNECT www.python.org:443 HTTP/1.1\n            #   Host: www.python.org\n            #\n            # next we must do TLS handshake and so on\n            # to do this we must wrap raw socket into secure one\n            # asyncio handles this perfectly\n            proxy_req.method = hdrs.METH_CONNECT\n            proxy_req.path = '{}:{}'.format(req.host, req.port)\n            key = (req.host, req.port, req.ssl)\n            conn = Connection(self, key, proxy_req,\n                              transport, proto, self._loop)\n            proxy_resp = proxy_req.send(conn.writer, conn.reader)\n            try:\n                resp = yield from proxy_resp.start(conn, True)\n            except:\n                proxy_resp.close()\n                conn.close()\n                raise\n            else:\n                conn.detach()\n                if resp.status != 200:\n                    raise HttpProxyError(code=resp.status, message=resp.reason)\n                rawsock = transport.get_extra_info('socket', default=None)\n                if rawsock is None:\n                    raise RuntimeError(\n                        \"Transport does not expose socket instance\")\n                transport.pause_reading()\n                transport, proto = yield from self._loop.create_connection(\n                    self._factory, ssl=True, sock=rawsock,\n                    server_hostname=req.host)\n\n        return transport, proto\n\n\nclass UnixConnector(BaseConnector):\n    \"\"\"Unix socket connector.\n\n    :param str path: Unix socket path.\n    :param args: see :class:`BaseConnector`\n    :param kwargs: see :class:`BaseConnector`\n\n    Usage:\n\n    >>> conn = UnixConnector(path='/path/to/socket')\n    >>> session = ClientSession(connector=conn)\n    >>> resp = yield from session.get('http://python.org')\n\n    \"\"\"\n\n    def __init__(self, path, *args, **kw):\n        super().__init__(*args, **kw)\n        self._path = path\n\n    @property\n    def path(self):\n        \"\"\"Path to unix socket.\"\"\"\n        return self._path\n\n    @asyncio.coroutine\n    def _create_connection(self, req):\n        return (yield from self._loop.create_unix_connection(\n            self._factory, self._path))\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:** Cleanup Task Not Scheduled Correctly After Granular Update

**Description:**
After updating the cleanup procedure to be more granular with 1-second steps, the cleanup task is not being scheduled as expected. When initiating the cleanup process, the scheduler fails to invoke the `call_at` method with the correct timestamp, preventing the cleanup function from executing on schedule.

**Example Buggy Code:**
```python
import unittest.mock

def test_cleanup_task():
    loop = unittest.mock.Mock()
    loop.time.return_value = 1.5
    conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)
    conn._start_cleanup_task()
    # Expected call_at to be invoked with time=12 and the cleanup method
    loop.call_at.assert_called_with(12, conn._cleanup)
```

**Expected Behavior:**
The `call_at` method should be called with the calculated timestamp (`ceil(now + keepalive_timeout)`) and the cleanup function, ensuring that the cleanup task is scheduled to run at the correct time.

**Actual Behavior:**
The `call_at` method is not being called, resulting in the cleanup function not being scheduled. This leads to potential delays or failures in resource cleanup.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### aiohttp/connector.py
import asyncio
import aiohttp
import functools
import http.cookies
import ssl
import socket
import sys
import traceback
import warnings


from . import hdrs
from .client import ClientRequest
from .errors import ServerDisconnectedError
from .errors import HttpProxyError, ProxyConnectionError
from .errors import ClientOSError, ClientTimeoutError
from .helpers import BasicAuth


__all__ = ('BaseConnector', 'TCPConnector', 'ProxyConnector', 'UnixConnector')

PY_34 = sys.version_info >= (3, 4)
PY_343 = sys.version_info >= (3, 4, 3)


class Connection(object):

    _source_traceback = None
    _transport = None

    def __init__(self, connector, key, request, transport, protocol, loop):
        self._key = key
        self._connector = connector
        self._request = request
        self._transport = transport
        self._protocol = protocol
        self._loop = loop
        self.reader = protocol.reader
        self.writer = protocol.writer

        if loop.get_debug():
            self._source_traceback = traceback.extract_stack(sys._getframe(1))

    if PY_34:
        def __del__(self):
            if self._transport is not None:
                self._connector._release(
                    self._key, self._request, self._transport, self._protocol,
                    should_close=True)

                warnings.warn("Unclosed connection {!r}".format(self),
                              ResourceWarning)
                context = {'client_connection': self,
                           'message': 'Unclosed connection'}
                if self._source_traceback is not None:
                    context['source_traceback'] = self._source_traceback
                self._loop.call_exception_handler(context)

    @property
    def loop(self):
        return self._loop

    def close(self):
        if self._transport is not None:
            self._connector._release(
                self._key, self._request, self._transport, self._protocol,
                should_close=True)
            self._transport = None

    def release(self):
        if self._transport is not None:
            self._connector._release(
                self._key, self._request, self._transport, self._protocol,
                should_close=False)
            self._transport = None

    def detach(self):
        self._transport = None

    @property
    def closed(self):
        return self._transport is None


class BaseConnector(object):
    """Base connector class.

    :param conn_timeout: (optional) Connect timeout.
    :param keepalive_timeout: (optional) Keep-alive timeout.
    :param bool force_close: Set to True to force close and do reconnect
        after each request (and between redirects).
    :param loop: Optional event loop.
    """

    _closed = True  # prevent AttributeError in __del__ if ctor was failed
    _source_traceback = None

    def __init__(self, *, conn_timeout=None, keepalive_timeout=30,
                 share_cookies=False, force_close=False, loop=None):
        if loop is None:
            loop = asyncio.get_event_loop()

        self._closed = False
        if loop.get_debug():
            self._source_traceback = traceback.extract_stack(sys._getframe(1))

        self._conns = {}
        self._conn_timeout = conn_timeout
        self._keepalive_timeout = keepalive_timeout
        if share_cookies:
            warnings.warn(
                'Using `share_cookies` is deprecated. '
                'Use Session object instead', DeprecationWarning)
        self._share_cookies = share_cookies
        self._cleanup_handle = None
        self._force_close = force_close

        self._loop = loop
        self._factory = functools.partial(
            aiohttp.StreamProtocol, loop=loop,
            disconnect_error=ServerDisconnectedError)

        self.cookies = http.cookies.SimpleCookie()

    if PY_34:
        def __del__(self):
            if self._closed:
                return
            if not self._conns:
                return

            loop_is_not_closed = not self._loop.is_closed()

            for key, data in self._conns.items():
                for transport, proto, t0 in data:
                    if loop_is_not_closed:
                        transport.close()
            self._conns.clear()

            # N.B.
            # Don't check for self._cleanup_handle!
            # The reason is: if self._cleanup_handle was scheduled
            # a reference to self is stored in event loop.
            # Thus __del__ will not be called until cleanup handler executes.

            warnings.warn("Unclosed connector {!r}".format(self),
                          ResourceWarning)
            context = {'connector': self,
                       'message': 'Unclosed connector'}
            if self._source_traceback is not None:
                context['source_traceback'] = self._source_traceback
            self._loop.call_exception_handler(context)

    def _cleanup(self):
        """Cleanup unused transports."""
        if self._cleanup_handle:
            self._cleanup_handle.cancel()
            self._cleanup_handle = None

        now = self._loop.time()

        connections = {}
        for key, conns in self._conns.items():
            alive = []
            for transport, proto, t0 in conns:
                if transport is not None:
                    if proto and not proto.is_connected():
                        transport = None
                    elif (now - t0) > self._keepalive_timeout:
                        transport.close()
                        transport = None

                if transport:
                    alive.append((transport, proto, t0))
            if alive:
                connections[key] = alive

        if connections:
            self._cleanup_handle = self._loop.call_later(
                self._keepalive_timeout, self._cleanup)

        self._conns = connections

    def _start_cleanup_task(self):
        if self._cleanup_handle is None:
            self._cleanup_handle = self._loop.call_later(
                self._keepalive_timeout, self._cleanup)

    def close(self):
        """Close all opened transports."""
        if self._closed:
            return
        self._closed = True

        for key, data in self._conns.items():
            for transport, proto, t0 in data:
                transport.close()

        self._conns.clear()

        if self._cleanup_handle:
            self._cleanup_handle.cancel()
            self._cleanup_handle = None

    @property
    def closed(self):
        """Is connector closed.

        A readonly property.
        """
        return self._closed

    def update_cookies(self, cookies):
        """Update shared cookies.

        Deprecated, use ClientSession instead.
        """
        if isinstance(cookies, dict):
            cookies = cookies.items()

        for name, value in cookies:
            if PY_343:
                self.cookies[name] = value
            else:
                if isinstance(value, http.cookies.Morsel):
                    # use dict method because SimpleCookie class modifies value
                    dict.__setitem__(self.cookies, name, value)
                else:
                    self.cookies[name] = value

    @asyncio.coroutine
    def connect(self, req):
        """Get from pool or create new connection."""
        key = (req.host, req.port, req.ssl)

        transport, proto = self._get(key)
        if transport is None:
            try:
                if self._conn_timeout:
                    transport, proto = yield from asyncio.wait_for(
                        self._create_connection(req),
                        self._conn_timeout, loop=self._loop)
                else:
                    transport, proto = yield from self._create_connection(req)
            except asyncio.TimeoutError as exc:
                raise ClientTimeoutError(
                    'Connection timeout to host %s:%s ssl:%s' % key) from exc
            except OSError as exc:
                raise ClientOSError(
                    'Cannot connect to host %s:%s ssl:%s' % key) from exc

        return Connection(self, key, req, transport, proto, self._loop)

    def _get(self, key):
        conns = self._conns.get(key)
        t1 = self._loop.time()
        while conns:
            transport, proto, t0 = conns.pop()
            if transport is not None and proto.is_connected():
                if t1 - t0 > self._keepalive_timeout:
                    transport.close()
                    transport = None
                else:
                    return transport, proto

        return None, None

    def _release(self, key, req, transport, protocol, *, should_close=False):
        resp = req.response

        if not should_close:
            if resp is not None:
                if resp.message is None:
                    should_close = True
                else:
                    should_close = resp.message.should_close

            if self._force_close:
                should_close = True

        reader = protocol.reader
        if should_close or (reader.output and not reader.output.at_eof()):
            conns = self._conns.get(key)
            if conns is not None and len(conns) == 0:
                # Issue #253: An empty array will eventually be
                # removed by cleanup, but it's better to pop straight
                # away, because cleanup might not get called (e.g. if
                # keepalive is False).
                self._conns.pop(key, None)

            transport.close()
        else:
            conns = self._conns.get(key)
            if conns is None:
                conns = self._conns[key] = []
            conns.append((transport, protocol, self._loop.time()))
            reader.unset_parser()

            self._start_cleanup_task()

    @asyncio.coroutine
    def _create_connection(self, req):
        raise NotImplementedError()


_SSL_OP_NO_COMPRESSION = getattr(ssl, "OP_NO_COMPRESSION", 0)
_SSH_HAS_CREATE_DEFAULT_CONTEXT = hasattr(ssl, 'create_default_context')


class TCPConnector(BaseConnector):
    """TCP connector.

    :param bool verify_ssl: Set to True to check ssl certifications.
    :param bool resolve: Set to True to do DNS lookup for host name.
    :param family: socket address family
    :param args: see :class:`BaseConnector`
    :param kwargs: see :class:`BaseConnector`
    """

    def __init__(self, *args, verify_ssl=True,
                 resolve=False, family=socket.AF_INET, ssl_context=None,
                 **kwargs):
        super().__init__(*args, **kwargs)

        if not verify_ssl and ssl_context is not None:
            raise ValueError(
                "Either disable ssl certificate validation by "
                "verify_ssl=False or specify ssl_context, not both.")

        self._verify_ssl = verify_ssl
        self._ssl_context = ssl_context
        self._family = family
        self._resolve = resolve
        self._resolved_hosts = {}

    @property
    def verify_ssl(self):
        """Do check for ssl certifications?"""
        return self._verify_ssl

    @property
    def ssl_context(self):
        """SSLContext instance for https requests.

        Lazy property, creates context on demand.
        """
        if self._ssl_context is None:
            if not self._verify_ssl:
                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                sslcontext.options |= ssl.OP_NO_SSLv2
                sslcontext.options |= ssl.OP_NO_SSLv3
                sslcontext.options |= _SSL_OP_NO_COMPRESSION
                sslcontext.set_default_verify_paths()
            elif _SSH_HAS_CREATE_DEFAULT_CONTEXT:
                # Python 3.4+
                sslcontext = ssl.create_default_context()
            else:
                # Fallback for Python 3.3.
                sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                sslcontext.options |= ssl.OP_NO_SSLv2
                sslcontext.options |= ssl.OP_NO_SSLv3
                sslcontext.options |= _SSL_OP_NO_COMPRESSION
                sslcontext.set_default_verify_paths()
                sslcontext.verify_mode = ssl.CERT_REQUIRED
            self._ssl_context = sslcontext
        return self._ssl_context

    @property
    def family(self):
        """Socket family like AF_INET."""
        return self._family

    @property
    def resolve(self):
        """Do DNS lookup for host name?"""
        return self._resolve

    @property
    def resolved_hosts(self):
        """The dict of (host, port) -> (ipaddr, port) pairs."""
        return dict(self._resolved_hosts)

    def clear_resolved_hosts(self, host=None, port=None):
        """Remove specified host/port or clear all resolve cache."""
        if host is not None and port is not None:
            key = (host, port)
            if key in self._resolved_hosts:
                del self._resolved_hosts[key]
        else:
            self._resolved_hosts.clear()

    @asyncio.coroutine
    def _resolve_host(self, host, port):
        if self._resolve:
            key = (host, port)

            if key not in self._resolved_hosts:
                infos = yield from self._loop.getaddrinfo(
                    host, port, type=socket.SOCK_STREAM, family=self._family)

                hosts = []
                for family, _, proto, _, address in infos:
                    hosts.append(
                        {'hostname': host,
                         'host': address[0], 'port': address[1],
                         'family': family, 'proto': proto,
                         'flags': socket.AI_NUMERICHOST})
                self._resolved_hosts[key] = hosts

            return list(self._resolved_hosts[key])
        else:
            return [{'hostname': host, 'host': host, 'port': port,
                     'family': self._family, 'proto': 0, 'flags': 0}]

    @asyncio.coroutine
    def _create_connection(self, req):
        """Create connection.

        Has same keyword arguments as BaseEventLoop.create_connection.
        """
        if req.ssl:
            sslcontext = self.ssl_context
        else:
            sslcontext = None

        hosts = yield from self._resolve_host(req.host, req.port)

        while hosts:
            hinfo = hosts.pop()
            try:
                return (yield from self._loop.create_connection(
                    self._factory, hinfo['host'], hinfo['port'],
                    ssl=sslcontext, family=hinfo['family'],
                    proto=hinfo['proto'], flags=hinfo['flags'],
                    server_hostname=hinfo['hostname'] if sslcontext else None))
            except OSError as exc:
                if not hosts:
                    raise ClientOSError('Can not connect to %s:%s' %
                                        (req.host, req.port)) from exc


class ProxyConnector(TCPConnector):
    """Http Proxy connector.

    :param str proxy: Proxy URL address. Only http proxy supported.
    :param proxy_auth: (optional) Proxy HTTP Basic Auth
    :type proxy_auth: aiohttp.helpers.BasicAuth
    :param args: see :class:`TCPConnector`
    :param kwargs: see :class:`TCPConnector`

    Usage:

    >>> conn = ProxyConnector(proxy="http://some.proxy.com")
    >>> session = ClientSession(connector=conn)
    >>> resp = yield from session.get('http://python.org')

    """

    def __init__(self, proxy, *args, proxy_auth=None, **kwargs):
        super().__init__(*args, **kwargs)
        self._proxy = proxy
        self._proxy_auth = proxy_auth
        assert proxy.startswith('http://'), (
            "Only http proxy supported", proxy)
        assert proxy_auth is None or isinstance(proxy_auth, BasicAuth), (
            "proxy_auth must be None or BasicAuth() tuple", proxy_auth)

    @property
    def proxy(self):
        """Proxy URL."""
        return self._proxy

    @asyncio.coroutine
    def _create_connection(self, req):
        proxy_req = ClientRequest(
            hdrs.METH_GET, self._proxy,
            headers={hdrs.HOST: req.host},
            auth=self._proxy_auth,
            loop=self._loop)
        try:
            transport, proto = yield from super()._create_connection(proxy_req)
        except OSError as exc:
            raise ProxyConnectionError(*exc.args) from exc

        if not req.ssl:
            req.path = '{scheme}://{host}{path}'.format(scheme=req.scheme,
                                                        host=req.netloc,
                                                        path=req.path)
        if hdrs.AUTHORIZATION in proxy_req.headers:
            auth = proxy_req.headers[hdrs.AUTHORIZATION]
            del proxy_req.headers[hdrs.AUTHORIZATION]
            req.headers[hdrs.PROXY_AUTHORIZATION] = auth

        if req.ssl:
            # For HTTPS requests over HTTP proxy
            # we must notify proxy to tunnel connection
            # so we send CONNECT command:
            #   CONNECT www.python.org:443 HTTP/1.1
            #   Host: www.python.org
            #
            # next we must do TLS handshake and so on
            # to do this we must wrap raw socket into secure one
            # asyncio handles this perfectly
            proxy_req.method = hdrs.METH_CONNECT
            proxy_req.path = '{}:{}'.format(req.host, req.port)
            key = (req.host, req.port, req.ssl)
            conn = Connection(self, key, proxy_req,
                              transport, proto, self._loop)
            proxy_resp = proxy_req.send(conn.writer, conn.reader)
            try:
                resp = yield from proxy_resp.start(conn, True)
            except:
                proxy_resp.close()
                conn.close()
                raise
            else:
                conn.detach()
                if resp.status != 200:
                    raise HttpProxyError(code=resp.status, message=resp.reason)
                rawsock = transport.get_extra_info('socket', default=None)
                if rawsock is None:
                    raise RuntimeError(
                        "Transport does not expose socket instance")
                transport.pause_reading()
                transport, proto = yield from self._loop.create_connection(
                    self._factory, ssl=True, sock=rawsock,
                    server_hostname=req.host)

        return transport, proto


class UnixConnector(BaseConnector):
    """Unix socket connector.

    :param str path: Unix socket path.
    :param args: see :class:`BaseConnector`
    :param kwargs: see :class:`BaseConnector`

    Usage:

    >>> conn = UnixConnector(path='/path/to/socket')
    >>> session = ClientSession(connector=conn)
    >>> resp = yield from session.get('http://python.org')

    """

    def __init__(self, path, *args, **kw):
        super().__init__(*args, **kw)
        self._path = path

    @property
    def path(self):
        """Path to unix socket."""
        return self._path

    @asyncio.coroutine
    def _create_connection(self, req):
        return (yield from self._loop.create_unix_connection(
            self._factory, self._path))

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